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.

_ast : Core.Program` when `p` is an identifier, and every procedure as +`_ast : Core.Procedure`. Statements about a procedure, such as its contract triple, are +made on these definitions; the program literal carries the functions, axioms and type +declarations the procedure's names refer to. -/ + +open Lean Elab Command + +namespace Strata.Reflect + +syntax (name := booleReflect) "boole_reflect " term : command + +@[command_elab booleReflect] def elabBooleReflect : CommandElab := fun stx => do + let `(boole_reflect $t:term) := stx | throwUnsupportedSyntax + let prog ← liftTermElabM (evalProgram t) + let ns ← getCurrNamespace + if let `($x:ident) := t then + let pgmName := ns ++ Name.mkSimple s!"{x.getId.eraseMacroScopes.getString!}_ast" + liftTermElabM (addProgramAst pgmName prog) + else + logWarning "boole_reflect: the program is bound as a whole only when the argument is an \ + identifier; its procedures are bound either way" + for d in prog.decls do + if let .proc p _ := d then + let astName := ns ++ Name.mkSimple s!"{p.header.name.name}_ast" + liftTermElabM (addProcedureAst astName p) + +end Strata.Reflect diff --git a/StrataBoole/HoareLogic/Reflect/Core.lean b/StrataBoole/HoareLogic/Reflect/Core.lean new file mode 100644 index 0000000..ee64b7b --- /dev/null +++ b/StrataBoole/HoareLogic/Reflect/Core.lean @@ -0,0 +1,264 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Lean +import Strata.Languages.Core.DDMTransform.Translate +import Strata.Languages.Core.Verifier + +/-! # Core programs as Lean terms + +`core_reflect prog` takes a program `prog` written in Core syntax +(`def prog := #strata program Core; … #end`). At elaboration time it runs Strata's Core +translator and type checker on it, and defines ` : Core.Procedure` in the current +namespace for each procedure ``. The value of that definition is the translated AST, +written out as a term, so that the procedure's statements and expressions are visible to +`rfl`, `simp` and the rules, which the result of `translateProgram` is not: the translation is +built from `partial` definitions and never reduces. The definition is reducible, so that +tactics see through the name without being told it. + +The AST is the *type-checked* program, the one Core's verifier works on. Type checking also +annotates every variable and operator with its type, which the typing witnesses of the +denotational reading require. + +Statement metadata is replaced by `MetaData.empty` and the source location of every expression +by `Core.valueLoc`: evaluation reads neither (`Core.Expression.eval_eraseLocs`). Type +declarations and CFG bodies are rejected. + +This file is not a `module`, so its elaborator needs no `meta` phase annotations. A file that +uses `core_reflect` imports it as an ordinary file. -/ + +namespace Strata.CoreReflect + +open Lean Elab Command Meta + +/-- Run Strata's Core translator and type checker, reporting their errors. -/ +def translateCore (p : StrataDDM.Program) : Except String Core.Program := + let (prog, errs) := TransM.run Inhabited.default (translateProgram p) + if errs.isEmpty then + match Core.typeCheck { Core.VerifyOptions.default with verbose := .quiet } prog with + | .ok prog => .ok prog + | .error msg => .error s!"type checking failed: {msg}" + else .error (String.intercalate "\n" errs.toList) + +/-! ## Building terms -/ + +/-- The implicit arguments every AST constructor takes. -/ +structure Ctx where + /-- The `LExprParamsT` of `Core.Expression.Expr`. -/ + T : Lean.Expr + /-- `Core.Expression`. -/ + P : Lean.Expr + /-- `Core.Command`. -/ + C : Lean.Expr + +def mkCtx : MetaM Ctx := do + let P := mkConst ``Core.Expression + let exprTy ← whnfR (mkApp (mkConst ``Imperative.PureExpr.Expr [Level.one]) P) + let some T := exprTy.app1? ``Lambda.LExpr + | throwError "core_reflect: unexpected shape of Core.Expression.Expr: {exprTy}" + return { T, P, C := mkConst ``Core.Command } + +def mkList (ty : Lean.Expr) (xs : List Lean.Expr) : Lean.Expr := + xs.foldr (fun x acc => mkApp3 (mkConst ``List.cons [0]) ty x acc) + (mkApp (mkConst ``List.nil [0]) ty) + +def mkOption (ty : Lean.Expr) : Option Lean.Expr → Lean.Expr + | none => mkApp (mkConst ``Option.none [0]) ty + | some e => mkApp2 (mkConst ``Option.some [0]) ty e + +def mkPair (α β a b : Lean.Expr) : Lean.Expr := mkApp4 (mkConst ``Prod.mk [0, 0]) α β a b + +def mkProd (α β : Lean.Expr) : Lean.Expr := mkApp2 (mkConst ``Prod [0, 0]) α β + +def unitE : Lean.Expr := mkConst ``Unit.unit +/-- The location every reflected expression gets. -/ +def locE : Lean.Expr := mkConst ``Core.valueLoc +def stringTy : Lean.Expr := mkConst ``String +def monoTyTy : Lean.Expr := mkConst ``Lambda.LMonoTy +def identTy : Lean.Expr := mkApp (mkConst ``Lambda.Identifier) (mkConst ``Unit) + +def identE (x : Lambda.Identifier Unit) : Lean.Expr := + mkApp3 (mkConst ``Lambda.Identifier.mk) (mkConst ``Unit) (toExpr x.name) unitE + +partial def monoTyE : Lambda.LMonoTy → Lean.Expr + | .ftvar n => mkApp (mkConst ``Lambda.LMonoTy.ftvar) (toExpr n) + | .tcons n args => + mkApp2 (mkConst ``Lambda.LMonoTy.tcons) (toExpr n) (mkList monoTyTy (args.map monoTyE)) + | .bitvec n => mkApp (mkConst ``Lambda.LMonoTy.bitvec) (toExpr n) + +def lTyTy : Lean.Expr := mkConst ``Lambda.LTy + +def lTyE : Lambda.LTy → Lean.Expr + | .forAll vs ty => + mkApp2 (mkConst ``Lambda.LTy.forAll) (mkList stringTy (vs.map toExpr)) (monoTyE ty) + +partial def sortE : Lambda.LSort → Lean.Expr + | .tcons n args => + mkApp2 (mkConst ``Lambda.LSort.tcons) (toExpr n) (mkList (mkConst ``Lambda.LSort) (args.map sortE)) + | .bitvec n => mkApp (mkConst ``Lambda.LSort.bitvec) (toExpr n) + +def mkArray (ty : Lean.Expr) (xs : List Lean.Expr) : Lean.Expr := + mkApp2 (mkConst ``List.toArray [0]) ty (mkList ty xs) + +partial def constE : Lambda.LConst → Lean.Expr + | .intConst i => mkApp (mkConst ``Lambda.LConst.intConst) (toExpr i) + | .strConst s => mkApp (mkConst ``Lambda.LConst.strConst) (toExpr s) + | .rationalConst r => + mkApp (mkConst ``Lambda.LConst.rationalConst) + (mkApp2 (mkConst ``Rat.divInt) (toExpr r.num) (toExpr (r.den : Int))) + | .bitvecConst n b => mkApp2 (mkConst ``Lambda.LConst.bitvecConst) (toExpr n) (toExpr b) + | .boolConst b => mkApp (mkConst ``Lambda.LConst.boolConst) (toExpr b) + | .mapConst k v d es => + let cTy := mkConst ``Lambda.LConst + mkApp4 (mkConst ``Lambda.LConst.mapConst) (sortE k) (sortE v) (constE d) + (mkArray (mkProd cTy cTy) (es.toList.map fun (a, b) => mkPair cTy cTy (constE a) (constE b))) + | .sequenceConst s es => + mkApp2 (mkConst ``Lambda.LConst.sequenceConst) (sortE s) + (mkArray (mkConst ``Lambda.LConst) (es.toList.map constE)) + +def quantE : Lambda.QuantifierKind → Lean.Expr + | .all => mkConst ``Lambda.QuantifierKind.all + | .exist => mkConst ``Lambda.QuantifierKind.exist + +def optTyE (ty : Option Lambda.LMonoTy) : Lean.Expr := mkOption monoTyTy (ty.map monoTyE) + +partial def exprE (c : Ctx) : Core.Expression.Expr → Lean.Expr + | .const _ k => mkApp3 (mkConst ``Lambda.LExpr.const) c.T locE (constE k) + | .op _ o ty => mkApp4 (mkConst ``Lambda.LExpr.op) c.T locE (identE o) (optTyE ty) + | .bvar _ i => mkApp3 (mkConst ``Lambda.LExpr.bvar) c.T locE (toExpr i) + | .fvar _ x ty => mkApp4 (mkConst ``Lambda.LExpr.fvar) c.T locE (identE x) (optTyE ty) + | .abs _ n ty e => + mkApp5 (mkConst ``Lambda.LExpr.abs) c.T locE (toExpr n) (optTyE ty) (exprE c e) + | .quant _ k n ty tr e => + mkAppN (mkConst ``Lambda.LExpr.quant) + #[c.T, locE, quantE k, toExpr n, optTyE ty, exprE c tr, exprE c e] + | .app _ f a => mkApp4 (mkConst ``Lambda.LExpr.app) c.T locE (exprE c f) (exprE c a) + | .ite _ x y z => + mkApp5 (mkConst ``Lambda.LExpr.ite) c.T locE (exprE c x) (exprE c y) (exprE c z) + | .eq _ a b => mkApp4 (mkConst ``Lambda.LExpr.eq) c.T locE (exprE c a) (exprE c b) + +def exprTy (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.PureExpr.Expr [Level.one]) c.P + +def mdE (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.MetaData.empty [Level.one]) c.P + +def eonE (c : Ctx) : Imperative.ExprOrNondet Core.Expression → Lean.Expr + | .det e => mkApp2 (mkConst ``Imperative.ExprOrNondet.det [Level.one]) c.P (exprE c e) + | .nondet => mkApp (mkConst ``Imperative.ExprOrNondet.nondet [Level.one]) c.P + +def cmdE (c : Ctx) : Imperative.Cmd Core.Expression → Lean.Expr + | .init x ty e _ => + mkApp5 (mkConst ``Imperative.Cmd.init [Level.one]) c.P (identE x) (lTyE ty) (eonE c e) (mdE c) + | .set x e _ => mkApp4 (mkConst ``Imperative.Cmd.set [Level.one]) c.P (identE x) (eonE c e) (mdE c) + | .assert l e _ => + mkApp4 (mkConst ``Imperative.Cmd.assert [Level.one]) c.P (toExpr l) (exprE c e) (mdE c) + | .assume l e _ => + mkApp4 (mkConst ``Imperative.Cmd.assume [Level.one]) c.P (toExpr l) (exprE c e) (mdE c) + | .cover l e _ => + mkApp4 (mkConst ``Imperative.Cmd.cover [Level.one]) c.P (toExpr l) (exprE c e) (mdE c) + +def callArgE (c : Ctx) : Imperative.CallArg Core.Expression → Lean.Expr + | .inArg e => mkApp2 (mkConst ``Imperative.CallArg.inArg [Level.one]) c.P (exprE c e) + | .inoutArg x => mkApp2 (mkConst ``Imperative.CallArg.inoutArg [Level.one]) c.P (identE x) + | .outArg x => mkApp2 (mkConst ``Imperative.CallArg.outArg [Level.one]) c.P (identE x) + +def commandE (c : Ctx) : Core.Command → Lean.Expr + | .cmd k => mkApp2 (mkConst ``Imperative.CmdExt.cmd [Level.one]) c.P (cmdE c k) + | .call p tys args _ => + mkApp5 (mkConst ``Imperative.CmdExt.call [Level.one]) c.P (toExpr p) + (mkOption (mkApp (mkConst ``List [Level.zero]) lTyTy) (tys.map fun ts => mkList lTyTy (ts.map lTyE))) + (mkList (mkApp (mkConst ``Imperative.CallArg [Level.one]) c.P) (args.map (callArgE c))) (mdE c) + +mutual +partial def stmtE (c : Ctx) : Core.Statement → Except String Lean.Expr + | .cmd k => pure <| mkApp3 (mkConst ``Imperative.Stmt.cmd [Level.one]) c.P c.C (commandE c k) + | .block l b _ => do + pure <| mkApp5 (mkConst ``Imperative.Stmt.block [Level.one]) c.P c.C (toExpr l) (← stmtsE c b) (mdE c) + | .ite g t f _ => do + pure <| mkAppN (mkConst ``Imperative.Stmt.ite [Level.one]) + #[c.P, c.C, eonE c g, ← stmtsE c t, ← stmtsE c f, mdE c] + | .loop g m invs b _ => do + let invTy := mkProd stringTy (exprTy c) + let invsE := mkList invTy (invs.map fun (l, e) => mkPair stringTy (exprTy c) (toExpr l) (exprE c e)) + pure <| mkAppN (mkConst ``Imperative.Stmt.loop [Level.one]) + #[c.P, c.C, eonE c g, mkOption (exprTy c) (m.map (exprE c)), invsE, ← stmtsE c b, mdE c] + | .exit l _ => pure <| mkApp4 (mkConst ``Imperative.Stmt.exit [Level.one]) c.P c.C (toExpr l) (mdE c) + | .typeDecl _ _ => throw "type declarations are not supported" + +partial def stmtsE (c : Ctx) (ss : List Core.Statement) : Except String Lean.Expr := do + return mkList (mkApp2 (mkConst ``Imperative.Stmt [Level.one]) c.P c.C) (← ss.mapM (stmtE c)) +end + +def checkE (c : Ctx) (ch : Imperative.Check Core.Expression) : Lean.Expr := + let attr := match ch.attr with + | .Free => mkConst ``Imperative.CheckAttr.Free + | .Default => mkConst ``Imperative.CheckAttr.Default + mkApp4 (mkConst ``Imperative.Check.mk [Level.one]) c.P (exprE c ch.expr) attr (mdE c) + +def specE (c : Ctx) (s : Imperative.Spec Core.Expression) : Lean.Expr := + let checkTy := mkApp (mkConst ``Imperative.Check [Level.one]) c.P + let clauses (cs : ListMap String (Imperative.Check Core.Expression)) := + mkList (mkProd stringTy checkTy) + (cs.toList.map fun (l, ch) => mkPair stringTy checkTy (toExpr l) (checkE c ch)) + mkApp3 (mkConst ``Imperative.Spec.mk [Level.one]) c.P (clauses s.preconditions) (clauses s.postconditions) + +def sigE (sig : @Lambda.LMonoTySignature Unit) : Lean.Expr := + mkList (mkProd identTy monoTyTy) + (sig.toList.map fun (x, ty) => mkPair identTy monoTyTy (identE x) (monoTyE ty)) + +def headerE (h : Core.Procedure.Header) : Lean.Expr := + mkApp5 (mkConst ``Core.Procedure.Header.mk) (identE h.name) + (mkList stringTy (h.typeArgs.map toExpr)) (sigE h.inputs) (sigE h.outputs) + (mkList stringTy (h.lemmas.map toExpr)) + +def procedureE (c : Ctx) (p : Core.Procedure) : MetaM Lean.Expr := do + let body ← match p.body with + | .structured ss opq => + match stmtsE c ss with + | .ok e => pure (mkApp4 (mkConst ``Imperative.Body.structured [Level.one]) c.P c.C e (toExpr opq)) + | .error msg => throwError "core_reflect: procedure {p.header.name.name}: {msg}" + | .cfg _ _ => throwError "core_reflect: procedure {p.header.name.name} has a CFG body" + | .abstract => pure (mkApp2 (mkConst ``Imperative.Body.abstract [Level.one]) c.P c.C) + mkAppM ``Imperative.Procedure.mk #[headerE p.header, specE c p.spec, body] + +/-! ## The command -/ + +/-- Translate `prog`. The call is elaborated from syntax, so that `#strata`'s +`SourcedProgram` is coerced to the `Program` the translator expects. -/ +unsafe def evalTranslateUnsafe (prog : Name) : TermElabM (Except String Core.Program) := do + let ty := mkApp2 (mkConst ``Except [0, 0]) stringTy (mkConst ``Core.Program) + let e ← Term.elabTermEnsuringType (← `(translateCore $(mkIdent prog))) ty + Term.synthesizeSyntheticMVarsNoPostponing + Meta.evalExpr (Except String Core.Program) ty (← instantiateMVars e) + +@[implemented_by evalTranslateUnsafe] +opaque evalTranslate (prog : Name) : TermElabM (Except String Core.Program) + +/-- `core_reflect prog` defines ` : Core.Procedure` in the current namespace for +each procedure `` of the Core program `prog`, with the translated AST as its +value. -/ +syntax (name := coreReflect) "core_reflect " ident : command + +@[command_elab coreReflect] def elabCoreReflect : CommandElab := fun stx => do + let prog ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo stx[1] + let pgm ← match ← liftTermElabM (evalTranslate prog) with + | .ok pgm => pure pgm + | .error msg => throwError "core_reflect: {msg}" + let ctx ← liftTermElabM mkCtx + for d in pgm.decls do + let .proc p _ := d | continue + let value ← liftTermElabM (procedureE ctx p) + let name := (← getCurrNamespace) ++ .mkSimple p.header.name.name + liftTermElabM <| do + let type := mkConst ``Core.Procedure + check value + unless ← isDefEq (← inferType value) type do + throwError "core_reflect: the term for {name} does not have type Core.Procedure" + liftCoreM <| addDecl <| .defnDecl { + name, levelParams := [], type := mkConst ``Core.Procedure, value, + hints := .abbrev, safety := .safe } + liftCoreM <| setReducibilityStatus name .reducible + logInfo m!"defined {name} : Core.Procedure" + +end Strata.CoreReflect diff --git a/StrataBoole/HoareLogic/Reflect/ToExpr.lean b/StrataBoole/HoareLogic/Reflect/ToExpr.lean new file mode 100644 index 0000000..65e5cef --- /dev/null +++ b/StrataBoole/HoareLogic/Reflect/ToExpr.lean @@ -0,0 +1,249 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Verify + +/-! # Reflection: a type-checked Core procedure as a Lean term + +`boole_reflect` obtains the Core program by *running* `Strata.Boole.typeCheck` at elaboration +time. That result is a value in the elaborator's memory, not a term the kernel can compute +with: the lowering is built from `partial` definitions, so `typeCheck p` never reduces. To +state and prove anything about the program, each procedure is turned back into a closed term +made of constructors and literals (`ToExpr`) and bound to a definition +`_ast : Core.Procedure`; the whole program is bound as well, since its functions, axioms +and type declarations give the procedure's names their meaning. On these definitions `rfl`, +`simp` and `decide` work by structural reduction. + +Leaf types derive `ToExpr`. The types parametrised by `PureExpr` or `LExprParamsT` cannot be +derived (the parameter is a bundle of `Type`s, not a `Type`), so their instances are written +for the Core instantiation `Core.Expression`. -/ + +open Lean Meta +open Lambda Imperative + +namespace Strata.Reflect + +/-! ## Leaves -/ + +deriving instance ToExpr for Lambda.QuantifierKind +deriving instance ToExpr for Lambda.LMonoTy +deriving instance ToExpr for Lambda.LTy +deriving instance ToExpr for Lambda.LSort +deriving instance ToExpr for Lambda.LConst +deriving instance ToExpr for Lambda.Identifier +deriving instance ToExpr for Imperative.CheckAttr +deriving instance ToExpr for Boundedness +deriving instance ToExpr for TypeConstructor +deriving instance ToExpr for Strata.SynthesizedOrigin +deriving instance ToExpr for Strata.Uri +deriving instance ToExpr for StrataDDM.SourceRange +deriving instance ToExpr for Strata.Provenance +deriving instance ToExpr for ExprSourceLoc + +/-- `ListMap` is a definition, not an abbreviation, so the `List` instance is not found +through it. -/ +instance {α β : Type} [ToExpr α] [ToExpr β] : ToExpr (ListMap α β) := + inferInstanceAs (ToExpr (List (α × β))) + +deriving instance ToExpr for Core.Procedure.Header + +/-! ## The Core instantiation + +The implicit parameters every constructor takes, as terms. -/ + +/-- `Core.Expression : PureExpr`. -/ +def pureExprE : Expr := mkConst ``Core.Expression +/-- `Core.Command`, the command type of Core statements. -/ +def cmdE : Expr := mkConst ``Core.Command +/-- `Core.CoreLParams.mono : LExprParamsT`, the parameters of Core's `LExpr`. -/ +def lparamsE : Expr := mkApp (mkConst ``Lambda.LExprParams.mono) (mkConst ``Core.CoreLParams) + +/-- The source location of an expression. `Core.valueLoc`, the location every expression has +once its locations are erased, is written as that constant, which keeps the terms small. -/ +def locE (m : Core.ExpressionMetadata) : Expr := + if m = Core.valueLoc then mkConst ``Core.valueLoc else toExpr m + +/-- Core identifiers (`Lambda.Identifier Unit`). -/ +def identE (x : Core.CoreIdent) : Expr := toExpr x + +/-- Expressions. -/ +def exprE : Core.Expression.Expr → Expr + | .const m c => mkApp3 (mkConst ``LExpr.const) lparamsE (locE m) (toExpr c) + | .op m o ty => mkApp4 (mkConst ``LExpr.op) lparamsE (locE m) (identE o) (toExpr ty) + | .bvar m i => mkApp3 (mkConst ``LExpr.bvar) lparamsE (locE m) (toExpr i) + | .fvar m x ty => mkApp4 (mkConst ``LExpr.fvar) lparamsE (locE m) (identE x) (toExpr ty) + | .abs m n ty e => mkApp5 (mkConst ``LExpr.abs) lparamsE (locE m) (toExpr n) (toExpr ty) (exprE e) + | .quant m k n ty tr e => + mkApp7 (mkConst ``LExpr.quant) lparamsE (locE m) (toExpr k) (toExpr n) (toExpr ty) (exprE tr) + (exprE e) + | .app m f a => mkApp4 (mkConst ``LExpr.app) lparamsE (locE m) (exprE f) (exprE a) + | .ite m c t e => mkApp5 (mkConst ``LExpr.ite) lparamsE (locE m) (exprE c) (exprE t) (exprE e) + | .eq m a b => mkApp4 (mkConst ``LExpr.eq) lparamsE (locE m) (exprE a) (exprE b) + +instance : ToExpr Core.Expression.Expr where + toExpr := exprE + toTypeExpr := mkApp (mkConst ``Lambda.LExpr) lparamsE + +instance : ToExpr (ExprOrNondet Core.Expression) where + toExpr + | .det e => mkApp2 (mkConst ``ExprOrNondet.det [Level.one]) pureExprE (toExpr e) + | .nondet => mkApp (mkConst ``ExprOrNondet.nondet [Level.one]) pureExprE + toTypeExpr := mkApp (mkConst ``ExprOrNondet [Level.one]) pureExprE + +instance : ToExpr (MetaDataElem.Field Core.Expression) where + toExpr + | .var v => mkApp2 (mkConst ``MetaDataElem.Field.var [Level.one]) pureExprE (identE v) + | .label l => mkApp2 (mkConst ``MetaDataElem.Field.label [Level.one]) pureExprE (toExpr l) + toTypeExpr := mkApp (mkConst ``MetaDataElem.Field [Level.one]) pureExprE + +instance : ToExpr (MetaDataElem.Value Core.Expression) where + toExpr + | .expr e => mkApp2 (mkConst ``MetaDataElem.Value.expr [Level.one]) pureExprE (toExpr e) + | .msg s => mkApp2 (mkConst ``MetaDataElem.Value.msg [Level.one]) pureExprE (toExpr s) + | .switch b => mkApp2 (mkConst ``MetaDataElem.Value.switch [Level.one]) pureExprE (toExpr b) + | .provenance p => mkApp2 (mkConst ``MetaDataElem.Value.provenance [Level.one]) pureExprE (toExpr p) + toTypeExpr := mkApp (mkConst ``MetaDataElem.Value [Level.one]) pureExprE + +instance : ToExpr (MetaDataElem Core.Expression) where + toExpr e := mkApp3 (mkConst ``MetaDataElem.mk [Level.one]) pureExprE (toExpr e.fld) (toExpr e.value) + toTypeExpr := mkApp (mkConst ``MetaDataElem [Level.one]) pureExprE + +/-- Statement metadata. -/ +def mdE (md : Imperative.MetaData Core.Expression) : Expr := toExpr md + +instance : ToExpr (Cmd Core.Expression) where + toExpr + | .init x ty e md => + mkApp5 (mkConst ``Cmd.init [Level.one]) pureExprE (identE x) (toExpr ty) (toExpr e) (mdE md) + | .set x e md => mkApp4 (mkConst ``Cmd.set [Level.one]) pureExprE (identE x) (toExpr e) (mdE md) + | .assert l b md => mkApp4 (mkConst ``Cmd.assert [Level.one]) pureExprE (toExpr l) (toExpr b) (mdE md) + | .assume l b md => mkApp4 (mkConst ``Cmd.assume [Level.one]) pureExprE (toExpr l) (toExpr b) (mdE md) + | .cover l b md => mkApp4 (mkConst ``Cmd.cover [Level.one]) pureExprE (toExpr l) (toExpr b) (mdE md) + toTypeExpr := mkApp (mkConst ``Cmd [Level.one]) pureExprE + +instance : ToExpr (CallArg Core.Expression) where + toExpr + | .inArg e => mkApp2 (mkConst ``CallArg.inArg [Level.one]) pureExprE (toExpr e) + | .inoutArg x => mkApp2 (mkConst ``CallArg.inoutArg [Level.one]) pureExprE (identE x) + | .outArg x => mkApp2 (mkConst ``CallArg.outArg [Level.one]) pureExprE (identE x) + toTypeExpr := mkApp (mkConst ``CallArg [Level.one]) pureExprE + +instance : ToExpr Core.Command where + toExpr + | .cmd c => mkApp2 (mkConst ``CmdExt.cmd [Level.one]) pureExprE (toExpr c) + | .call n tys args md => + mkApp5 (mkConst ``CmdExt.call [Level.one]) pureExprE (toExpr n) (toExpr tys) (toExpr args) (mdE md) + toTypeExpr := cmdE + +mutual + +/-- Statements. -/ +partial def stmtE : Core.Statement → Expr + | .cmd c => mkApp3 (mkConst ``Stmt.cmd [Level.one]) pureExprE cmdE (toExpr c) + | .block l b md => mkApp5 (mkConst ``Stmt.block [Level.one]) pureExprE cmdE (toExpr l) (stmtsE b) (mdE md) + | .ite c t e md => + mkApp6 (mkConst ``Stmt.ite [Level.one]) pureExprE cmdE (toExpr c) (stmtsE t) (stmtsE e) (mdE md) + | .loop g m invs b md => + mkApp7 (mkConst ``Stmt.loop [Level.one]) pureExprE cmdE (toExpr g) (toExpr m) (toExpr invs) (stmtsE b) + (mdE md) + | .exit l md => mkApp4 (mkConst ``Stmt.exit [Level.one]) pureExprE cmdE (toExpr l) (mdE md) + | .typeDecl tc md => mkApp4 (mkConst ``Stmt.typeDecl [Level.one]) pureExprE cmdE (toExpr tc) (mdE md) + +/-- Statement lists, as `List Core.Statement` literals. -/ +partial def stmtsE : List Core.Statement → Expr + | [] => mkApp (mkConst ``List.nil [Level.zero]) (mkConst ``Core.Statement) + | s :: ss => mkApp3 (mkConst ``List.cons [Level.zero]) (mkConst ``Core.Statement) (stmtE s) (stmtsE ss) + +end + +instance : ToExpr Core.Statement where + toExpr := stmtE + toTypeExpr := mkConst ``Core.Statement + +instance : ToExpr (Check Core.Expression) where + toExpr c := mkApp4 (mkConst ``Check.mk [Level.one]) pureExprE (toExpr c.expr) (toExpr c.attr) (mdE c.md) + toTypeExpr := mkApp (mkConst ``Check [Level.one]) pureExprE + +instance : ToExpr (Spec Core.Expression) where + toExpr s := + mkApp3 (mkConst ``Spec.mk [Level.one]) pureExprE (toExpr s.preconditions) (toExpr s.postconditions) + toTypeExpr := mkApp (mkConst ``Spec [Level.one]) pureExprE + +/-! ## Procedures -/ + +/-- A procedure body: structured, or absent. The lowering never produces a CFG. -/ +def bodyE : Core.Procedure.Body → MetaM Expr + | .structured ss opq => + pure (mkApp4 (mkConst ``Body.structured [Level.one]) pureExprE cmdE (stmtsE ss) (toExpr opq)) + | .cfg _ _ => throwError "boole_reflect: a procedure body given as a CFG cannot be reflected" + | .abstract => pure (mkApp2 (mkConst ``Body.abstract [Level.one]) pureExprE cmdE) + +/-- The procedure `p` as a closed term of type `Core.Procedure`. -/ +def procedureE (p : Core.Procedure) : MetaM Expr := do + let body ← bodyE p.body + mkAppOptM ``Imperative.Procedure.mk + #[pureExprE, cmdE, mkConst ``Core.Procedure.Header, none, none, + toExpr p.header, toExpr p.spec, body] + +/-- Add `name : Core.Procedure := p` to the environment. -/ +def addProcedureAst (name : Name) (p : Core.Procedure) : MetaM Unit := do + let value ← procedureE p + let _ ← mkAuxDefinition name (mkConst ``Core.Procedure) value + enableRealizationsForConst name + +/-! ## Declarations and programs + +Functions, axioms, lemmas and type declarations carry the meaning of the names a procedure +uses, so the whole program is reflected as well. -/ + +/-- The expression type as Core's declarations spell it. -/ +instance : ToExpr (Lambda.LExpr Core.CoreLParams.mono) := inferInstanceAs (ToExpr Core.Expression.Expr) + +deriving instance ToExpr for Strata.DL.Util.FuncAttr +deriving instance ToExpr for Strata.DL.Util.FuncPrecondition +deriving instance ToExpr for Strata.DL.Util.Func +deriving instance ToExpr for Lambda.LConstr +deriving instance ToExpr for Core.TypeSynonym +deriving instance ToExpr for Core.Axiom +deriving instance ToExpr for Core.Lemma + +/-- `LDatatype` carries the proof that it has a constructor; on a literal, `rfl` is that proof. -/ +instance : ToExpr (Lambda.LDatatype Unit) where + toExpr d := + mkApp5 (mkConst ``Lambda.LDatatype.mk) (mkConst ``Unit) (toExpr d.name) (toExpr d.typeArgs) + (toExpr d.constrs) (mkApp2 (mkConst ``Eq.refl [.succ .zero]) (mkConst ``Bool) (mkConst ``Bool.true)) + toTypeExpr := mkApp (mkConst ``Lambda.LDatatype) (mkConst ``Unit) + +instance : ToExpr Core.TypeDecl where + toExpr + | .con tc => mkApp (mkConst ``Core.TypeDecl.con) (toExpr tc) + | .syn ts => mkApp (mkConst ``Core.TypeDecl.syn) (toExpr ts) + | .data ds => mkApp (mkConst ``Core.TypeDecl.data) (toExpr ds) + toTypeExpr := mkConst ``Core.TypeDecl + +/-- A declaration; procedures go through `procedureE`. -/ +def declE : Core.Decl → MetaM Expr + | .type t md => pure (mkApp2 (mkConst ``Core.Decl.type) (toExpr t) (mdE md)) + | .ax a md => pure (mkApp2 (mkConst ``Core.Decl.ax) (toExpr a) (mdE md)) + | .lemma l md => pure (mkApp2 (mkConst ``Core.Decl.lemma) (toExpr l) (mdE md)) + | .distinct x es md => + pure (mkApp3 (mkConst ``Core.Decl.distinct) (identE x) (toExpr es) (mdE md)) + | .proc p md => return mkApp2 (mkConst ``Core.Decl.proc) (← procedureE p) (mdE md) + | .func f md => pure (mkApp2 (mkConst ``Core.Decl.func) (toExpr f) (mdE md)) + | .recFuncBlock fs md => pure (mkApp2 (mkConst ``Core.Decl.recFuncBlock) (toExpr fs) (mdE md)) + +/-- The program `p` as a closed term of type `Core.Program`. -/ +def programE (p : Core.Program) : MetaM Expr := do + let ds ← p.decls.mapM declE + return mkApp2 (mkConst ``Core.Program.mk) (← mkListLit (mkConst ``Core.Decl) ds) + (toExpr p.usedIdentPrefixes) + +/-- Add `name : Core.Program := p` to the environment. -/ +def addProgramAst (name : Name) (p : Core.Program) : MetaM Unit := do + let value ← programE p + let _ ← mkAuxDefinition name (mkConst ``Core.Program) value + enableRealizationsForConst name + +end Strata.Reflect diff --git a/StrataBoole/HoareLogic/Reflect/TypeCheck.lean b/StrataBoole/HoareLogic/Reflect/TypeCheck.lean new file mode 100644 index 0000000..76da1aa --- /dev/null +++ b/StrataBoole/HoareLogic/Reflect/TypeCheck.lean @@ -0,0 +1,58 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Verify + +/-! # From Boole source to a type-checked Core program, at elaboration time + +`boole_reflect` (`Boole.lean`) starts from the Core program obtained by +`Strata.Boole.typeCheck`, that is `getProgram → toCoreProgram → Core.typeCheck`, before any Core +transform phase: the program Core's verifier works on. This file computes it. The computation +runs compiled code (`Term.evalTerm`): its result is a value in the elaborator, not a term the +kernel can reduce. + +The expressions of that program carry their source locations. `coreProgram` replaces the +location of every expression of a procedure by `Core.valueLoc` (`Core.eraseLocs`), as Strata's +own tests of its Hoare logic do: the terms stay small and do not change when the source text +moves. Typing has been checked before, and evaluation ignores locations +(`Core.Expression.eval_eraseLocs`). What is bound, and what every statement about a reflected +procedure is about, is the program with the locations erased. -/ + +open Lean Elab Term Meta + +namespace Strata.Reflect + +/-- Lower and type-check; render the error as a string so the result can be evaluated at +elaboration time without naming Strata's message type. -/ +def typeCheckStr (p : StrataDDM.Program) : Except String Core.Program := + match Strata.Boole.typeCheck p Core.VerifyOptions.quiet with + | .ok cp => .ok cp + | .error m => .error (toString (m.format none)) + +/-- `p` with the source location of every expression of its procedures replaced by +`Core.valueLoc`. Declarations other than procedures are left as they are. -/ +def eraseProcedureLocs (p : Core.Program) : Core.Program := + { p with decls := p.decls.map fun + | .proc proc md => .proc (Core.Procedure.mapExprs Core.eraseLocs proc) md + | d => d } + +/-- The program `boole_reflect` binds: lowered, type-checked, locations erased. -/ +def coreProgram (p : StrataDDM.Program) : Except String Core.Program := + (typeCheckStr p).map eraseProcedureLocs + +unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do + let ty := mkApp2 (mkConst ``Except [.zero, .zero]) (mkConst ``String) (mkConst ``Core.Program) + let r ← Term.evalTerm (Except String Core.Program) ty + (← `(Strata.Reflect.coreProgram $t)) + match r with + | .ok p => pure p + | .error m => throwError m!"Core type checking failed: {m}" + +/-- The type-checked Core program denoted by the term `t : StrataDDM.Program`, with the +locations of its procedures' expressions erased (`coreProgram`). -/ +@[implemented_by evalProgramUnsafe] +opaque evalProgram (t : Term) : TermElabM Core.Program + +end Strata.Reflect diff --git a/StrataBoole/Verify.lean b/StrataBoole/Verify.lean index a3163b7..a4e8236 100644 --- a/StrataBoole/Verify.lean +++ b/StrataBoole/Verify.lean @@ -1293,7 +1293,7 @@ private def translateProcedureDecl return [.proc { header := { name := mkIdent n, typeArgs := tys, inputs := allInputs, outputs := allOutputs } spec := spec - body := .structured body isOpaque + body := if body?.isSome then .structured body isOpaque else .abstract } .empty] private def toCoreDecls (cmd : BooleDDM.Command SourceRange) : TranslateM (List Core.Decl) := do diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index c16dfd9..e066bc0 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -64,6 +64,27 @@ import StrataBooleTest.FeatureRequests.scalar_reduce import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests +import StrataBooleTest.dalek_sum_of_slice +import StrataBooleTest.HoareLogic.hoare_lift_forall +import StrataBooleTest.HoareLogic.hoare_max2 +import StrataBooleTest.HoareLogic.generic_datatypes +import StrataBooleTest.HoareLogic.boole_reflect +import StrataBooleTest.HoareLogic.hoare_find_max_core +import StrataBooleTest.HoareLogic.hoare_locals_core +import StrataBooleTest.HoareLogic.hoare_ops_core +import StrataBooleTest.HoareLogic.hoare_frame_core +import StrataBooleTest.HoareLogic.hoare_quant_core +import StrataBooleTest.HoareLogic.hoare_havoc_core +import StrataBooleTest.HoareLogic.hoare_nondet_core +import StrataBooleTest.HoareLogic.hoare_call_core +import StrataBooleTest.HoareLogic.boole_globals +import StrataBooleTest.HoareLogic.boole_exit +import StrataBooleTest.HoareLogic.boole_call +import StrataBooleTest.HoareLogic.boole_functions +import StrataBooleTest.HoareLogic.boole_smt +import StrataBooleTest.HoareLogic.boole_unlabeled +import StrataBooleTest.HoareLogic.dalek_lift +import StrataBooleTest.HoareLogic.demo_pipeline import StrataBooleTest.option_native import StrataBooleTest.pair_native import StrataBooleTest.option_pair_detection diff --git a/StrataBooleTest/FeatureRequests/option_matches.lean b/StrataBooleTest/FeatureRequests/option_matches.lean index 0d6e644..9d7322b 100644 --- a/StrataBooleTest/FeatureRequests/option_matches.lean +++ b/StrataBooleTest/FeatureRequests/option_matches.lean @@ -76,11 +76,11 @@ Obligation: parse_surjective_seed_post_parse_surjective_seed_ensures_1_1513_call Property: assert Result: ✅ pass -Obligation: assume_$__callElimAssume_theorem_serialize_parse_roundtrip_ensures_0_1277_1_calls_option..val_0 +Obligation: assume_callElimPost_theorem_serialize_parse_roundtrip_ensures_0_1277_1_calls_option..val_0 Property: assert Result: ✅ pass -Obligation: assume_$__callElimAssume_theorem_serialize_parse_roundtrip_ensures_0_1277_1_calls_option..val_1 +Obligation: assume_callElimPost_theorem_serialize_parse_roundtrip_ensures_0_1277_1_calls_option..val_1 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/FeatureRequests/seq_slicing.lean b/StrataBooleTest/FeatureRequests/seq_slicing.lean index 51567a2..fa1e20e 100644 --- a/StrataBooleTest/FeatureRequests/seq_slicing.lean +++ b/StrataBooleTest/FeatureRequests/seq_slicing.lean @@ -166,8 +166,9 @@ example : Strata.smtVCsCorrectBoole seqSlicingSeed := by gen_smt_vcs_boole all_goals (try grind) --- Selecting from an empty sequence fails its bounds obligation. --- The result is unconstrained, so the ensures clause remains unknown. +-- Shape test: Sequence.select on an empty sequence is out of bounds, and the +-- bounds check reports it. The ensures clause is unknown: the result is +-- unconstrained. private def seqOutOfBoundsSeed : StrataDDM.Program := #strata program Boole; @@ -186,7 +187,7 @@ Obligation: set_v_calls_Sequence.select_0 Property: out-of-bounds access check Result: ❌ fail -Obligation: seq_oob_seed_ensures_0_4917 +Obligation: seq_oob_seed_ensures_0_4950 Property: assert Result: ❓ unknown-/ #guard_msgs in diff --git a/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean b/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean index ac10aa0..463cb62 100644 --- a/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean +++ b/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean @@ -223,7 +223,8 @@ spec { }; #end -/-- info: +/-- +info: Obligation: Seq_lib_insert_bv32_body_calls_Sequence.take_0 Property: out-of-bounds access check Result: ✅ pass @@ -344,11 +345,11 @@ Obligation: set_w15_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_3 +Obligation: callElimAssert_rotate_right_requires_1_3773_3 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_8 +Obligation: callElimAssert_rotate_right_requires_1_3773_8 Property: assert Result: ✅ pass @@ -360,11 +361,11 @@ Obligation: set_w2_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_13 +Obligation: callElimAssert_rotate_right_requires_1_3773_13 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_18 +Obligation: callElimAssert_rotate_right_requires_1_3773_18 Property: assert Result: ✅ pass @@ -384,15 +385,15 @@ Obligation: set_block_local_calls_Sequence.update_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_23 +Obligation: callElimAssert_rotate_right_requires_1_3773_23 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_28 +Obligation: callElimAssert_rotate_right_requires_1_3773_28 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_33 +Obligation: callElimAssert_rotate_right_requires_1_3773_33 Property: assert Result: ✅ pass @@ -400,15 +401,15 @@ Obligation: set_t1_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_38 +Obligation: callElimAssert_rotate_right_requires_1_3773_38 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_43 +Obligation: callElimAssert_rotate_right_requires_1_3773_43 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_rotate_right_requires_1_3773_48 +Obligation: callElimAssert_rotate_right_requires_1_3773_48 Property: assert Result: ✅ pass @@ -508,11 +509,11 @@ Obligation: init_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: $__callElimAssert_to_u32s_requires_4_4106_52 +Obligation: callElimAssert_to_u32s_requires_4_4106_52 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_compress_u32_requires_10_5085_57 +Obligation: callElimAssert_compress_u32_requires_10_5085_57 Property: assert Result: ✅ pass @@ -522,6 +523,7 @@ Result: ✅ pass Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_61_1 Property: assert -Result: ✅ pass-/ +Result: ✅ pass +-/ #guard_msgs in #eval Strata.Boole.verify "cvc5" sha256_compact_indexed_program (options := .quiet) diff --git a/StrataBooleTest/HoareLogic/boole_call.lean b/StrataBooleTest/HoareLogic/boole_call.lean new file mode 100644 index 0000000..51f9918 --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_call.lean @@ -0,0 +1,111 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Pipeline + +/-! # Calls, from Boole + +A Boole procedure declared without a body is lowered to an abstract procedure: its contract is +trusted, and a call of it is read through that contract. `Twice` calls `Inc` twice; the result of +the first call is the argument of the second. `Inc` itself meets its contract by definition. -/ + +namespace Strata.BooleTest + +def callPgm : StrataDDM.Program := +#strata +program Boole; + +procedure Inc (x : int) returns (r : int) +spec { + requires [nonneg]: x >= 0; + ensures [bigger]: r > x; +}; + +procedure Twice (n : int) returns (m : int) +spec { + requires [pos]: n >= 0; + ensures [res]: m > n; +} +{ + var t : int; + call t := Inc(n); + call m := Inc(t); +}; + +procedure Branch (n : int) returns (m : int) +spec { + ensures [res]: m >= n; +} +{ + if (n >= 5) { + call m := Inc(n); + } else { + m := n; + } +}; + +procedure Loop (n : int) returns (m : int) +spec { + requires [pos]: n >= 0; + ensures [res]: m >= 0; +} +{ + var i : int := 0; + m := 0; + while (i < n) + invariant [bounds]: (0 <= i && i <= n) + invariant [grows]: (m >= i) + { + call m := Inc(m); + i := i + 1; + } +}; +#end + +boole_reflect callPgm + +example : Inc_ast.body = .abstract := rfl + +boole_prove callPgm Inc +boole_prove callPgm Twice + +/-! A call inside a branch or a loop body: the goals it leaves carry the path to the call. The +callee's precondition `nonneg` is a goal of the caller. -/ + +open Lean Elab Tactic in +/-- Log the name of every goal. -/ +elab "goal_names" : tactic => do + logInfo m!"{← (← getGoals).mapM (·.getTag)}" + +/-- info: [then.nonneg, then.res, else.res] -/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple callPgm_ast params "Branch" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + goal_names + all_goals omega + +/-- info: [bounds, grows, step.nonneg, step.bounds, step.grows, exit.res] -/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple callPgm_ast params "Loop" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + goal_names + all_goals omega + +/-- info: 'Strata.BooleTest.Inc_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Inc_contract + +/-- info: 'Strata.BooleTest.Twice_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Twice_contract + +end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/boole_exit.lean b/StrataBooleTest/HoareLogic/boole_exit.lean new file mode 100644 index 0000000..0c2264f --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_exit.lean @@ -0,0 +1,72 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Pipeline + +/-! # `exit`, from Boole + +The lowering wraps a procedure body in a block named after the procedure, and `exit p` leaves +it: a `return`. The postcondition is asked at the `exit`, and the statements after it are not +run (`last`, `skipRest`). An `exit` inside a branch or a loop that leaves an enclosing block is +outside the fragment: Strata has no rule for a statement list that continues after a statement +that may escape (`escape`). -/ + +namespace Strata.BooleTest + +def exitPgm : StrataDDM.Program := +#strata +program Boole; + +procedure last (x: int) returns (r: int) +spec { + ensures [same]: (r == x); +} +{ + r := x; + exit last; +}; + +procedure skipRest (x: int) returns (r: int) +spec { + ensures [same]: (r == x); +} +{ + r := x; + exit skipRest; + r := x + 1; +}; + +procedure escape (x: int) returns (r: int) +spec { + ensures [same]: (r == x); +} +{ + r := x; + if (x > 0) { exit escape; } + r := x; +}; +#end + +boole_prove exitPgm last +boole_prove exitPgm skipRest + +/-- +error: hoare: an `exit` leaves a statement that others follow + ⟦if (x > 0) { exit escape }⟧ +Supported: an `exit` at the end of the block it leaves. +-/ +#guard_msgs in +boole_prove exitPgm escape + +/-- info: 'Strata.BooleTest.last_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms last_contract + +/-- info: 'Strata.BooleTest.skipRest_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms skipRest_contract + +end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/boole_functions.lean b/StrataBooleTest/HoareLogic/boole_functions.lean new file mode 100644 index 0000000..32ea792 --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_functions.lean @@ -0,0 +1,93 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Pipeline + +/-! # Functions with a body, from Boole + +A function declared before a procedure is an operator of the model, and every model interprets +it as its body. `hoare_vcs` introduces that fact for each such function as the hypothesis +`_def`: an equivalence for a Boolean function, an equation otherwise. The fact needs the +function the procedure's factory finds under the name, which is proved without `native_decide`: +the kernel searches the built-in functions for the names, once per procedure. -/ + +namespace Strata.BooleTest + +def functionsPgm : StrataDDM.Program := +#strata +program Boole; + +function small (x : int) : bool { x < 10 } +function twice (x : int) : int { x + x } +function both (x : int, y : int) : bool { small(x) && small(y) } +function limit () : int { 20 } + +procedure doubled (x : int) returns (r : int) +spec { + requires [sm]: small(x); + ensures [lt]: r < limit; +} +{ + r := twice(x); +}; + +procedure pair (x : int, y : int) returns (r : int) +spec { + requires [b]: both(x, y); + ensures [lt]: r < limit; +} +{ + r := x + y; +}; +#end + +boole_reflect functionsPgm + +/-! The goal `doubled` leaves, with the definitions of the functions among its hypotheses. -/ + +/-- +error: unsolved goals +case lt +small : Int → Bool +twice : Int → Int +both : Int → Int → Bool +limit x : Int +hsm : small x = true +small_def : ∀ (x : Int), small x = true ↔ x < 10 +twice_def : ∀ (x : Int), twice x = x + x +both_def : ∀ (x y : Int), both x y = true ↔ small x = true ∧ small y = true +limit_def : limit = 20 +⊢ twice x < limit +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple functionsPgm_ast params "doubled" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +theorem doubled_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple functionsPgm_ast params "doubled" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + rw [twice_def, limit_def] + have := (small_def x).mp hsm + omega + +/-! `pair` through the one-command pipeline: its finisher uses the definitions. -/ + +boole_prove functionsPgm pair + +/-- info: 'Strata.BooleTest.doubled_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms doubled_contract + +/-- info: 'Strata.BooleTest.pair_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms pair_contract + +end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/boole_globals.lean b/StrataBooleTest/HoareLogic/boole_globals.lean new file mode 100644 index 0000000..3cf3c62 --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_globals.lean @@ -0,0 +1,61 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Reflect.Boole +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic + +/-! # Two results, a modified global and `old` across a loop, from Boole + +`returns (count: int, last: int)` gives two `out` parameters, `modifies total` makes the global +an `inout` parameter with an `old total` snapshot, and the loop writes the global. The frame +carries `old total` and `n` through the loop. -/ + +namespace Strata.BooleTest + +def globalsPgm : StrataDDM.Program := +#strata +program Boole; + +var total : int; + +procedure addAll (n: int) returns (count: int, last: int) +spec { + modifies total; + requires (n >= 0); + ensures [cnt]: (count == n); + ensures [tot]: (total == old(total) + n); + ensures [lst]: (last == n); +} +{ + count := 0; + last := 0; + while (count < n) + invariant [c]: (0 <= count && count <= n) + invariant [t]: (total == old(total) + count) + invariant [l]: (last == count) + { + total := total + 1; + count := count + 1; + last := count; + } +}; +#end + +boole_reflect globalsPgm + +theorem addAll_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple globalsPgm_ast params "addAll" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +/-- info: 'Strata.BooleTest.addAll_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms addAll_contract + +end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/boole_reflect.lean b/StrataBooleTest/HoareLogic/boole_reflect.lean new file mode 100644 index 0000000..765e9a8 --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_reflect.lean @@ -0,0 +1,246 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Reflect.Boole + +/-! # Reflection of the type-checked Core procedure + +`boole_reflect` binds the type-checked Core program to `

