diff --git a/.gitignore b/.gitignore
index 2b00952..d05bdc2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,4 @@
.lake
+
+# macOS Finder metadata
+.DS_Store
diff --git a/StrataBoole.lean b/StrataBoole.lean
index 8e64d24..702f1da 100644
--- a/StrataBoole.lean
+++ b/StrataBoole.lean
@@ -7,6 +7,7 @@ module
public import StrataBoole.Boole
public import StrataBoole.Verify
+public import StrataBoole.HoareLogic.HoareLift
/-! ## Strata Boole Public Interface
@@ -29,6 +30,28 @@ dialect of Strata.
`Strata.BooleNat.prepend`. The implementation is `natCorePreamble` in
`StrataBoole/Verify.lean`; nothing imports this module. `lake build StrataBoole.Nat`.
+### `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 (`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`
+
+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.Reflect.Boole`
+
+`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
+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/Delab.lean b/StrataBoole/HoareLogic/Delab.lean
new file mode 100644
index 0000000..be99585
--- /dev/null
+++ b/StrataBoole/HoareLogic/Delab.lean
@@ -0,0 +1,623 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+import Lean
+import Strata.Languages.Core.Procedure
+import StrataBoole.HoareLogic.Hoare.Lift.Denote
+
+/-! # 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 { … } { … }⟧`;
+* the values of a Core type `T` in a model as `⟦T⟧ᵛ`, and a model's interpretation of an
+ operator `f` at the arguments `a`, `b` as `f a b`.
+
+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.Hoare.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
+/-- The values of a Core type in a model. -/
+syntax:max "⟦" core_type "⟧ᵛ" : term
+
+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 5 then
+ let some p := strLit? (e.getArg! 1) | embed
+ let some args ← withNaryArg 3 (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 4)
+ 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⟧)
+
+/-! ## Values of a model
+
+The lifting reads a condition as a proposition over the values of the model of the runtime
+factory. The type of the values of a Core type `T` prints as `⟦T⟧ᵛ`, and the model's
+interpretation of an operator as the operator's name applied to its arguments. The conversions
+between `Int` or `Bool` and the values of `int` or `bool` are identities and are not printed. -/
+
+@[delab app.Lambda.TyDenote]
+def delabTyDenote : Delab := whenPPOption getPPCore do
+ let e ← getExpr
+ guard (e.getAppNumArgs == 3)
+ let t ← withNaryArg 2 coreType
+ `(⟦$t⟧ᵛ)
+
+@[delab app.Lambda.Interp.opInterp]
+def delabOpInterp : Delab := whenPPOption getPPCore do
+ let e ← getExpr
+ let n := e.getAppNumArgs
+ guard (n ≥ 6)
+ let some name := strLit? (e.getArg! 4) | failure
+ let f := mkIdent ((name.splitOn ".").foldl Name.str .anonymous)
+ let mut args : Array Term := #[]
+ for i in [6:n] do
+ args := args.push (← withNaryArg i delab)
+ if args.isEmpty then `($f) else `($f $args*)
+
+open Lean.PrettyPrinter in
+@[app_unexpander Strata.Hoare.Denote.toInt, app_unexpander Strata.Hoare.Denote.toBool,
+ app_unexpander Strata.Hoare.Denote.ofInt, app_unexpander Strata.Hoare.Denote.ofBool]
+def unexpandConversion : Unexpander
+ | `($_ $x) => `($x)
+ | _ => throw ()
+
+end Strata.Hoare.Delab
diff --git a/StrataBoole/HoareLogic/Hoare/Call.lean b/StrataBoole/HoareLogic/Hoare/Call.lean
new file mode 100644
index 0000000..65ce0d1
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Call.lean
@@ -0,0 +1,403 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+module
+
+public import StrataBoole.HoareLogic.Hoare.Contract
+public import Strata.Languages.Core.Logic.HoareCall
+public import Strata.Languages.Core.Analysis.ProcedureCorrectnessProps
+import Strata.Languages.Core.ProcedureProps
+import all Strata.DL.Lambda.LTy
+
+/-! # Calls
+
+`Procedure.call_of_contract` gives a triple for a call from the callee's contract. Its triple is
+over the factory visible at the callee, and it asks, besides the contract, that every run of the
+callee's body writes only its outputs and leaves them typed.
+
+`call_wp_abstract` is that rule for a callee without a body, in `wp` form and over the factory
+visible at the caller. An abstract procedure has no run, so the two conditions on its body hold,
+and it meets its contract by definition: the contract is trusted. The two factories agree when
+no function or datatype is declared between the callee and the caller
+(`factoryBeforeProcedure_eq_of_between`). -/
+
+public section
+
+namespace Strata.Hoare
+
+open Core.Logic Core.Logic.Hoare
+
+/-- The factory visible at `callee` is the one visible at `caller` when `callee` is declared no
+later and no declaration between them adds a function. -/
+theorem factoryBeforeProcedure_eq_of_between {p : Core.Program} {caller callee : String}
+ (hbefore : (p.declsBeforeProcedure callee).length ≤ (p.declsBeforeProcedure caller).length)
+ (hnone : ((p.declsBeforeProcedure caller).drop (p.declsBeforeProcedure callee).length).all
+ fun d =>
+ match d with
+ | .func _ _ | .recFuncBlock _ _ => false
+ | .type (.data _) _ => false
+ | _ => true) :
+ p.factoryBeforeProcedure callee = p.factoryBeforeProcedure caller := by
+ obtain ⟨rest, hrest⟩ : p.declsBeforeProcedure callee <+: p.declsBeforeProcedure caller :=
+ List.prefix_of_prefix_length_le (List.takeWhile_prefix _) (List.takeWhile_prefix _) hbefore
+ unfold Core.Program.factoryBeforeProcedure
+ rw [← hrest, List.drop_left] at hnone
+ rw [← hrest, List.foldl_append]
+ clear hrest hbefore
+ generalize (p.declsBeforeProcedure callee).foldl Core.Decl.addToRuntimeFactory Core.Factory = F
+ induction rest generalizing F with
+ | nil => rfl
+ | cons d ds ih =>
+ simp only [List.all_cons, Bool.and_eq_true] at hnone
+ rw [List.foldl_cons]
+ have hd : Core.Decl.addToRuntimeFactory F d = F := by
+ cases d with
+ | func => simp at hnone
+ | recFuncBlock => simp at hnone
+ | type t =>
+ cases t with
+ | data => simp at hnone
+ | _ => rfl
+ | _ => rfl
+ rw [hd]
+ exact ih hnone.2 F
+
+/-- An abstract procedure meets its contract: it has no body to check. -/
+theorem contractTriple_abstract (p : Core.Program) (params : InitEnvWFParams)
+ (procName : String) (proc : Core.Procedure)
+ (hproc : p.findProcByString? procName = some proc)
+ (hbody : proc.body = .abstract)
+ (hchecksTyped : Procedure.contractChecksTyped proc)
+ (hmono : proc.header.typeArgs = []) :
+ Procedure.contractTriple p params procName :=
+ ⟨proc, hproc, Core.Procedure.forall_instance_of_typeArgs_nil hmono
+ ⟨hchecksTyped, by rw [hbody]; trivial⟩⟩
+
+/-- Weakest precondition of a call of `proc`, the procedure `procName` of `p`. At every callee
+frame the call can enter with, the callee's precondition and the axioms visible to it hold; and
+`Q` holds at every store the call can exit with, given the callee's postcondition and typed
+outputs at a callee store that agrees with the entry frame outside the outputs. -/
+@[expose] def wpCall (p : Core.Program) (procName : String) (proc : Core.Procedure)
+ (callArgs : List (Imperative.CallArg Core.Expression)) (Q : Pred) : Pred :=
+ fun ρ₀ =>
+ (∀ σAO, Imperative.Calls.CallEntry ρ₀.factory ρ₀.store proc callArgs σAO →
+ Procedure.contractPre (p.factoryBeforeProcedure procName) proc
+ { store := σAO, factory := ρ₀.factory } ∧
+ Core.Specification.AxiomsBeforeProcedureDecl procName p
+ { store := σAO, factory := ρ₀.factory }) ∧
+ (∀ (ρ' : Imperative.Env Core.Expression) (σ' σAO : Core.CoreStore),
+ Procedure.contractPost (p.factoryBeforeProcedure procName) proc ρ' →
+ Procedure.outputAsPredicate proc ρ' →
+ ρ'.factory = ρ₀.factory →
+ Imperative.Calls.CallEntry ρ₀.factory ρ₀.store proc callArgs σAO →
+ Procedure.storeFrame proc σAO ρ'.store →
+ Imperative.Calls.CallExit ρ₀.factory ρ₀.store proc callArgs ρ'.store σ' →
+ Q { ρ₀ with store := σ' })
+
+/-- A call of a procedure without a body, from inside the procedure `caller`. -/
+theorem call_wp_abstract (p : Core.Program) (params : InitEnvWFParams) (caller procName : String)
+ {tyArgs : Option (List Core.Expression.Ty)}
+ (callArgs : List (Imperative.CallArg Core.Expression))
+ (md : Imperative.MetaData Core.Expression) (proc : Core.Procedure) (Q : Pred)
+ (hproc : p.findProcByString? procName = some proc)
+ (hbody : proc.body = .abstract)
+ (hchecksTyped : Procedure.contractChecksTyped proc)
+ (hmono : proc.header.typeArgs = [])
+ (hfactory : p.factoryBeforeProcedure procName = p.factoryBeforeProcedure caller) :
+ Triple p.findProcByString? params (wpCall p procName proc callArgs Q)
+ [Core.Statement.call procName tyArgs callArgs md] Q
+ (factory := p.factoryBeforeProcedure caller) := by
+ have hinst : ∀ proc', Imperative.Calls.typeInstantiatedCallee p.findProcByString? procName
+ tyArgs = some proc' → proc' = proc := by
+ intro proc' h
+ simp only [Imperative.Calls.typeInstantiatedCallee, hproc, Option.bind_some] at h
+ exact ((Core.Procedure.instantiateTypes_of_typeArgs_nil hmono).1 h).2
+ rw [← hfactory]
+ refine Procedure.call_of_contract p params procName callArgs md _ Q
+ (contractTriple_abstract p params procName proc hproc hbody hchecksTyped hmono)
+ ?_ ?_ ?_ ?_ ?_
+ · intro proc' h σ fac σ' emitted hexec
+ obtain rfl := hinst proc' h
+ rw [hbody] at hexec
+ cases hexec
+ · intro proc' h σ fac σ' emitted _ _ hexec
+ obtain rfl := hinst proc' h
+ rw [hbody] at hexec
+ cases hexec
+ · intro ρ₀ proc' σAO hpre _ h hentry
+ obtain rfl := hinst proc' h
+ refine ⟨(hpre.1 σAO hentry).1, ?_⟩
+ simp [hbody, Imperative.Body.isOpaque]
+ · intro ρ₀ proc' σAO hpre _ h hentry
+ obtain rfl := hinst proc' h
+ exact (hpre.1 σAO hentry).2
+ · intro ρ₀ proc' ρ' σ' σAO hpre _ h hpost hout hfac hentry hframe hexit
+ obtain rfl := hinst proc' h
+ exact hpre.2 ρ' σ' σAO hpost hout hfac hentry hframe hexit
+
+/-! ## The call, one argument at a time
+
+`wpCall` speaks of the relations of the semantics: the callee frame the call enters with
+(`CallEntry`) and the store it exits with (`CallExit`). `wpCallArgs` states the same condition
+over one value per argument and one store fact per formal, which is what a lifting reads:
+
+* each input argument evaluates to a value, each `out` argument holds one;
+* the callee frame binds the input formals and the output-only formals to them;
+* at the frame, the callee's `requires` hold, its formals are typed and its axioms hold;
+* at a callee store that agrees with the frame outside the outputs and satisfies the callee's
+ `ensures`, the outputs hold values, and `Q` holds once they are written to the caller's
+ variables.
+
+It covers a callee without `inout` parameters. -/
+
+/-- `K` at the values the expressions `es` evaluate to, one expression at a time. -/
+@[expose] def forallEval (f : Core.Expression.Factory) (σ : Core.CoreStore) :
+ List Core.Expression.Expr → (List Core.Expression.Val → Prop) → Prop
+ | [], K => K []
+ | e :: es, K =>
+ ∀ v, Core.Expression.eval f σ e = some v → forallEval f σ es fun vs => K (v :: vs)
+
+theorem forallEval_elim {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {es : List Core.Expression.Expr} {vs : List Core.Expression.Val}
+ (hev : Imperative.EvalExpressions (P := Core.Expression) f σ es vs) :
+ ∀ {K : List Core.Expression.Val → Prop}, forallEval f σ es K → K vs := by
+ induction hev with
+ | eval_none => exact fun h => h
+ | eval_some _ he _ ih => exact fun h => ih (h _ he)
+
+/-- `K` at the values of `f` the variables `xs` hold, one variable at a time. -/
+@[expose] def forallRead (f : Core.Expression.Factory) (σ : Core.CoreStore) :
+ List Core.Expression.Ident → (List Core.Expression.Val → Prop) → Prop
+ | [], K => K []
+ | x :: xs, K =>
+ ∀ v, σ x = some v → Imperative.HasVal.value (P := Core.Expression) f v →
+ forallRead f σ xs fun vs => K (v :: vs)
+
+theorem forallRead_elim {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {xs : List Core.Expression.Ident} {vs : List Core.Expression.Val}
+ (hrd : Imperative.ReadValues (P := Core.Expression) f σ xs vs) :
+ ∀ {K : List Core.Expression.Val → Prop}, forallRead f σ xs K → K vs := by
+ induction hrd with
+ | read_none => exact fun h => h
+ | read_some hx hv _ ih => exact fun h => ih (h _ hx hv)
+
+/-- `K` at the store after assigning `vs` to `xs`, one assignment at a time. -/
+@[expose] def forallUpdates : Core.CoreStore → List Core.Expression.Ident →
+ List Core.Expression.Val → (Core.CoreStore → Prop) → Prop
+ | σ, [], [], K => K σ
+ | σ, x :: xs, v :: vs, K =>
+ ∀ σ', Imperative.UpdateState Core.Expression σ x v σ' → forallUpdates σ' xs vs K
+ | _, _, _, _ => True
+
+theorem forallUpdates_elim {σ σ' : Core.CoreStore} {xs : List Core.Expression.Ident}
+ {vs : List Core.Expression.Val}
+ (hup : Imperative.UpdateStates (P := Core.Expression) σ xs vs σ') :
+ ∀ {K : Core.CoreStore → Prop}, forallUpdates σ xs vs K → K σ' := by
+ induction hup with
+ | update_none => exact fun h => h
+ | update_some hu _ ih => exact fun h => ih (h _ hu)
+
+/-- The store binds the names `xs` to the values `vs`, positionally. -/
+@[expose] def binds (σ : Core.CoreStore) :
+ List Core.Expression.Ident → List Core.Expression.Val → Prop
+ | x :: xs, v :: vs => σ x = some v ∧ binds σ xs vs
+ | _, _ => True
+
+/-- Declaring `xs` with the values `vs` binds them, and keeps what the store bound. -/
+theorem binds_of_initStates {σ σ' : Core.CoreStore} {xs : List Core.Expression.Ident}
+ {vs : List Core.Expression.Val}
+ (h : Imperative.InitStates (P := Core.Expression) σ xs vs σ') :
+ binds σ' xs vs ∧ ∀ y w, σ y = some w → σ' y = some w := by
+ induction h with
+ | init_none => exact ⟨trivial, fun _ _ h => h⟩
+ | @init_some σ x v σ₁ xs vs σ₂ hi _ ih =>
+ cases hi with
+ | init hnone hnew hoth =>
+ refine ⟨⟨ih.2 x v hnew, ih.1⟩, fun y w hy => ih.2 y w ?_⟩
+ have hne : x ≠ y := fun h => by rw [h, hy] at hnone; cases hnone
+ rw [hoth y hne]
+ exact hy
+
+theorem binds_mono {σ σ' : Core.CoreStore} (hmono : ∀ y w, σ y = some w → σ' y = some w) :
+ ∀ {xs : List Core.Expression.Ident} {vs : List Core.Expression.Val},
+ binds σ xs vs → binds σ' xs vs
+ | _ :: _, _ :: _, h => ⟨hmono _ _ h.1, binds_mono hmono h.2⟩
+ | [], _, _ => trivial
+ | _ :: _, [], _ => trivial
+
+/-- Weakest precondition of a call, over one value per argument and one store fact per
+formal. The arguments and the formals are given as lists: the input expressions `ins`, the `out`
+variables `outArgs`, the variables written `lhs`, and the callee's input, output-only and
+output formals. -/
+@[expose] def wpCallArgs (factory : Lambda.Factory Core.CoreLParams) (p : Core.Program)
+ (procName : String) (proc : Core.Procedure) (ins : List Core.Expression.Expr)
+ (outArgs lhs inF outOnlyF outF : List Core.Expression.Ident) (Q : Pred) : Pred :=
+ fun ρ₀ =>
+ forallEval ρ₀.factory ρ₀.store ins fun ivs =>
+ forallRead ρ₀.factory ρ₀.store outArgs fun ovs =>
+ ∀ σAO : Core.CoreStore, binds σAO inF ivs → binds σAO outOnlyF ovs →
+ (Procedure.preAsPredicate factory proc { store := σAO, factory := ρ₀.factory } ∧
+ ρ₀.factory.factory = factory ∧
+ Procedure.inputAsPredicate proc { store := σAO, factory := ρ₀.factory } ∧
+ Procedure.outputAsPredicate proc { store := σAO, factory := ρ₀.factory } ∧
+ Core.Specification.AxiomsBeforeProcedureDecl procName p
+ { store := σAO, factory := ρ₀.factory }) ∧
+ ∀ σE : Core.CoreStore,
+ Procedure.contractPost factory proc { store := σE, factory := ρ₀.factory } →
+ Procedure.outputAsPredicate proc { store := σE, factory := ρ₀.factory } →
+ agreeExcept outF σE σAO →
+ forallRead ρ₀.factory σE outF fun outs =>
+ forallUpdates ρ₀.store lhs outs fun σ' => Q { ρ₀ with store := σ' }
+
+/-- The callee frame of a call to a procedure without `inout` parameters binds the input
+formals and the output-only formals. -/
+theorem binds_of_callEntry {f : Core.Expression.Factory} {σ σAO : Core.CoreStore}
+ {proc : Core.Procedure} {callArgs : List (Imperative.CallArg Core.Expression)}
+ (hinout : Imperative.Calls.inoutParams (P := Core.Expression) proc.header = [])
+ (h : Imperative.Calls.CallEntry f σ proc callArgs σAO) :
+ ∃ ivs ovs,
+ Imperative.EvalExpressions (P := Core.Expression) f σ (Core.CallArg.getInputExprs callArgs)
+ ivs ∧
+ Imperative.ReadValues (P := Core.Expression) f σ (Imperative.CallArg.getOutArgs callArgs)
+ ovs ∧
+ binds σAO (ListMap.keys proc.header.inputs) ivs ∧
+ binds σAO (Imperative.Calls.outputOnlyParams (P := Core.Expression) proc.header) ovs := by
+ obtain ⟨ivs, ovs, hev, hrd, σA, σIO, hA, hIO, rfl⟩ := h
+ have hsnap : Imperative.Calls.withOldSnapshots
+ (Imperative.Calls.inoutParams (P := Core.Expression) proc.header) σIO = σIO := by
+ rw [hinout]; rfl
+ rw [hsnap]
+ have h₁ := binds_of_initStates hA
+ have h₂ := binds_of_initStates hIO
+ exact ⟨ivs, ovs, hev, hrd, binds_mono h₂.2 h₁.1, h₂.1⟩
+
+theorem wpCall_of_args {factory : Lambda.Factory Core.CoreLParams} {p : Core.Program}
+ {procName : String} {proc : Core.Procedure}
+ {callArgs : List (Imperative.CallArg Core.Expression)} {Q : Pred}
+ (hfactory : p.factoryBeforeProcedure procName = factory)
+ (hinout : Imperative.Calls.inoutParams (P := Core.Expression) proc.header = [])
+ (hinout' : ListMap.keys proc.header.getInoutParams = [])
+ {ρ₀ : Imperative.Env Core.Expression}
+ (h : wpCallArgs factory p procName proc (Core.CallArg.getInputExprs callArgs)
+ (Imperative.CallArg.getOutArgs callArgs) (Imperative.CallArg.getLhs callArgs)
+ (ListMap.keys proc.header.inputs)
+ (Imperative.Calls.outputOnlyParams (P := Core.Expression) proc.header)
+ (ListMap.keys proc.header.outputs) Q ρ₀) :
+ wpCall p procName proc callArgs Q ρ₀ := by
+ subst hfactory
+ refine ⟨fun σAO hentry => ?_, fun ρ' σ' σAO hpost hout hfac hentry hframe hexit => ?_⟩
+ · obtain ⟨ivs, ovs, hev, hrd, hin, hoo⟩ := binds_of_callEntry hinout hentry
+ obtain ⟨⟨hpre, hf, hti, hto, hax⟩, -⟩ :=
+ forallRead_elim hrd (forallEval_elim hev h) σAO hin hoo
+ refine ⟨⟨hpre, hf, ?_, hti, hto⟩, hax⟩
+ intro id hid
+ rw [hinout'] at hid
+ cases hid
+ · obtain ⟨ivs, ovs, hev, hrd, hin, hoo⟩ := binds_of_callEntry hinout hentry
+ obtain ⟨-, hK⟩ := forallRead_elim hrd (forallEval_elim hev h) σAO hin hoo
+ obtain ⟨σE, fE⟩ := ρ'
+ obtain rfl : fE = ρ₀.factory := hfac
+ obtain ⟨-, outs, hro, hup, -⟩ := hexit
+ have hagree : agreeExcept (ListMap.keys proc.header.outputs) σE σAO := fun x hx =>
+ (hframe [x] (fun a ha hk => hx (by simpa using (List.mem_singleton.mp ha) ▸ hk)) x x
+ (by simp)).symm
+ exact forallUpdates_elim hup (forallRead_elim hro (hK σE hpost hout hagree))
+
+/-- A call of a procedure without a body and without `inout` parameters, in the form a lifting
+reads: over the factory visible at the caller, with the arguments and formals as lists. -/
+theorem call_wp_args (p : Core.Program) (params : InitEnvWFParams) (caller procName : String)
+ {tyArgs : Option (List Core.Expression.Ty)}
+ (callArgs : List (Imperative.CallArg Core.Expression))
+ (md : Imperative.MetaData Core.Expression) (proc : Core.Procedure) (Q : Pred)
+ (ins : List Core.Expression.Expr)
+ (outArgs lhs inF outOnlyF outF : List Core.Expression.Ident)
+ (hproc : p.findProcByString? procName = some proc)
+ (hbody : proc.body = .abstract)
+ (hchecksTyped : Procedure.contractChecksTyped proc)
+ (hmono : proc.header.typeArgs = [])
+ (hinout : Imperative.Calls.inoutParams (P := Core.Expression) proc.header = [])
+ (hinout' : ListMap.keys proc.header.getInoutParams = [])
+ (hfactory : p.factoryBeforeProcedure procName = p.factoryBeforeProcedure caller)
+ (hins : Core.CallArg.getInputExprs callArgs = ins)
+ (houtArgs : Imperative.CallArg.getOutArgs callArgs = outArgs)
+ (hlhs : Imperative.CallArg.getLhs callArgs = lhs)
+ (hinF : ListMap.keys proc.header.inputs = inF)
+ (hoo : Imperative.Calls.outputOnlyParams (P := Core.Expression) proc.header = outOnlyF)
+ (houtF : ListMap.keys proc.header.outputs = outF) :
+ Triple p.findProcByString? params
+ (wpCallArgs (p.factoryBeforeProcedure caller) p procName proc ins outArgs lhs inF
+ outOnlyF outF Q)
+ [Core.Statement.call procName tyArgs callArgs md] Q
+ (factory := p.factoryBeforeProcedure caller) := by
+ subst hins houtArgs hlhs hinF hoo houtF
+ exact Core.Logic.Hoare.consequence _ params
+ (call_wp_abstract p params caller procName callArgs md proc Q hproc hbody hchecksTyped hmono
+ hfactory)
+ (fun _ h => wpCall_of_args hfactory hinout hinout' h) (fun _ h => h)
+
+/-! ## Reading a call's condition -/
+
+/-- `preAsPredicate` clause by clause, over the list of `requires`. -/
+theorem preAsPredicate_intro {factory : Lambda.Factory Core.CoreLParams} {proc : Core.Procedure}
+ {ρ : Imperative.Env Core.Expression}
+ (h : ∀ lc ∈ proc.spec.preconditions.toList, ClauseHolds factory (clauseArg ρ lc.1 lc.2)) :
+ Procedure.preAsPredicate factory proc ρ :=
+ fun label check hmem => h (label, check) hmem
+
+/-- An `ensures` clause of the callee evaluates to `true` at the callee's exit. -/
+theorem ensures_eval {factory : Lambda.Factory Core.CoreLParams} {proc : Core.Procedure}
+ {ρ : Imperative.Env Core.Expression}
+ (hpost : Procedure.contractPost factory proc ρ) (hfac : ρ.factory.factory = factory)
+ {label : Core.CoreLabel} {check : Core.Procedure.Check}
+ (hmem : (label, check) ∈ proc.spec.postconditions.toList)
+ (hattr : check.attr = Core.Procedure.CheckAttr.Default) :
+ Core.Expression.eval ρ.factory ρ.store check.expr =
+ some (Imperative.HasBool.ttVal ρ.factory) :=
+ clause_eval (c := clauseArg ρ label check) (hpost label check hmem hattr) hfac
+
+/-- The value an output of the callee holds at its exit is a value of the output's type, as the
+value of a declaration is. -/
+theorem callee_output_valueOfTy {proc : Core.Procedure} {f : Core.Expression.Factory}
+ {σE : Core.CoreStore} (hout : Procedure.outputAsPredicate proc { store := σE, factory := f })
+ {id : Core.Expression.Ident} {ty : Lambda.LMonoTy}
+ (hmem : (id, ty) ∈ proc.header.outputs.toList) {o : Core.Expression.Val}
+ (ho : σE id = some o) (hval : Imperative.HasVal.value (P := Core.Expression) f o) :
+ Imperative.HasVal.valueOfTy (P := Core.Expression) f o (Lambda.LTy.forAll [] ty) := by
+ obtain ⟨v, hv, hty⟩ := hout id ty hmem
+ obtain rfl : v = o := Option.some.inj (hv.symm.trans ho)
+ exact ⟨hval, by rw [← hty]; rfl⟩
+
+/-- The formals of the callee are typed at its frame, one binding at a time. -/
+theorem inputAsPredicate_intro {proc : Core.Procedure} {ρ : Imperative.Env Core.Expression}
+ (h : ∀ id ty, (id, ty) ∈ proc.header.inputs.toList →
+ ∃ v, ρ.store id = some v ∧ Procedure.valueHasType ty v) :
+ Procedure.inputAsPredicate proc ρ := h
+
+theorem outputAsPredicate_intro {proc : Core.Procedure} {ρ : Imperative.Env Core.Expression}
+ (h : ∀ id ty, (id, ty) ∈ proc.header.outputs.toList →
+ ∃ v, ρ.store id = some v ∧ Procedure.valueHasType ty v) :
+ Procedure.outputAsPredicate proc ρ := h
+
+/-- A slot that holds an integer of the factory holds a value of type `int`. -/
+theorem slot_typed_int {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {a : Int} (h : σ x = some (Eval.intVal f a)) :
+ ∃ v, σ x = some v ∧ Procedure.valueHasType (.tcons "int" []) v :=
+ ⟨_, h, rfl⟩
+
+theorem slot_typed_bool {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {p : Bool} (h : σ x = some (Eval.boolVal f p)) :
+ ∃ v, σ x = some v ∧ Procedure.valueHasType (.tcons "bool" []) v :=
+ ⟨_, h, rfl⟩
+
+theorem slot_typed_sort {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {T : Lambda.LMonoTy}
+ {a : Lambda.TyDenote f.model.tcInterp f.tyVarVal T} (h : σ x = some (Eval.sortVal f T a))
+ (hT : (T.substTyVars f.tyVarVal).toMonoTy = T) :
+ ∃ v, σ x = some v ∧ Procedure.valueHasType T v :=
+ ⟨_, h, hT⟩
+
+end Strata.Hoare
+
+end -- public section
diff --git a/StrataBoole/HoareLogic/Hoare/Contract.lean b/StrataBoole/HoareLogic/Hoare/Contract.lean
new file mode 100644
index 0000000..dd01092
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Contract.lean
@@ -0,0 +1,356 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+module
+
+public import StrataBoole.HoareLogic.Hoare.WP
+public import StrataBoole.HoareLogic.Hoare.Lift.Eval
+public import StrataBoole.HoareLogic.Hoare.Lift.Denote
+public import Strata.Languages.Core.Logic.ContractToHoareTripleProps
+public import Strata.Languages.Core.ProgramProps
+
+/-! # From a procedure's contract to the rules and back
+
+`Procedure.contractTriple` is the statement a user proves. Its entry,
+`Procedure.contractTriple_of_core_typed`, asks for one triple from `contractPre` to `contractPost`
+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 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
+over the ambient one: a condition holds exactly when it evaluates to `true`. `clause_intro` and
+`clause_eval` are that reading for any captured condition: a contract clause, an `assert`, a
+loop invariant.
+
+`loopInv` is the invariant `while_wp_frame` is given: besides the program's `invariant` clauses
+it carries what the rules after the loop rely on and the loop rule would otherwise forget, the
+runtime factory and the typed bindings of the variables the loop writes. -/
+
+public section
+
+namespace Strata.Hoare
+
+open Core.Logic Core.Logic.Hoare
+
+variable {factory : Lambda.Factory Core.CoreLParams}
+
+/-! ## Entry -/
+
+/-- 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, 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`). -/
+theorem contract_intro (p : Core.Program) (params : InitEnvWFParams) (procName : String)
+ (proc : Core.Procedure) (bss : Core.Statements) {opq : Bool}
+ (hproc : p.findProcByString? procName = some proc)
+ (hbody : proc.body = .structured bss opq)
+ (hchecksTyped : Procedure.contractChecksTyped proc)
+ (h : ∀ F : Core.Expression.Factory, Triple p.findProcByString? params
+ (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_axioms p params procName proc bss hproc hbody
+ hchecksTyped ?_ hmono
+ 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.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 -/
+
+/-- Under a runtime factory over `factory`, a condition holds in a world exactly when it
+evaluates to `true`. -/
+theorem holds_iff (world : DenoteValuation factory) (c : Imperative.EventArg Core.Expression)
+ (hfac : c.factory.factory = factory) :
+ (DenoteBasedInterp factory).holds world c ↔
+ Core.Expression.eval c.factory c.store c.expr =
+ some (Imperative.HasBool.ttVal c.factory) := by
+ simp only [DenoteBasedInterp, hfac, true_and, ne_eq, not_true_eq_false, false_and, or_false]
+
+/-- A captured condition holds in every world once it evaluates to `true`. -/
+theorem clause_intro {c : Imperative.EventArg Core.Expression}
+ (hfac : c.factory.factory = factory)
+ (h : Core.Expression.eval c.factory c.store c.expr =
+ some (Imperative.HasBool.ttVal c.factory)) :
+ ClauseHolds factory c :=
+ fun world => (holds_iff world c hfac).mpr h
+
+/-- A captured condition that holds evaluates to `true`. -/
+theorem clause_eval {c : Imperative.EventArg Core.Expression}
+ (h : ClauseHolds factory c) (hfac : c.factory.factory = factory) :
+ Core.Expression.eval c.factory c.store c.expr =
+ some (Imperative.HasBool.ttVal c.factory) :=
+ (holds_iff ⟨fun _ => False⟩ c hfac).mp (h _)
+
+/-- The event argument a contract clause is checked as. -/
+abbrev clauseArg (ρ : Imperative.Env Core.Expression) (label : Core.CoreLabel)
+ (check : Core.Procedure.Check) : Imperative.EventArg Core.Expression :=
+ { factory := ρ.factory, store := ρ.store, label := label, expr := check.expr, metadata := check.md }
+
+/-! ## Typed bindings -/
+
+/-- The variables of `Γ` are bound to values of the runtime factory, of their types. -/
+@[expose] def typedVars (Γ : List (Core.Expression.Ident × Lambda.LMonoTy)) : Pred :=
+ fun ρ => ∀ id ty, (id, ty) ∈ Γ →
+ ∃ v, ρ.store id = some v ∧ v.tc = ρ.factory.model.tcInterp ∧ Procedure.valueHasType ty v
+
+/-- A typed integer binding, with the integer in place of the bound value. -/
+theorem typed_int_of {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident}
+ (h : ∃ v, σ x = some v ∧ v.tc = f.model.tcInterp ∧
+ Procedure.valueHasType (.tcons "int" []) v) :
+ ∃ a : Int, σ x = some (Eval.intVal f a) := by
+ obtain ⟨v, hv, htc, hty⟩ := h
+ obtain ⟨a, rfl⟩ := Eval.value_int htc hty
+ exact ⟨a, hv⟩
+
+/-- A typed Boolean binding, with the Boolean in place of the bound value. -/
+theorem typed_bool_of {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident}
+ (h : ∃ v, σ x = some v ∧ v.tc = f.model.tcInterp ∧
+ Procedure.valueHasType (.tcons "bool" []) v) :
+ ∃ p : Bool, σ x = some (Eval.boolVal f p) := by
+ obtain ⟨v, hv, htc, hty⟩ := h
+ obtain ⟨p, rfl⟩ := Eval.value_bool htc hty
+ exact ⟨p, hv⟩
+
+/-- A typed binding at any type, with the value of that type in place of the bound value. -/
+theorem typed_sort_of {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {T : Lambda.LMonoTy}
+ (h : ∃ v, σ x = some v ∧ v.tc = f.model.tcInterp ∧ Procedure.valueHasType T v) :
+ ∃ a : Lambda.TyDenote f.model.tcInterp f.tyVarVal T, σ x = some (Eval.sortVal f T a) := by
+ obtain ⟨v, hv, htc, hty⟩ := h
+ obtain ⟨a, rfl⟩ := Eval.value_sort htc hty
+ exact ⟨a, hv⟩
+
+/-- The converse of `typed_sort_of`, for a type that names its own sort. -/
+theorem typed_of_sort {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {T : Lambda.LMonoTy}
+ {a : Lambda.TyDenote f.model.tcInterp f.tyVarVal T} (h : σ x = some (Eval.sortVal f T a))
+ (hT : (T.substTyVars f.tyVarVal).toMonoTy = T) :
+ ∃ v, σ x = some v ∧ v.tc = f.model.tcInterp ∧ Procedure.valueHasType T v :=
+ ⟨_, h, rfl, hT⟩
+
+/-- The converse of `typed_int_of`: an integer of the factory is a typed binding. -/
+theorem typed_of_int {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {a : Int} (h : σ x = some (Eval.intVal f a)) :
+ ∃ v, σ x = some v ∧ v.tc = f.model.tcInterp ∧
+ Procedure.valueHasType (.tcons "int" []) v :=
+ ⟨_, h, rfl, rfl⟩
+
+theorem typed_of_bool {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {p : Bool} (h : σ x = some (Eval.boolVal f p)) :
+ ∃ v, σ x = some v ∧ v.tc = f.model.tcInterp ∧
+ Procedure.valueHasType (.tcons "bool" []) v :=
+ ⟨_, h, rfl, rfl⟩
+
+/-- A value of a declared type `int` is an integer of the factory: what a `var x : int`
+without an initializer binds. -/
+theorem valueOfTy_int {f : Core.Expression.Factory} {v : Core.Expression.Val}
+ {ty : Core.Expression.Ty} (hty : ty.toMonoType? = some (.tcons "int" []))
+ (h : Imperative.HasVal.valueOfTy (P := Core.Expression) f v ty) :
+ ∃ a : Int, v = Eval.intVal f a := by
+ obtain ⟨htc, hs⟩ := h
+ rw [hty] at hs
+ exact Eval.value_int htc (Option.some.inj hs).symm
+
+theorem valueOfTy_bool {f : Core.Expression.Factory} {v : Core.Expression.Val}
+ {ty : Core.Expression.Ty} (hty : ty.toMonoType? = some (.tcons "bool" []))
+ (h : Imperative.HasVal.valueOfTy (P := Core.Expression) f v ty) :
+ ∃ p : Bool, v = Eval.boolVal f p := by
+ obtain ⟨htc, hs⟩ := h
+ rw [hty] at hs
+ exact Eval.value_bool htc (Option.some.inj hs).symm
+
+/-- A value of a declared type is a value of that type in the model: what a `var` of a type
+other than `int` and `bool` binds without an initializer. -/
+theorem valueOfTy_sort {f : Core.Expression.Factory} {v : Core.Expression.Val}
+ {ty : Core.Expression.Ty} {T : Lambda.LMonoTy} (hty : ty.toMonoType? = some T)
+ (h : Imperative.HasVal.valueOfTy (P := Core.Expression) f v ty) :
+ ∃ a : Lambda.TyDenote f.model.tcInterp f.tyVarVal T, v = Eval.sortVal f T a := by
+ obtain ⟨htc, hs⟩ := h
+ rw [hty] at hs
+ exact Eval.value_sort htc (Option.some.inj hs).symm
+
+/-- A value of the type of a stored value of the type `T` is a value of `T`: what `havoc`
+assigns to a variable of a type other than `int` and `bool`. -/
+theorem valueOfStoredTy_sort {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {v : Core.Expression.Val} {T : Lambda.LMonoTy}
+ {a : Lambda.TyDenote f.model.tcInterp f.tyVarVal T} (hx : σ x = some (Eval.sortVal f T a))
+ (h : Imperative.HasVal.valueOfStoredTy (P := Core.Expression) f σ x v) :
+ ∃ b : Lambda.TyDenote f.model.tcInterp f.tyVarVal T, v = Eval.sortVal f T b := by
+ obtain ⟨prev, ty, hprev, ⟨-, hp⟩, htc, hs⟩ := h
+ rw [hx] at hprev
+ obtain rfl := Option.some.inj hprev
+ have hsort : v.sort.toMonoTy = (T.substTyVars f.tyVarVal).toMonoTy :=
+ Option.some.inj (hs.symm.trans hp)
+ have hv : v.sort = T.substTyVars f.tyVarVal := Lambda.LSort.toMonoTy_injective hsort
+ obtain ⟨tc, s, val⟩ := v
+ obtain rfl : tc = f.model.tcInterp := htc
+ obtain rfl : s = T.substTyVars f.tyVarVal := hv
+ exact ⟨val, rfl⟩
+
+/-- A value of the type of a stored integer is an integer of the factory: what `havoc` assigns
+to an integer variable. -/
+theorem valueOfStoredTy_int {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {v : Core.Expression.Val} {a : Int}
+ (hx : σ x = some (Eval.intVal f a))
+ (h : Imperative.HasVal.valueOfStoredTy (P := Core.Expression) f σ x v) :
+ ∃ b : Int, v = Eval.intVal f b := by
+ obtain ⟨prev, ty, hprev, ⟨-, hp⟩, htc, hs⟩ := h
+ rw [hx] at hprev
+ obtain rfl := Option.some.inj hprev
+ exact Eval.value_int htc (Option.some.inj (hs.symm.trans hp))
+
+theorem valueOfStoredTy_bool {f : Core.Expression.Factory} {σ : Core.CoreStore}
+ {x : Core.Expression.Ident} {v : Core.Expression.Val} {p : Bool}
+ (hx : σ x = some (Eval.boolVal f p))
+ (h : Imperative.HasVal.valueOfStoredTy (P := Core.Expression) f σ x v) :
+ ∃ q : Bool, v = Eval.boolVal f q := by
+ obtain ⟨prev, ty, hprev, ⟨-, hp⟩, htc, hs⟩ := h
+ rw [hx] at hprev
+ obtain rfl := Option.some.inj hprev
+ exact Eval.value_bool htc (Option.some.inj (hs.symm.trans hp))
+
+/-- Quantification over the members of a signature, one binding at a time. -/
+theorem forall_mem_cons_pair {α β : Type _} {P : α → β → Prop} {x : α} {τ : β}
+ {rest : List (α × β)} :
+ (∀ id ty, (id, ty) ∈ (x, τ) :: rest → P id ty) ↔
+ P x τ ∧ ∀ id ty, (id, ty) ∈ rest → P id ty := by
+ constructor
+ · intro h
+ exact ⟨h x τ (List.mem_cons_self ..), fun id ty hm => h id ty (List.mem_cons_of_mem _ hm)⟩
+ · rintro ⟨hx, hrest⟩ id ty hm
+ rcases List.mem_cons.mp hm with heq | hm
+ · cases heq
+ exact hx
+ · exact hrest id ty hm
+
+theorem forall_mem_nil_pair {α β : Type _} {P : α → β → Prop} :
+ (∀ id ty, (id, ty) ∈ ([] : List (α × β)) → P id ty) ↔ True := by
+ simp
+
+/-- Quantification over the members of a list, one element at a time. -/
+theorem forall_mem_cons_elem {α : Type _} {P : α → Prop} {x : α} {rest : List α} :
+ (∀ a ∈ x :: rest, P a) ↔ P x ∧ ∀ a ∈ rest, P a := by
+ constructor
+ · intro h
+ exact ⟨h x (List.mem_cons_self ..), fun a hm => h a (List.mem_cons_of_mem _ hm)⟩
+ · rintro ⟨hx, hrest⟩ a hm
+ rcases List.mem_cons.mp hm with rfl | hm
+ · exact hx
+ · exact hrest a hm
+
+theorem forall_mem_nil_elem {α : Type _} {P : α → Prop} :
+ (∀ a ∈ ([] : List α), P a) ↔ True := by
+ simp
+
+/-! ## The precondition -/
+
+/-- The inputs of a procedure are typed bindings of a well-formed entry store. -/
+theorem inputs_typed {proc : Core.Procedure} {ρ : Imperative.Env Core.Expression}
+ (hwf : Imperative.WellFormedStore ρ.store ρ.factory)
+ (hin : Procedure.inputAsPredicate proc ρ) : typedVars proc.header.inputs.toList ρ := by
+ intro id ty hmem
+ 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)
+ {label : Core.CoreLabel} {check : Core.Procedure.Check}
+ (hmem : (label, check) ∈ proc.spec.preconditions.toList) :
+ Core.Expression.eval ρ.factory ρ.store check.expr =
+ some (Imperative.HasBool.ttVal ρ.factory) :=
+ clause_eval (c := clauseArg ρ label check) (hpre label check hmem) hfac
+
+/-! ## Reading a store through a frame
+
+A loop obligation knows the store it runs on agrees with the entry store outside the body's
+write set `M`. A statement of the body preserves that agreement, and a variable outside `M`
+is read at the entry store. -/
+
+theorem agreeExcept_update {M : List Core.Expression.Ident} {σ σ' : Core.CoreStore}
+ {y : Core.Expression.Ident} {v : Core.Expression.Val}
+ (hup : Imperative.UpdateState Core.Expression σ y v σ') (hy : y ∈ M) :
+ agreeExcept M σ' σ :=
+ fun _ hx => Eval.UpdateState.at_other hup (fun h => hx (h ▸ hy))
+
+theorem agreeExcept_init {M : List Core.Expression.Ident} {σ σ' : Core.CoreStore}
+ {y : Core.Expression.Ident} {v : Core.Expression.Val}
+ (hini : Imperative.InitState Core.Expression σ y v σ') (hy : y ∈ M) :
+ agreeExcept M σ' σ :=
+ fun _ hx => Eval.InitState.at_other hini (fun h => hx (h ▸ hy))
+
+theorem agreeExcept_read {M : List Core.Expression.Ident} {σ σ₀ : Core.CoreStore}
+ {x : Core.Expression.Ident} (h : agreeExcept M σ σ₀) (hx : x ∉ M) : σ x = σ₀ x :=
+ h x hx
+
+/-! ## Loop invariants -/
+
+/-- The invariant of a loop: the runtime factory is `F`, the variables of `Γ` are typed, and
+each `invariant` clause holds in every world. -/
+@[expose] def loopInv (F : Core.Expression.Factory)
+ (Γ : List (Core.Expression.Ident × Lambda.LMonoTy))
+ (inv : List (String × Core.Expression.Expr)) : Pred :=
+ fun ρ => ρ.factory = F ∧ typedVars Γ ρ ∧
+ ∀ lc ∈ inv, ClauseHolds F.factory (condArg ρ lc.1 lc.2 #[])
+
+theorem loopInv_intro {F : Core.Expression.Factory}
+ {Γ : List (Core.Expression.Ident × Lambda.LMonoTy)}
+ {inv : List (String × Core.Expression.Expr)} {ρ : Imperative.Env Core.Expression}
+ (hF : ρ.factory = F) (hΓ : typedVars Γ ρ)
+ (hinv : ∀ lc ∈ inv, ClauseHolds F.factory (condArg ρ lc.1 lc.2 #[])) :
+ loopInv F Γ inv ρ :=
+ ⟨hF, hΓ, hinv⟩
+
+/-! ## The postcondition -/
+
+/-- `contractPost` clause by clause, over the list of `ensures`. -/
+theorem contractPost_intro {proc : Core.Procedure} {ρ : Imperative.Env Core.Expression}
+ (h : ∀ lc ∈ proc.spec.postconditions.toList,
+ lc.2.attr = Core.Procedure.CheckAttr.Default →
+ ClauseHolds factory (clauseArg ρ lc.1 lc.2)) :
+ Procedure.contractPost factory proc ρ := by
+ intro label check hmem hattr
+ exact h (label, check) hmem hattr
+
+end Strata.Hoare
+
+end -- public section
diff --git a/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean b/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean
new file mode 100644
index 0000000..e128b48
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean
@@ -0,0 +1,1083 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+module
+
+public import Strata.DL.Lambda.Denote.LExprDenote
+public import Strata.DL.Lambda.LExprDenoteEvalProps
+public import StrataBoole.HoareLogic.Hoare.Lift.Eval
+public import Strata.DL.Lambda.Denote.LExprDenoteSubst
+public import Strata.Languages.Core.SeqEvalProps
+import all Strata.DL.Lambda.Denote.LExprDenote
+import all Strata.DL.Lambda.LExprDenoteEval
+import all Strata.DL.Lambda.LExprWF
+import Strata.DL.Lambda.LExprWFProps
+
+/-! # Denoting Core conditions under binders
+
+A condition with a quantifier cannot be read by the evaluation lemmas of `Eval.lean`: its body
+mentions a bound variable, which no store binds. Evaluation is denotation in the model of the
+runtime factory, so such a condition is read at the level of `Lambda.LExpr.denote` instead.
+`eval_tt_eq_denote` crosses from "the condition evaluates to `true`" to "its denotation is
+`true`", and the lemmas here read the denotation node by node: an operator is its
+interpretation in the model, which is the Lean operation whenever the runtime factory is over
+`Core.Factory`; a free variable is the value the store binds it to; a quantifier over `int` is
+the Lean quantifier over `Int`, with the body read at the valuation extended by the bound value.
+
+`TyDenote tc vt (tcons "bool" [])` is `Bool` by computation, not by a reducible unfolding, so an
+equation between a denotation and a `Bool` does not type check at the transparency `simp` works
+at. `toBool` and `toInt` make the conversion a term.
+
+As in `Eval.lean`, every lemma is stated for any source location on every node and with the
+types spelled as the lowering writes them. Each takes the typing witnesses of the sub-expressions
+as hypotheses; a caller supplies them by type checking (`Lambda.LExpr.typeCheck_to_HasTypeA`). -/
+
+public section
+
+namespace Strata.Hoare.Denote
+
+open _root_.Core _root_.Lambda
+
+local notation "tInt" => LMonoTy.tcons "int" []
+local notation "tBool" => LMonoTy.tcons "bool" []
+local notation "tArrow" a:max b:max => LMonoTy.tcons "arrow" [a, b]
+
+/-- A denotation at `bool`, as a `Bool`. -/
+@[expose] def toBool {tc : TyConstrInterp} {vt : TyVarVal} (x : TyDenote tc vt tBool) : Bool := x
+
+/-- A denotation at `int`, as an `Int`. -/
+@[expose] def toInt {tc : TyConstrInterp} {vt : TyVarVal} (x : TyDenote tc vt tInt) : Int := x
+
+/-- An `Int` as a value of the sort `int`, the form a bound integer takes in a valuation. -/
+@[expose] def ofInt {tc : TyConstrInterp} {vt : TyVarVal} (v : Int) : TyDenote tc vt tInt := v
+
+/-! ## Nodes, in any model
+
+Stated with Strata's abbreviations for the types (`LMonoTy.int`, `LMonoTy.arrow`), which is how
+its unfolding lemmas of `denote` rewrite. -/
+
+section Nodes
+
+variable {tc : TyConstrInterp} {op : OpInterp tc} (fv : FreeVarVal CoreLParams tc) (vt : TyVarVal)
+variable {Δ : List LMonoTy} (bv : BVarVal tc vt Δ)
+variable {m m' m'' : ExpressionMetadata}
+
+/-- A binary operator: its interpretation at the denotations of the operands. -/
+private theorem denote_app2 {name : String} {a b c : LMonoTy} {e₁ e₂ : Expression.Expr}
+ (h₁ : LExpr.HasTypeA Δ e₁ a) (h₂ : LExpr.HasTypeA Δ e₂ b)
+ (h : LExpr.HasTypeA Δ
+ (.app m (.app m' (.op m'' ⟨name, ()⟩ (some (.arrow a (.arrow b c)))) e₁) e₂) c) :
+ LExpr.denote tc op fv vt bv
+ (.app m (.app m' (.op m'' ⟨name, ()⟩ (some (.arrow a (.arrow b c)))) e₁) e₂) c h
+ = (op name ((LMonoTy.arrow a (.arrow b c)).substTyVars vt)
+ : SortDenote tc (a.substTyVars vt) → SortDenote tc (b.substTyVars vt) →
+ SortDenote tc (c.substTyVars vt))
+ (LExpr.denote tc op fv vt bv e₁ a h₁) (LExpr.denote tc op fv vt bv e₂ b h₂) := by
+ have hop' : LExpr.HasTypeA (T := CoreLParams) Δ
+ (.op m'' ⟨name, ()⟩ (some (.arrow a (.arrow b c)))) (.arrow a (.arrow b c)) := .op
+ have happ1 : LExpr.HasTypeA (T := CoreLParams) Δ
+ (.app m' (.op m'' ⟨name, ()⟩ (some (.arrow a (.arrow b c)))) e₁) (.arrow b c) :=
+ .app hop' h₁
+ rw [Lambda.denote_app bv happ1 h₂ h, Lambda.denote_app bv hop' h₁ happ1, Lambda.denote_op]
+
+/-- A unary operator: its interpretation at the denotation of the operand. -/
+private theorem denote_app1 {name : String} {a c : LMonoTy} {e : Expression.Expr}
+ (h₁ : LExpr.HasTypeA Δ e a)
+ (h : LExpr.HasTypeA Δ (.app m (.op m' ⟨name, ()⟩ (some (.arrow a c))) e) c) :
+ LExpr.denote tc op fv vt bv (.app m (.op m' ⟨name, ()⟩ (some (.arrow a c))) e) c h
+ = (op name ((LMonoTy.arrow a c).substTyVars vt)
+ : SortDenote tc (a.substTyVars vt) → SortDenote tc (c.substTyVars vt))
+ (LExpr.denote tc op fv vt bv e a h₁) := by
+ have hop' : LExpr.HasTypeA (T := CoreLParams) Δ
+ (.op m' ⟨name, ()⟩ (some (.arrow a c))) (.arrow a c) := .op
+ rw [Lambda.denote_app bv hop' h₁ h, Lambda.denote_op]
+
+/-- An equality holds exactly when its operands denote the same value. -/
+private theorem denote_eq_iff {τ : LMonoTy} {e₁ e₂ : Expression.Expr}
+ (h₁ : LExpr.HasTypeA Δ e₁ τ) (h₂ : LExpr.HasTypeA Δ e₂ τ)
+ (h : LExpr.HasTypeA Δ (.eq m e₁ e₂) .bool) :
+ ((LExpr.denote tc op fv vt bv (.eq m e₁ e₂) .bool h : Bool) = true)
+ ↔ LExpr.denote tc op fv vt bv e₁ τ h₁ = LExpr.denote tc op fv vt bv e₂ τ h₂ := by
+ constructor
+ · intro htrue
+ exact Classical.byContradiction fun hne => by
+ rw [Lambda.denote_eq_false bv h₁ h₂ h hne] at htrue
+ exact Bool.false_ne_true htrue
+ · intro heq
+ exact Lambda.denote_eq_true bv h₁ h₂ h heq
+
+/-- An `Int` as a value of the sort `int`, at Strata's spelling of the type. -/
+private def ofIntA {tc : TyConstrInterp} {vt : TyVarVal} (v : Int) : TyDenote tc vt .int := v
+
+private theorem denote_forall_int_iff {name : String} {tr body : Expression.Expr}
+ (hb : LExpr.HasTypeA (T := CoreLParams) (.int :: Δ) body .bool)
+ (h : LExpr.HasTypeA Δ (.quant m .all name (some .int) tr body) .bool) :
+ ((LExpr.denote tc op fv vt bv (.quant m .all name (some .int) tr body) .bool h : Bool) = true)
+ ↔ ∀ v : Int,
+ (LExpr.denote tc op fv vt (.cons (ofIntA v) bv) body .bool hb : Bool) = true := by
+ constructor
+ · intro hall v
+ refine Classical.byContradiction fun hv => ?_
+ have hf := Lambda.denote_quant_all_false bv hb h (ofIntA v) (Bool.eq_false_iff.mpr hv)
+ rw [hf] at hall
+ exact Bool.false_ne_true hall
+ · intro hall
+ exact Lambda.denote_quant_all_true bv hb h (fun x => hall x)
+
+private theorem denote_exists_int_iff {name : String} {tr body : Expression.Expr}
+ (hb : LExpr.HasTypeA (T := CoreLParams) (.int :: Δ) body .bool)
+ (h : LExpr.HasTypeA Δ (.quant m .exist name (some .int) tr body) .bool) :
+ ((LExpr.denote tc op fv vt bv (.quant m .exist name (some .int) tr body) .bool h : Bool) = true)
+ ↔ ∃ v : Int,
+ (LExpr.denote tc op fv vt (.cons (ofIntA v) bv) body .bool hb : Bool) = true := by
+ constructor
+ · intro hex
+ refine Classical.byContradiction fun hnone => ?_
+ have hall : ∀ x : TyDenote tc vt .int,
+ (LExpr.denote tc op fv vt (.cons x bv) body .bool hb : Bool) = false :=
+ fun x => Bool.eq_false_iff.mpr (fun hx => hnone ⟨x, hx⟩)
+ rw [Lambda.denote_quant_exist_false bv hb h hall] at hex
+ exact Bool.false_ne_true hex
+ · rintro ⟨v, hv⟩
+ exact Lambda.denote_quant_exist_true bv hb h (ofIntA v) hv
+
+private theorem denote_fvar_int_abbr [TyConstrInterp.AllInhabited tc] {σ : CoreStore}
+ {x : CoreIdent} {n : Int} (hx : σ x = some (SemValue.ofInt tc n))
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some .int)) .int) :
+ (LExpr.denote tc op (ValStore.fvarVal (T := CoreLParams) tc σ) vt bv
+ (.fvar m x (some .int)) .int h : Int) = n := by
+ rw [Lambda.denote_fvar]
+ show (ValStore.fvarVal (T := CoreLParams) tc σ x (LMonoTy.int.substTyVars vt) : Int) = n
+ simp only [ValStore.fvarVal, hx, Option.bind_some]
+ have hr : (SemValue.ofInt tc n).read tc (LMonoTy.int.substTyVars vt) = some n :=
+ SemValue.read_self (SemValue.ofInt tc n)
+ rw [hr]
+ rfl
+
+private theorem denote_fvar_bool_abbr [TyConstrInterp.AllInhabited tc] {σ : CoreStore}
+ {x : CoreIdent} {p : Bool} (hx : σ x = some (SemValue.ofBool tc p))
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some .bool)) .bool) :
+ (LExpr.denote tc op (ValStore.fvarVal (T := CoreLParams) tc σ) vt bv
+ (.fvar m x (some .bool)) .bool h : Bool) = p := by
+ rw [Lambda.denote_fvar]
+ show (ValStore.fvarVal (T := CoreLParams) tc σ x (LMonoTy.bool.substTyVars vt) : Bool) = p
+ simp only [ValStore.fvarVal, hx, Option.bind_some]
+ have hr : (SemValue.ofBool tc p).read tc (LMonoTy.bool.substTyVars vt) = some p :=
+ SemValue.read_self (SemValue.ofBool tc p)
+ rw [hr]
+ rfl
+
+private theorem denote_forall_iff {name : String} {tr body : Expression.Expr} {qty : LMonoTy}
+ (hb : LExpr.HasTypeA (T := CoreLParams) (qty :: Δ) body .bool)
+ (h : LExpr.HasTypeA Δ (.quant m .all name (some qty) tr body) .bool) :
+ ((LExpr.denote tc op fv vt bv (.quant m .all name (some qty) tr body) .bool h : Bool) = true)
+ ↔ ∀ v : TyDenote tc vt qty,
+ (LExpr.denote tc op fv vt (.cons v bv) body .bool hb : Bool) = true := by
+ constructor
+ · intro hall v
+ refine Classical.byContradiction fun hv => ?_
+ have hf := Lambda.denote_quant_all_false bv hb h v (Bool.eq_false_iff.mpr hv)
+ rw [hf] at hall
+ exact Bool.false_ne_true hall
+ · intro hall
+ exact Lambda.denote_quant_all_true bv hb h (fun x => hall x)
+
+private theorem denote_exists_iff {name : String} {tr body : Expression.Expr} {qty : LMonoTy}
+ (hb : LExpr.HasTypeA (T := CoreLParams) (qty :: Δ) body .bool)
+ (h : LExpr.HasTypeA Δ (.quant m .exist name (some qty) tr body) .bool) :
+ ((LExpr.denote tc op fv vt bv (.quant m .exist name (some qty) tr body) .bool h : Bool) = true)
+ ↔ ∃ v : TyDenote tc vt qty,
+ (LExpr.denote tc op fv vt (.cons v bv) body .bool hb : Bool) = true := by
+ constructor
+ · intro hex
+ refine Classical.byContradiction fun hnone => ?_
+ have hall : ∀ x : TyDenote tc vt qty,
+ (LExpr.denote tc op fv vt (.cons x bv) body .bool hb : Bool) = false :=
+ fun x => Bool.eq_false_iff.mpr (fun hx => hnone ⟨x, hx⟩)
+ rw [Lambda.denote_quant_exist_false bv hb h hall] at hex
+ exact Bool.false_ne_true hex
+ · rintro ⟨v, hv⟩
+ exact Lambda.denote_quant_exist_true bv hb h v hv
+
+private theorem denote_fvar_sort [TyConstrInterp.AllInhabited tc] {σ : CoreStore}
+ {x : CoreIdent} {T : LMonoTy} {a : TyDenote tc vt T}
+ (hx : σ x = some ⟨tc, T.substTyVars vt, a⟩)
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some T)) T) :
+ LExpr.denote tc op (ValStore.fvarVal (T := CoreLParams) tc σ) vt bv
+ (.fvar m x (some T)) T h = a := by
+ rw [Lambda.denote_fvar]
+ show ValStore.fvarVal (T := CoreLParams) tc σ x (T.substTyVars vt) = a
+ simp only [ValStore.fvarVal, hx, Option.bind_some]
+ have hr : (⟨tc, T.substTyVars vt, a⟩ : SemValue).read tc (T.substTyVars vt) = some a :=
+ SemValue.read_self _
+ rw [hr]
+ rfl
+
+end Nodes
+
+/-! ## Leaves, equality, conditionals and binders -/
+
+section Leaves
+
+variable {tc : TyConstrInterp} {op : OpInterp tc} {fv : FreeVarVal CoreLParams tc} {vt : TyVarVal}
+variable {Δ : List LMonoTy} {bv : BVarVal tc vt Δ}
+variable {m : ExpressionMetadata}
+
+theorem denote_lit_int {i : Int}
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.const m (.intConst i)) tInt) :
+ toInt (LExpr.denote tc op fv vt bv (.const m (.intConst i)) tInt h) = i :=
+ Lambda.denote_intConst tc op fv vt bv h
+
+theorem denote_lit_bool {b : Bool}
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.const m (.boolConst b)) tBool) :
+ toBool (LExpr.denote tc op fv vt bv (.const m (.boolConst b)) tBool h) = b :=
+ Lambda.denote_boolConst tc op fv vt bv h
+
+/-- A bit-vector literal is the `BitVec` it writes. -/
+theorem denote_lit_bv {n : Nat} {b : BitVec n}
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.const m (.bitvecConst n b)) (.bitvec n)) :
+ LExpr.denote tc op fv vt bv (.const m (.bitvecConst n b)) (.bitvec n) h = b :=
+ Lambda.denote_bitvecConst tc op fv vt bv h
+
+/-- An integer variable, read from a store that binds it to an integer of the model. -/
+theorem denote_var_int [TyConstrInterp.AllInhabited tc] {σ : CoreStore} {x : CoreIdent} {n : Int}
+ (hx : σ x = some (SemValue.ofInt tc n))
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some tInt)) tInt) :
+ toInt (LExpr.denote tc op (ValStore.fvarVal (T := CoreLParams) tc σ) vt bv
+ (.fvar m x (some tInt)) tInt h) = n :=
+ denote_fvar_int_abbr vt bv hx h
+
+/-- A Boolean variable, read from a store that binds it to a Boolean of the model. -/
+theorem denote_var_bool [TyConstrInterp.AllInhabited tc] {σ : CoreStore} {x : CoreIdent}
+ {p : Bool} (hx : σ x = some (SemValue.ofBool tc p))
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some tBool)) tBool) :
+ toBool (LExpr.denote tc op (ValStore.fvarVal (T := CoreLParams) tc σ) vt bv
+ (.fvar m x (some tBool)) tBool h) = p :=
+ denote_fvar_bool_abbr vt bv hx h
+
+/-- Equality of two integer operands, as the Boolean it denotes. -/
+theorem denote_eq_int {e₁ e₂ : Expression.Expr}
+ (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt)
+ (h : LExpr.HasTypeA Δ (.eq m e₁ e₂) tBool) :
+ toBool (LExpr.denote tc op fv vt bv (.eq m e₁ e₂) tBool h)
+ = decide (toInt (LExpr.denote tc op fv vt bv e₁ tInt h₁)
+ = toInt (LExpr.denote tc op fv vt bv e₂ tInt h₂)) := by
+ rw [Bool.eq_iff_iff, decide_eq_true_eq]
+ exact denote_eq_iff fv vt bv h₁ h₂ h
+
+theorem denote_eq_bool {e₁ e₂ : Expression.Expr}
+ (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool)
+ (h : LExpr.HasTypeA Δ (.eq m e₁ e₂) tBool) :
+ toBool (LExpr.denote tc op fv vt bv (.eq m e₁ e₂) tBool h)
+ = decide (toBool (LExpr.denote tc op fv vt bv e₁ tBool h₁)
+ = toBool (LExpr.denote tc op fv vt bv e₂ tBool h₂)) := by
+ rw [Bool.eq_iff_iff, decide_eq_true_eq]
+ exact denote_eq_iff fv vt bv h₁ h₂ h
+
+theorem toInt_cond (b : Bool) (x y : TyDenote tc vt tInt) :
+ toInt (cond b x y) = cond b (toInt x) (toInt y) := by
+ cases b <;> rfl
+
+theorem toBool_cond (b : Bool) (x y : TyDenote tc vt tBool) :
+ toBool (cond b x y) = cond b (toBool x) (toBool y) := by
+ cases b <;> rfl
+
+/-- A conditional expression at `int` is the conditional of its branches. -/
+theorem denote_ite_int {c t e : Expression.Expr}
+ (hc : LExpr.HasTypeA Δ c tBool)
+ (ht : LExpr.HasTypeA Δ t tInt) (he : LExpr.HasTypeA Δ e tInt)
+ (h : LExpr.HasTypeA Δ (.ite m c t e) tInt) :
+ toInt (LExpr.denote tc op fv vt bv (.ite m c t e) tInt h)
+ = cond (toBool (LExpr.denote tc op fv vt bv c tBool hc))
+ (toInt (LExpr.denote tc op fv vt bv t tInt ht))
+ (toInt (LExpr.denote tc op fv vt bv e tInt he)) :=
+ (congrArg toInt (Lambda.denote_ite (bvarVal := bv) hc ht he h)).trans (toInt_cond _ _ _)
+
+theorem denote_ite_bool {c t e : Expression.Expr}
+ (hc : LExpr.HasTypeA Δ c tBool)
+ (ht : LExpr.HasTypeA Δ t tBool) (he : LExpr.HasTypeA Δ e tBool)
+ (h : LExpr.HasTypeA Δ (.ite m c t e) tBool) :
+ toBool (LExpr.denote tc op fv vt bv (.ite m c t e) tBool h)
+ = cond (toBool (LExpr.denote tc op fv vt bv c tBool hc))
+ (toBool (LExpr.denote tc op fv vt bv t tBool ht))
+ (toBool (LExpr.denote tc op fv vt bv e tBool he)) :=
+ (congrArg toBool (Lambda.denote_ite (bvarVal := bv) hc ht he h)).trans (toBool_cond _ _ _)
+
+/-! ### Bound variables and quantifiers
+
+A quantifier in a clause binds a variable its body reads as `bvar 0` (an enclosing binder's
+variable as `bvar 1`, and so on). Its denotation at `bool` is the Lean quantifier over the
+values of the bound type, with the body read at the valuation extended by the value. Only
+integer bound variables are lifted. -/
+
+/-- The innermost bound integer. -/
+theorem denote_bvar_zero_int {τs : List LMonoTy} {bv : BVarVal tc vt τs} {v : Int}
+ (h : LExpr.HasTypeA (T := CoreLParams) (tInt :: τs) (.bvar m 0) tInt) :
+ toInt (LExpr.denote tc op fv vt (.cons (ofInt v) bv) (.bvar m 0) tInt h) = v := by
+ unfold toInt
+ rw [Lambda.denote_bvar]
+ rfl
+
+/-- A bound integer of an enclosing binder. -/
+theorem denote_bvar_succ_int {τ : LMonoTy} {τs : List LMonoTy} {bv : BVarVal tc vt τs}
+ {x : TyDenote tc vt τ} {i : Nat}
+ (h : LExpr.HasTypeA (T := CoreLParams) (τ :: τs) (.bvar m (i + 1)) tInt)
+ (h' : LExpr.HasTypeA (T := CoreLParams) τs (.bvar m i) tInt) :
+ toInt (LExpr.denote tc op fv vt (.cons x bv) (.bvar m (i + 1)) tInt h)
+ = toInt (LExpr.denote tc op fv vt bv (.bvar m i) tInt h') := by
+ unfold toInt
+ rw [Lambda.denote_bvar, Lambda.denote_bvar]
+ rfl
+
+/-- A universal quantifier over `int`. -/
+theorem denote_forall_int {name : String} {tr body : Expression.Expr}
+ (hb : LExpr.HasTypeA (T := CoreLParams) (tInt :: Δ) body tBool)
+ (h : LExpr.HasTypeA Δ (.quant m .all name (some tInt) tr body) tBool) :
+ (toBool (LExpr.denote tc op fv vt bv (.quant m .all name (some tInt) tr body) tBool h) = true)
+ = ∀ v : Int, toBool (LExpr.denote tc op fv vt (.cons (ofInt v) bv) body tBool hb) = true :=
+ propext (denote_forall_int_iff fv vt bv hb h)
+
+/-- An existential quantifier over `int`. -/
+theorem denote_exists_int {name : String} {tr body : Expression.Expr}
+ (hb : LExpr.HasTypeA (T := CoreLParams) (tInt :: Δ) body tBool)
+ (h : LExpr.HasTypeA Δ (.quant m .exist name (some tInt) tr body) tBool) :
+ (toBool (LExpr.denote tc op fv vt bv (.quant m .exist name (some tInt) tr body) tBool h) = true)
+ = ∃ v : Int, toBool (LExpr.denote tc op fv vt (.cons (ofInt v) bv) body tBool hb) = true :=
+ propext (denote_exists_int_iff fv vt bv hb h)
+
+end Leaves
+
+section Operators
+
+variable {f : Expression.Factory} {fv : FreeVarVal CoreLParams f.model.tcInterp} {vt : TyVarVal}
+variable {Δ : List LMonoTy} {bv : BVarVal f.model.tcInterp vt Δ}
+variable {m m' m'' : ExpressionMetadata} {e₁ e₂ : Expression.Expr}
+
+/-! ## Operators, in the model of a runtime factory over `Core.Factory` -/
+
+/-! ### Integer arithmetic -/
+
+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₂)
+ tInt) :
+ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Add", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂)
+ tInt h)
+ = 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) _ _)
+
+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₂)
+ tInt) :
+ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Sub", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂)
+ tInt h)
+ = 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) _ _)
+
+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₂)
+ tInt) :
+ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Mul", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂)
+ tInt h)
+ = 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) _ _)
+
+/-- Division, at a divisor that denotes a non-zero integer. -/
+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₂)
+ tInt)
+ (hb : toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) ≠ 0) :
+ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Div", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂)
+ tInt h)
+ = 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.intDiv_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intDiv) _ _ hb)
+
+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₂)
+ tInt)
+ (hb : toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) ≠ 0) :
+ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Mod", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂)
+ tInt h)
+ = 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.intMod_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intMod) _ _ hb)
+
+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) _)
+
+/-! ### Integer comparisons -/
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Lt", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂)
+ tBool h)
+ = 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) _ _)
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Le", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂)
+ tBool h)
+ = 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) _ _)
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Gt", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂)
+ tBool h)
+ = 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) _ _)
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Int.Ge", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂)
+ tBool h)
+ = 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) _ _)
+
+/-! ### Boolean connectives -/
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Bool.And", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂)
+ tBool h)
+ = (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) _ _)
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Bool.Or", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂)
+ tBool h)
+ = (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) _ _)
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Bool.Implies", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂)
+ tBool h)
+ = (!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.boolImplies_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolImplies) _ _)
+
+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₂)
+ tBool) :
+ toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv
+ (.app m (.app m' (.op m'' ⟨"Bool.Equiv", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂)
+ tBool h)
+ = (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) _ _)
+
+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) _)
+
+end Operators
+
+/-! ## Operators that are not built in, and values of other sorts
+
+A function the program declares, or a built-in function with no Lean operation here, is read as
+its interpretation in the model, applied to the denotations of its arguments. A variable of a
+type other than `int` and `bool` is read as the value of that type the store binds it to
+(`Eval.sortVal`), and equality, conditionals and quantifiers are read at any type.
+
+These lemmas match the nodes the lemmas above match. Each asks that the operator is not one of
+`builtinOps`, or the type not `int` or `bool`, so that the lemmas above apply where they can.
+
+An argument of such an operator is marked `arg`. At `int` or `bool` the mark is where the
+denotation is read as an `Int` or a `Bool` again (`arg_int`, `arg_bool`); elsewhere it is
+dropped once the reading is done. -/
+
+/-- The operators read as Lean operations. -/
+@[expose] def builtinOps : List String :=
+ ["Int.Add", "Int.Sub", "Int.Mul", "Int.Div", "Int.Mod", "Int.Neg", "Int.Lt", "Int.Le",
+ "Int.Gt", "Int.Ge", "Bool.And", "Bool.Or", "Bool.Implies", "Bool.Equiv", "Bool.Not"]
+
+/-- An argument of an operator that is not built in, or an operand at a type other than `int`
+and `bool`. -/
+@[expose] def arg {tc : TyConstrInterp} {vt : TyVarVal} {T : LMonoTy} (x : TyDenote tc vt T) :
+ TyDenote tc vt T := x
+
+/-- A `Bool` as a value of the sort `bool`. -/
+@[expose] def ofBool {tc : TyConstrInterp} {vt : TyVarVal} (b : Bool) : TyDenote tc vt tBool := b
+
+theorem arg_int {tc : TyConstrInterp} {vt : TyVarVal} (x : TyDenote tc vt tInt) :
+ arg x = ofInt (toInt x) := rfl
+
+theorem arg_bool {tc : TyConstrInterp} {vt : TyVarVal} (x : TyDenote tc vt tBool) :
+ arg x = ofBool (toBool x) := rfl
+
+theorem toInt_ofInt {tc : TyConstrInterp} {vt : TyVarVal} (v : Int) :
+ toInt (ofInt (tc := tc) (vt := vt) v) = v := rfl
+
+theorem toBool_ofBool {tc : TyConstrInterp} {vt : TyVarVal} (b : Bool) :
+ toBool (ofBool (tc := tc) (vt := vt) b) = b := rfl
+
+section Opaque
+
+variable {tc : TyConstrInterp} {op : OpInterp tc} {fv : FreeVarVal CoreLParams tc} {vt : TyVarVal}
+variable {Δ : List LMonoTy} {bv : BVarVal tc vt Δ}
+variable {m m' m'' : ExpressionMetadata}
+
+/-- A constant that is not built in: its interpretation. -/
+theorem denote_op0 {name : String} {c : LMonoTy} (_hname : name ∉ builtinOps)
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.op m ⟨name, ()⟩ (some c)) c) :
+ LExpr.denote tc op fv vt bv (.op m ⟨name, ()⟩ (some c)) c h = op name (c.substTyVars vt) := by
+ rw [Lambda.denote_op]
+
+/-- A unary operator that is not built in: its interpretation at the argument. -/
+theorem denote_op1 {name : String} {a c : LMonoTy} {e : Expression.Expr}
+ (_hname : name ∉ builtinOps) (h₁ : LExpr.HasTypeA Δ e a)
+ (h : LExpr.HasTypeA Δ (.app m (.op m' ⟨name, ()⟩ (some (tArrow a c))) e) c) :
+ LExpr.denote tc op fv vt bv (.app m (.op m' ⟨name, ()⟩ (some (tArrow a c))) e) c h
+ = (op name ((tArrow a c).substTyVars vt) : TyDenote tc vt a → TyDenote tc vt c)
+ (arg (LExpr.denote tc op fv vt bv e a h₁)) :=
+ denote_app1 fv vt bv h₁ h
+
+/-- A binary operator that is not built in: its interpretation at the arguments. -/
+theorem denote_op2 {name : String} {a b c : LMonoTy} {e₁ e₂ : Expression.Expr}
+ (_hname : name ∉ builtinOps) (h₁ : LExpr.HasTypeA Δ e₁ a) (h₂ : LExpr.HasTypeA Δ e₂ b)
+ (h : LExpr.HasTypeA Δ
+ (.app m (.app m' (.op m'' ⟨name, ()⟩ (some (tArrow a (tArrow b c)))) e₁) e₂) c) :
+ LExpr.denote tc op fv vt bv
+ (.app m (.app m' (.op m'' ⟨name, ()⟩ (some (tArrow a (tArrow b c)))) e₁) e₂) c h
+ = (op name ((tArrow a (tArrow b c)).substTyVars vt)
+ : TyDenote tc vt a → TyDenote tc vt b → TyDenote tc vt c)
+ (arg (LExpr.denote tc op fv vt bv e₁ a h₁)) (arg (LExpr.denote tc op fv vt bv e₂ b h₂)) :=
+ denote_app2 fv vt bv h₁ h₂ h
+
+/-- A variable of any type, read from a store that binds it to a value of that type. -/
+theorem denote_var_sort [TyConstrInterp.AllInhabited tc] {σ : CoreStore} {x : CoreIdent}
+ {T : LMonoTy} {a : TyDenote tc vt T} (_hT : T ≠ tInt ∧ T ≠ tBool)
+ (hx : σ x = some ⟨tc, T.substTyVars vt, a⟩)
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some T)) T) :
+ LExpr.denote tc op (ValStore.fvarVal (T := CoreLParams) tc σ) vt bv
+ (.fvar m x (some T)) T h = a :=
+ denote_fvar_sort vt bv hx h
+
+open Classical in
+/-- Equality of two operands at a type other than `int` and `bool`. -/
+theorem denote_eq_sort {τ : LMonoTy} {e₁ e₂ : Expression.Expr}
+ (h₁ : LExpr.HasTypeA Δ e₁ τ) (h₂ : LExpr.HasTypeA Δ e₂ τ) (_hτ : τ ≠ tInt ∧ τ ≠ tBool)
+ (h : LExpr.HasTypeA Δ (.eq m e₁ e₂) tBool) :
+ toBool (LExpr.denote tc op fv vt bv (.eq m e₁ e₂) tBool h)
+ = decide (arg (LExpr.denote tc op fv vt bv e₁ τ h₁)
+ = arg (LExpr.denote tc op fv vt bv e₂ τ h₂)) := by
+ rw [Bool.eq_iff_iff, decide_eq_true_eq]
+ exact denote_eq_iff fv vt bv h₁ h₂ h
+
+/-- A conditional expression at a type other than `int` and `bool`. -/
+theorem denote_ite_sort {τ : LMonoTy} {c t e : Expression.Expr}
+ (hc : LExpr.HasTypeA Δ c tBool) (ht : LExpr.HasTypeA Δ t τ) (he : LExpr.HasTypeA Δ e τ)
+ (_hτ : τ ≠ tInt ∧ τ ≠ tBool) (h : LExpr.HasTypeA Δ (.ite m c t e) τ) :
+ LExpr.denote tc op fv vt bv (.ite m c t e) τ h
+ = cond (toBool (LExpr.denote tc op fv vt bv c tBool hc))
+ (arg (LExpr.denote tc op fv vt bv t τ ht)) (arg (LExpr.denote tc op fv vt bv e τ he)) :=
+ Lambda.denote_ite (bvarVal := bv) hc ht he h
+
+/-- The innermost bound variable. -/
+theorem denote_bvar_zero {τ : LMonoTy} {τs : List LMonoTy} {bv : BVarVal tc vt τs}
+ {x : TyDenote tc vt τ} (h : LExpr.HasTypeA (T := CoreLParams) (τ :: τs) (.bvar m 0) τ) :
+ LExpr.denote tc op fv vt (.cons x bv) (.bvar m 0) τ h = x := by
+ rw [Lambda.denote_bvar]
+ rfl
+
+/-- A bound variable of an enclosing binder. -/
+theorem denote_bvar_succ {τ τ' : LMonoTy} {τs : List LMonoTy} {bv : BVarVal tc vt τs}
+ {x : TyDenote tc vt τ'} {i : Nat}
+ (h : LExpr.HasTypeA (T := CoreLParams) (τ' :: τs) (.bvar m (i + 1)) τ)
+ (h' : LExpr.HasTypeA (T := CoreLParams) τs (.bvar m i) τ) :
+ LExpr.denote tc op fv vt (.cons x bv) (.bvar m (i + 1)) τ h
+ = LExpr.denote tc op fv vt bv (.bvar m i) τ h' := by
+ rw [Lambda.denote_bvar, Lambda.denote_bvar]
+ rfl
+
+/-- A universal quantifier over a type other than `int`. -/
+theorem denote_forall_sort {name : String} {tr body : Expression.Expr} {qty : LMonoTy}
+ (_hq : qty ≠ tInt) (hb : LExpr.HasTypeA (T := CoreLParams) (qty :: Δ) body tBool)
+ (h : LExpr.HasTypeA Δ (.quant m .all name (some qty) tr body) tBool) :
+ (toBool (LExpr.denote tc op fv vt bv (.quant m .all name (some qty) tr body) tBool h) = true)
+ = ∀ v : TyDenote tc vt qty,
+ toBool (LExpr.denote tc op fv vt (.cons v bv) body tBool hb) = true :=
+ propext (denote_forall_iff fv vt bv hb h)
+
+/-- An existential quantifier over a type other than `int`. -/
+theorem denote_exists_sort {name : String} {tr body : Expression.Expr} {qty : LMonoTy}
+ (_hq : qty ≠ tInt) (hb : LExpr.HasTypeA (T := CoreLParams) (qty :: Δ) body tBool)
+ (h : LExpr.HasTypeA Δ (.quant m .exist name (some qty) tr body) tBool) :
+ (toBool (LExpr.denote tc op fv vt bv (.quant m .exist name (some qty) tr body) tBool h) = true)
+ = ∃ v : TyDenote tc vt qty,
+ toBool (LExpr.denote tc op fv vt (.cons v bv) body tBool hb) = true :=
+ propext (denote_exists_iff fv vt bv hb h)
+
+end Opaque
+
+/-! ## From evaluation to denotation
+
+`Lambda.LExpr.denoteEval` first asks that the store bind every free variable to a value of the
+model, annotates each occurrence with the sort of that value, and type checks. `BoundIn` is the
+first condition together with the fact that the annotation changes nothing, one variable
+occurrence at a time, so that it is proved by walking the condition. -/
+
+/-- Every free variable of `e` is bound in `σ` to a value of the model `tc` whose sort is the
+annotation the variable carries. A structure, so that a rule for one node never applies to
+another by unfolding. -/
+structure BoundIn (σ : CoreStore) (tc : TyConstrInterp) (e : Expression.Expr) : Prop where
+ bound : ∀ x ty, (x, ty) ∈ e.freeVars → ∃ v, σ x = some v ∧ v.tc = tc ∧ ty = some v.sort.toMonoTy
+
+namespace BoundIn
+
+variable {σ : CoreStore} {tc : TyConstrInterp} {m : ExpressionMetadata}
+
+theorem const {c : LConst} : BoundIn σ tc (.const m c) :=
+ ⟨fun x ty hx => by simp [LExpr.freeVars] at hx⟩
+
+theorem op {o : CoreIdent} {ty : Option LMonoTy} : BoundIn σ tc (.op m o ty) :=
+ ⟨fun x ty' hx => by simp [LExpr.freeVars] at hx⟩
+
+theorem bvar {i : Nat} : BoundIn σ tc (.bvar m i) :=
+ ⟨fun x ty hx => by simp [LExpr.freeVars] at hx⟩
+
+theorem fvar {x : CoreIdent} {ty : Option LMonoTy} {v : Expression.Val} (hx : σ x = some v)
+ (htc : v.tc = tc) (hty : ty = some v.sort.toMonoTy) : BoundIn σ tc (.fvar m x ty) := by
+ refine ⟨fun y ty' hy => ?_⟩
+ simp only [LExpr.freeVars, List.mem_singleton, Prod.mk.injEq] at hy
+ obtain ⟨rfl, rfl⟩ := hy
+ exact ⟨v, hx, htc, hty⟩
+
+/-- An integer variable bound to an integer of the factory. -/
+theorem var_int {F : Expression.Factory} {x : CoreIdent} {a : Int}
+ (hx : σ x = some (Eval.intVal F a)) :
+ BoundIn σ F.model.tcInterp (.fvar m x (some tInt)) :=
+ fvar hx rfl rfl
+
+/-- A Boolean variable bound to a Boolean of the factory. -/
+theorem var_bool {F : Expression.Factory} {x : CoreIdent} {p : Bool}
+ (hx : σ x = some (Eval.boolVal F p)) :
+ BoundIn σ F.model.tcInterp (.fvar m x (some tBool)) :=
+ fvar hx rfl rfl
+
+/-- A variable bound to a value of its type in the model of the factory. -/
+theorem var_sort {F : Expression.Factory} {x : CoreIdent} {T : LMonoTy}
+ {a : TyDenote F.model.tcInterp F.tyVarVal T} (hx : σ x = some (Eval.sortVal F T a))
+ (hT : (T.substTyVars F.tyVarVal).toMonoTy = T) :
+ BoundIn σ F.model.tcInterp (.fvar m x (some T)) :=
+ fvar hx rfl (by rw [hT])
+
+theorem app {f a : Expression.Expr} (hf : BoundIn σ tc f) (ha : BoundIn σ tc a) :
+ BoundIn σ tc (.app m f a) := by
+ refine ⟨fun x ty hx => ?_⟩
+ simp only [LExpr.freeVars, List.mem_append] at hx
+ exact hx.elim (hf.bound x ty) (ha.bound x ty)
+
+theorem eq {a b : Expression.Expr} (ha : BoundIn σ tc a) (hb : BoundIn σ tc b) :
+ BoundIn σ tc (.eq m a b) := by
+ refine ⟨fun x ty hx => ?_⟩
+ simp only [LExpr.freeVars, List.mem_append] at hx
+ exact hx.elim (ha.bound x ty) (hb.bound x ty)
+
+theorem ite {c t e : Expression.Expr} (hc : BoundIn σ tc c) (ht : BoundIn σ tc t)
+ (he : BoundIn σ tc e) : BoundIn σ tc (.ite m c t e) := by
+ refine ⟨fun x ty hx => ?_⟩
+ simp only [LExpr.freeVars, List.mem_append] at hx
+ exact hx.elim (fun h => h.elim (hc.bound x ty) (ht.bound x ty)) (he.bound x ty)
+
+theorem abs {name : String} {ty : Option LMonoTy} {e : Expression.Expr} (he : BoundIn σ tc e) :
+ BoundIn σ tc (.abs m name ty e) := by
+ refine ⟨fun x ty' hx => ?_⟩
+ simp only [LExpr.freeVars] at hx
+ exact he.bound x ty' hx
+
+theorem quant {k : QuantifierKind} {name : String} {ty : Option LMonoTy}
+ {tr e : Expression.Expr} (htr : BoundIn σ tc tr) (he : BoundIn σ tc e) :
+ BoundIn σ tc (.quant m k name ty tr e) := by
+ refine ⟨fun x ty' hx => ?_⟩
+ simp only [LExpr.freeVars, List.mem_append] at hx
+ exact hx.elim (htr.bound x ty') (he.bound x ty')
+
+end BoundIn
+
+/-- **From evaluation to denotation.** A condition whose free variables the store binds, at
+their annotations, evaluates to the Boolean it denotes. -/
+theorem evalBool_eq_denote {F : Expression.Factory} {σ : CoreStore} {e : Expression.Expr}
+ {b : Bool} (hb : BoundIn σ F.model.tcInterp e) (hty : LExpr.HasTypeA [] e tBool) :
+ (LExpr.denoteEval F σ e = some (Eval.boolVal F b)) =
+ (toBool (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e tBool hty) = b) := by
+ have hd : ValStore.Defines σ F.model.tcInterp e := by
+ intro x hx
+ rw [getVars_eq_freeVars_idents] at hx
+ obtain ⟨⟨x', ty⟩, hmem, rfl⟩ := List.mem_map.mp hx
+ obtain ⟨v, hv, htc, -⟩ := hb.bound x' ty hmem
+ exact ⟨v, hv, htc⟩
+ have hann : LExpr.annotateFvars (ValStore.ann σ) e = e :=
+ LExpr.annotateFvars_eq_self e (fun x ty hx => by
+ obtain ⟨v, hv, -, hty⟩ := hb.bound x ty hx
+ exact ⟨_, hty, by simp [ValStore.ann, hv]⟩)
+ apply propext
+ rw [LExpr.denoteEval_eq_ofBool_iff (T := CoreLParams)]
+ have key : ∀ (e' : Expression.Expr) (he : e' = e) (h : LExpr.HasTypeA [] e' .bool),
+ (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e' .bool h) =
+ (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e .bool hty) := by
+ intro e' he h; subst he; rfl
+ constructor
+ · rintro ⟨-, h, hv⟩
+ rw [key _ hann h] at hv
+ exact hv
+ · intro hv
+ have hty' : LExpr.HasTypeA [] (LExpr.annotateFvars (ValStore.ann σ) e) .bool := by
+ rw [hann]; exact hty
+ exact ⟨hd, hty', by rw [key _ hann hty']; exact hv⟩
+
+/-- `evalBool_eq_denote` for a condition that holds, as the rules state it. -/
+theorem eval_tt_eq_denote {F : Expression.Factory} {σ : CoreStore} {e : Expression.Expr}
+ (hb : BoundIn σ F.model.tcInterp e) (hty : LExpr.HasTypeA [] e tBool) :
+ (Core.Expression.eval F σ e = some (Imperative.HasBool.ttVal F)) =
+ (toBool (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e tBool hty) = true) :=
+ evalBool_eq_denote hb hty
+
+/-- `evalBool_eq_denote` for a condition that fails: the guard of an `else` branch or of a
+loop's exit. -/
+theorem eval_ff_eq_denote {F : Expression.Factory} {σ : CoreStore} {e : Expression.Expr}
+ (hb : BoundIn σ F.model.tcInterp e) (hty : LExpr.HasTypeA [] e tBool) :
+ (Core.Expression.eval F σ e = some (Imperative.HasBool.ffVal F)) =
+ (toBool (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e tBool hty) = false) :=
+ evalBool_eq_denote hb hty
+
+/-- **From evaluation to denotation, at any type.** An expression whose free variables the
+store binds, at their annotations, evaluates to the value it denotes. -/
+theorem eval_eq_denote {F : Expression.Factory} {σ : CoreStore} {e : Expression.Expr}
+ {T : LMonoTy} {v : Expression.Val} (hb : BoundIn σ F.model.tcInterp e)
+ (hty : LExpr.HasTypeA [] e T) (hg : T.IsGround) :
+ (Core.Expression.eval F σ e = some v) =
+ (v = Eval.sortVal F T (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e T hty)) := by
+ have hd : ValStore.Defines σ F.model.tcInterp e := by
+ intro x hx
+ rw [getVars_eq_freeVars_idents] at hx
+ obtain ⟨⟨x', ty⟩, hmem, rfl⟩ := List.mem_map.mp hx
+ obtain ⟨w, hw, htc, -⟩ := hb.bound x' ty hmem
+ exact ⟨w, hw, htc⟩
+ have hann : LExpr.annotateFvars (ValStore.ann σ) e = e :=
+ LExpr.annotateFvars_eq_self e (fun x ty hx => by
+ obtain ⟨w, hw, -, hty⟩ := hb.bound x ty hx
+ exact ⟨_, hty, by simp [ValStore.ann, hw]⟩)
+ have key : ∀ (e' : Expression.Expr) (he : e' = e) (h : LExpr.HasTypeA [] e' T),
+ (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e' T h) =
+ (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e T hty) := by
+ intro e' he h; subst he; rfl
+ have hty' : LExpr.HasTypeA [] (LExpr.annotateFvars (ValStore.ann σ) e) T := by
+ rw [hann]; exact hty
+ have hev : Core.Expression.eval F σ e = some (Eval.sortVal F T (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e T hty)) := by
+ show LExpr.denoteEval F σ e = _
+ rw [LExpr.denoteEval_of_hasTypeA (T := CoreLParams) hd hty' hg]
+ unfold LExpr.denoteEvalResult
+ rw [key _ hann hty']
+ rw [hev]
+ exact propext ⟨fun h => (Option.some.inj h).symm, fun h => by rw [h]⟩
+
+/-- `eval_eq_denote` at `int`: the value is an integer of the factory. -/
+theorem eval_eq_denote_int {F : Expression.Factory} {σ : CoreStore} {e : Expression.Expr}
+ {v : Expression.Val} (hb : BoundIn σ F.model.tcInterp e) (hty : LExpr.HasTypeA [] e tInt) :
+ (Core.Expression.eval F σ e = some v) =
+ (v = Eval.intVal F (toInt (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e tInt hty))) :=
+ eval_eq_denote hb hty rfl
+
+/-- `eval_eq_denote` at `bool`: the value is a Boolean of the factory. -/
+theorem eval_eq_denote_bool {F : Expression.Factory} {σ : CoreStore} {e : Expression.Expr}
+ {v : Expression.Val} (hb : BoundIn σ F.model.tcInterp e) (hty : LExpr.HasTypeA [] e tBool) :
+ (Core.Expression.eval F σ e = some v) =
+ (v = Eval.boolVal F (toBool (letI := F.model.allInhabited
+ LExpr.denote F.model.tcInterp F.model.opInterp (ValStore.fvarVal F.model.tcInterp σ)
+ F.tyVarVal .nil e tBool hty))) :=
+ eval_eq_denote hb hty rfl
+
+/-! ## A declared function is its body -/
+
+/-- A valuation of the free variables for the body of a function, whose free variables are its
+parameters: every other variable is read as a default value. -/
+@[expose] noncomputable def closedVal (F : Expression.Factory) :
+ FreeVarVal CoreLParams F.model.tcInterp :=
+ fun _ s => @default _ (@SortDenote.instInhabited F.model.tcInterp F.model.allInhabited s)
+
+section Functions
+
+variable {tc : TyConstrInterp} {op : OpInterp tc} {fv : FreeVarVal CoreLParams tc} {vt : TyVarVal}
+variable {Δ : List LMonoTy} {bv : BVarVal tc vt Δ} {m : ExpressionMetadata}
+
+/-- A parameter in the valuation of a function body: the first one. -/
+theorem denote_param_self {x : CoreIdent} {T : LMonoTy} {rest : List (CoreIdent × LSort)}
+ {v : TyDenote tc vt T} {vs : HList (SortDenote tc) (rest.map Prod.snd)}
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some T)) T) :
+ LExpr.denote tc op (IdentInterp.withArgs fv ((x, T.substTyVars vt) :: rest) (.cons v vs)) vt bv
+ (.fvar m x (some T)) T h = v := by
+ rw [Lambda.denote_fvar]
+ exact IdentInterp.withArgs_cons_self fv x _ rest v vs
+
+/-- A parameter in the valuation of a function body: one after the first. -/
+theorem denote_param_next {x y : CoreIdent} {T : LMonoTy} {s : LSort}
+ {rest : List (CoreIdent × LSort)} {v : SortDenote tc s}
+ {vs : HList (SortDenote tc) (rest.map Prod.snd)} (hne : x ≠ y)
+ (h : LExpr.HasTypeA (T := CoreLParams) Δ (.fvar m x (some T)) T) :
+ LExpr.denote tc op (IdentInterp.withArgs fv ((y, s) :: rest) (.cons v vs)) vt bv
+ (.fvar m x (some T)) T h
+ = LExpr.denote tc op (IdentInterp.withArgs fv rest vs) vt bv (.fvar m x (some T)) T h := by
+ rw [Lambda.denote_fvar, Lambda.denote_fvar]
+ exact IdentInterp.withArgs_cons_of_ne fv _ rest v vs hne
+
+end Functions
+
+/-- A declared constant is its body, in every model of a factory that resolves its name to it. -/
+theorem op_eq_body0 {F : Expression.Factory} {name : String} {c : LMonoTy}
+ {fn : LFunc CoreLParams} {body : Expression.Expr}
+ (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = []) (hout : fn.output = c)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body c)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp) :
+ F.model.opInterp name (c.substTyVars F.tyVarVal)
+ = LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [] .nil) F.tyVarVal .nil body c hty := by
+ have h := HoareLift.opInterp_of_body F.model hlookup hbody
+ rcases fn with ⟨⟨fname, _, _, _, inputs, output, fbody, _, _, _, _, _⟩, _⟩
+ dsimp only at hname hin hout
+ subst hname hin hout
+ exact h F.tyVarVal fv hty .nil
+
+/-- A declared function of one parameter is its body. -/
+theorem op_eq_body1 {F : Expression.Factory} {name : String} {x : CoreIdent} {a c : LMonoTy}
+ {fn : LFunc CoreLParams} {body : Expression.Expr}
+ (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = [(x, a)]) (hout : fn.output = c)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body c)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp)
+ (v : TyDenote F.model.tcInterp F.tyVarVal a) :
+ (F.model.opInterp name ((tArrow a c).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal a → TyDenote F.model.tcInterp F.tyVarVal c) v
+ = LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [(x, a.substTyVars F.tyVarVal)] (.cons v .nil))
+ F.tyVarVal .nil body c hty := by
+ have h := HoareLift.opInterp_of_body F.model hlookup hbody
+ rcases fn with ⟨⟨fname, _, _, _, inputs, output, fbody, _, _, _, _, _⟩, _⟩
+ dsimp only at hname hin hout
+ subst hname hin hout
+ exact h F.tyVarVal fv hty (.cons v .nil)
+
+/-- A declared function of two parameters is its body. -/
+theorem op_eq_body2 {F : Expression.Factory} {name : String} {x y : CoreIdent} {a b c : LMonoTy}
+ {fn : LFunc CoreLParams} {body : Expression.Expr}
+ (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = [(x, a), (y, b)]) (hout : fn.output = c)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body c)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp)
+ (v : TyDenote F.model.tcInterp F.tyVarVal a) (w : TyDenote F.model.tcInterp F.tyVarVal b) :
+ (F.model.opInterp name ((tArrow a (tArrow b c)).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal a → TyDenote F.model.tcInterp F.tyVarVal b →
+ TyDenote F.model.tcInterp F.tyVarVal c) v w
+ = LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [(x, a.substTyVars F.tyVarVal), (y, b.substTyVars F.tyVarVal)]
+ (.cons v (.cons w .nil)))
+ F.tyVarVal .nil body c hty := by
+ have h := HoareLift.opInterp_of_body F.model hlookup hbody
+ rcases fn with ⟨⟨fname, _, _, _, inputs, output, fbody, _, _, _, _, _⟩, _⟩
+ dsimp only at hname hin hout
+ subst hname hin hout
+ exact h F.tyVarVal fv hty (.cons v (.cons w .nil))
+
+/-! ### At `bool` and at `int`
+
+The same equations in the form the reading lemmas rewrite: a Boolean function holds exactly when
+its body does, and an integer function has the integer value of its body. -/
+
+section Typed
+
+variable {F : Expression.Factory} {name : String} {x y : CoreIdent} {a b : LMonoTy}
+variable {fn : LFunc CoreLParams} {body : Expression.Expr}
+
+theorem op_iff_body0 (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = []) (hout : fn.output = tBool)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body tBool)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp) :
+ toBool (F.model.opInterp name ((tBool).substTyVars F.tyVarVal)) = true
+ ↔ toBool (LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [] .nil) F.tyVarVal .nil body tBool hty) = true :=
+ iff_of_eq (congrArg (fun r => toBool r = true) (op_eq_body0 hlookup hname hin hout hbody hty fv))
+
+theorem op_iff_body1 (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = [(x, a)]) (hout : fn.output = tBool)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body tBool)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp)
+ (v : TyDenote F.model.tcInterp F.tyVarVal a) :
+ toBool ((F.model.opInterp name ((tArrow a tBool).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal a → TyDenote F.model.tcInterp F.tyVarVal tBool) v)
+ = true
+ ↔ toBool (LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [(x, a.substTyVars F.tyVarVal)] (.cons v .nil))
+ F.tyVarVal .nil body tBool hty) = true :=
+ iff_of_eq (congrArg (fun r => toBool r = true)
+ (op_eq_body1 hlookup hname hin hout hbody hty fv v))
+
+theorem op_iff_body2 (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = [(x, a), (y, b)]) (hout : fn.output = tBool)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body tBool)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp)
+ (v : TyDenote F.model.tcInterp F.tyVarVal a) (w : TyDenote F.model.tcInterp F.tyVarVal b) :
+ toBool ((F.model.opInterp name ((tArrow a (tArrow b tBool)).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal a → TyDenote F.model.tcInterp F.tyVarVal b →
+ TyDenote F.model.tcInterp F.tyVarVal tBool) v w) = true
+ ↔ toBool (LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [(x, a.substTyVars F.tyVarVal), (y, b.substTyVars F.tyVarVal)]
+ (.cons v (.cons w .nil)))
+ F.tyVarVal .nil body tBool hty) = true :=
+ iff_of_eq (congrArg (fun r => toBool r = true)
+ (op_eq_body2 hlookup hname hin hout hbody hty fv v w))
+
+theorem op_int_body0 (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = []) (hout : fn.output = tInt)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body tInt)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp) :
+ toInt (F.model.opInterp name ((tInt).substTyVars F.tyVarVal))
+ = toInt (LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [] .nil) F.tyVarVal .nil body tInt hty) :=
+ congrArg toInt (op_eq_body0 hlookup hname hin hout hbody hty fv)
+
+theorem op_int_body1 (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = [(x, a)]) (hout : fn.output = tInt)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body tInt)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp)
+ (v : TyDenote F.model.tcInterp F.tyVarVal a) :
+ toInt ((F.model.opInterp name ((tArrow a tInt).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal a → TyDenote F.model.tcInterp F.tyVarVal tInt) v)
+ = toInt (LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [(x, a.substTyVars F.tyVarVal)] (.cons v .nil))
+ F.tyVarVal .nil body tInt hty) :=
+ congrArg toInt (op_eq_body1 hlookup hname hin hout hbody hty fv v)
+
+theorem op_int_body2 (hlookup : F.factory[name]? = some fn)
+ (hname : fn.name = ⟨name, ()⟩) (hin : fn.inputs = [(x, a), (y, b)]) (hout : fn.output = tInt)
+ (hbody : fn.body = some body) (hty : LExpr.HasTypeA (T := CoreLParams) [] body tInt)
+ (fv : FreeVarVal CoreLParams F.model.tcInterp)
+ (v : TyDenote F.model.tcInterp F.tyVarVal a) (w : TyDenote F.model.tcInterp F.tyVarVal b) :
+ toInt ((F.model.opInterp name ((tArrow a (tArrow b tInt)).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal a → TyDenote F.model.tcInterp F.tyVarVal b →
+ TyDenote F.model.tcInterp F.tyVarVal tInt) v w)
+ = toInt (LExpr.denote F.model.tcInterp F.model.opInterp
+ (IdentInterp.withArgs fv [(x, a.substTyVars F.tyVarVal), (y, b.substTyVars F.tyVarVal)]
+ (.cons v (.cons w .nil)))
+ F.tyVarVal .nil body tInt hty) :=
+ congrArg toInt (op_eq_body2 hlookup hname hin hout hbody hty fv v w)
+
+end Typed
+
+/-! ## Sequences -/
+
+/-- The length of a sequence is not negative, in the model of a runtime factory over
+`Core.Factory`. -/
+theorem seqLength_nonneg {F : Expression.Factory} (hfac : Eval.OverCore F.factory) {A : LMonoTy}
+ (s : TyDenote F.model.tcInterp F.tyVarVal (.tcons "Sequence" [A])) :
+ 0 ≤ toInt ((F.model.opInterp "Sequence.length"
+ ((tArrow (.tcons "Sequence" [A]) tInt).substTyVars F.tyVarVal)
+ : TyDenote F.model.tcInterp F.tyVarVal (.tcons "Sequence" [A]) →
+ TyDenote F.model.tcInterp F.tyVarVal tInt) s) :=
+ Core.seqLength_nonneg F.model (hfac _ _ Core.coreFactory_seqLength)
+ (hfac _ _ Core.coreFactory_intGe) (A.substTyVars F.tyVarVal) s
+
+end Strata.Hoare.Denote
+
+end -- public section
diff --git a/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean b/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean
new file mode 100644
index 0000000..7008e99
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean
@@ -0,0 +1,594 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+module
+
+public import Strata.Languages.Core.IntEvalProps
+public import Strata.Languages.Core.ProgramProps
+public import Strata.DL.Lambda.DatatypeFactoryWFProps
+public import StrataBoole.HoareLogic.HoareLift
+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
+import all Strata.DL.Lambda.LExprWF
+
+/-! # Evaluating Core expressions over a store of values
+
+Statements evaluate their expressions with `Core.Expression.eval`, which is denotational
+(`Lambda.LExpr.denoteEval`): an expression evaluates to what it denotes in the model the runtime
+factory carries. A verification condition therefore reads `eval ρ.factory ρ.store e = some v`
+for the guard or right-hand side `e`, with the store known slot by slot:
+`ρ.store x = some (intVal ρ.factory a)`. The lemmas here compute such evaluations: a variable
+yields its stored value, a literal its value, and a built-in operator on sub-expressions that
+evaluate to integers or Booleans yields the integer or Boolean of the Lean operation.
+
+Each operator lemma is Strata's `Core.eval_app2_op`, or its unary counterpart
+`Core.eval_app1_op`, at the operator's interpretation in the model, which is the Lean operation
+whenever the 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.
+
+Division and remainder are interpreted only at a non-zero divisor, which is the guard of their
+factory entries. -/
+
+public section
+
+namespace Strata.Hoare.Eval
+
+open _root_.Core _root_.Lambda
+
+local notation "tInt" => LMonoTy.tcons "int" []
+local notation "tBool" => LMonoTy.tcons "bool" []
+local notation "tArrow" a:max b:max => LMonoTy.tcons "arrow" [a, b]
+
+/-! ## Values -/
+
+/-- The integer `a` as a value of the runtime factory `f`. -/
+abbrev intVal (f : Expression.Factory) (a : Int) : Expression.Val :=
+ SemValue.ofInt f.model.tcInterp a
+
+/-- The Boolean `p` as a value of the runtime factory `f`. -/
+abbrev boolVal (f : Expression.Factory) (p : Bool) : Expression.Val :=
+ SemValue.ofBool f.model.tcInterp p
+
+/-- A value of the type `T` in the model of the runtime factory `f`, as a value of `f`: the
+form a variable of a type other than `int` and `bool` holds. -/
+abbrev sortVal (f : Expression.Factory) (T : LMonoTy)
+ (a : TyDenote f.model.tcInterp f.tyVarVal T) : Expression.Val :=
+ ⟨f.model.tcInterp, T.substTyVars f.tyVarVal, a⟩
+
+/-- A value of the factory `f` whose sort is that of the type `T` is a value of `T` in the
+model of `f`. -/
+theorem value_sort {f : Expression.Factory} {v : Expression.Val} {T : LMonoTy}
+ (hv : v.tc = f.model.tcInterp) (hs : v.sort.toMonoTy = T) :
+ ∃ a : TyDenote f.model.tcInterp f.tyVarVal T, v = sortVal f T a := by
+ obtain ⟨tc, s, val⟩ := v
+ obtain rfl : tc = f.model.tcInterp := hv
+ obtain rfl : s.toMonoTy = T := hs
+ have hsort : s.toMonoTy.substTyVars f.tyVarVal = s := LSort.toMonoTy_substTyVars _ s
+ unfold sortVal TyDenote
+ generalize s.toMonoTy.substTyVars f.tyVarVal = s' at hsort ⊢
+ subst hsort
+ exact ⟨val, rfl⟩
+
+/-- A value whose sort is `bool` is a Boolean. -/
+theorem exists_ofBool {v : SemValue} (hs : v.sort.toMonoTy = tBool) :
+ ∃ p, v = SemValue.ofBool v.tc p := by
+ obtain ⟨tc, s, val⟩ := v
+ obtain rfl : s = .bool := LSort.toMonoTy_injective (t := .bool) hs
+ exact ⟨val, rfl⟩
+
+/-- A value of the factory `f` whose sort is `int` is an integer of `f`. -/
+theorem value_int {f : Expression.Factory} {v : Expression.Val}
+ (hv : v.tc = f.model.tcInterp) (hs : v.sort.toMonoTy = tInt) : ∃ a : Int, v = intVal f a := by
+ obtain ⟨a, ha⟩ := SemValue.exists_ofInt hs
+ exact ⟨a, by rw [ha, hv]⟩
+
+/-- A value of the factory `f` whose sort is `bool` is a Boolean of `f`. -/
+theorem value_bool {f : Expression.Factory} {v : Expression.Val}
+ (hv : v.tc = f.model.tcInterp) (hs : v.sort.toMonoTy = tBool) :
+ ∃ p : Bool, v = boolVal f p := by
+ obtain ⟨p, hp⟩ := exists_ofBool hs
+ exact ⟨p, by rw [hp, hv]⟩
+
+section
+variable {f : Expression.Factory} {σ : CoreStore} {m m' m'' : ExpressionMetadata}
+ {x y : Expression.Expr}
+
+/-- `Expression.eval` is denotational evaluation. The lemmas below are stated on the latter,
+which is what `Expression.eval` reduces to. -/
+theorem eval_def (e : Expression.Expr) :
+ Core.Expression.eval f σ e = LExpr.denoteEval f σ e := rfl
+
+/-! ## Leaves -/
+
+theorem eval_var_int {ty : Option LMonoTy} {v : CoreIdent} {a : Int}
+ (hx : σ v = some (intVal f a)) : LExpr.denoteEval f σ (.fvar m v ty) = some (intVal f a) :=
+ Core.eval_fvar_int f hx
+
+theorem eval_var_bool {ty : Option LMonoTy} {v : CoreIdent} {p : Bool}
+ (hx : σ v = some (boolVal f p)) : LExpr.denoteEval f σ (.fvar m v ty) = some (boolVal f p) :=
+ Core.eval_fvar f hx rfl
+
+theorem eval_lit_int (a : Int) :
+ LExpr.denoteEval f σ (.const m (.intConst a)) = some (intVal f a) :=
+ Core.eval_intConst f σ a
+
+theorem eval_lit_bool (p : Bool) :
+ LExpr.denoteEval f σ (.const m (.boolConst p)) = some (boolVal f p) :=
+ Core.eval_boolConst f σ p
+
+end
+
+/-! ## The built-in functions Strata has no lemma for -/
+
+/-- A function of `Core.WFFactoryArray` is what `Core.Factory` resolves its name to. -/
+theorem coreFactory_of_mem {wf : Lambda.WFLFunc CoreLParams}
+ (hmem : wf.func ∈ Core.WFFactoryArray.map (·.func)) :
+ (Core.Factory)[wf.func.name.name]? = some wf.func := by
+ 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
+
+/-- Membership of a built-in function in `Core.WFFactoryArray`, by walking the array. -/
+syntax "wf_factory_mem" : tactic
+macro_rules
+ | `(tactic| wf_factory_mem) => `(tactic| (
+ refine Array.mem_map.mpr ⟨_, ?_, rfl⟩
+ rw [Array.mem_def]
+ unfold Core.WFFactoryArray
+ simp only [Array.toList_appendList]
+ repeat (first | exact List.Mem.head _ | apply List.Mem.tail)))
+
+theorem coreFactory_intNeg :
+ (Core.Factory)["Int.Neg"]? = some (Lambda.intNegFunc (T := CoreLParams)).func :=
+ coreFactory_of_mem (wf := Lambda.intNegFunc (T := CoreLParams)) (by wf_factory_mem)
+
+theorem coreFactory_boolEquiv :
+ (Core.Factory)["Bool.Equiv"]? = some (Lambda.boolEquivFunc (T := CoreLParams)).func :=
+ coreFactory_of_mem (wf := Lambda.boolEquivFunc (T := CoreLParams)) (by wf_factory_mem)
+
+/-! ### Their interpretation in every consistent model
+
+A function's concrete evaluation on literals is its interpretation in every model consistent
+with the factory (`Core.opInterp_of_concreteEval`). -/
+
+/-- `Int.Neg` is integer negation. -/
+theorem intNeg_opInterp_of_lookup {factory : Lambda.Factory CoreLParams}
+ (model : Lambda.Interp factory)
+ (hlookup : factory["Int.Neg"]? = some (Lambda.intNegFunc (T := CoreLParams)).func)
+ (a : Int) :
+ (model.opInterp "Int.Neg" (Lambda.LSort.mkArrow .int [.int]) a : Int) = -a := by
+ have heval : (Lambda.intNegFunc (T := CoreLParams)).func.concreteEval.bind
+ (fun ce => ce Core.coreLoc
+ (some ((Lambda.intNegFunc (T := CoreLParams)).func.instTy Lambda.Subst.empty))
+ [.intConst Core.coreLoc a]) =
+ some (.intConst Core.coreLoc (-a)) := by
+ 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) .nil) (.const rfl)).symm
+
+/-- `Bool.Equiv` is equality of Booleans. -/
+theorem boolEquiv_opInterp_of_lookup {factory : Lambda.Factory CoreLParams}
+ (model : Lambda.Interp factory)
+ (hlookup : factory["Bool.Equiv"]? = some (Lambda.boolEquivFunc (T := CoreLParams)).func)
+ (p q : Bool) :
+ (model.opInterp "Bool.Equiv" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool)
+ = (p == q) := by
+ have heval : (Lambda.boolEquivFunc (T := CoreLParams)).func.concreteEval.bind
+ (fun ce => ce Core.coreLoc
+ (some ((Lambda.boolEquivFunc (T := CoreLParams)).func.instTy Lambda.Subst.empty))
+ [.boolConst Core.coreLoc p, .boolConst Core.coreLoc q]) =
+ some (.boolConst Core.coreLoc (p == q)) := by
+ 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
+
+/-! ## 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'
+
+/-- The factory visible at a procedure is over `Core.Factory`. -/
+theorem OverCore.factoryBeforeProcedure (p : Core.Program) (procName : String) :
+ OverCore (p.factoryBeforeProcedure procName) :=
+ fun _ _ h => p.factoryBeforeProcedure_getElem?_of_core procName h
+
+/-! ## Looking a declared function up
+
+A factory finds a name through a hash map, which the kernel cannot run. The lemmas here resolve
+the name of a declared function in the factory visible at a procedure from two facts the kernel
+can check: the name is not among the names of the built-in functions, and the declarations before
+the procedure give the name to that function (`lookupDecls`, a walk of the declarations). A datatype declaration adds generated functions; their names are
+`MutualDatatype.generatedFuncNames`, so the walk does not run the generator. -/
+
+/-- The functions a declaration adds to a runtime factory, read off the declaration. -/
+@[expose] def declFuncs : Core.Decl → List (LFunc CoreLParams)
+ | .func f _ => [f.toLFunc]
+ | .recFuncBlock fs _ => fs.map (·.toLFunc)
+ | _ => []
+
+/-- The names of the functions a datatype declaration generates. -/
+@[expose] def declGenerated : Core.Decl → List String
+ | .type (.data block) _ => Lambda.MutualDatatype.generatedFuncNames block
+ | _ => []
+
+/-- The function a list of declarations gives the name `n`: the first one declared under it.
+`none` from a datatype on that generates a function of that name. -/
+@[expose] def lookupDecls (n : String) : List Core.Decl → Option (LFunc CoreLParams)
+ | [] => none
+ | d :: ds =>
+ if n ∈ declGenerated d then none
+ else ((declFuncs d).find? (fun f => f.name.name == n)).or (lookupDecls n ds)
+
+/-- A declaration that generates no function named `n` resolves `n` as the factory did, or else
+to the first function of that name it declares. -/
+theorem addToRuntimeFactory_getElem? (d : Core.Decl) (F : Lambda.Factory CoreLParams) {n : String}
+ (hn : n ∉ declGenerated d) :
+ (d.addToRuntimeFactory F)[n]? =
+ (F[n]?).or ((declFuncs d).find? (fun f => f.name.name == n)) := by
+ cases d with
+ | type t md =>
+ cases t with
+ | data block =>
+ simp only [Core.Decl.addToRuntimeFactory]
+ split
+ · rename_i fs hgen
+ simp only [Lambda.Factory.append, ← Array.foldl_toList]
+ rw [Lambda.Factory.getElem?_foldl_pushIfNew]
+ have hnames := Lambda.genBlockFactory_names hgen
+ have hnone : fs.toArray.toList.find? (fun f => f.name.name == n) = none := by
+ rw [List.find?_eq_none]
+ intro f hf hfn
+ apply hn
+ simp only [declGenerated]
+ rw [← hnames]
+ exact List.mem_map.mpr ⟨f, hf, by simpa using hfn⟩
+ simp [hnone, declFuncs]
+ · simp [declFuncs]
+ | _ => simp [Core.Decl.addToRuntimeFactory, Core.Decl.addFunctionsToFactory, declFuncs]
+ | func f md =>
+ simp only [Core.Decl.addToRuntimeFactory, Core.Decl.addFunctionsToFactory, declFuncs]
+ exact Lambda.Factory.getElem?_foldl_pushIfNew [f.toLFunc] F n
+ | recFuncBlock fs md =>
+ simp only [Core.Decl.addToRuntimeFactory, Core.Decl.addFunctionsToFactory, declFuncs]
+ rw [← List.foldl_map]
+ exact Lambda.Factory.getElem?_foldl_pushIfNew _ F n
+ | _ => simp [Core.Decl.addToRuntimeFactory, Core.Decl.addFunctionsToFactory, declFuncs]
+
+/-- Declarations keep the function a factory finds under a name. -/
+theorem foldl_addToRuntimeFactory_getElem?_of_some (ds : List Core.Decl)
+ {F : Lambda.Factory CoreLParams} {n : String} {fn : LFunc CoreLParams} (h : F[n]? = some fn) :
+ (ds.foldl Core.Decl.addToRuntimeFactory F)[n]? = some fn := by
+ induction ds generalizing F with
+ | nil => exact h
+ | cons d ds ih => exact ih (Core.Decl.addToRuntimeFactory_getElem?_of_some d h)
+
+/-- A name the factory does not resolve is resolved by the declarations as `lookupDecls` says. -/
+theorem foldl_addToRuntimeFactory_getElem?_of_lookupDecls (ds : List Core.Decl)
+ {F : Lambda.Factory CoreLParams} {n : String} {fn : LFunc CoreLParams}
+ (hF : F[n]? = none) (h : lookupDecls n ds = some fn) :
+ (ds.foldl Core.Decl.addToRuntimeFactory F)[n]? = some fn := by
+ induction ds generalizing F with
+ | nil => simp [lookupDecls] at h
+ | cons d ds ih =>
+ simp only [lookupDecls] at h
+ split at h
+ · exact absurd h (by simp)
+ · rename_i hn
+ have hA := addToRuntimeFactory_getElem? d F hn
+ rw [hF, Option.none_or] at hA
+ rw [List.foldl_cons]
+ cases hfind : (declFuncs d).find? (fun f => f.name.name == n) with
+ | none =>
+ rw [hfind] at hA h
+ rw [Option.none_or] at h
+ exact ih hA h
+ | some g =>
+ rw [hfind] at hA h
+ rw [Option.some_or] at h
+ obtain rfl := Option.some.inj h
+ exact foldl_addToRuntimeFactory_getElem?_of_some ds hA
+
+/-- **A declared function, found without running a hash map.** A name that is not a built-in
+resolves, in the factory visible to a procedure, to the first function declared under it. -/
+theorem factoryBeforeProcedure_getElem?_of_lookupDecls (p : Core.Program) (procName : String)
+ {n : String} {fn : LFunc CoreLParams} (hcore : Core.Factory[n]? = none)
+ (h : lookupDecls n (p.declsBeforeProcedure procName) = some fn) :
+ (p.factoryBeforeProcedure procName)[n]? = some fn :=
+ foldl_addToRuntimeFactory_getElem?_of_lookupDecls _ hcore h
+
+/-- A name that is not the name of a built-in function is not resolved by `Core.Factory`. The
+names of the built-in functions are a hypothesis, so that they are computed once. -/
+theorem coreFactory_getElem?_of_not_mem {names : List String}
+ (hnames : (Core.WFFactoryArray.map (·.func)).toList.map (·.name.name) = names)
+ {n : String} (hn : n ∉ names) : Core.Factory[n]? = none := by
+ have hcore : Core.Factory = Lambda.Factory.ofArray (Core.WFFactoryArray.map (·.func)) := rfl
+ rw [hcore, Lambda.Factory.getElem?_ofArray, List.find?_eq_none]
+ intro f hf hfn
+ apply hn
+ rw [← hnames]
+ exact List.mem_map.mpr ⟨f, hf, by simpa using hfn⟩
+
+/-! ## Operators -/
+
+section
+variable {f : Expression.Factory} {σ : CoreStore} {m m' m'' : ExpressionMetadata}
+ {x y : Expression.Expr}
+
+/-! ### Integer arithmetic -/
+
+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)
+
+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)
+
+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)
+
+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)
+
+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)
+
+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)
+
+/-! ### Integer comparisons -/
+
+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)
+
+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)
+
+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)
+
+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)
+
+/-! ### Boolean connectives -/
+
+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)
+
+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)
+
+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 σ
+ (.app m (.app m' (.op m'' ⟨"Bool.Implies", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) x)
+ 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)
+
+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 σ
+ (.app m (.app m' (.op m'' ⟨"Bool.Equiv", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) x)
+ 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)
+
+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)
+
+/-! ### Equality and conditionals -/
+
+theorem eval_eq_int {a b : Int}
+ (hx : LExpr.denoteEval f σ x = some (intVal f a))
+ (hy : LExpr.denoteEval f σ y = some (intVal f b)) :
+ LExpr.denoteEval f σ (.eq m x y) = some (boolVal f (decide (a = b))) :=
+ HoareLift.eval_eq_ints f hx hy
+
+theorem eval_eq_bool {p q : Bool}
+ (hx : LExpr.denoteEval f σ x = some (boolVal f p))
+ (hy : LExpr.denoteEval f σ y = some (boolVal f q)) :
+ LExpr.denoteEval f σ (.eq m x y) = some (boolVal f (decide (p = q))) := by
+ by_cases hpq : p = q
+ · subst hpq
+ simpa using Core.eval_eq_true f hx hy
+ · simpa [hpq] using
+ Core.eval_eq_false f hx hy rfl (fun h => hpq (SemValue.ofBool_injective h))
+
+/-- A conditional with integer branches, folded into one integer so that the condition's
+normalization never reaches the value level. -/
+theorem eval_ite_int {c t e : Expression.Expr} {p : Bool} {a b : Int}
+ (hc : LExpr.denoteEval f σ c = some (boolVal f p))
+ (ht : LExpr.denoteEval f σ t = some (intVal f a))
+ (he : LExpr.denoteEval f σ e = some (intVal f b)) :
+ LExpr.denoteEval f σ (.ite m c t e) = some (intVal f (cond p a b)) := by
+ have h := Core.eval_ite (m := m) f hc ht he rfl
+ cases p <;> exact h
+
+theorem eval_ite_bool {c t e : Expression.Expr} {p q r : Bool}
+ (hc : LExpr.denoteEval f σ c = some (boolVal f p))
+ (ht : LExpr.denoteEval f σ t = some (boolVal f q))
+ (he : LExpr.denoteEval f σ e = some (boolVal f r)) :
+ LExpr.denoteEval f σ (.ite m c t e) = some (boolVal f (cond p q r)) := by
+ have h := Core.eval_ite (m := m) f hc ht he rfl
+ cases p <;> exact h
+
+/-! ## Reading a result -/
+
+/-- An evaluated Boolean is `true`: the comparison the rules state for a guard that holds. -/
+theorem boolVal_eq_tt {p : Bool} : (boolVal f p = Imperative.HasBool.ttVal f) = (p = true) :=
+ propext ⟨fun h => SemValue.ofBool_injective h, fun h => h ▸ rfl⟩
+
+/-- An evaluated Boolean is `false`. -/
+theorem boolVal_eq_ff {p : Bool} : (boolVal f p = Imperative.HasBool.ffVal f) = (p = false) :=
+ propext ⟨fun h => SemValue.ofBool_injective h, fun h => h ▸ rfl⟩
+
+theorem intVal_inj {a b : Int} : (intVal f a = intVal f b) = (a = b) :=
+ propext ⟨fun h => SemValue.ofInt_injective h, fun h => h ▸ rfl⟩
+
+theorem boolVal_inj {p q : Bool} : (boolVal f p = boolVal f q) = (p = q) :=
+ propext ⟨fun h => SemValue.ofBool_injective h, fun h => h ▸ rfl⟩
+
+end
+
+/-! ## Boolean normal forms
+
+`&&`, `||` and `!` of decided propositions are the decision of the connective, so that a guard or
+a clause built from them is read as one proposition. -/
+
+theorem and_decide_eq {p q : Prop} [Decidable p] [Decidable q] :
+ (decide p && decide q) = decide (p ∧ q) := (Bool.decide_and p q).symm
+
+theorem or_decide_eq {p q : Prop} [Decidable p] [Decidable q] :
+ (decide p || decide q) = decide (p ∨ q) := (Bool.decide_or p q).symm
+
+theorem not_decide_eq {p : Prop} [Decidable p] : (!decide p) = decide (¬ p) := decide_not.symm
+
+/-- `==>` lifts to an implication, not to the disjunction its encoding is. -/
+theorem not_or_eq_imp (p q : Prop) : (¬ p ∨ q) = (p → q) :=
+ propext ⟨fun h hp => h.elim (fun hn => absurd hp hn) id,
+ fun h => (Classical.em p).elim (fun hp => .inr (h hp)) .inl⟩
+
+/-- `not_or_eq_imp` for a premise that is a Boolean variable. -/
+theorem eq_false_or_eq_imp (b : Bool) (q : Prop) : (b = false ∨ q) = (b = true → q) := by
+ cases b <;> simp
+
+/-! ## Store updates and projections -/
+
+/-- A slot a block's exit did not drop reads as before the exit. -/
+theorem dropVars_of_not_mem {D : List Expression.Ident} {σ : CoreStore} {x : Expression.Ident}
+ (h : x ∉ D) : Imperative.dropVars D σ x = σ x := by
+ simp [Imperative.dropVars, h]
+
+theorem UpdateState.at_self {σ σ' : CoreStore} {x : Expression.Ident} {v : Expression.Val}
+ (h : Imperative.UpdateState Expression σ x v σ') : σ' x = some v := by
+ cases h with | update _ hnew _ => exact hnew
+
+theorem UpdateState.at_other {σ σ' : CoreStore} {x y : Expression.Ident} {v : Expression.Val}
+ (h : Imperative.UpdateState Expression σ x v σ') (hne : x ≠ y) : σ' y = σ y := by
+ cases h with | update _ _ hrest => exact hrest y hne
+
+/-- A slot the update did not touch, read through to its binding before the update. Unlike
+`at_other`, the right-hand side is the binding itself, so `simp` does not take the lemma for
+a permutation and can rewrite with it whenever the binding is known. -/
+theorem UpdateState.at_other_val {σ σ' : CoreStore} {x y : Expression.Ident}
+ {v w : Expression.Val}
+ (h : Imperative.UpdateState Expression σ x v σ') (hne : x ≠ y) (hy : σ y = some w) :
+ σ' y = some w := by
+ rw [UpdateState.at_other h hne, hy]
+
+theorem InitState.at_self {σ σ' : CoreStore} {x : Expression.Ident} {v : Expression.Val}
+ (h : Imperative.InitState Expression σ x v σ') : σ' x = some v := by
+ cases h with | init _ hnew _ => exact hnew
+
+theorem InitState.at_other {σ σ' : CoreStore} {x y : Expression.Ident} {v : Expression.Val}
+ (h : Imperative.InitState Expression σ x v σ') (hne : x ≠ y) : σ' y = σ y := by
+ cases h with | init _ _ hrest => exact hrest y hne
+
+theorem InitState.at_other_val {σ σ' : CoreStore} {x y : Expression.Ident}
+ {v w : Expression.Val}
+ (h : Imperative.InitState Expression σ x v σ') (hne : x ≠ y) (hy : σ y = some w) :
+ σ' y = some w := by
+ rw [InitState.at_other h hne, hy]
+
+end Strata.Hoare.Eval
+
+end -- public section
diff --git a/StrataBoole/HoareLogic/Hoare/Proj.lean b/StrataBoole/HoareLogic/Hoare/Proj.lean
new file mode 100644
index 0000000..2fedcd5
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Proj.lean
@@ -0,0 +1,446 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+module
+
+public import Strata.DL.Imperative.Logic.HoareTemplate
+import all Strata.DL.Imperative.Logic.HoareTemplate
+
+/-! # Block rules with the projection in the postcondition
+
+`Imperative.Logic.Hoare.block` and `ite` ask for `PostWF`: the postcondition must be stable
+under dropping the names the body declares from the store, since leaving the block drops them.
+For a postcondition a verification-condition generator synthesizes, that stability is a real
+proof obligation about an arbitrary predicate.
+
+The rules here ask for nothing. The body's postcondition is stated at the projected
+environment, `Post { ρ with store := dropVars (Block.definedVars ss true) ρ.store }`, which is
+exactly the environment that leaves the block, so no stability is needed. `PostWF` is traded for
+a store transformer inside the verification conditions, which a lifting reads through as it
+reads through an update. The proofs are those of `block` and `ite` with the stability step
+removed. -/
+
+public section
+
+namespace Strata.Hoare.Proj
+
+open Imperative Imperative.Logic Strata.Logic.Hoare Imperative.Logic.Hoare
+
+variable {P : Imperative.PureExpr}
+variable {conditionInterp : Imperative.ConditionInterp P}
+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 (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`. -/
+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 : 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},
+ evalCmd f σ c σ' emitted → σ y = none →
+ y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none)
+ (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 blockInitEnvWF)
+ conditionInterp bparams Pre ss
+ (projected (Block.definedVars (P := P) (C := CmdT) ss true) Post)) :
+ TripleWith (EventLang.imperativeE P CmdT evalCmd initEnvWF) conditionInterp params
+ Pre (.block l ss md) Post := by
+ 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 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
+ 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 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 : 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},
+ evalCmd f σ c σ' emitted → σ y = none →
+ y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none)
+ (hthenWF : ∀ ρ, initEnvWF params (.ite (.det cond) tss ess md) ρ →
+ blockInitEnvWF bparams tss ρ)
+ (helseWF : ∀ ρ, initEnvWF params (.ite (.det cond) tss ess md) ρ →
+ blockInitEnvWF bparams ess ρ)
+ (hthenDefs : ∀ ρ, initEnvWF params (.ite (.det cond) tss ess md) ρ →
+ ∀ 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 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 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 initEnvWF) conditionInterp params
+ Pre (.ite (.det cond) tss ess md) Post := by
+ 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 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 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 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 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
+
+`if (*)` takes either branch and `while (*)` runs any number of iterations; neither has a guard
+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 : 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},
+ evalCmd f σ c σ' emitted → σ y = none →
+ y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none)
+ (hthenWF : ∀ ρ, initEnvWF params (.ite .nondet tss ess md) ρ →
+ blockInitEnvWF bparams tss ρ)
+ (helseWF : ∀ ρ, initEnvWF params (.ite .nondet tss ess md) ρ →
+ blockInitEnvWF bparams ess ρ)
+ (hthenDefs : ∀ ρ, initEnvWF params (.ite .nondet tss ess md) ρ →
+ ∀ 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 blockInitEnvWF)
+ conditionInterp bparams Pre tss
+ (projected (Block.definedVars (P := P) (C := CmdT) tss true) Post))
+ (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 initEnvWF) conditionInterp params
+ Pre (.ite .nondet tss ess md) Post := by
+ 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 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 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 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 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 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 : 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) (trace : Trace P) (n : Nat)
+ (hInv : Inv ρ₀)
+ (hwf : initEnvWF params (.loop .nondet measure inv body md) ρ₀)
+ (hrunT : ReflTransTraceT (StepStmtE P evalCmd)
+ (.stmt (.loop .nondet measure inv body md) ρ₀) trace (.terminal ρ'))
+ (hlen : hrunT.len ≤ n) :
+ Trace.Reachable P conditionInterp trace → Inv ρ' := by
+ induction n generalizing ρ₀ ρ' trace with
+ | zero =>
+ match hrunT, hlen with
+ | .step _ _ _ _ _ _ _, hlen => simp only [ReflTransTraceT.len] at hlen; omega
+ | succ n ih =>
+ match hrunT, hlen with
+ | .step _ _ _ restTr _ .step_loop_nondet_exit hrest, hlen =>
+ obtain ⟨hc, _⟩ := Imperative.stepStmtStarE_from_terminal (reflTransTraceT_to_prop hrest)
+ injection hc with hρ
+ subst hρ
+ 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 ⟨ρ_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
+ (reflTransTraceT_to_prop h_nil)
+ subst htail_nil
+ have hρx : ρ_x = ρ' := by
+ rcases htail_cfg with hcfg | hcfg
+ · exact absurd hcfg (by simp)
+ · injection hcfg with hρ; exact hρ.symm
+ subst ρ_x
+ simp only [List.append_nil] at htr2
+ rw [htr2] at htr
+ rw [htr]
+ 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 : 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},
+ 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) :
+ TripleWith (EventLang.imperativeE P CmdT evalCmd initEnvWF) conditionInterp params
+ Inv (.loop .nondet measure inv body md) Inv := by
+ 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 _) hreach
+ · exact absurd hexit (exitsCoveredByBlocks_noEscapeE evalCmd
+ (.loop .nondet measure inv body md) hcov ρ₀ lbl ρ')
+
+end Strata.Hoare.Proj
+
+end -- public section
diff --git a/StrataBoole/HoareLogic/Hoare/Rules.lean b/StrataBoole/HoareLogic/Hoare/Rules.lean
new file mode 100644
index 0000000..ef8c51e
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Rules.lean
@@ -0,0 +1,267 @@
+/-
+ 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.LangDefProps
+public import StrataBoole.HoareLogic.Hoare.Proj
+
+/-! # Core Hoare rules beyond `Core.Logic.Hoare`
+
+`Procedure.contractTriple` states a contract as a `Core.Logic.Hoare.Triple`, the judgement the
+rules of `Core.Logic.Hoare` are about, so those rules apply to a contract as they are. This file
+adds the rules they do not cover, for the same judgement:
+
+* `nil`, the empty statement list;
+* `block_proj` and `ite_proj`, the block rules of `StrataBoole/HoareLogic/Hoare/Proj.lean` that
+ carry the store projection in the postcondition instead of asking for `PostWF`;
+* `ite_nondet_proj` and `while_nondet`, for a nondeterministic guard. -/
+
+public section
+
+namespace Strata.Hoare
+
+open Core.Logic
+open Core.Logic.Hoare (Triple)
+
+variable (π : String → Option Core.Procedure) (params : Core.Logic.InitEnvWFParams)
+variable {factory : Lambda.Factory Core.CoreLParams}
+
+/-! ## Structural rules -/
+
+/-- The empty statement list leaves the environment alone. -/
+theorem nil (Pre : Imperative.Env Core.Expression → Prop) :
+ Triple π params Pre [] Pre (factory := factory) :=
+ Imperative.Logic.Hoare.skip_block (Core.EvalCommandE π) Core.Logic.BlockInitEnvWF params Pre
+
+/-- `block` with the projection in the body's postcondition: `Post` is checked at the environment
+with the body's declarations dropped, which is the one leaving the block. -/
+theorem block_proj {ss : Core.Statements} {l : String} {md : Imperative.MetaData Core.Expression}
+ {Pre Post : Imperative.Env Core.Expression → Prop}
+ (h : Triple π params Pre ss
+ (Proj.projected (Imperative.Block.definedVars (P := Core.Expression) (C := Core.Command) ss true)
+ Post) (factory := factory)) :
+ Triple π params Pre [.block l ss md] Post (factory := factory) :=
+ Imperative.Logic.Hoare.singleton (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun _ hb => blockInitEnvWF_singleton hb)
+ (Proj.block_proj (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun he hn hnd => Core.evalCommandE_preserves_none_of_not_def π he hn hnd)
+ (fun _ hb => blockInitEnvWF_of_block hb)
+ (fun _ hb => blockInitEnvWF_bodyDefsUndefined (blockInitEnvWF_of_block hb))
+ h)
+
+/-- `ite` with the projection in each branch's postcondition. -/
+theorem ite_proj {cond : Core.Expression.Expr} {tss ess : Core.Statements}
+ {md : Imperative.MetaData Core.Expression}
+ {Pre Post : Imperative.Env Core.Expression → Prop}
+ (ht : Triple π params
+ (fun ρ => Pre ρ ∧
+ Core.Expression.eval ρ.factory ρ.store cond = some (Imperative.HasBool.ttVal ρ.factory))
+ tss (Proj.projected
+ (Imperative.Block.definedVars (P := Core.Expression) (C := Core.Command) tss true) Post)
+ (factory := factory))
+ (he : Triple π params
+ (fun ρ => Pre ρ ∧
+ Core.Expression.eval ρ.factory ρ.store cond = some (Imperative.HasBool.ffVal ρ.factory))
+ ess (Proj.projected
+ (Imperative.Block.definedVars (P := Core.Expression) (C := Core.Command) ess true) Post)
+ (factory := factory)) :
+ Triple π params Pre [.ite (.det cond) tss ess md] Post (factory := factory) :=
+ Imperative.Logic.Hoare.singleton (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun _ hb => blockInitEnvWF_singleton hb)
+ (Proj.ite_proj (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun he hn hnd => Core.evalCommandE_preserves_none_of_not_def π he hn hnd)
+ (fun _ hb => blockInitEnvWF_of_ite_then hb)
+ (fun _ hb => blockInitEnvWF_of_ite_else hb)
+ (fun _ hb => blockInitEnvWF_bodyDefsUndefined (blockInitEnvWF_of_ite_then hb))
+ (fun _ hb => blockInitEnvWF_bodyDefsUndefined (blockInitEnvWF_of_ite_else hb))
+ ht he)
+
+/-! ## Nondeterministic branches and loops
+
+The well-formedness lemmas of `Core.Logic` are stated for a deterministic guard. A
+nondeterministic guard puts no variable and no operator into the def-use check, so the same
+proofs go through at `.nondet`. -/
+
+theorem blockInitEnvWF_of_ite_then_nondet {params : InitEnvWFParams}
+ {tss ess : Core.Statements} {md : Imperative.MetaData Core.Expression}
+ {ρ : Imperative.Env Core.Expression}
+ (h : InitEnvWF params (.ite .nondet tss ess md) ρ) : BlockInitEnvWF params tss ρ := by
+ have hdu := h.defUseOk
+ have hdefs := h.defsUndefined
+ have hdnr := h.definedVarsNotReserved
+ simp only [Imperative.Stmt.defUseWellFormed, Bool.and_eq_true] at hdu
+ simp only [Imperative.Stmt.definedVars, Bool.false_eq_true, ite_false] at hdefs hdnr
+ exact BlockInitEnvWF.of_defUseOk h.toWellFormedSemanticEval h.storeWellDefined
+ (fun n hn => hdefs n (List.mem_append.mpr (Or.inl hn)))
+ (fun n hn => hdnr n (List.mem_append.mpr (Or.inl hn)))
+ 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 h.runtimeFactoryDeclared
+ (fun ty hty => h.initTypesInhabited ty
+ (by simp only [Imperative.Stmt.initTypes]; exact List.mem_append.mpr (Or.inl hty)))
+ (by
+ obtain ⟨Γ, hσ, hw⟩ := h.fvarTypesOk
+ simp only [Imperative.Stmt.fvarTypesWellAnnotated] at hw
+ exact ⟨Γ, hσ, hw.2.1⟩)
+ (fun m hm => h.measuresTyped m
+ (by simp only [Imperative.Stmt.measures]; exact List.mem_append.mpr (Or.inl hm)))
+
+theorem blockInitEnvWF_of_ite_else_nondet {params : InitEnvWFParams}
+ {tss ess : Core.Statements} {md : Imperative.MetaData Core.Expression}
+ {ρ : Imperative.Env Core.Expression}
+ (h : InitEnvWF params (.ite .nondet tss ess md) ρ) : BlockInitEnvWF params ess ρ := by
+ have hdu := h.defUseOk
+ have hdefs := h.defsUndefined
+ have hdnr := h.definedVarsNotReserved
+ simp only [Imperative.Stmt.defUseWellFormed, Bool.and_eq_true] at hdu
+ simp only [Imperative.Stmt.definedVars, Bool.false_eq_true, ite_false] at hdefs hdnr
+ exact BlockInitEnvWF.of_defUseOk h.toWellFormedSemanticEval h.storeWellDefined
+ (fun n hn => hdefs n (List.mem_append.mpr (Or.inr hn)))
+ (fun n hn => hdnr n (List.mem_append.mpr (Or.inr hn)))
+ 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 h.runtimeFactoryDeclared
+ (fun ty hty => h.initTypesInhabited ty
+ (by simp only [Imperative.Stmt.initTypes]; exact List.mem_append.mpr (Or.inr hty)))
+ (by
+ obtain ⟨Γ, hσ, hw⟩ := h.fvarTypesOk
+ simp only [Imperative.Stmt.fvarTypesWellAnnotated] at hw
+ exact ⟨Γ, hσ, hw.2.2⟩)
+ (fun m hm => h.measuresTyped m
+ (by simp only [Imperative.Stmt.measures]; exact List.mem_append.mpr (Or.inr hm)))
+
+theorem blockInitEnvWF_of_loop_body_nondet {params : InitEnvWFParams}
+ {m : Option Core.Expression.Expr} {inv : List (String × Core.Expression.Expr)}
+ {body : Core.Statements} {md : Imperative.MetaData Core.Expression}
+ {ρ : Imperative.Env Core.Expression}
+ (h : InitEnvWF params (.loop .nondet m inv body md) ρ) : BlockInitEnvWF params body ρ := by
+ have hdu := h.defUseOk
+ have hdefs := h.defsUndefined
+ have hdnr := h.definedVarsNotReserved
+ simp only [Imperative.Stmt.defUseWellFormed, Bool.and_eq_true] at hdu
+ simp only [Imperative.Stmt.definedVars, Bool.false_eq_true, ite_false] at hdefs hdnr
+ 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 h.runtimeFactoryDeclared
+ (fun ty hty => h.initTypesInhabited ty (by simp only [Imperative.Stmt.initTypes]; exact hty))
+ (by
+ obtain ⟨Γ, hσ, hw⟩ := h.fvarTypesOk
+ simp only [Imperative.Stmt.fvarTypesWellAnnotated] at hw
+ exact ⟨Γ, hσ, hw.2.2.2⟩)
+ (fun m' hm => h.measuresTyped m'
+ (by simp only [Imperative.Stmt.measures]; exact List.mem_append.mpr (Or.inr hm)))
+
+theorem initEnvWF_loop_iterateE_nondet {params : InitEnvWFParams}
+ {m : Option Core.Expression.Expr} {inv : List (String × Core.Expression.Expr)}
+ {body : Core.Statements} {md : Imperative.MetaData Core.Expression}
+ {ρ ρ_inner : Imperative.Env Core.Expression} {tr : Imperative.Trace Core.Expression}
+ (h : InitEnvWF params (.loop .nondet m inv body md) ρ)
+ (hrun : Imperative.StepStmtStarE Core.Expression (Core.EvalCommandE π)
+ (.stmts body ρ) tr (.terminal ρ_inner)) :
+ InitEnvWF params (.loop .nondet m inv body md)
+ { ρ_inner with store := Imperative.projectStore ρ.store ρ_inner.store } := by
+ have hstore : ∀ n, ((Imperative.projectStore ρ.store ρ_inner.store) n).isSome
+ = (ρ.store n).isSome := by
+ intro n
+ by_cases hn : (ρ.store n).isSome = Bool.true
+ · simp only [Imperative.projectStore, hn, ite_true]
+ exact Core.core_stmts_preserves_isSomeE π hrun hn
+ · have hnone : ρ.store n = none := by
+ cases hq : ρ.store n with
+ | none => rfl
+ | some v => rw [hq] at hn; simp at hn
+ simp [Imperative.projectStore, hnone]
+ have hfun : (fun n => ((Imperative.projectStore ρ.store ρ_inner.store) n).isSome)
+ = (fun n => (ρ.store n).isSome) := funext hstore
+ have hfac : ρ.factory = ρ_inner.factory := Imperative.starE_preserves_factory hrun
+ have hproj : Imperative.WellFormedStore (Imperative.projectStore ρ.store ρ_inner.store)
+ ρ_inner.factory := by
+ have hpres : ∀ {f : Core.Expression.Factory} {σ σ' : Core.CoreStore} {c : Core.Command}
+ {emitted : Imperative.Trace Core.Expression},
+ Core.EvalCommandE π f σ c σ' emitted →
+ Imperative.WellFormedStore σ f → Imperative.WellFormedStore σ' f :=
+ fun hc hs => Core.evalCommandE_storeWellDefined π hc hs
+ have hinner : Imperative.WellFormedStore ρ_inner.store ρ_inner.factory :=
+ Imperative.Config.storeWellDefined_star_ofE (EvalCmd := Core.EvalCommandE π) hpres
+ hrun h.storeWellDefined
+ intro x w hx
+ simp only [Imperative.projectStore] at hx
+ split at hx
+ · exact hinner x w hx
+ · 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.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 ⊢
+ simp [Imperative.projectStore, hdef]
+ · exact h.reservedFresh n (by rw [← hstore n]; exact hn)
+ · show Imperative.Stmt.defUseWellFormed
+ (fun n => ((Imperative.projectStore ρ.store ρ_inner.store) n).isSome) params.declaredFuncs _
+ = Bool.true
+ rw [hfun]; exact h.defUseOk
+ · obtain ⟨Γ, hσ, hw⟩ := h.fvarTypesOk
+ refine ⟨Γ, fun y ty hy => ?_, hw⟩
+ have hsome : (ρ.store y).isSome = Bool.true := by
+ obtain ⟨w, hw', _⟩ := hσ y ty hy
+ simp [hw']
+ obtain ⟨v, hv, hvt⟩ := Core.core_stmts_preserves_typedAtE π hrun (hσ y ty hy)
+ exact ⟨v, by simp [Imperative.projectStore, hsome, hv], hvt⟩
+
+/-- `if (*)` with the projection in each branch's postcondition. -/
+theorem ite_nondet_proj {tss ess : Core.Statements} {md : Imperative.MetaData Core.Expression}
+ {Pre Post : Imperative.Env Core.Expression → Prop}
+ (ht : Triple π params Pre tss (Proj.projected
+ (Imperative.Block.definedVars (P := Core.Expression) (C := Core.Command) tss true) Post)
+ (factory := factory))
+ (he : Triple π params Pre ess (Proj.projected
+ (Imperative.Block.definedVars (P := Core.Expression) (C := Core.Command) ess true) Post)
+ (factory := factory)) :
+ Triple π params Pre [.ite .nondet tss ess md] Post (factory := factory) :=
+ Imperative.Logic.Hoare.singleton (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun _ hb => blockInitEnvWF_singleton hb)
+ (Proj.ite_nondet_proj (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun he hn hnd => Core.evalCommandE_preserves_none_of_not_def π he hn hnd)
+ (fun _ hb => blockInitEnvWF_of_ite_then_nondet hb)
+ (fun _ hb => blockInitEnvWF_of_ite_else_nondet hb)
+ (fun _ hb => blockInitEnvWF_bodyDefsUndefined (blockInitEnvWF_of_ite_then_nondet hb))
+ (fun _ hb => blockInitEnvWF_bodyDefsUndefined (blockInitEnvWF_of_ite_else_nondet hb))
+ ht he)
+
+/-- `while (*)`: the invariant is preserved by the body and is all that is known at the exit. -/
+theorem while_nondet {measure : Option Core.Expression.Expr}
+ {inv : List (String × Core.Expression.Expr)} {body : Core.Statements}
+ {md : Imperative.MetaData Core.Expression} {Inv : Imperative.Env Core.Expression → Prop}
+ (hbody : Triple π params Inv body Inv (factory := factory))
+ (hcov : Imperative.Block.exitsCoveredByBlocks
+ (P := Core.Expression) (CmdT := Core.Command) [] body)
+ (hInv_proj : Imperative.Logic.Hoare.PostWF body Inv) :
+ Triple π params Inv [.loop .nondet measure inv body md] Inv (factory := factory) :=
+ Imperative.Logic.Hoare.singleton (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun _ hb => blockInitEnvWF_singleton hb)
+ (Proj.while_nondet (Core.EvalCommandE π)
+ Core.Logic.InitEnvWF Core.Logic.BlockInitEnvWF params params
+ (fun he hn hnd => Core.evalCommandE_preserves_none_of_not_def π he hn hnd)
+ (fun _ hl => blockInitEnvWF_bodyDefsUndefined (blockInitEnvWF_of_loop_body_nondet hl))
+ (fun _ hl => blockInitEnvWF_of_loop_body_nondet hl)
+ (fun _ _ _ hl hr => initEnvWF_loop_iterateE_nondet π hl hr)
+ hbody hcov hInv_proj)
+
+end Strata.Hoare
+
+end -- public section
diff --git a/StrataBoole/HoareLogic/Hoare/Tactic.lean b/StrataBoole/HoareLogic/Hoare/Tactic.lean
new file mode 100644
index 0000000..2377911
--- /dev/null
+++ b/StrataBoole/HoareLogic/Hoare/Tactic.lean
@@ -0,0 +1,1889 @@
+/-
+ Copyright Strata Contributors
+
+ SPDX-License-Identifier: Apache-2.0 OR MIT
+-/
+import Lean
+import StrataBoole.HoareLogic.Hoare.Contract
+import StrataBoole.HoareLogic.Hoare.Call
+import StrataBoole.HoareLogic.Lift.Names
+
+/-! # The tactics
+
+* `hoare_wp` walks a statement list with the `wp`-form rules, synthesizing every intermediate
+ assertion by unification and discharging the structural side conditions (the declared names,
+ the write set, `exitsCoveredByBlocks`) on the concrete AST. At a `while` it builds the
+ invariant predicate from the program's `invariant` clauses and reads the body's write set
+ (`hoare_loop`); the body is verified under its entry store. It stops at a statement no rule
+ covers, leaving that goal open.
+* `hoare_contract` opens `Procedure.contractTriple`: the runtime factory `F` of the entry, the
+ two blocks around the body, then `hoare_wp`, so that what is left is the implication from
+ `entryPre` to the synthesized precondition, which contains the preservation and exit
+ obligations of each loop at the loop's entry.
+* `hoare_vcs` introduces that implication statement by statement, opens each loop obligation it
+ meets (`hoare_open_loop`) and splits the conjunctions the rules leave, so that each
+ verification condition is its own goal with the run's store facts as hypotheses; a variable
+ the loop does not write is read through the agreement with the entry store (`hagree`).
+* `hoare_lift` evaluates the stores and reads the conditions, leaving goals over `Int` and
+ `Bool`.
+
+Typical use: `hoare_contract <;> hoare_vcs <;> hoare_lift <;> omega`.
+
+The names in the goals come from the program: `hoare_typed` introduces each integer or Boolean
+variable as an `Int` or a `Bool` named like the variable, `hoare_requires` and
+`hoare_invariants` lift each clause into a hypothesis named after its label, and the goal tags
+read `then.