_ast` and each of its procedures to +`_ast`, with the source locations of the procedures' expressions erased. The literals must +be the very values the type checker produced, up to that erasure (both are computed and compared +here), and they must compute by kernel reduction. The programs cover `havoc` and `assume`, `Map` +types, quantifiers, nested loops, metadata and provenance. -/ + +namespace Strata.ReflectTest + +open Strata + +def pickNatPgm : StrataDDM.Program := #strata +program Boole; + +procedure pick_nat() returns (x : int) +spec { ensures x >= 0; } +{ havoc x; assume x >= 0; }; +#end + +def sumToPgm : StrataDDM.Program := #strata +program Boole; + +procedure sum_to(n : int) returns (r : int) +spec { requires n >= 0; ensures 2 * r == n * (n + 1); } +{ + var i : int := 0; + r := 0; + while (i < n) + invariant 0 <= i && i <= n && 2 * r == i * (i + 1) + { + i := i + 1; + r := r + i; + } +}; +#end + +def findMaxPgm : StrataDDM.Program := #strata +program Boole; + +procedure witnessOccurs(nums: Map int int, n: int, idx: int, value: int) returns () +spec { + requires 0 <= idx && idx < n; + requires value == nums[idx]; + ensures ∃ j: int . 0 <= j && j < n && value == nums[j]; +} +{ + assume ∃ j: int . 0 <= j && j < n && value == nums[j]; +}; + +procedure findMax (nums: Map int int, n: int) returns (ret: int) +spec { + requires n > 0; + ensures ∀ i: int . 0 <= i && i < n ==> ret >= nums[i]; + ensures ∃ j: int . 0 <= j && j < n && ret == nums[j]; +} +{ + var max : int := nums[0]; + var maxIndex : int := 0; + var i : int := 1; + + while (i < n) + decreases n - i + invariant (1 <= i && i <= n) + invariant (∀ k: int . 0 <= k && k < i ==> max >= nums[k]) + invariant (0 <= maxIndex && maxIndex < i && max == nums[maxIndex]) + { + if (nums[i] > max) { + max := nums[i]; + maxIndex := i; + } + i := i + 1; + } + assert 0 <= maxIndex && maxIndex < n && max == nums[maxIndex]; + ret := nums[maxIndex]; +}; +#end + +def loopNoStatePgm : StrataDDM.Program := #strata +program Boole; + +procedure loop_no_state(n : int) returns () +spec { requires n >= 0; } +{ + var j : int := 0; + while (j < 0) + invariant j == 0 + { var t : int := 1; assert t == 1; } + assert j == 0; +}; +#end + +def loopOneVarPgm : StrataDDM.Program := #strata +program Boole; + +procedure loop_one_var(n : int) returns (r : int) +spec { requires n >= 0; ensures r == n; } +{ + r := 0; + while (r < n) + invariant 0 <= r && r <= n + { r := r + 1; } +}; +#end + +def loopNestedPgm : StrataDDM.Program := #strata +program Boole; + +procedure loop_nested(n : int) returns (s : int) +spec { requires n >= 0; ensures s >= 0; } +{ + var i : int := 0; + s := 0; + while (i < n) + invariant 0 <= i && i <= n && s >= 0 + { + var j : int := 0; + while (j < i) + invariant 0 <= j && j <= i && s >= 0 + { s := s + 1; j := j + 1; } + i := i + 1; + } +}; +#end + +#guard_msgs in +boole_reflect pickNatPgm +#guard_msgs in +boole_reflect sumToPgm +#guard_msgs in +boole_reflect findMaxPgm +#guard_msgs in +boole_reflect loopNoStatePgm +#guard_msgs in +boole_reflect loopOneVarPgm +#guard_msgs in +boole_reflect loopNestedPgm + +example : Core.Procedure := sum_to_ast + +/-- Every procedure of the type-checked program, with the locations of its expressions erased, +is among the reflected literals, and conversely. -/ +def reflectedFaithfully (pgm : StrataDDM.Program) (asts : List Core.Procedure) : Bool := + match Strata.Reflect.typeCheckStr pgm with + | .ok cp => + let procs := cp.decls.filterMap fun + | .proc p _ => some (Core.Procedure.mapExprs Core.eraseLocs p) + | _ => none + procs.length == asts.length && procs.all fun p => asts.any fun a => decide (p = a) + | .error _ => false + +/-- info: [true, true, true, true, true, true] -/ +#guard_msgs in +#eval [reflectedFaithfully pickNatPgm [pick_nat_ast], + reflectedFaithfully sumToPgm [sum_to_ast], + reflectedFaithfully findMaxPgm [witnessOccurs_ast, findMax_ast], + reflectedFaithfully loopNoStatePgm [loop_no_state_ast], + reflectedFaithfully loopOneVarPgm [loop_one_var_ast], + reflectedFaithfully loopNestedPgm [loop_nested_ast]] + +/-! The whole program is bound as well, named after the identifier. -/ + +example : Core.Program := findMaxPgm_ast + +def programFaithful (pgm : StrataDDM.Program) (ast : Core.Program) : Bool := + match Strata.Reflect.coreProgram pgm with + | .ok cp => decide (cp = ast) + | .error _ => false + +/-- info: [true, true, true, true, true, true] -/ +#guard_msgs in +#eval [programFaithful pickNatPgm pickNatPgm_ast, + programFaithful sumToPgm sumToPgm_ast, + programFaithful findMaxPgm findMaxPgm_ast, + programFaithful loopNoStatePgm loopNoStatePgm_ast, + programFaithful loopOneVarPgm loopOneVarPgm_ast, + programFaithful loopNestedPgm loopNestedPgm_ast] + +/-! ## Declarations other than procedures + +An uninterpreted type and function, an axiom, a function with a body, and a datatype. -/ + +def declsPgm : StrataDDM.Program := #strata +program Boole; + +type Scalar; +function reduce(b : Scalar) : Scalar; +axiom (∀ s : Scalar . (reduce(reduce(s)) == reduce(s))); +function twice(x : int) : int { x + x } +datatype OptionInt () { None(), Some(val: int) }; + +procedure use_decls(x : int) returns (r : int) +spec { ensures r == twice(x); } +{ + var o : OptionInt; + o := Some(x); + r := OptionInt..val(o) + x; +}; +#end + +#guard_msgs in +boole_reflect declsPgm + +/-- info: true -/ +#guard_msgs in +#eval programFaithful declsPgm declsPgm_ast + +def hasKind (p : Core.Program) (k : Core.Decl → Bool) : Bool := p.decls.any k + +example : hasKind declsPgm_ast (fun | .type (.con _) _ => true | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .type (.data _) _ => true | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .ax .. => true | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .func f _ => f.body.isSome | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .func f _ => f.body.isNone | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .proc .. => true | _ => false) = true := by decide + +/-! Every expression of a reflected procedure has the location `Core.valueLoc`: erasing the +locations again changes nothing. -/ + +/-- info: [true, true, true] -/ +#guard_msgs in +#eval [decide (Core.Procedure.mapExprs Core.eraseLocs sum_to_ast = sum_to_ast), + decide (Core.Procedure.mapExprs Core.eraseLocs findMax_ast = findMax_ast), + decide (Core.Procedure.mapExprs Core.eraseLocs loop_nested_ast = loop_nested_ast)] + +/-! The literal computes by kernel reduction. -/ + +example : sum_to_ast.header.name.name = "sum_to" := rfl +example : sum_to_ast.spec.preconditions.toList.length = 1 := rfl +example : sum_to_ast.spec.postconditions.toList.length = 1 := rfl + +/-- The lowering wraps the body in a block named after the procedure. -/ +example : (match sum_to_ast.body with + | .structured [.block "sum_to" _ _] _ => true + | _ => false) = true := by + decide + +end Strata.ReflectTest diff --git a/StrataBooleTest/HoareLogic/boole_smt.lean b/StrataBooleTest/HoareLogic/boole_smt.lean new file mode 100644 index 0000000..09e3906 --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_smt.lean @@ -0,0 +1,88 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Pipeline +import Smt +import Smt.Real + +/-! # Closing the conditions with `smt`, from Boole + +`hoare_lift` leaves each condition as a goal about uninterpreted types and functions: a type of +the program other than `int`, `bool` and the bitvectors is a type variable, and a function of +the program, or a built-in one with no Lean operation here, is a function variable named after +it. The definitions of the functions and the axioms are hypotheses. `smt [*]` sends the goal with +all its hypotheses to cvc5 and replays the proof in Lean, so the theorem depends on no axiom +beyond the three standard ones. -/ + +namespace Strata.BooleTest + +def smtPgm : StrataDDM.Program := +#strata +program Boole; + +type Scalar := Sequence (bv W8); +function small (x : int) : bool { x < 10 } +function twice (x : int) : int { x + x } +function weight (s : Scalar, j : int) : int; +function limit () : int { 20 } + +procedure bounded (x : int, s : Scalar) returns (r : int) +spec { + requires [sm]: small(x); + requires [len]: Sequence.length(s) == 32; + requires [all]: forall j : int :: 0 <= j && j < Sequence.length(s) ==> weight(s, j) >= 0; + ensures [lt]: r < limit; + ensures [last]: r <= r + weight(s, 31); +} +{ + r := twice(x); +}; +#end + +boole_reflect smtPgm + +/-! The goals as `hoare_lift` leaves them. -/ + +/-- +error: unsolved goals +case lt +Sequence_bv8 : Type +inst : Nonempty Sequence_bv8 +small : ℤ → Bool +Sequence.length : Sequence_bv8 → ℤ +weight : Sequence_bv8 → ℤ → ℤ +twice : ℤ → ℤ +limit x : ℤ +s : Sequence_bv8 +hsm : small x = true +hlen : Sequence.length s = 32 +hall : ∀ (v : ℤ), 0 ≤ v ∧ v < Sequence.length s → weight s v ≥ 0 +small_def : ∀ (x : ℤ), small x = true ↔ x < 10 +twice_def : ∀ (x : ℤ), twice x = x + x +limit_def : limit = 20 +s_length : 0 ≤ Sequence.length s +⊢ twice x < limit +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple smtPgm_ast params "bounded" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case last => smt [*] + +theorem bounded_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple smtPgm_ast params "bounded" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals smt [*] + +/-- info: 'Strata.BooleTest.bounded_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bounded_contract + +end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/boole_unlabeled.lean b/StrataBooleTest/HoareLogic/boole_unlabeled.lean new file mode 100644 index 0000000..7777a44 --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_unlabeled.lean @@ -0,0 +1,84 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Pipeline + +/-! # Clauses written without a label + +The lowering labels such a clause `__`, where the offset is the position +of the clause in the source text. A goal or a hypothesis is named after the label without the +offset, so the names below do not change when the text before a clause does. -/ + +namespace Strata.BooleTest.Unlabeled + +def unlabeledPgm : StrataDDM.Program := +#strata +program Boole; + +function bound () : int { 100 } + +axiom bound > 0; + +procedure Inc (x : int) returns (r : int) +spec { + requires x >= 0; + ensures r > x; +}; + +procedure Use (n : int) returns (m : int) +spec { + requires n >= 0; + ensures m > n; + ensures m > bound; +} +{ + assume n >= bound; + call m := Inc(n); + assert m > 0; +}; +#end + +boole_reflect unlabeledPgm + +/-! The goals of `Use`: the `requires` and the first `ensures` are closed by the lifting, the +`assert` and the second `ensures` are left, each named after its clause. -/ + +/-- +error: unsolved goals +case assert_7 +bound n : Int +hUse_requires_3 : n ≥ 0 +axiom_0 : bound > 0 +bound_def : bound = 100 +m : Int +hInc_ensures_2 : m > n +hassume_6 : n ≥ bound +⊢ m > 0 + +case Use_ensures_5 +bound n : Int +hUse_requires_3 : n ≥ 0 +axiom_0 : bound > 0 +bound_def : bound = 100 +m : Int +hInc_ensures_2 : m > n +hassume_6 : n ≥ bound +⊢ m > bound +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple unlabeledPgm_ast params "Use" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +boole_prove unlabeledPgm Use + +/-- info: 'Strata.BooleTest.Unlabeled.Use_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Use_contract + +end Strata.BooleTest.Unlabeled diff --git a/StrataBooleTest/HoareLogic/dalek_lift.lean b/StrataBooleTest/HoareLogic/dalek_lift.lean new file mode 100644 index 0000000..81c0b2b --- /dev/null +++ b/StrataBooleTest/HoareLogic/dalek_lift.lean @@ -0,0 +1,182 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Pipeline +import Smt +import Smt.Real + +/-! # `sum_of_slice` from dalek-lite, against `Core.Logic.Hoare` + +The program is the one of `StrataBooleTest/dalek_sum_of_slice.lean` with one difference: the +trusted callee `Scalar_add` is declared without a body, where the generated program gives it a +body that assumes its `ensures`. A procedure without a body is lowered to an abstract procedure, +which a call reads through its contract. + +`Scalar_add` meets its contract by definition. `sum_of_slice` is proved, twice. + +Its conditions are goals about uninterpreted types and functions: `scalars` is a value of the +type variable `Sequence_Sequence_bv8`, and `Sequence.length`, `is_canonical_scalar`, `nat.toInt` +and the other functions are function variables. The axioms declared before the procedure are +hypotheses, named after the axioms, and so are the definitions of the functions (`_def`); +a sequence has a length that is not negative. + +* `sum_of_slice_contract` closes every condition with `smt [*]`: cvc5 finds the proof and Lean + replays it. +* `sum_of_slice_contract_by_hand` closes them without a solver. Two conditions are arithmetic. + The other five follow from the axioms and the definitions by rewriting: the two axioms that + relate `nat.toInt` and `nat.fromInt` make a `nat` the `nat` of its integer, so no reasoning + about the remainder is needed. -/ + +open Strata + +namespace Strata.DalekLift + +def dalekPgm : StrataDDM.Program := +#strata +program Boole; +type Scalar := Sequence (bv W8); +function u8_32_as_nat (bytes : Sequence (bv W8)) : nat { + nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 0))), nat_fromInt(1)), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 1))), nat_fromInt(256))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 2))), nat_fromInt(65536))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 3))), nat_fromInt(16777216))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 4))), nat_fromInt(4294967296))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 5))), nat_fromInt(1099511627776))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 6))), nat_fromInt(281474976710656))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 7))), nat_fromInt(72057594037927936))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 8))), nat_fromInt(18446744073709551616))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 9))), nat_fromInt(4722366482869645213696))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 10))), nat_fromInt(1208925819614629174706176))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 11))), nat_fromInt(309485009821345068724781056))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 12))), nat_fromInt(79228162514264337593543950336))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 13))), nat_fromInt(20282409603651670423947251286016))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 14))), nat_fromInt(5192296858534827628530496329220096))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 15))), nat_fromInt(1329227995784915872903807060280344576))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 16))), nat_fromInt(340282366920938463463374607431768211456))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 17))), nat_fromInt(87112285931760246646623899502532662132736))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 18))), nat_fromInt(22300745198530623141535718272648361505980416))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 19))), nat_fromInt(5708990770823839524233143877797980545530986496))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 20))), nat_fromInt(1461501637330902918203684832716283019655932542976))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 21))), nat_fromInt(374144419156711147060143317175368453031918731001856))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 22))), nat_fromInt(95780971304118053647396689196894323976171195136475136))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 23))), nat_fromInt(24519928653854221733733552434404946937899825954937634816))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 24))), nat_fromInt(6277101735386680763835789423207666416102355444464034512896))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 25))), nat_fromInt(1606938044258990275541962092341162602522202993782792835301376))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 26))), nat_fromInt(411376139330301510538742295639337626245683966408394965837152256))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 27))), nat_fromInt(105312291668557186697918027683670432318895095400549111254310977536))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 28))), nat_fromInt(26959946667150639794667015087019630673637144422540572481103610249216))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 29))), nat_fromInt(6901746346790563787434755862277025452451108972170386555162524223799296))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 30))), nat_fromInt(1766847064778384329583297500742918515827483896875618958121606201292619776))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 31))), nat_fromInt(452312848583266388373324160190187140051835877600158453279131187530910662656))) +} +function group_order () : nat { + nat_fromInt(7237005577332262213973186563042994240857116359379907606001950938285454250989) +} +function is_canonical_scalar (s : Scalar) : bool { + nat_lt(u8_32_as_nat(s), group_order) && Sequence.select!(s, 31) <= bv{8}(127) +} +function scalar_as_nat (s : Scalar) : nat { + u8_32_as_nat(s) +} +function group_canonical (n : nat) : nat { + nat_mod(n, group_order) +} +function u8_32_as_group_canonical (bytes : Sequence (bv W8)) : nat { + group_canonical(u8_32_as_nat(bytes)) +} +function scalar_as_canonical (s : Scalar) : nat { + u8_32_as_group_canonical(s) +} +rec function sum_of_scalars (scalars : Sequence Scalar, n : nat) : nat + requires nat_toInt(n) <= Sequence.length(scalars); + decreases nat_toInt(n) +{ + if nat_toInt(n) == 0 then nat_fromInt(0) else group_canonical(nat_add(sum_of_scalars(scalars, nat_fromInt(nat_toInt(n) - 1)), scalar_as_nat(Sequence.select(scalars, nat_toInt(n) - 1)))) +}; +axiom [sum_of_scalars_unfold]: ∀ scalars : (Sequence Scalar), n : nat :: nat_toInt(n) <= Sequence.length(scalars) ==> sum_of_scalars(scalars, n) == (if nat_toInt(n) == 0 then nat_fromInt(0) else group_canonical(nat_add(sum_of_scalars(scalars, nat_fromInt(nat_toInt(n) - 1)), scalar_as_nat(Sequence.select(scalars, nat_toInt(n) - 1))))); +function scalar_congruent_nat (s : Scalar, n : nat) : bool { + nat_toInt(scalar_as_canonical(s)) == nat_toInt(group_canonical(n)) +} +function Scalar_obeys_add_spec () : bool { + false +} +function Scalar_add_req (self : Scalar, rhs : Scalar) : bool { + is_canonical_scalar(self) && is_canonical_scalar(rhs) +} +function Scalar_add_spec (self : Scalar, rhs : Scalar) : Scalar; +function Scalar_ZERO () : Scalar; +axiom [Scalar_ZERO_lit_0]: Sequence.length(Scalar_ZERO) == 32; +axiom [Scalar_ZERO_lit_1]: ∀ k : int :: 0 <= k && k < 32 ==> Sequence.select!(Scalar_ZERO, k) == bv{8}(0); +axiom [lemma_scalar_zero_properties_ensures_0]: nat_toInt(scalar_as_nat(Scalar_ZERO)) == 0; +axiom [lemma_scalar_zero_properties_ensures_1]: nat_lt(scalar_as_nat(Scalar_ZERO), group_order); +axiom [lemma_scalar_zero_properties_ensures_2]: is_canonical_scalar(Scalar_ZERO); +axiom [lemma_scalar_zero_properties_ensures_3]: scalar_congruent_nat(Scalar_ZERO, nat_fromInt(0)); +procedure Scalar_add (self : Scalar, _rhs : Scalar) returns (result : Scalar) +spec { + requires Scalar_add_req(self, _rhs); + ensures Scalar_obeys_add_spec ==> result == Scalar_add_spec(self, _rhs); + ensures nat_toInt(scalar_as_nat(result)) == nat_toInt(group_canonical(nat_add(scalar_as_nat(self), scalar_as_nat(_rhs)))); + ensures is_canonical_scalar(result); +}; +procedure sum_of_slice (scalars : Sequence Scalar) returns (result : Scalar) +spec { + requires ∀ i : int :: 0 <= i && i < Sequence.length(scalars) ==> is_canonical_scalar(Sequence.select(scalars, i)); + ensures nat_lt(scalar_as_nat(result), group_order); + ensures is_canonical_scalar(result); + ensures scalar_congruent_nat(result, sum_of_scalars(scalars, nat_fromInt(Sequence.length(scalars)))); +} +{ + var n : int; + var acc : Scalar; + assume Sequence.length(scalars) <= 18446744073709551615; + n := Sequence.length(scalars); + acc := Scalar_ZERO; + for i : int := 0 to Sequence.length(scalars) - 1 + invariant 0 <= i && i <= Sequence.length(scalars) + invariant n == Sequence.length(scalars) + invariant ∀ j : int :: 0 <= j && j < Sequence.length(scalars) ==> is_canonical_scalar(Sequence.select(scalars, j)) + invariant nat_lt(scalar_as_nat(acc), group_order) + invariant is_canonical_scalar(acc) + invariant nat_toInt(scalar_as_nat(acc)) == nat_toInt(sum_of_scalars(scalars, nat_fromInt(i))) + { + call acc := Scalar_add(acc, Sequence.select(scalars, i)); + } + result := acc; + exit sum_of_slice; +}; +#end + +boole_reflect dalekPgm + +theorem Scalar_add_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple dalekPgm_ast params "Scalar_add" := by + hoare_contract + +/-- info: 'Strata.DalekLift.Scalar_add_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Scalar_add_contract + +set_option maxRecDepth 4096 in +set_option maxHeartbeats 4000000 in +theorem sum_of_slice_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple dalekPgm_ast params "sum_of_slice" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals smt [*] + +/-- info: 'Strata.DalekLift.sum_of_slice_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sum_of_slice_contract + +set_option maxRecDepth 4096 in +set_option maxHeartbeats 4000000 in +theorem sum_of_slice_contract_by_hand (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple dalekPgm_ast params "sum_of_slice" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + -- the bounds of the index, at the entry and after a step + any_goals omega + -- entry, `inv_6`: the sum of no scalars + · have h0 := nat_fromInt_toInt 0 (by omega) + rw [sum_of_scalars_unfold, ite_eq_left h0, h0] + · exact lemma_scalar_zero_properties_ensures_0 + · rw [h0]; exact scalars_length + -- the precondition of the call + · rw [Scalar_add_req_def] + exact ⟨hinv_5, hinv_3 i ⟨by omega, by omega⟩⟩ + -- step, `inv_4` + · rw [scalar_as_nat_def] + refine ((is_canonical_scalar_def _).mp ?_).1 + assumption + -- step, `inv_6`: one more scalar + · have hi := nat_fromInt_toInt (i + 1) (by omega) + have hacc := (nat_toInt_fromInt _).symm.trans ((congrArg _ hinv_6).trans (nat_toInt_fromInt _)) + rw [sum_of_scalars_unfold, hi, ite_eq_right (show ¬ (i + 1 = 0) by omega), + Int.add_sub_cancel, ← hacc] + · assumption + · rw [hi]; omega + -- exit: the postcondition + · have hi := Int.le_antisymm hinv_1.2 (by omega) + subst hi + have hacc := (nat_toInt_fromInt _).symm.trans ((congrArg _ hinv_6).trans (nat_toInt_fromInt _)) + rw [scalar_congruent_nat_def, scalar_as_canonical_def, u8_32_as_group_canonical_def, + ← scalar_as_nat_def, hacc] + +/-- info: 'Strata.DalekLift.sum_of_slice_contract_by_hand' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sum_of_slice_contract_by_hand + +end Strata.DalekLift diff --git a/StrataBooleTest/HoareLogic/demo_pipeline.lean b/StrataBooleTest/HoareLogic/demo_pipeline.lean new file mode 100644 index 0000000..3758570 --- /dev/null +++ b/StrataBooleTest/HoareLogic/demo_pipeline.lean @@ -0,0 +1,226 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Pipeline + +namespace Strata.PipelineDemo + +def demoPgm : StrataDDM.Program := +#strata +program Boole; + +procedure max2 (x: int, y: int) returns (r: int) +spec { + ensures [ge_x]: (r >= x); + ensures [ge_y]: (r >= y); + ensures [one_of]: (r == x || r == y); +} +{ + if (x >= y) { + r := x; + } else { + r := y; + } +}; + +procedure loopSimple (n: int) returns (r: int) +spec { + requires [nonneg]: (n >= 0); +} +{ + var sum : int; + var i : int; + + sum := 0; + i := 0; + while(i < n) + invariant (i <= n && ((i * (i-1)) div 2 == sum)) + { + sum := sum + i; + i := i + 1; + } + assert [sum_assert]: ((n * (n-1)) div 2 == sum); + assert [neg_cond]: (i == n); + r := sum; +}; + +procedure max2Wrong (x: int, y: int) returns (r: int) +spec { + ensures [strict]: (r > x); +} +{ + if (x >= y) { + r := x; + } else { + r := y; + } +}; + +procedure caller (x: int) returns (r: int) +spec { + ensures [same]: (r == x); +} +{ + call r := max2(x, x); +}; +#end + +boole_reflect demoPgm + +/-- +info: def Strata.PipelineDemo.max2_ast : Core.Procedure := +⟦procedure max2(x : int, y : int, out r : int) + spec { + ensures [ge_x]: r >= x; + ensures [ge_y]: r >= y; + ensures [one_of]: r == x || r == y; + } + { + max2: { if (x >= y) { r := x } else { r := y } } + }⟧ +-/ +#guard_msgs in +#print max2_ast + +/-- +info: def Strata.PipelineDemo.loopSimple_ast : Core.Procedure := +⟦procedure loopSimple(n : int, out r : int) + spec { + requires [nonneg]: n >= 0; + } + { + loopSimple: { + var sum : int; + var i : int; + sum := 0; + i := 0; + while (i < n) + invariant i <= n && i * (i - 1) / 2 == sum + { sum := sum + i; i := i + 1 }; + assert [sum_assert]: n * (n - 1) / 2 == sum; + assert [neg_cond]: i == n; + r := sum + } + }⟧ +-/ +#guard_msgs in +#print loopSimple_ast + +theorem max2_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple demoPgm_ast params "max2" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +theorem loopSimple_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple demoPgm_ast params "loopSimple" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +def morePgm : StrataDDM.Program := +#strata +program Boole; + +var total : int; + +procedure sumTo (n: int) returns (s: int) +spec { + requires (n >= 0); + ensures [total]: (2 * s == n * (n + 1)); +} +{ + s := 0; + for i : int := 1 to n + invariant [range]: (1 <= i && i <= n + 1) + invariant [partial]: (2 * s == (i - 1) * i) + { + s := s + i; + } +}; + +procedure bounds (n: int) returns (r: int) +spec { + requires (n >= 0); + ensures [all]: (∀ i : int :: (i <= n ==> i < r)); + ensures [pairs]: (∀ i : int :: (∀ j : int :: (i <= j ==> i + r <= j + r))); +} +{ + r := n + 2; +}; + +procedure pick (n: int) returns (r: int) +spec { + requires (n >= 0); + ensures [range]: (0 <= r && r <= n); + ensures [positive]: (r + 1 > 0); +} +{ + if * { + r := 0; + } else { + r := n; + } + cover [reach]: (r >= 0); + assume [extra]: (r + 1 > 0); +}; + +procedure addAll (n: int) returns (count: int) +spec { + modifies total; + requires (n >= 0); + ensures [cnt]: (count == n); + ensures [tot]: (total == old(total) + n); +} +{ + count := 0; + while (count < n) + invariant [c]: (0 <= count && count <= n) + invariant [t]: (total == old(total) + count) + { + total := total + 1; + count := count + 1; + } +}; +#end + +boole_prove morePgm sumTo +boole_prove morePgm bounds +boole_prove morePgm pick +boole_prove morePgm addAll + +/-- +error: unsolved goals +case then.strict +x y : Int +hguard : x ≥ y +⊢ x > x +-/ +#guard_msgs in +boole_prove demoPgm max2Wrong + +/-- +error: hoare: no rule for the call + ⟦call max2(x, x, out r)⟧ +Supported: a call of a procedure without a body and without `inout` parameters, with no function or datatype declared between it and the caller. +-/ +#guard_msgs in +boole_prove demoPgm caller + +/-- info: 'Strata.PipelineDemo.max2_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms max2_contract + +/-- info: 'Strata.PipelineDemo.loopSimple_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loopSimple_contract + +/-- info: 'Strata.PipelineDemo.sumTo_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sumTo_contract + +end Strata.PipelineDemo diff --git a/StrataBooleTest/HoareLogic/generic_datatypes.lean b/StrataBooleTest/HoareLogic/generic_datatypes.lean new file mode 100644 index 0000000..11e5d8a --- /dev/null +++ b/StrataBooleTest/HoareLogic/generic_datatypes.lean @@ -0,0 +1,101 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ + +/-! # A generic model of datatypes + +One Lean inductive of constructor applications interprets every datatype of +every program, so the interpreter knows a single type and nothing is generated +per program. The datatype laws (disjointness, injectivity, inversion) are +proved once; induction is recursion on the term. `pos` and `nat` from Boole's +`nat` library serve as the example. + +Not covered yet: `Map` fields keyed by a datatype (a negative occurrence) and +parametric datatypes. See `docs/HoareLogic.md`. +-/ + +mutual +inductive DT : Type where + | mk (ctor : String) (args : List Arg) +inductive Arg : Type where + | int (i : Int) + | bool (b : Bool) + | dt (d : DT) +end + +namespace DT + +inductive ArgSort | int | bool | dt (name : String) +abbrev Sig := String → List (String × List ArgSort) + +mutual +inductive WS (sig : Sig) : String → DT → Prop where + | mk {d c args sorts} : (c, sorts) ∈ sig d → WSArgs sig sorts args → WS sig d (DT.mk c args) +inductive WSArgs (sig : Sig) : List ArgSort → List Arg → Prop where + | nil : WSArgs sig [] [] + | int {i ss as} : WSArgs sig ss as → WSArgs sig (.int :: ss) (.int i :: as) + | bool {b ss as} : WSArgs sig ss as → WSArgs sig (.bool :: ss) (.bool b :: as) + | dt {name v ss as} : WS sig name v → WSArgs sig ss as → WSArgs sig (.dt name :: ss) (.dt v :: as) +end + +/-- The carrier of datatype `d`: its well-sorted values. -/ +def Carrier (sig : Sig) (d : String) := { v : DT // WS sig d v } + +/-! The datatype laws, once, for all signatures. -/ + +theorem disjoint {c c' : String} {as as' : List Arg} (h : c ≠ c') : DT.mk c as ≠ DT.mk c' as' := by + intro e; cases e; exact h rfl + +theorem injective {c : String} {as as' : List Arg} (h : DT.mk c as = DT.mk c as') : as = as' := by + cases h; rfl + +theorem inversion {sig : Sig} {d : String} {v : DT} (h : WS sig d v) : + ∃ c args sorts, v = DT.mk c args ∧ (c, sorts) ∈ sig d ∧ WSArgs sig sorts args := by + cases h with + | mk hc hargs => exact ⟨_, _, _, rfl, hc, hargs⟩ + +/-! `pos = xH | xO pos | xI pos`, `nat = N0 | Npos pos` on the generic model. -/ + +def posSig : Sig + | "pos" => [("xH", []), ("xO", [.dt "pos"]), ("xI", [.dt "pos"])] + | "nat" => [("N0", []), ("Npos", [.dt "pos"])] + | _ => [] + +def is_xO : DT → Prop | .mk "xO" [_] => True | _ => False +def xO_h : DT → DT | .mk "xO" [.dt h] => h | _ => .mk "xH" [] + +/-- `pos.toInt` by structural recursion on the generic term. -/ +def posToInt : DT → Int + | .mk "xH" [] => 1 + | .mk "xO" [.dt h] => 2 * posToInt h + | .mk "xI" [.dt h] => 2 * posToInt h + 1 + | _ => 0 + +example : posToInt (.mk "xI" [.dt (.mk "xO" [.dt (.mk "xH" [])])]) = 5 := by decide + +example : Carrier posSig "pos" := ⟨.mk "xH" [], .mk (by simp [posSig]) .nil⟩ +example : Carrier posSig "nat" := ⟨.mk "N0" [], .mk (by simp [posSig]) .nil⟩ + +/-- A well-sorted `pos` is `xH`, or `xO`/`xI` of a well-sorted `pos`. -/ +theorem pos_cases {v : DT} (h : WS posSig "pos" v) : + v = .mk "xH" [] ∨ (∃ h', WS posSig "pos" h' ∧ (v = .mk "xO" [.dt h'] ∨ v = .mk "xI" [.dt h'])) := by + cases h with + | mk hc hargs => + simp [posSig] at hc + rcases hc with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ + · cases hargs; exact .inl rfl + · cases hargs with | dt hv hrest => cases hrest; exact .inr ⟨_, hv, .inl rfl⟩ + · cases hargs with | dt hv hrest => cases hrest; exact .inr ⟨_, hv, .inr rfl⟩ + +/-- Induction over `pos`: recursion on the term size, using `pos_cases`. -/ +theorem posToInt_pos (v : DT) (hw : WS posSig "pos" v) : 0 < posToInt v := by + rcases pos_cases hw with e | ⟨h', hh', e | e⟩ <;> rw [e] + · simp [posToInt] + · have := posToInt_pos h' hh'; simp [posToInt]; omega + · have := posToInt_pos h' hh'; simp [posToInt]; omega +termination_by sizeOf v +decreasing_by all_goals (subst e; simp_wf; (try simp); omega) + +end DT diff --git a/StrataBooleTest/HoareLogic/hoare_call_core.lean b/StrataBooleTest/HoareLogic/hoare_call_core.lean new file mode 100644 index 0000000..75620e4 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_call_core.lean @@ -0,0 +1,124 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Calls, against `Core.Logic.Hoare` + +A call of a procedure without a body is read through the callee's contract: the callee's +`requires` are conditions at the call, named after their labels and read at the values of the +arguments, and its `ensures` are hypotheses about the values the call writes. `Twice` calls `Inc` +twice; the result of the first call is the argument of the second. The value an `out` argument +receives is named like the variable, primed until the name is new. + +A procedure without a body meets its contract by definition, so nothing is proved about `Inc`: +its contract is trusted. A callee with a body is outside the fragment (`viaBody`). -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def callPgm : Program := +#strata +program Core; + +procedure Inc(x : int, out r : int) +spec { + requires [nonneg]: int.ge(x, 0); + ensures [bigger]: int.gt(r, x); +}; + +procedure Twice(n : int, out m : int) +spec { + requires [pos]: int.ge(n, 0); + ensures [res]: int.gt(m, n); +} +{ + var t : int; + call Inc(n, out t); + call Inc(t, out m); +}; + +procedure Id(x : int, out r : int) +spec { + ensures [same]: r == x; +} +{ + r := x; +}; + +procedure viaBody(n : int, out m : int) +spec { + ensures [same]: m == n; +} +{ + call Id(n, out m); +}; +#end + +core_reflect callPgm + +noncomputable def callProg : Core.Program := + { decls := [.proc Inc .empty, .proc Twice .empty, .proc Id .empty, .proc viaBody .empty] } + +theorem Twice_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple callProg params "Twice" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +/-! `Inc` has no body: its contract holds by definition. -/ + +theorem Inc_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple callProg params "Inc" := by + hoare_contract + +/-! The conditions of `Twice` as the lifting leaves them. The `requires` of the first call +follows from `pos` as it stands; that of the second call is about `t'`, the value the first call +gave `t`. -/ + +/-- +error: unsolved goals +case nonneg +n : Int +hpos : n ≥ 0 +t t' : Int +hbigger : t' > n +⊢ t' ≥ 0 + +case res +n : Int +hpos : n ≥ 0 +t t' m : Int +hbigger✝ : t' > n +hbigger : m > t' +⊢ m > n +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple callProg params "Twice" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +/-- +error: hoare: no rule for the call + ⟦call Id(n, out m)⟧ +Supported: a call of a procedure without a body and without `inout` parameters, with no function or datatype declared between it and the caller. +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple callProg params "viaBody" := by + hoare_contract + +/-- info: 'Strata.HoareTest.Twice_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Twice_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_find_max_core.lean b/StrataBooleTest/HoareLogic/hoare_find_max_core.lean new file mode 100644 index 0000000..3d5cb7f --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_find_max_core.lean @@ -0,0 +1,108 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # The maximum of a map's first `n` entries + +The procedure reads `nums[0]` and `nums[i]`, applications of `select` to a map. `select` is not +an operator the lifting has a Lean operation for, so it is read as what the model of the runtime +factory interprets it as, and the goal is then generalized over the model: `select` below is a +function variable, and `nums` a value of the type variable `Map_int_int`. The conditions hold +whatever `select` is, so they are closed without a fact about maps. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def findMaxPgm : Program := +#strata +program Core; + +procedure findMax(nums : Map int int, n : int, out ret : int) +spec { + requires [nonempty]: int.gt(n, 0); + ensures [upper]: forall __q0 : int :: int.le(0, __q0) && int.lt(__q0, n) ==> int.ge(ret, nums[__q0]); + ensures [attained]: exists __q0 : int :: int.le(0, __q0) && int.lt(__q0, n) && ret == nums[__q0]; +} +{ + var max : int := nums[0]; + var maxIndex : int := 0; + var i : int := 1; + while (int.lt(i, n)) + decreases int.sub(n, i) + invariant [bounds]: int.le(1, i) && int.le(i, n) + invariant [above]: forall __q0 : int :: int.le(0, __q0) && int.lt(__q0, i) ==> int.ge(max, nums[__q0]) + invariant [witness]: int.le(0, maxIndex) && int.lt(maxIndex, i) && max == nums[maxIndex] + { + if (int.gt(nums[i], max)) { + max := nums[i]; + maxIndex := i; + } + i := int.add(i, 1); + } + assert [found]: int.le(0, maxIndex) && int.lt(maxIndex, n) && max == nums[maxIndex]; + ret := nums[maxIndex]; +}; +#end + +core_reflect findMaxPgm + +noncomputable def findMaxProg : Core.Program := { decls := [.proc findMax .empty] } + +example : findMaxProg.findProcByString? "findMax" = some findMax := rfl + +open Lean Elab Tactic in +/-- Fail with the goal named `tag`, as it stands. -/ +elab "report_goal " tag:ident : tactic => do + for g in ← getGoals do + if (← g.getTag) == tag.getId then throwError "left unread:\n{g}" + throwError "no goal named `{tag.getId}`" + +set_option maxHeartbeats 2000000 in +theorem findMax_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple findMaxProg params "findMax" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-! The invariant `above` after an iteration that took the `then` branch, as the lifting leaves +it. -/ + +/-- +error: left unread: +case step.then.above +Map_int_int : Type +inst : Nonempty Map_int_int +select : Map_int_int → Int → Int +nums : Map_int_int +n : Int +hnonempty : n > 0 +i max maxIndex : Int +hbounds : 1 ≤ i ∧ i ≤ n +habove : ∀ (v : Int), 0 ≤ v ∧ v < i → max ≥ select nums v +hwitness : (0 ≤ maxIndex ∧ maxIndex < i) ∧ max = select nums maxIndex +hguard✝ : i < n +hguard : select nums i > max +⊢ ∀ (v : Int), 0 ≤ v ∧ v < i + 1 → select nums i ≥ select nums v +-/ +#guard_msgs in +set_option maxHeartbeats 2000000 in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple findMaxProg params "findMax" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + report_goal step.then.above + +/-- info: 'Strata.HoareTest.findMax_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms findMax_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_frame_core.lean b/StrataBooleTest/HoareLogic/hoare_frame_core.lean new file mode 100644 index 0000000..6e9b4bb --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_frame_core.lean @@ -0,0 +1,126 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Variables a loop does not write, against `Core.Logic.Hoare` + +A loop only changes the variables its body writes. What the entry knew about any other variable +survives the loop without being repeated in an invariant: a precondition on an input (`addK`), +an assignment before the loop (`keep`), and both across nested loops (`nested`). -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def framePgm : Program := +#strata +program Core; + +procedure addK(n : int, k : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + requires [pos]: int.gt(k, 0); + ensures [res]: r == int.add(n, k); + ensures [more]: int.gt(r, n); +} +{ + var i : int := 0; + r := k; + while (int.lt(i, n)) + invariant [range]: int.le(0, i) && int.le(i, n) + invariant [acc]: r == int.add(k, i) + { + r := int.add(r, 1); + i := int.add(i, 1); + } +}; + +procedure keep(n : int, c : int, out r : int, out k : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [count]: r == n; + ensures [kept]: k == int.add(c, 1); +} +{ + var t : int := int.add(c, 1); + r := 0; + while (int.lt(r, n)) + invariant [range]: int.le(0, r) && int.le(r, n) + { + r := int.add(r, 1); + } + k := t; +}; + +procedure nested(n : int, k : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + requires [pos]: int.gt(k, 0); + ensures [res]: int.gt(r, 0); +} +{ + var i : int := 0; + r := k; + while (int.lt(i, n)) + invariant [range]: int.le(0, i) && int.le(i, n) + invariant [acc]: int.ge(r, k) + { + var j : int := 0; + while (int.lt(j, i)) + invariant [jrange]: int.le(0, j) && int.le(j, i) + invariant [acc]: int.ge(r, k) + { + r := int.add(r, 1); + j := int.add(j, 1); + } + i := int.add(i, 1); + } +}; +#end + +core_reflect framePgm + +noncomputable def frameProg : Core.Program := + { decls := [.proc addK .empty, .proc keep .empty, .proc nested .empty] } + +theorem addK_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple frameProg params "addK" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem keep_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple frameProg params "keep" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +set_option maxHeartbeats 400000 in +theorem nested_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple frameProg params "nested" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-- info: 'Strata.HoareTest.addK_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms addK_contract + +/-- info: 'Strata.HoareTest.keep_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms keep_contract + +/-- info: 'Strata.HoareTest.nested_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms nested_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_havoc_core.lean b/StrataBooleTest/HoareLogic/hoare_havoc_core.lean new file mode 100644 index 0000000..8cdd4e8 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_havoc_core.lean @@ -0,0 +1,178 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Values the program does not determine, against `Core.Logic.Hoare` + +`var x : int;` and `havoc x` give `x` a value about which the semantics says its type: a value +of the runtime factory whose sort is the declared one, or that of the value `x` held. The lifting +reads such a value as an `Int` or a `Bool` named like the variable, so what follows is read as +for any other value. `chosen` is the shape a Boole `choose` lowers to, into a local variable: an +`assert` of an `exists`, a `havoc`, an `assume`. A Boolean parameter is read like an integer one. + +`havoc` asks for the value the variable held, so its value is read for a variable whose value +has a known type: one that was declared or assigned, or a parameter, which holds a value of its +declared type at the entry. `unassigned` havocs an output parameter that was never assigned. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def havocPgm : Program := +#strata +program Core; + +procedure fresh(n : int, out r : int) +spec { + ensures [ge]: int.ge(r, n); +} +{ + var x : int; + assume [big]: int.ge(x, n); + r := x; +}; + +procedure again(n : int, b : bool, out r : int, out q : bool) +spec { + requires [pos]: int.gt(n, 0); + ensures [ge]: int.gt(r, 0); + ensures [flag]: q ==> b; +} +{ + r := n; + havoc r; + assume [up]: int.ge(r, n); + q := b; + havoc q; + assume [down]: !q || b; +}; + +procedure chosen(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [ge]: int.ge(r, n); + ensures [lt]: int.lt(r, int.add(n, 2)); +} +{ + var z : int; + assert [some_pick]: exists i : int :: int.ge(i, n) && int.lt(i, int.add(n, 2)); + havoc z; + assume [pick]: int.ge(z, n) && int.lt(z, int.add(n, 2)); + r := z; +}; + +procedure unassigned(n : int, out r : int) +spec { + ensures [ge]: int.ge(r, n); +} +{ + havoc r; + assume [up]: int.gt(r, n); +}; +#end + +core_reflect havocPgm + +noncomputable def havocProg : Core.Program := + { decls := [.proc fresh .empty, .proc again .empty, .proc chosen .empty, .proc unassigned .empty] } + +theorem fresh_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "fresh" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem again_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "again" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem chosen_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "chosen" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | exact ⟨n, by omega⟩ + +/-! The conditions of `chosen` as the lifting leaves them: `z` is the value the declaration gave, +`z'` the one the `havoc` gave. -/ + +/-- +error: unsolved goals +case some_pick +n : Int +hnonneg : n ≥ 0 +z : Int +⊢ ∃ v, v ≥ n ∧ v < n + 2 + +case ge +n : Int +hnonneg : n ≥ 0 +z z' : Int +hpick : z' ≥ n ∧ z' < n + 2 +⊢ z' ≥ n + +case lt +n : Int +hnonneg : n ≥ 0 +z z' : Int +hpick : z' ≥ n ∧ z' < n + 2 +⊢ z' < n + 2 +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "chosen" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +/-! `r` was never assigned: the value `havoc r` gives it has the type of the value `r` held at the +entry, which is the declared one. -/ + +/-- +error: unsolved goals +case ge +n r : Int +hup : r > n +⊢ r ≥ n +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "unassigned" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +theorem unassigned_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "unassigned" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +/-- info: 'Strata.HoareTest.fresh_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms fresh_contract + +/-- info: 'Strata.HoareTest.again_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms again_contract + +/-- info: 'Strata.HoareTest.chosen_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms chosen_contract + +/-- info: 'Strata.HoareTest.unassigned_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms unassigned_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_lift_forall.lean b/StrataBooleTest/HoareLogic/hoare_lift_forall.lean new file mode 100644 index 0000000..57dd763 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_lift_forall.lean @@ -0,0 +1,132 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import StrataBoole.HoareLogic.HoareLift +public import Strata.Languages.Core.SeqEvalProps +public import Strata.DL.Lambda.LExprDenoteEvalProps +import all Strata.DL.Lambda.Denote.LExprDenote +import all Strata.DL.Lambda.Denote.LExprDenoteCompute +import all Strata.DL.Lambda.Denote.LExprAnnotated +import all Strata.DL.Lambda.LExprDenoteEval +import all Strata.DL.Lambda.LExprWF + +/-! # Lifting a quantified clause: a worked example + +A contract clause of the Hoare-logic route is a Core expression that evaluates to `true` +in a store. Lifting turns that fact into a proposition over Lean values. This file does it +by hand, once, for the clause + + forall j : int :: 0 <= j && j < Sequence.length(s) ==> ok(Sequence.select(s, j)) + +which has the shape of the quantified `requires` and loop invariant of +`dalek_sum_of_slice`, with a user function `ok` in the place of `is_canonical_scalar`. +`all_lift` concludes that `ok` holds of every element of the sequence in range. + +The five steps of its proof are the ones a lifting tactic has to automate +(step 2 of `docs/HoareLogic.md`): + +1. evaluation to `true` is the denotation being `true` (`LExpr.denoteEval_eq_ofBool_iff`); +2. the store types the variables as the clause does, so annotating changes nothing + (`LExpr.annotateFvars_eq_self`); +3. the `denotes` tactic computes the denotation: a quantifier becomes a Lean `∀`, and the + body a term in the model's operators (`denote_true_iff_of_Denotes`); +4. a variable read from the store is the value the store holds + (`HoareLift.fvarVal_of_store`); +5. the built-in operators are their Lean operations (the `_opInterp_of_lookup` lemmas of + Strata's `IntEvalProps` and `BoolEvalProps`). + +A user function stays an operator of the model here. `HoareLift.opInterp_of_body` replaces +it by its body where a proof needs that. + +The `denotes` tactic and its lemmas are internal to Strata's denotation modules, so lifting +code has to live in a module that imports them with `import all`, as this file does. +-/ + +public section + +namespace HoareLiftForall + +open Lambda + +abbrev L := Core.valueLoc +abbrev seqInt : LMonoTy := .tcons "Sequence" [LMonoTy.int] +abbrev sId : Core.Expression.Ident := ⟨"s", ()⟩ +abbrev sV : Core.Expression.Expr := .fvar L sId (some seqInt) +abbrev b0 : Core.Expression.Expr := .bvar L 0 +abbrev opE (n : String) (ty : LMonoTy) : Core.Expression.Expr := .op L ⟨n, ()⟩ (some ty) +abbrev bool2 : LMonoTy := .arrow .bool (.arrow .bool .bool) +abbrev int2b : LMonoTy := .arrow LMonoTy.int (.arrow LMonoTy.int .bool) + +/-- `0 <= j && j < length(s) ==> ok(select(s, j))`, under the binder of `j`. -/ +abbrev allBody : Core.Expression.Expr := + .app L (.app L (opE "Bool.Implies" bool2) + (.app L (.app L (opE "Bool.And" bool2) + (.app L (.app L (opE "Int.Le" int2b) (.intConst L 0)) b0)) + (.app L (.app L (opE "Int.Lt" int2b) b0) + (.app L (opE "Sequence.length" (.arrow seqInt LMonoTy.int)) sV)))) + (.app L (opE "ok" (.arrow LMonoTy.int .bool)) + (.app L (.app L (opE "Sequence.select" (.arrow seqInt (.arrow LMonoTy.int LMonoTy.int))) sV) b0)) + +abbrev allE : Core.Expression.Expr := .quant L .all "j" (some LMonoTy.int) b0 allBody + +/-- **A quantified clause as a Lean `∀`.** If the clause evaluates to `true` in a store that + binds `s` to the sequence `sv`, then `ok` holds of every element of `sv` in range. -/ +theorem all_lift (Fm : Core.Expression.Factory) (σ : Core.CoreStore) + (himp : Fm.factory["Bool.Implies"]? = some (Lambda.boolImpliesFunc (T := Core.CoreLParams)).func) + (hand : Fm.factory["Bool.And"]? = some (Lambda.boolAndFunc (T := Core.CoreLParams)).func) + (hle : Fm.factory["Int.Le"]? = some (Lambda.intLeFunc (T := Core.CoreLParams)).func) + (hlt : Fm.factory["Int.Lt"]? = some (Lambda.intLtFunc (T := Core.CoreLParams)).func) + (sv : SortDenote Fm.model.tcInterp (.tcons "Sequence" [.int])) + (hs : σ sId = some ⟨Fm.model.tcInterp, .tcons "Sequence" [.int], sv⟩) + (h : Core.Expression.eval Fm σ allE = some (SemValue.ofBool Fm.model.tcInterp true)) : + ∀ j : Int, 0 ≤ j → j < Core.seqLengthOf Fm.model .int sv → + (Fm.model.opInterp "ok" (LSort.mkArrow .bool [.int]) + (Core.seqSelectOf Fm.model .int sv j) : Bool) = true := by + -- 1. Evaluation to `true` is the denotation being `true`. + obtain ⟨hdef, hty, hden⟩ := (LExpr.denoteEval_eq_ofBool_iff (T := Core.CoreLParams)).mp h + -- 2. The store types `s` as the clause does, so its annotation changes nothing. + have hann : allE.annotateFvars (ValStore.ann σ) = allE := + LExpr.annotateFvars_eq_self allE (by + intro x ty hx + simp only [LExpr.freeVars, List.mem_append, List.mem_cons, List.not_mem_nil, or_false, + Prod.mk.injEq, or_self, List.nil_append] at hx + obtain ⟨rfl, rfl⟩ := hx + exact ⟨seqInt, rfl, by simp only [ValStore.ann, hs, Option.map_some]; rfl⟩) + revert hty hden + rw [hann] + intro hty hden + letI := Fm.model.allInhabited + -- 3. The quantifier is a Lean `∀`; its body is a term in the model's operators. + have hv := Eq.mp (denote_true_iff_of_Denotes (by denotes)) hden + rw [classical_decide_eq_true] at hv + intro j h0 hj + have hb := Eq.mp (denote_true_iff_of_Denotes (by denotes)) (hv j) + -- 4. The store read of `s` is the sequence it holds. + have hfv : ValStore.fvarVal (T := Core.CoreLParams) Fm.model.tcInterp σ sId + (LSort.tcons "Sequence" [LSort.int]) = sv := HoareLift.fvarVal_of_store hs + dsimp only [LMonoTy.substTyVars, LMonoTy.substTyVars.map, denoteConst, LConst.ty] at hb + rw [hfv] at hb + -- 5. The built-in operators are their Lean operations. + have e1 := Core.intLe_opInterp_of_lookup Fm.model hle 0 j + have e2 := Core.intLt_opInterp_of_lookup Fm.model hlt j (Core.seqLengthOf Fm.model .int sv) + have e3 := Core.boolAnd_opInterp_of_lookup Fm.model hand (decide (0 ≤ j)) + (decide (j < Core.seqLengthOf Fm.model .int sv)) + have e4 := Core.boolImplies_opInterp_of_lookup Fm.model himp + (decide (0 ≤ j) && decide (j < Core.seqLengthOf Fm.model .int sv)) + (Fm.model.opInterp "ok" (LSort.mkArrow .bool [.int]) (Core.seqSelectOf Fm.model .int sv j)) + dsimp only [LSort.mkArrow, List.foldr, Core.seqLengthOf, Core.seqSelectOf, LSort.int, + LSort.bool] at e1 e2 e3 e4 hb ⊢ + rw [e1, e2, e3, e4] at hb + have h0' : decide (0 ≤ j) = true := decide_eq_true h0 + have hj' := decide_eq_true hj + dsimp only [Core.seqLengthOf, LSort.mkArrow, List.foldr, LSort.int] at hj' + rw [h0', hj'] at hb + exact hb + +end HoareLiftForall + +end -- public section diff --git a/StrataBooleTest/HoareLogic/hoare_locals_core.lean b/StrataBooleTest/HoareLogic/hoare_locals_core.lean new file mode 100644 index 0000000..e169f16 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_locals_core.lean @@ -0,0 +1,89 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Declarations that go out of scope, against `Core.Logic.Hoare` + +Leaving a block drops the variables it declared, so the rules for blocks, branches and loop +bodies have to say how the postcondition survives that. The rules here state it at the projected +environment instead of asking for `PostWF`, so the three placements a Boole lowering produces +all go through: `sumTo` declares its locals at the procedure level and has an `ensures`; +`count` declares one in a nested block, as a `for` loop lowers, and one in a branch. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def localsPgm : Program := +#strata +program Core; + +procedure sumTo(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [sum]: int.mul(2, r) == int.mul(n, int.add(n, 1)); +} +{ + var s : int := 0; + var i : int := 0; + while (int.lt(i, n)) + invariant [bounds]: int.le(0, i) && int.le(i, n) + invariant [partial]: int.mul(2, s) == int.mul(i, int.add(i, 1)) + { + i := int.add(i, 1); + s := int.add(s, i); + } + r := s; +}; + +procedure count(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [counted]: r == n; +} +{ + var c : int := 0; + loop: { + var i : int := 0; + while (int.lt(i, n)) + invariant [range]: int.le(0, i) && int.le(i, n) + invariant [tracks]: c == i + { + c := int.add(c, 1); + i := int.add(i, 1); + } + } + if (int.lt(c, 0)) { + var t : int := 0; + c := t; + } else { + } + r := c; +}; +#end + +core_reflect localsPgm + +noncomputable def localsProg : Core.Program := { decls := [.proc sumTo .empty, .proc count .empty] } + +theorem sumTo_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple localsProg params "sumTo" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem count_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple localsProg params "count" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_max2.lean b/StrataBooleTest/HoareLogic/hoare_max2.lean new file mode 100644 index 0000000..f13012e --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_max2.lean @@ -0,0 +1,235 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.HoareLift +import StrataBoole.MetaVerifier +import Strata.Languages.Core.ProgramProps + +/-! # `max2` against Core's Hoare logic, by hand + +The first procedure proved on the Lean route of `docs/HoareLogic.md`: a Boole block, +lowered to Core inside Lean, whose contract is proved by applying Core's Hoare rules. +Everything the tactic of step 1 will automate is written out once here. Expressions are +evaluated denotationally, so the values of variables are semantic values and the +evaluation lemmas of `Strata.Languages.Core.IntEvalProps`, `BoolEvalProps` and +`StrataBoole.HoareLogic.HoareLift` turn each rule's goal into a fact about integers. +-/ + +open Strata Lambda Core HoareLift + +namespace HoareMax2 + +/-! ## The program -/ + +def max2Pgm : StrataDDM.Program := +#strata +program Boole; +procedure max2 (x: int, y: int) returns (r: int) +spec { + ensures r >= x && r >= y; + ensures r == x || r == y; +} +{ + if (x >= y) { r := x; } else { r := y; } +}; +#end + +/-- The type-checked Core program the Boole block lowers to, with every expression's + location replaced by `valueLoc`, as in Strata's own Hoare tests. Typing and + evaluation ignore locations (`Core.Expression.eval_eraseLocs`), and the shapes below + then match Strata's operator constants and do not depend on the locations the + translation attaches. -/ +def max2Core : Core.Program := + match Strata.Boole.typeCheck max2Pgm with + | .ok p => { p with decls := p.decls.map fun d => match d with + | .proc proc md => .proc (Core.Procedure.mapExprs Core.eraseLocs proc) md + | other => other } + | .error _ => default + +def max2Proc : Core.Procedure := (max2Core.findProcByString? "max2").get! + +theorem max2_findProc : max2Core.findProcByString? "max2" = some max2Proc := by native_decide + +abbrev E := Core.Expression.Expr +def intTy : Option LMonoTy := some (.tcons "int" []) +def xV : Core.Expression.Ident := ⟨"x", ()⟩ +def yV : Core.Expression.Ident := ⟨"y", ()⟩ +def rV : Core.Expression.Ident := ⟨"r", ()⟩ + +/-- `a >= b`, `a && b`, `a || b` as the lowering writes them. -/ +abbrev geE (a b : E) : E := .app Core.valueLoc (.app Core.valueLoc Core.intGeOp a) b +abbrev andE (a b : E) : E := .app Core.valueLoc (.app Core.valueLoc Core.boolAndOp a) b +abbrev orE (a b : E) : E := .app Core.valueLoc (.app Core.valueLoc Core.boolOrOp a) b + +/-- The condition of the `if`. -/ +abbrev cond : E := geE (.fvar Core.valueLoc xV intTy) (.fvar Core.valueLoc yV intTy) + +/-- Metadata and labels of the statements and clauses, read off the program so the shapes + below are exact. -/ +def max2Body : Core.Statements := + match max2Proc.body with | .structured ss _ => ss | _ => [] +def md4 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ _ md] => md | _ => #[] +def md3 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ [.ite _ _ _ md] _] => md | _ => #[] +def md1 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ [.ite _ [.cmd (.cmd (.set _ _ md))] _ _] _] => md | _ => #[] +def md2 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ [.ite _ _ [.cmd (.cmd (.set _ _ md))] _] _] => md | _ => #[] + +theorem max2_body_eq : max2Proc.body = .structured + [.block "max2" + [.ite (.det cond) + [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc xV intTy)) md1))] + [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc yV intTy)) md2))] md3] md4] false := by + native_decide + +def lbl0 : Core.CoreLabel := + match max2Proc.spec.postconditions.toList with | (l, _) :: _ => l | _ => "" +def lbl1 : Core.CoreLabel := + match max2Proc.spec.postconditions.toList with | _ :: (l, _) :: _ => l | _ => "" +def mdP0 : Imperative.MetaData Core.Expression := + match max2Proc.spec.postconditions.toList with | (_, c) :: _ => c.md | _ => #[] +def mdP1 : Imperative.MetaData Core.Expression := + match max2Proc.spec.postconditions.toList with | _ :: (_, c) :: _ => c.md | _ => #[] + +theorem max2_posts : max2Proc.spec.postconditions.toList = + [(lbl0, { expr := andE (geE (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc xV intTy)) + (geE (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc yV intTy)), + attr := .Default, md := mdP0 }), + (lbl1, { expr := orE (.eq Core.valueLoc (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc xV intTy)) + (.eq Core.valueLoc (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc yV intTy)), + attr := .Default, md := mdP1 })] := by + native_decide + +theorem max2_inputs : max2Proc.header.inputs.toList = + [(xV, .tcons "int" []), (yV, .tcons "int" [])] := by + native_decide + +theorem max2_checksTyped : Core.Logic.Hoare.Procedure.contractChecksTyped max2Proc := by + native_decide + +/-- No function precedes `max2`, so its visible factory is `Core.Factory`. -/ +theorem max2_factory : max2Core.factoryBeforeProcedure "max2" = Core.Factory := + Core.Program.factoryBeforeProcedure_eq_core_of_noFunctions (by native_decide) + +/-- Gate parameters: no reserved prefixes, every operator counts as declared. -/ +def params : Core.Logic.InitEnvWFParams := + { prefixIdents := [], declaredFuncs := fun _ => true } + +/-! ## The values of the inputs -/ + +/-- An integer value of the environment's factory. -/ +abbrev intV (f : Core.Expression.Factory) (n : Int) : Core.Expression.Val := + SemValue.ofInt f.model.tcInterp n + +/-- Inside either branch the condition has evaluated, which binds `x` and `y` to values of + the factory; with their declared type `int` they are integers. -/ +theorem inputs_of_cond (ρ : Imperative.Env Core.Expression) {b : Bool} + (hpre : Core.Logic.Hoare.Procedure.contractPre Core.Factory max2Proc ρ) + (hcond : Core.Expression.eval ρ.factory ρ.store cond = + some (SemValue.ofBool ρ.factory.model.tcInterp b)) : + ρ.factory.factory = Core.Factory ∧ + ∃ a c : Int, ρ.store xV = some (intV ρ.factory a) ∧ ρ.store yV = some (intV ρ.factory c) := by + obtain ⟨-, hfac, -, hin, -⟩ := hpre + refine ⟨hfac, ?_⟩ + obtain ⟨vx, hx, hsx⟩ := hin xV (.tcons "int" []) (by rw [max2_inputs]; simp) + obtain ⟨vy, hy, hsy⟩ := hin yV (.tcons "int" []) (by rw [max2_inputs]; simp) + have hd := Lambda.LExpr.denoteEval_defines hcond + have hvars : ∀ z ∈ [xV, yV], z ∈ Lambda.LExpr.LExpr.getVars cond := by + simp [Lambda.LExpr.LExpr.getVars, Core.intGeOp, Lambda.WFLFunc.opExpr, + Lambda.LFunc.opExpr, Lambda.LFuncDefined.opExpr] + obtain ⟨wx, hwx, htx⟩ := hd xV (hvars xV (by simp)) + obtain ⟨wy, hwy, hty⟩ := hd yV (hvars yV (by simp)) + rw [hx] at hwx; cases hwx + rw [hy] at hwy; cases hwy + obtain ⟨a, ha⟩ := Lambda.SemValue.exists_ofInt hsx + obtain ⟨c, hc⟩ := Lambda.SemValue.exists_ofInt hsy + rw [ha, htx] at hx + rw [hc, hty] at hy + exact ⟨a, c, hx, hy⟩ + +/-- The condition's Boolean, once the inputs are known. -/ +theorem cond_eval (ρ : Imperative.Env Core.Expression) (a c : Int) + (hfac : ρ.factory.factory = Core.Factory) + (hx : ρ.store xV = some (intV ρ.factory a)) (hy : ρ.store yV = some (intV ρ.factory c)) : + Core.Expression.eval ρ.factory ρ.store cond = + some (SemValue.ofBool ρ.factory.model.tcInterp (decide (a ≥ c))) := + Core.eval_intGe (by rw [hfac]; exact Core.coreFactory_intGe) + (Core.eval_fvar_int (ty := intTy) _ hx) (Core.eval_fvar_int (ty := intTy) _ hy) + +/-! ## The postconditions -/ + +/-- The two `ensures` clauses hold in every world once the store binds `x`, `y` and `r` to + integers satisfying them. -/ +theorem max2_post (ρ : Imperative.Env Core.Expression) (a b c : Int) + (hfac : ρ.factory.factory = Core.Factory) + (hx : ρ.store xV = some (intV ρ.factory a)) (hy : ρ.store yV = some (intV ρ.factory b)) + (hr : ρ.store rV = some (intV ρ.factory c)) + (h1 : c ≥ a) (h2 : c ≥ b) (h3 : c = a ∨ c = b) : + Core.Logic.Hoare.Procedure.contractPost Core.Factory max2Proc ρ := by + intro label check hmem _ + rw [max2_posts] at hmem + simp only [List.mem_cons, List.not_mem_nil, or_false, Prod.mk.injEq] at hmem + have er := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hx + have ex := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hx + have ey := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hy + have err := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hr + have hge : ρ.factory.factory["Int.Ge"]? = some (Lambda.intGeFunc (T := CoreLParams)).func := by + rw [hfac]; exact Core.coreFactory_intGe + rcases hmem with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ <;> intro world <;> refine Or.inl ⟨hfac, ?_⟩ <;> + show Core.Expression.eval ρ.factory ρ.store _ = some (Imperative.HasBool.ttVal ρ.factory) + · rw [eval_boolAnd (by rw [hfac]; exact coreFactory_boolAnd) + (Core.eval_intGe hge err ex) (Core.eval_intGe hge err ey)] + simp [Imperative.HasBool.ttVal, h1, h2] + · rw [eval_boolOr (by rw [hfac]; exact coreFactory_boolOr) + (eval_eq_ints _ err ex) (eval_eq_ints _ err ey)] + rcases h3 with rfl | rfl <;> simp [Imperative.HasBool.ttVal] + +/-! ## The triple -/ + +theorem max2_triple : Core.Logic.Hoare.Procedure.contractTriple max2Core params "max2" := by + refine Core.Logic.Hoare.Procedure.contractTriple_of_core_typed max2Core params "max2" max2Proc _ + max2_findProc max2_body_eq max2_checksTyped ?_ (hmono := by native_decide) + rw [max2_factory] + -- the procedure block, then the labelled block + refine Core.Logic.Hoare.block max2Core.findProcByString? params ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + refine Core.Logic.Hoare.block max2Core.findProcByString? params ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + -- the if: one assignment per branch + refine Core.Logic.Hoare.ite max2Core.findProcByString? params ?_ ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + · -- then: r := x, under x >= y + refine Core.Logic.Hoare.set max2Core.findProcByString? params rV _ md1 _ _ ?_ + intro ρ₀ σ' v ⟨hpre, hcond⟩ hev hup + obtain ⟨hfac, a, c, hx, hy⟩ := inputs_of_cond ρ₀ hpre hcond + have hge : a ≥ c := of_decide_eq_true (Lambda.SemValue.ofBool_injective + (Option.some.inj ((cond_eval ρ₀ a c hfac hx hy).symm.trans hcond))) + have hv : v = intV ρ₀.factory a := + Option.some.inj (hev.symm.trans (Core.eval_fvar_int (ty := intTy) _ hx)) + subst hv + cases hup with + | update _ hnew hoth => + exact max2_post { ρ₀ with store := σ' } a c a hfac + ((hoth xV (by decide)).trans hx) ((hoth yV (by decide)).trans hy) hnew + (Int.le_refl a) hge (Or.inl rfl) + · -- else: r := y, under not (x >= y) + refine Core.Logic.Hoare.set max2Core.findProcByString? params rV _ md2 _ _ ?_ + intro ρ₀ σ' v ⟨hpre, hcond⟩ hev hup + obtain ⟨hfac, a, c, hx, hy⟩ := inputs_of_cond ρ₀ hpre hcond + have hlt : ¬ a ≥ c := of_decide_eq_false (Lambda.SemValue.ofBool_injective + (Option.some.inj ((cond_eval ρ₀ a c hfac hx hy).symm.trans hcond))) + have hv : v = intV ρ₀.factory c := + Option.some.inj (hev.symm.trans (Core.eval_fvar_int (ty := intTy) _ hy)) + subst hv + cases hup with + | update _ hnew hoth => + exact max2_post { ρ₀ with store := σ' } a c c hfac + ((hoth xV (by decide)).trans hx) ((hoth yV (by decide)).trans hy) hnew + (by omega) (Int.le_refl c) (Or.inr rfl) + +end HoareMax2 diff --git a/StrataBooleTest/HoareLogic/hoare_nondet_core.lean b/StrataBooleTest/HoareLogic/hoare_nondet_core.lean new file mode 100644 index 0000000..e3c4904 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_nondet_core.lean @@ -0,0 +1,83 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Nondeterministic control and `cover`, against `Core.Logic.Hoare` + +`if (*)` proves both branches, `while (*)` is the framed loop rule with nothing learned from a +guard, and `cover` is a skip. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def nondetPgm : Program := +#strata +program Core; + +procedure pick(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [range]: int.le(0, r) && int.le(r, n); +} +{ + if * { + r := 0; + } else { + r := n; + } + cover [reach]: int.ge(r, 0); +}; + +procedure drift(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [bound]: int.le(0, r) && int.le(r, n); +} +{ + r := 0; + while * + invariant [inv]: int.le(0, r) && int.le(r, n) + { + if (int.lt(r, n)) { + r := int.add(r, 1); + } else { + } + } +}; +#end + +core_reflect nondetPgm + +noncomputable def nondetProg : Core.Program := + { decls := [.proc pick .empty, .proc drift .empty] } + +theorem pick_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple nondetProg params "pick" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +theorem drift_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple nondetProg params "drift" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +/-- info: 'Strata.HoareTest.pick_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms pick_contract + +/-- info: 'Strata.HoareTest.drift_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms drift_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_ops_core.lean b/StrataBooleTest/HoareLogic/hoare_ops_core.lean new file mode 100644 index 0000000..5ad60b7 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_ops_core.lean @@ -0,0 +1,157 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # The remaining integer and boolean operators, against `Core.Logic.Hoare` + +Unary negation and `!`, the connectives `==>` and `<==>`, `==` on booleans, conditional +expressions, guards built from `&&`, `||` and `!`, and division. Each is read in two places: by +the evaluation lemmas when it sits in a guard, on the right of an assignment or in a clause +without a quantifier, and by the denotation lemmas when it sits under a quantifier. A division is +read where its divisor is known to be non-zero. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def opsPgm : Program := +#strata +program Core; + +procedure absVal(x : int, out r : int) +spec { + ensures [nonneg]: int.ge(r, 0); + ensures [neg]: int.lt(x, 0) ==> r == int.neg(x); + ensures [pos]: int.ge(x, 0) ==> r == x; +} +{ + r := if int.lt(x, 0) then int.neg(x) else x; +}; + +procedure clamp(x : int, lo : int, hi : int, out r : int) +spec { + requires [ord]: int.le(lo, hi); + ensures [inRange]: int.le(lo, r) && int.le(r, hi); + ensures [fixed]: !(int.lt(x, lo) || int.gt(x, hi)) ==> r == x; + ensures [same]: (r == x) <==> (int.le(lo, x) && int.le(x, hi)); + ensures [flags]: (int.lt(r, x) == int.gt(x, hi)) && (int.gt(r, x) == int.lt(x, lo)); +} +{ + if (int.lt(x, lo) || int.gt(x, hi)) { + if (int.lt(x, lo)) { + r := lo; + } else { + r := hi; + } + } else { + r := x; + } +}; + +procedure ratio(x : int, y : int, out r : int) +spec { + requires [pos]: int.gt(y, 0); + ensures [half]: int.le(int.mul(2, int.div(r, 2)), r); + ensures [same]: r == int.div(x, y); +} +{ + r := int.div(x, y); +}; + +procedure unguarded(x : int, y : int, out r : int) +spec { + ensures [same]: r == int.div(x, y); +} +{ + r := int.div(x, y); +}; + +procedure countDown(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [zero]: r == 0; +} +{ + r := n; + while (!(r == 0) && int.gt(r, 0)) + invariant [range]: int.ge(r, 0) + { + r := int.sub(r, 1); + } +}; +#end + +core_reflect opsPgm + +noncomputable def opsProg : Core.Program := + { decls := [.proc absVal .empty, .proc clamp .empty, .proc ratio .empty, .proc unguarded .empty, + .proc countDown .empty] } + +theorem absVal_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "absVal" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem clamp_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "clamp" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem ratio_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "ratio" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-! Without a non-zero divisor the division is not read: `Int.Div` is interpreted only there. -/ + +/-- +error: unsolved goals +case same +F : Core.Expression.Factory +x y : Int +σ' : Core.CoreStore +⊢ Lambda.LExpr.denoteEval F σ' ⟪r == x / y⟫ = some (Imperative.HasBool.ttVal F) +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "unguarded" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +theorem countDown_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "countDown" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-- info: 'Strata.HoareTest.absVal_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms absVal_contract + +/-- info: 'Strata.HoareTest.clamp_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms clamp_contract + +/-- info: 'Strata.HoareTest.ratio_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ratio_contract + +/-- info: 'Strata.HoareTest.countDown_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms countDown_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_quant_core.lean b/StrataBooleTest/HoareLogic/hoare_quant_core.lean new file mode 100644 index 0000000..f8860e8 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_quant_core.lean @@ -0,0 +1,125 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Quantifiers in clauses, against `Core.Logic.Hoare` + +`forall` and `exists` over integers lift to the Lean quantifiers wherever a clause is read: a +`requires` (a hypothesis to instantiate), an `ensures` and an `assert` (goals), an `invariant` +(both), nested binders included. An `assume` lifts to a hypothesis at the store it was passed +with. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def quantPgm : Program := +#strata +program Core; + +procedure bounds(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [all]: forall i : int :: int.le(i, n) ==> int.lt(i, r); + ensures [witness]: exists i : int :: int.gt(i, n) && int.lt(i, r); + ensures [pairs]: forall i : int :: forall j : int :: + int.le(i, j) ==> int.le(int.add(i, r), int.add(j, r)); +} +{ + r := int.add(n, 2); +}; + +procedure fromForall(n : int, out r : int) +spec { + requires [lb]: forall i : int :: int.ge(i, n) ==> int.ge(i, 0); + ensures [nonneg]: int.ge(r, 0); +} +{ + r := n; +}; + +procedure fill(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [done]: forall i : int :: int.le(0, i) && int.lt(i, n) ==> int.lt(i, r); +} +{ + r := 0; + while (int.lt(r, n)) + invariant [range]: int.le(0, r) && int.le(r, n) + invariant [below]: forall i : int :: int.lt(i, r) ==> int.lt(i, n) + { + r := int.add(r, 1); + } +}; + +procedure assumed(n : int, out r : int) +spec { + ensures [big]: int.gt(r, n); +} +{ + r := n; + assume [bump]: int.gt(n, 0); + assert [gap]: exists i : int :: int.gt(i, 0) && int.le(i, n); + r := int.add(r, n); +}; +#end + +core_reflect quantPgm + +noncomputable def quantProg : Core.Program := + { decls := [.proc bounds .empty, .proc fromForall .empty, .proc fill .empty, .proc assumed .empty] } + +theorem bounds_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "bounds" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case witness => exact ⟨n + 1, by omega⟩ + all_goals (intros; omega) + +theorem fromForall_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "fromForall" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case nonneg => have := hlb n; omega + +theorem fill_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "fill" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals (intros; omega) + +theorem assumed_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "assumed" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case gap => exact ⟨n, by omega⟩ + all_goals omega + +/-- info: 'Strata.HoareTest.bounds_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bounds_contract + +/-- info: 'Strata.HoareTest.fromForall_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms fromForall_contract + +/-- info: 'Strata.HoareTest.fill_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms fill_contract + +/-- info: 'Strata.HoareTest.assumed_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms assumed_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/code_expression.lean b/StrataBooleTest/code_expression.lean index 4f29d1b..588a216 100644 --- a/StrataBooleTest/code_expression.lean +++ b/StrataBooleTest/code_expression.lean @@ -68,11 +68,11 @@ procedure D(a : (Map int T), n : int) returns () #end /-- info: -Obligation: $__callElimAssert_Q_requires_1_630_2 +Obligation: callElimAssert_Q_requires_1_630_2 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_P_requires_0_481_5 +Obligation: callElimAssert_P_requires_0_481_5 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/dalek_sum_of_slice.lean b/StrataBooleTest/dalek_sum_of_slice.lean new file mode 100644 index 0000000..c5afdda --- /dev/null +++ b/StrataBooleTest/dalek_sum_of_slice.lean @@ -0,0 +1,335 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ + +import StrataBoole.MetaVerifier + +open Strata + +/- +`sum_of_slice` from dalek-lite: Verus to Boole to cvc5. +Generated by `verus-boole/dalek/rust_to_boole.sh`; do not edit. On this branch it is the +target of the Lean route of `docs/HoareLogic.md`, which will prove the same contracts +against Core's Hoare logic; the kernel stage of the demo branch is not carried over. + +Level 1: the Verus source. + + /// Compute the sum of all scalars in a slice. + /// + /// # Returns + /// + /// The sum of all scalars modulo the group order. + /// + /// # Example + /// + /// ``` + /// # use curve25519_dalek::scalar::Scalar; + /// let scalars = [ + /// Scalar::from(2u64), + /// Scalar::from(3u64), + /// Scalar::from(5u64), + /// ]; + /// + /// let sum = Scalar::sum_of_slice(&scalars); + /// assert_eq!(sum, Scalar::from(10u64)); + /// ``` + #[allow(clippy::needless_range_loop, clippy::op_ref)] + pub fn sum_of_slice(scalars: &[Scalar]) -> (result: Scalar) + requires + forall|i: int| #![auto] 0 <= i < scalars@.len() ==> is_canonical_scalar(&scalars@[i]), + ensures + scalar_as_nat(&result) < group_order(), + is_canonical_scalar(&result), + scalar_congruent_nat(&result, sum_of_scalars(scalars@)), + { + let n = scalars.len(); + let mut acc = Scalar::ZERO; + + proof { + lemma_scalar_zero_properties(); + assert(scalars@.subrange(0, 0) =~= Seq::::empty()); + } + + for i in 0..n + invariant + n == scalars.len(), + forall|j: int| + #![auto] + 0 <= j < scalars@.len() ==> is_canonical_scalar(&scalars@[j]), + scalar_as_nat(&acc) < group_order(), + is_canonical_scalar(&acc), + scalar_congruent_nat(&acc, sum_of_scalars(scalars@.subrange(0, i as int))), + { + let _old_acc = acc; + + proof { + // Inline: sum extends by one element + let sub = scalars@.subrange(0, (i + 1) as int); + assert(sub.subrange(0, i as int) =~= scalars@.subrange(0, i as int)); + } + + acc = &acc + &scalars[i]; + + proof { + let L = group_order(); + let acc_val = u8_32_as_nat(&acc.bytes); + let old_acc_val = u8_32_as_nat(&_old_acc.bytes); + let scalar_val = u8_32_as_nat(&scalars[i as int].bytes); + let sum_prev = sum_of_scalars(scalars@.subrange(0, i as int)); + + lemma_mod_bound(old_acc_val as int + scalar_val as int, L as int); + lemma_add_mod_noop(old_acc_val as int, scalar_val as int, L as int); + lemma_add_mod_noop(sum_prev as int, scalar_val as int, L as int); + lemma_mod_twice(sum_prev as int + scalar_val as int, L as int); + } + } + + proof { + assert(scalars@.subrange(0, n as int) =~= scalars@); + } + + acc + } +-/ + +-- Level 2: the Boole program, checked by cvc5. +private def sumofsliceTranslatedSeed : StrataDDM.Program := +#strata +program Boole; +type Scalar := Sequence (bv W8); +function u8_32_as_nat (bytes : Sequence (bv W8)) : nat { + nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 0))), nat_fromInt(1)), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 1))), nat_fromInt(256))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 2))), nat_fromInt(65536))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 3))), nat_fromInt(16777216))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 4))), nat_fromInt(4294967296))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 5))), nat_fromInt(1099511627776))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 6))), nat_fromInt(281474976710656))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 7))), nat_fromInt(72057594037927936))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 8))), nat_fromInt(18446744073709551616))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 9))), nat_fromInt(4722366482869645213696))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 10))), nat_fromInt(1208925819614629174706176))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 11))), nat_fromInt(309485009821345068724781056))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 12))), nat_fromInt(79228162514264337593543950336))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 13))), nat_fromInt(20282409603651670423947251286016))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 14))), nat_fromInt(5192296858534827628530496329220096))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 15))), nat_fromInt(1329227995784915872903807060280344576))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 16))), nat_fromInt(340282366920938463463374607431768211456))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 17))), nat_fromInt(87112285931760246646623899502532662132736))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 18))), nat_fromInt(22300745198530623141535718272648361505980416))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 19))), nat_fromInt(5708990770823839524233143877797980545530986496))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 20))), nat_fromInt(1461501637330902918203684832716283019655932542976))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 21))), nat_fromInt(374144419156711147060143317175368453031918731001856))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 22))), nat_fromInt(95780971304118053647396689196894323976171195136475136))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 23))), nat_fromInt(24519928653854221733733552434404946937899825954937634816))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 24))), nat_fromInt(6277101735386680763835789423207666416102355444464034512896))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 25))), nat_fromInt(1606938044258990275541962092341162602522202993782792835301376))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 26))), nat_fromInt(411376139330301510538742295639337626245683966408394965837152256))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 27))), nat_fromInt(105312291668557186697918027683670432318895095400549111254310977536))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 28))), nat_fromInt(26959946667150639794667015087019630673637144422540572481103610249216))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 29))), nat_fromInt(6901746346790563787434755862277025452451108972170386555162524223799296))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 30))), nat_fromInt(1766847064778384329583297500742918515827483896875618958121606201292619776))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 31))), nat_fromInt(452312848583266388373324160190187140051835877600158453279131187530910662656))) +} +function group_order () : nat { + nat_fromInt(7237005577332262213973186563042994240857116359379907606001950938285454250989) +} +function is_canonical_scalar (s : Scalar) : bool { + nat_lt(u8_32_as_nat(s), group_order) && Sequence.select!(s, 31) <= bv{8}(127) +} +function scalar_as_nat (s : Scalar) : nat { + u8_32_as_nat(s) +} +function group_canonical (n : nat) : nat { + nat_mod(n, group_order) +} +function u8_32_as_group_canonical (bytes : Sequence (bv W8)) : nat { + group_canonical(u8_32_as_nat(bytes)) +} +function scalar_as_canonical (s : Scalar) : nat { + u8_32_as_group_canonical(s) +} +rec function sum_of_scalars (scalars : Sequence Scalar, n : nat) : nat + requires nat_toInt(n) <= Sequence.length(scalars); + decreases nat_toInt(n) +{ + if nat_toInt(n) == 0 then nat_fromInt(0) else group_canonical(nat_add(sum_of_scalars(scalars, nat_fromInt(nat_toInt(n) - 1)), scalar_as_nat(Sequence.select(scalars, nat_toInt(n) - 1)))) +}; +axiom [sum_of_scalars_unfold]: ∀ scalars : (Sequence Scalar), n : nat :: nat_toInt(n) <= Sequence.length(scalars) ==> sum_of_scalars(scalars, n) == (if nat_toInt(n) == 0 then nat_fromInt(0) else group_canonical(nat_add(sum_of_scalars(scalars, nat_fromInt(nat_toInt(n) - 1)), scalar_as_nat(Sequence.select(scalars, nat_toInt(n) - 1))))); +function scalar_congruent_nat (s : Scalar, n : nat) : bool { + nat_toInt(scalar_as_canonical(s)) == nat_toInt(group_canonical(n)) +} +function Scalar_obeys_add_spec () : bool { + false +} +function Scalar_add_req (self : Scalar, rhs : Scalar) : bool { + is_canonical_scalar(self) && is_canonical_scalar(rhs) +} +function Scalar_add_spec (self : Scalar, rhs : Scalar) : Scalar; +function Scalar_ZERO () : Scalar; +axiom [Scalar_ZERO_lit_0]: Sequence.length(Scalar_ZERO) == 32; +axiom [Scalar_ZERO_lit_1]: ∀ k : int :: 0 <= k && k < 32 ==> Sequence.select!(Scalar_ZERO, k) == bv{8}(0); +axiom [lemma_scalar_zero_properties_ensures_0]: nat_toInt(scalar_as_nat(Scalar_ZERO)) == 0; +axiom [lemma_scalar_zero_properties_ensures_1]: nat_lt(scalar_as_nat(Scalar_ZERO), group_order); +axiom [lemma_scalar_zero_properties_ensures_2]: is_canonical_scalar(Scalar_ZERO); +axiom [lemma_scalar_zero_properties_ensures_3]: scalar_congruent_nat(Scalar_ZERO, nat_fromInt(0)); +procedure Scalar_add (self : Scalar, _rhs : Scalar) returns (result : Scalar) +spec { + requires Scalar_add_req(self, _rhs); + ensures Scalar_obeys_add_spec ==> result == Scalar_add_spec(self, _rhs); + ensures nat_toInt(scalar_as_nat(result)) == nat_toInt(group_canonical(nat_add(scalar_as_nat(self), scalar_as_nat(_rhs)))); + ensures is_canonical_scalar(result); +} +{ + havoc result; + assume [trusted_0]: Scalar_obeys_add_spec ==> result == Scalar_add_spec(self, _rhs); + assume [trusted_1]: nat_toInt(scalar_as_nat(result)) == nat_toInt(group_canonical(nat_add(scalar_as_nat(self), scalar_as_nat(_rhs)))); + assume [trusted_2]: is_canonical_scalar(result); +}; +procedure sum_of_slice (scalars : Sequence Scalar) returns (result : Scalar) +spec { + requires ∀ i : int :: 0 <= i && i < Sequence.length(scalars) ==> is_canonical_scalar(Sequence.select(scalars, i)); + ensures nat_lt(scalar_as_nat(result), group_order); + ensures is_canonical_scalar(result); + ensures scalar_congruent_nat(result, sum_of_scalars(scalars, nat_fromInt(Sequence.length(scalars)))); +} +{ + var n : int; + var acc : Scalar; + assume Sequence.length(scalars) <= 18446744073709551615; + n := Sequence.length(scalars); + acc := Scalar_ZERO; + for i : int := 0 to Sequence.length(scalars) - 1 + invariant 0 <= i && i <= Sequence.length(scalars) + invariant n == Sequence.length(scalars) + invariant ∀ j : int :: 0 <= j && j < Sequence.length(scalars) ==> is_canonical_scalar(Sequence.select(scalars, j)) + invariant nat_lt(scalar_as_nat(acc), group_order) + invariant is_canonical_scalar(acc) + invariant nat_toInt(scalar_as_nat(acc)) == nat_toInt(sum_of_scalars(scalars, nat_fromInt(i))) + { + call acc := Scalar_add(acc, Sequence.select(scalars, i)); + } + result := acc; + exit sum_of_slice; +}; +#end + +/-- info: +Obligation: pos.toInt_terminates_0 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_terminates_1 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_body_calls_pos..xO_h_0 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_body_calls_pos..xI_h_1 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_0 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_1 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_2 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_3 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_terminates_0 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_terminates_1 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_body_calls_sum_of_scalars_0 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_body_calls_Sequence.select_1 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: Scalar_add_ensures_2_9437 +Property: assert +Result: ✅ pass + +Obligation: Scalar_add_ensures_3_9512 +Property: assert +Result: ✅ pass + +Obligation: Scalar_add_ensures_4_9637 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_pre_sum_of_slice_requires_5_10058_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: sum_of_slice_post_sum_of_slice_ensures_8_10270_calls_sum_of_scalars_0 +Property: assert +Result: ✅ pass + +Obligation: loop_invariant_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: loop_invariant_calls_sum_of_scalars_0 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_0 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_1 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_2 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_3 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_4 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_5 +Property: assert +Result: ✅ pass + +Obligation: init_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: callElimAssert_Scalar_add_requires_1_9398_3 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_0 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_1 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_2 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_3 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_4 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_5 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_ensures_6_10177 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_ensures_7_10231 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_ensures_8_10270 +Property: assert +Result: ✅ pass +-/ +#guard_msgs in +#eval Strata.Boole.verify "cvc5" sumofsliceTranslatedSeed + (options := { Core.VerifyOptions.quiet with solverTimeout := 30 }) diff --git a/StrataBooleTest/demo.lean b/StrataBooleTest/demo.lean index 7f784ff..49e84e6 100644 --- a/StrataBooleTest/demo.lean +++ b/StrataBooleTest/demo.lean @@ -40,10 +40,12 @@ theorem loopSimple_smtVCsCorrectBoole : smtVCsCorrectBoole loopSimple := by gen_smt_vcs_boole all_goals (try grind) -/-- info: 'loopSimple_smtVCsCorrectBoole' depends on axioms: [propext, +/-- +info: 'loopSimple_smtVCsCorrectBoole' depends on axioms: [propext, Classical.choice, Quot.sound, loopSimple_smtVCsCorrectBoole._genSMTVCsBoole_tcbBridge_1_2, - loopSimple_smtVCsCorrectBoole._native.native_decide.ax_1_1]-/ + loopSimple_smtVCsCorrectBoole._native.native_decide.ax_1_1] +-/ #guard_msgs in #print axioms loopSimple_smtVCsCorrectBoole diff --git a/StrataBooleTest/find_max_verus.lean b/StrataBooleTest/find_max_verus.lean index 4873b15..1b9407f 100644 --- a/StrataBooleTest/find_max_verus.lean +++ b/StrataBooleTest/find_max_verus.lean @@ -135,11 +135,11 @@ Obligation: assert_7_1958 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_witnessOccurs_requires_0_1174_4 +Obligation: callElimAssert_witnessOccurs_requires_0_1174_4 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_witnessOccurs_requires_1_1206_5 +Obligation: callElimAssert_witnessOccurs_requires_1_1206_5 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/global_readonly_call.lean b/StrataBooleTest/global_readonly_call.lean index b4c8456..0200124 100644 --- a/StrataBooleTest/global_readonly_call.lean +++ b/StrataBooleTest/global_readonly_call.lean @@ -115,7 +115,34 @@ spec /-- info: Except.ok ["call inc(inout(g), inout(z), in(5))"] -/ #guard_msgs in #eval callHelper callerPgm -/-- info: [Strata.Core] Type checking succeeded. +/-- +info: [Strata.Core] Type checking succeeded. + + +VCs: +Label: inc_ensures_1_2613 +Property: assert +Assumptions: +inc_requires_0_2595: int.gt(z@1, 0) +Obligation: +true + +Label: callElimAssert_inc_requires_0_2595_6 +Property: assert +Assumptions: +main_caller_requires_2_2729: z@2 == 10 +main_caller_requires_3_2749: g@2 == 0 +Obligation: +int.gt(z@2, 0) + +Label: main_caller_ensures_4_2768 +Property: assert +Assumptions: +main_caller_requires_2_2729: z@2 == 10 +main_caller_requires_3_2749: g@2 == 0 +$__callElimAssume_inc_ensures_1_2613_7: g@3 == int.add(int.add(g@2, 5), z@3) +Obligation: +g@3 == 15 --- info: @@ -123,7 +150,7 @@ Obligation: inc_ensures_1_2613 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_inc_requires_0_2595_6 +Obligation: callElimAssert_inc_requires_0_2595_6 Property: assert Result: ✅ pass @@ -131,7 +158,8 @@ Obligation: main_caller_ensures_4_2768 Property: assert Result: ❓ unknown Model: -(g@9, 5) (z@2, 10) (g@0, 0) (z@10, 0)-/ +(g@3, 5) (g@2, 0) (z@2, 10) (z@3, 0) +-/ #guard_msgs in #eval Strata.Boole.verify "cvc5" callerPgm diff --git a/StrataBooleTest/stack_array_based.lean b/StrataBooleTest/stack_array_based.lean index a1acfaf..4af4ded 100644 --- a/StrataBooleTest/stack_array_based.lean +++ b/StrataBooleTest/stack_array_based.lean @@ -115,6 +115,73 @@ spec /-- info: [Strata.Core] Type checking succeeded. + +VCs: +Label: StackInit_ensures_1_1071 +Property: assert +Assumptions: +StackInit_requires_0_1020: int.ge(cap@1, 0) +Obligation: +true + +Label: StackInit_ensures_2_1091 +Property: assert +Assumptions: +StackInit_requires_0_1020: int.ge(cap@1, 0) +Obligation: +true + +Label: StackEmpty_ensures_3_1210 +Property: assert +Assumptions: +: if top@2 == 0 then top@2 == 0 else true +: if if top@2 == 0 then false else true then if top@2 == 0 then false else true else true +Obligation: +(if top@2 == 0 then true else false) ==> top@2 == 0 + +Label: StackEmpty_ensures_4_1238 +Property: assert +Assumptions: +: if top@2 == 0 then top@2 == 0 else true +: if if top@2 == 0 then false else true then if top@2 == 0 then false else true else true +Obligation: +top@2 == 0 ==> (if top@2 == 0 then true else false) + +Label: Push_ensures_6_1499 +Property: assert +Assumptions: +Push_requires_5_1448: int.lt(top@3, n@3) +Obligation: +true + +Label: Push_ensures_7_1530 +Property: assert +Assumptions: +Push_requires_5_1448: int.lt(top@3, n@3) +Obligation: +(S@3[int.add(top@3, 1):=x@1])[int.add(top@3, 1)] == x@1 + +Label: Push_ensures_8_1588 +Property: assert +Assumptions: +Push_requires_5_1448: int.lt(top@3, n@3) +Obligation: +forall __q0 : int :: int.le(1, __q0) && int.le(__q0, top@3) ==> (S@3[int.add(top@3, 1):=x@1])[__q0] == S@3[__q0] + +Label: Pop_ensures_10_1845 +Property: assert +Assumptions: +Pop_requires_9_1808: int.gt(top@4, 0) +Obligation: +true + +Label: Pop_ensures_11_1876 +Property: assert +Assumptions: +Pop_requires_9_1808: int.gt(top@4, 0) +Obligation: +true + --- info: Obligation: StackInit_ensures_1_1071 diff --git a/StrataBooleTest/verification_coverage.lean b/StrataBooleTest/verification_coverage.lean index d4dd8a7..f903e3a 100644 --- a/StrataBooleTest/verification_coverage.lean +++ b/StrataBooleTest/verification_coverage.lean @@ -223,11 +223,11 @@ Obligation: testEnsuresCallee_ensures_21_2030 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_testEnsuresCallee_requires_19_1946_2 +Obligation: callElimAssert_testEnsuresCallee_requires_19_1946_2 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_testEnsuresCallee_requires_19_1946_7 +Obligation: callElimAssert_testEnsuresCallee_requires_19_1946_7 Property: assert Result: ✅ pass @@ -247,7 +247,7 @@ Obligation: contradictoryEnsuresClause_ensures_29_3054 Property: assert Result: ✅ pass -Obligation: $__callElimAssert_contradictoryEnsuresClause_requires_28_2984_12 +Obligation: callElimAssert_contradictoryEnsuresClause_requires_28_2984_12 Property: assert Result: ✅ pass diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md new file mode 100644 index 0000000..f7ed6c8 --- /dev/null +++ b/docs/HoareLogic.md @@ -0,0 +1,306 @@ +# Verifying Boole programs in Lean + +## Goal + +Verify Boole programs in Lean with proofs that are sound by construction. Today's Lean +path, `gen_smt_vcs_boole`, trusts the VC generator, the SMT encoding and a bridge axiom; +strata-org/Strata#1488 showed it could prove `False`, and strata-org/Strata#1490 closed +that by refusing every VC the denotation does not cover. This route aims to trust only +Core's semantics and Lean (see Trusted base). Its goals range over Lean values, so Lean +tactics work on them without a solver. Boole programs reach it through their lowering to +Core. + +```mermaid +flowchart TD + B["Boole program"] -->|toCoreProgram| C["Strata Core program"] + subgraph solver ["Solver path"] + V["VC generation and SMT encoding"] --> S["cvc5, or Lean via lean-smt"] + end + subgraph lean ["Lean path"] + H["Core.Logic.Hoare: contract as a triple"] --> T["tactic applies the proved rules"] + T --> G["lifted goals over Lean values"] --> P["Lean proof"] + end + C --> V + C --> H + O["Core operational semantics"] -. rules are theorems about it .- H +``` + +## What Strata provides + +`Strata/Languages/Core/Logic/` is a Hoare logic for Core over Core's own operational +semantics: + +- `Triple π params Pre ss Post factory`, quantified over every model of `factory` + (`Lambda.Interp`). A model satisfies the factory's axioms. One is shown to exist for + Core's own factory (`Core.factoryInterp`: maps as functions, sequences as lists, sets as + predicates), none for a program's. +- Proved rules: `cmd`, `set`, `init`, `seq`, `block`, `exit_cons`, `ite`, `while_rule` + (partial correctness) and `Procedure.call_of_contract`. +- `Procedure.contractTriple`: `requires` and `ensures` as the triple to prove, with `old` + snapshots and typed parameters and clauses. Its factory is Core's operators plus the + functions declared before the procedure, with or without body + (`Program.factoryBeforeProcedure`). Datatype declarations add their constructors, + testers and destructors (strata-org/Strata#1502). Its + precondition assumes the axioms declared before the procedure + (`AxiomsBeforeProcedureDecl`), since strata-org/Strata#1499. +- Strata's notion of correctness, `ProcedureAssertsValidOnTraces.denote`: every assertion + on every run is valid and the postconditions hold, from entry environments satisfying + the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`). + The partial triple also asks that the assertions of every finite execution hold, + finished or not, so a proved contract triple gives all of this notion + (`procedureAssertsValidOnTraces_of_contractTriple`) without a termination premise. The + rules kept their signatures; only proofs that unfold the triple change. +- Denotational evaluation (since November 2026): `Expression.eval` is `LExpr.denoteEval` + over the factory and a model of it, and stores hold semantic values. Lifting lemmas + exist for `+`, `-`, `*` and the comparisons on `int`, three `bv16` operators, free + variables, `==` and `if` (`IntEvalProps.lean`, `BitVecEvalProps.lean`), with a generic + one for any binary operator that has a concrete evaluation (`eval_app2_op`). + +Its tests prove procedures by hand, with `native_decide` for facts about the AST, among +them ones with axioms, datatypes, maps and sequences. There is no automation and its +authors plan none: the triple is their specification of partial correctness, and +generating verification conditions against it is open to others. So the tactic is ours to +build, on a stable target. + +## Plan + +1. **Tactic.** Prove Strata's contract triple. Its precondition has the axioms declared + before the procedure, as Strata's notion of correctness assumes them, and a proved + triple gives all of that notion (`procedureAssertsValidOnTraces_of_contractTriple`). + Apply the rules + backwards and discharge their side conditions: `exitsCoveredByBlocks`, and `PostWF` for + a block that declares nothing, by evaluation on the concrete AST; `PostWF` for a block + with declarations from `denoteEval_congr`, since a postcondition does not read the + variables the block drops; and for a call `bodyFrame` and `bodyOutputsTyped`, which are + facts about every run of the callee's body. The rules for `assume`, `assert`, `havoc` + and a declaration without initialiser came with strata-org/Strata#1498. The result is one + goal per `assert`, loop invariant and `ensures`, over the store. This is `core_vcgen` + of the `StrataBoole/Deep/` experiment (fork branch `exp/deep-embedding`), retargeted to + Strata's `Triple`. +2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type + `int` is an `Int`, and evaluating an operator on values is the Lean operation. These are + lemmas in Strata, next to its `IntEvalProps`. + - Done: the integer operators and comparisons, equality and conditionals. + - In review: the Boolean connectives, `Sequence.length`, `select` and `select!` with the + facts their axioms give in every model, and that the factory of any procedure + resolves the built-ins as `Core.Factory` does (strata-org/Strata#1506); `div` and + `mod` at a non-zero divisor (strata-org/Strata#1507). + - In `StrataBoole/HoareLogic/HoareLift.lean`, until Strata has them: the Boolean of an integer + equality, reading a variable of the store inside a denotation, and a function as its + body from a factory lookup. + - The `bv` operators and conversions and `Map` follow when a program needs them. + + Lifting a clause takes five steps, done by hand once in + `StrataBooleTest/HoareLogic/hoare_lift_forall.lean` for a quantified clause of the shape + `dalek_sum_of_slice` has: + 1. evaluation to `true` is the denotation being `true` + (`LExpr.denoteEval_eq_ofBool_iff`); + 2. the store types the variables as the clause does, so annotating changes nothing + (`LExpr.annotateFvars_eq_self`); + 3. Strata's `denotes` tactic computes the denotation: a quantifier becomes a Lean `∀`, + the body a term in the model's operators; + 4. a variable read from the store is the value the store holds + (`HoareLift.fvarVal_of_store`); + 5. the built-in operators are their Lean operations (the `_opInterp_of_lookup` lemmas), + and a user function is its body where the proof needs it + (`HoareLift.opInterp_of_body`). + + So the lemmas for the benchmark are there once the two pull requests merge, and what is + left of this step is the tactic that runs the five steps. Its code has to live in a + module that imports Strata's denotation modules with `import all`, since `denotes` and + its lemmas are internal to them. + + This is `core_lift` of the same experiment. +3. **Boole entry.** `Strata.Boole.typeCheck` gives the type-checked Core program of a + `#strata program Boole` block as a Lean term, and the triple is stated on its + procedures, as in `hoare_max2.lean`. A reflection command on a fork branch wraps this. +4. **The model, in Strata.** Not needed to prove a triple, needed to trust one. + - Datatypes: done upstream. Constructors, testers and destructors are in the visible + factory (`Program.factoryBeforeProcedure` folds with `Decl.addToRuntimeFactory`, + strata-org/Strata#1502), and the model's datatype laws are disjointness, injectivity, + inversion and induction. + - A model exists for a program's factory with its axioms, built on the carrier + (Decisions). This rules out a vacuous triple, and proves the `nat` bridge axioms of + the intended `nat` instead of assuming them. A model holds every function to its + body, so termination of recursive functions belongs here: a terminating definition + always has a solution, a non-terminating one may have none. + - At a call, the callee's axioms are shown in the callee's entry store + (`call_of_contract` asks for them). For axioms that read no variable and a callee + declared no later than the caller, they follow from the caller's entry + (`AxiomsBeforeProcedureDecl.callee`, strata-org/Strata#1501), and + `Hoare.frame_factory` carries the caller's entry assumption to each call. + - Function preconditions, stated beside the triple. A precondition is an annotation and + a function stays total, so the triple holds without it; the checks the solver path + makes, such as sequence bounds, are a separate property. + - Rules for nondeterministic `if` and `while`. +5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so that + Boole has a meaning in its own terms and the lowering is proved, not trusted. It + follows steps 1 to 3 because the agreement theorem needs Core's semantics on the other + side. It is not for running programs; Strata's `StatementEval.lean` does that. Its + prerequisites are merged (strata-org/Strata-Boole#25, #26). Candidate: Velvet's + nondeterministic state monad with its VC generator. + +Milestones: `max2`, the counting loop of `demo.lean`, a loop over a sequence, `find_max`, +then the benchmark below. + +## Decisions + +- Build on `Core.Logic.Hoare`, not on a semantics of our own. `Deep/`'s `Exec` is not + connected to Core's semantics, and an interpreter with an adequacy proof would redo what + Strata's rules already prove. +- Core first, then Boole: Core is where the proved semantics lives, so a Boole semantics + has something to agree with. +- Goals over Lean values come from lifting, not from a monadic encoding, so + `Std.Do`/`mvcgen` is off the path. +- Failure is never vacuous: a construct the tactic cannot handle leaves its goal open. +- Termination is a separate proof. The tactic proves the partial triple. Strata has + total-correctness triples since November 2026 (`Core.Logic.HoareTotal`, + `Procedure.contractTripleTotal`, a `while_rule` with a natural-number measure), and + `TripleWith.of_partial_of_true` gives the total triple from the partial one and a total + triple with postcondition `True`. So termination needs only a measure per loop, reuses + the partial proof unchanged, and follows the benchmark. +- Datatypes: keep Strata's approach of stating their laws as conditions on every model, + and supply the model from one generic carrier, a single inductive of constructor + applications with a well-sortedness predicate (`DT.Carrier`, strata-org/Strata#1493, + written for the SMT denotation). `nat` is its `pos`/`nat` with `toInt` by structural + recursion. Per-program Lean inductives (strata-org/Strata#1480, closed) are not used: the SMT + path's goals must equal its denotation, which is over the carrier too. Readable goals + are notation added later. +- This is a deep embedding with shallow goals: the program stays data, and the user sees + goals over Lean values. + +## Coverage + +| Core | State | +| --- | --- | +| assignments, `init` with or without a value, `havoc`, `assert`, `assume`, blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | +| `if *`, `while *`, loop measures, `cover` | to add | +| `int`, `bool`, `bv n` | lifted: `+`, `-`, `*` and comparisons on `int`, `&&`, `\|\|`, three `bv16` operators; the rest to add (step 2) | +| `Map`, `Sequence`, `Set`, `string` | constrained in every model; lifting to add (step 2) | +| functions, with or without body | in the model | +| `axiom` | through `AxiomsBeforeProcedureDecl` (step 1); assumed until step 4 | +| datatypes, `nat` | constructors, testers and destructors in the visible factory (strata-org/Strata#1502), with disjointness, injectivity, inversion and induction | + +## Target: `dalek_sum_of_slice` + +`StrataBooleTest/dalek_sum_of_slice.lean` is the program this route has to reach. On this +branch it is checked on the solver path only, with all 36 obligations passing as on the +frozen demo branch; the demo's kernel stage relied on the trusted bridge of +`gen_smt_vcs_boole` and is not carried over. On the current Strata it type checks, both +contracts pass `contractChecksTyped`, and caller and callee see the same factory, as +`call_of_contract` requires. + +| It uses | Step | +| --- | --- | +| a `for` loop with six invariants and a `call`, `exit`, `assume`, two declarations without initialiser | 1 | +| `&&`, `==>`, `<=`, `<`, `Sequence` `select` and `length`, a quantified `requires` and invariant, functions to unfold (`Scalar_add_req`, `scalar_congruent_nat` and those they call) | 2 | +| 19 axioms, 12 of them the `nat` library's | assumed until 4 | + +- `nat` is used only through its library and those axioms, so the proof should need no + datatype reasoning and does not wait on step 4. +- `as_uint`, `select!` and the byte arithmetic occur only in the body of `u8_32_as_nat`, + which the proof does not open. `Int.Mod` enters through the `nat` library's axiom for + `nat.mod`, not through the procedure. +- The callee is trusted. Its body gives the result an arbitrary value and assumes each + `ensures` (`assume [trusted_k]`), so a call can run and what the callee promises is + its contract. A body `assume false` would also meet the contract, but a call runs the + callee's body, and every obligation of the caller after the first call would hold + vacuously. +- Lifted goals stay within what lean-smt closes (`Int`, `Bool`, `BitVec`): sequences as + a length and an index function, `nat` through `nat.toInt`. + +## Trusted base + +What a proved triple rests on, beyond Lean's kernel, Core's semantics and the contract as +written: + +| Trusted today | Removed by | +| --- | --- | +| the Boole to Core lowering | step 5 | +| the program's axioms, and that a model of the program with them exists, which for recursive functions includes their termination | step 4 | +| the Lean compiler, through `native_decide` on facts about the AST | kernel-checked facts in the tactic | + +Function preconditions and the termination of loops are not assumed: the partial triple +does not claim them, and each is a separate proof (step 4 and Decisions). + +The solver path trusts the lowering and the axioms too, and in addition Strata's +transformation pipeline, the SMT encoding and the solver. The tactic needs no adequacy +theorem: it builds a proof from rules that are theorems about the semantics, and the +kernel checks that proof for each program. + +## Status + +- Everything this document describes is in `StrataBoole/HoareLogic/`, with its tests in + `StrataBooleTest/HoareLogic/`. +- Steps 1 to 3 are automated for integer programs. `boole_prove pgm proc` + (`StrataBoole/HoareLogic/Pipeline.lean`) proves `Procedure.contractTriple` for a + procedure of a Boole program with `hoare_contract`, `hoare_vcs`, `hoare_lift` and `omega` + or `grind`. The milestone is reached: `max2` and the counting loop of `demo.lean` + (`StrataBooleTest/HoareLogic/demo_pipeline.lean`). +- `hoare_contract` and `hoare_vcs` apply weakest-precondition rules proved from Strata's, + `if *` and `while *` included (`StrataBoole/HoareLogic/Hoare/`), and leave one goal per + `assert`, invariant and `ensures`, named after its clause. +- `hoare_lift` (`StrataBoole/HoareLogic/Hoare/Lift/`) lifts the `int` and `bool` + built-ins, `==`, `if … then … else` and `∀`/`∃` over `int` to Lean propositions. A value + of any other type and an operator without a Lean counterpart are read in the model, and + the goal is then generalized over the model, so they end as type and function variables. + The axioms and the function definitions declared before the procedure are hypotheses. +- Also covered: `exit` at the end of its block, `call` of a procedure without a body, + `bool` parameters, `bv` literals. +- `sum_of_slice` of the dalek benchmark is proved + (`StrataBooleTest/HoareLogic/dalek_lift.lean`), its goals closed by lean-smt's `smt`. + `Scalar_add` is declared without a body there, which lowers to an abstract procedure: + its contract is trusted. +- Not covered yet: `call` of a procedure with a body, `inout` arguments of a call, loop + measures, the `bv` operators, `choose`. +- `max2` is proved against Strata's triple by hand (`StrataBooleTest/HoareLogic/hoare_max2.lean`): + `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, side conditions + by `native_decide`, operators lifted with Strata's lemmas (`IntEvalProps`, + `BoolEvalProps`) and `StrataBoole/HoareLogic/HoareLift.lean`. It is the specification of the tactic for straight-line + bodies with `if`. +- What the hand proof settled: under the module system, facts about factory entries need + `import all` and `simp`, not `rfl`. Typing derivations no longer have to be written: + Strata's lemmas take the evaluation of the subterms. +- Risk: discharging the side conditions is the bulk of step 1. Strata's hand proof of a + two-branch `if` is some 25 lines, its call test some 1400 lines for three procedures. +- `StrataBooleTest/HoareLogic/generic_datatypes.lean` is a first prototype of the carrier. + +## Strata changes for this route + +This branch pins the `integration/lean-route` branch of the fork: Strata main plus the +pull requests below that are still open, strata-org/Strata#1501, strata-org/Strata#1493, +strata-org/Strata#1506, strata-org/Strata#1507 and strata-org/Strata#1483. The pin returns +to strata-org/Strata when they merge. + +| Change | State | Used by | +| --- | --- | --- | +| strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | merged | step 1 | +| strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | merged | quantifier lifting in step 2 | +| strata-org/Strata#1499: the contract triple assumes the axioms declared before the procedure, and a proved triple gives the contract of Strata's notion of correctness | merged | step 1 | +| strata-org/Strata#1501: the callee's axioms at a call from the caller's entry, and a frame rule for facts about the factory | open | calls in step 1 | +| strata-org/Strata#1502: the constructors, testers and destructors of a datatype in the factory visible to a procedure | merged | datatypes in step 4 | +| strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, in review | the SMT path now, the model of step 4 later | +| strata-org/Strata#1506: evaluation lemmas for sequences and the Boolean connectives, and the built-ins in the factory of any procedure | open | step 2 | +| strata-org/Strata#1507: evaluation lemmas for integer division and remainder | open | step 2 | +| strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | +| strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | + +The integration branch also carries strata-org/Strata#1483, which concerns the solver path +only. Of step 4, the datatype functions are merged (strata-org/Strata#1502); the rest has +no pull request yet. + +## Open questions + +- `cover` is a reachability check, not a Hoare fact. How to state it? +- Goal names: carry the program's clause names into the goals the tactic leaves. +- Program models (step 4): how to show that a model of a program's factory and axioms + exists. Agree the shape with Strata before building. +- Trusted procedures: `Triple` runs a callee's body, so a trusted callee needs a body that + assumes its contract (Target). That body can go once Core's semantics gives a bodyless + procedure a meaning. + +## Sources + +- [Velvet (CAV'26)](https://ilyasergey.net/assets/pdf/papers/velvet-cav26.pdf) +- [Foundational Multi-Modal Program Verifiers (Loom, POPL'26)](https://ilyasergey.net/assets/pdf/papers/loom-popl26.pdf) +- [ilyasergey/lean-vcgen-tutorial](https://github.com/ilyasergey/lean-vcgen-tutorial) diff --git a/docs/onboarding.md b/docs/onboarding.md index 09e4185..656ed37 100644 --- a/docs/onboarding.md +++ b/docs/onboarding.md @@ -41,7 +41,7 @@ before you read the code as though it were the design. Rather than checking the SMT-LIB that comes out, it proves contracts against Core's Hoare logic, whose rules are theorems about Core's operational semantics, so the generator and encoder leave the trusted base. The program - is still data, so this is a deep embedding too. + is still data, so this is a deep embedding too. See `docs/HoareLogic.md`. * **cvc5 is one prover among several.** A Lean goal can be closed by `smt` (lean-smt, which calls cvc5 and replays its proof), by Lean Hammer, by `grind`, or by LLM-based and other AI-based provers. diff --git a/lake-manifest.json b/lake-manifest.json index 58a5330..e06e3cf 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -11,14 +11,14 @@ "inputRev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", "inherited": false, "configFile": "lakefile.lean"}, - {"url": "https://github.com/strata-org/Strata", + {"url": "https://github.com/kondylidou/Strata", "type": "git", "subDir": null, "scope": "", - "rev": "f64935eb433c9c099a9aee1091777b9b3fac755f", + "rev": "53a3ff3c404da9de3cafc24d19082cd3ecce8673", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "f64935eb433c9c099a9aee1091777b9b3fac755f", + "inputRev": "53a3ff3c404da9de3cafc24d19082cd3ecce8673", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", @@ -65,7 +65,7 @@ "type": "git", "subDir": null, "scope": "", - "rev": "aa0bf21c7317b7dafdd1e8f548d1ad68308a27af", + "rev": "08511c15d49117eb6108b06593c4b0cfd15e2449", "name": "StrataDDM", "manifestFile": "lake-manifest.json", "inputRev": "main", diff --git a/lakefile.toml b/lakefile.toml index efbebeb..5b48470 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -7,14 +7,20 @@ weakLeanArgs = ["--tstack=32768"] [[require]] name = "Strata" -git = "https://github.com/strata-org/Strata" -rev = "f64935eb433c9c099a9aee1091777b9b3fac755f" +# On this branch Strata is the `integration/lean-route` branch of the fork: Strata main +# plus the open PRs the Lean route needs (datatype denotation, checked-to-total sequence +# pass, the callee's axioms at a call, evaluation lemmas). It moves back to +# strata-org/Strata when they merge. +# A fixed commit, not a branch name, so `lake update` cannot move it. +git = "https://github.com/kondylidou/Strata" +rev = "53a3ff3c404da9de3cafc24d19082cd3ecce8673" [[require]] name = "smt" git = "https://github.com/ufmg-smite/lean-smt" rev = "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207" + [[lean_lib]] name = "StrataBoole"