Hoare Logic

5. Hoare: Hoare Logic, Part I🔗

Note to developers (Benjamin Pierce @bcpierce00, before next release, 2025)

There is an excellent and fairly polished problem on a Hoare Logic for a little assembly language in the materials for the 2025 CIS 5000 final exam at Penn. We should turn it into an exercise in this chapter!

Note to developers (Niklas Halonen @xhalo32)

Reply to Benjamin's note above: The way we do it now in Lean is to have a custom elaborater which avoids all the coercions plus doesn't need the syntax category for assertions.

Note to developers (Benjamin Pierce @bcpierce00, before next release, 2021)

Any chance we could move the (awkwardly placed) weakest precondition discussion to this chapter instead?

The terse version of the chapter needs serious work -- it has gotten quite ragged after a bunch of reorganization of the chapter over the past couple years. BCP 23: Did some work on it. Bit better now. But the notation issues make everything a bit heavy.

Note to developers
HIDE: What about typesetting multi-line triples as
{{ P }}
   c
{{ Q }}
instead of
  {{ P }}
c
  {{ Q }}
when we print them?
HIDE: At some point we should try one more time to see if it's
possible to use single curly braces for Hoare triples.  The Rocq
manual says "For the sake of factorization with Rocq predefined
rules, simple rules have to be observed for notations starting with
a symbol: e.g., rules starting with { or ( should be put at level
0."  Maybe this suggests a way forward...?
BCP 10/18: Nope.  Writing
   Notation "'{' P '}' c '{' Q '}'" :=
     (ValidHoareTriple P c Q) (at level 0, c at next level)
     : hoare_spec_scope.
yields
    Error: A notation must include at least one symbol.

HIDE: This file and all later ones should make a habit of always presenting both syntax and semantics of new language constructs in informal style as well as formal. See MoreStlc.v for a template.

Our goal in this chapter is to develop the tools to work through some simple examples of program verification -- i.e., to use the precise definition of Imp to prove formally that particular programs satisfy particular specifications of their behavior.

We'll develop a reasoning system called Floyd-Hoare Logic -- often shortened to just Hoare Logic -- in which each of the syntactic constructs of Imp is equipped with a generic "proof rule" that can be used to reason compositionally about the correctness of programs involving this construct.

Hoare Logic combines two beautiful ideas: a natural way of writing down specifications of programs, and a structured proof technique for proving that programs are correct with respect to such specifications -- where by "structured" we mean that the structure of proofs directly mirrors the structure of the programs that they are about.

Note to developers
HIDE: MRC'20: The terse version used to start with just an outline of
what we've done and of this chapter, but it never mentioned Hoare logic!
The text above seems like a better intro.

MRC'20: this is the former terse intro.

 What we've done so far:

 - Formalized Imp
      - identifiers and states
      - abstract syntax trees
      - evaluation functions (for [aexp]s and [bexp]s)
      - evaluation relation (for commands)

 - Proved some _metatheoretic_ properties
     - determinism of evaluation
     - equivalence of some different ways of writing down the
       definitions (e.g., functional and relational definitions of
       arithmetic expression evaluation)
     - guaranteed termination of certain classes of programs
     - meaning-preservation of some program transformations
     - behavioral equivalence of programs ([Equiv])

 We've dealt with a few sorts of properties of Imp programs:
   - Termination
   - Nontermination
   - Equivalence

 Topic:
   - A systematic method for reasoning about the _functional
     correctness_ of programs in Imp

 Goals:
   - a natural notation for _program specifications_ and
   - a _compositional_ proof technique for program correctness

 Plan:
   - specifications (assertions / Hoare triples)
   - proof rules
   - loop invariants
   - decorated programs
   - examples

5.1. Assertions🔗

An assertion is a logical claim about the state of a program's memory -- formally, a predicate of States.

open scoped Com MyGetElem abbrev Assertion := State → Prop
Note to developers

HIDE: MRC'20: pulled up these examples from the quiz/optional exercise so that there would be some modeling of the kinds of answers we expect.

For example,

  • fun st => st[X] = 3 holds for states st in which value of X is 3,

  • fun st => True hold for all states, and

  • fun st => False holds for no states.

Quiz

Paraphrase the following assertions in English (i.e., say which states satisfy them)

(A) fun st => st[X] ≤ st[Y]

(B) fun st => st[X] = 3 ∨ st[X] ≤ st[Y]

(C) fun st => st[Z] * st[Z] ≤ st[X] ∧ ¬ ((st[Z] + 1) * (st[Z] + 1) ≤ st[X])

5.1.1. Notations for Assertions🔗

We'll use Lean's notation features to make assertions look as much like informal math as possible.

For example, instead of writing

fun st => st[X] = m

we'll usually write just

{{ X = m }}
Note to developers (before next release)

RRand 2022: The coercion printing in recent updates is making the Hoare logic statements we're aiming to prove essentially unreadable. If the implicit coercions are too hard to deal with (I don't see why they would be, given the number of coercion happening here and in Imp) I would roll back to a previous version. I cannot read what's happening in my Rocq buffer.

Note to developers
HIDE: SAZ  2024: I'm confused by the above discussion.  Doesn't
[Add Printing Coercion Aexp_of_nat Aexp_of_aexp assert_of_Prop]
request Rocq to _show_ those coercions?  I've removed it.
HIDE: SAZ 2024:
From what I can tell, the reason the notations expand during
the proofs is that they're writen in such a way that they
inlude type annotations [(a : Aexp)] and explicit lambdas
[(fun st => a st + b st)], neither of which is stable under
simplification.  For example:

 [(fun st =>
    (fun st => (X:Aexp) st + (Y:Aexp) st) st +
    (fun st => (Z:Aexp) st) st)]

Will print as [X + Y + Z] until simplification, at which point
we have [(fun st => st X + st Y + st Z)] but there is no notation
that covers this case.

Here, the {{ A }} brackets delimit the scope of the assertion notation.

Note to developers

HIDE: Make things easily unfoldable.

HIDE: MRC'20: Recording this here because it took a merry chase through the Rocq manual to find it: this version of the Arguments command is documented under simpl.

Note to developers (One An @meluge)

The Rocq source here issues Arguments assert_of_Prop /. (and likewise for the other two lifting functions) so that simpl always unfolds them, with this instructors note: "These Arguments commands tell Rocq that these functions should always be unfolded during simplification (by simpl)."

SAZ 2024 - Why do we want these functions to simplify?
Ans: If [a : aexp] then in the assertion_scope [(X →ₜ a st; st)] and
[(X →ₜ aeval st a; st)] look different but are actually identical
thanks to the coercion [Aexp_of_aexp].

Claude suggested @[simp]-tagged characterizing lemmas next to the three lifting functions, a global simp attribute means every simp unfolds applied occurrences. Is there a better way?

Note to developers

NOTATION: BCP 20: It probably makes sense now to put all these in a custom grammar, so that we can really control how it looks and get rid of things like ap.

NOTATION: SAZ 2024: I have tried to implement the suggestion above.

There is now a custom entry [assn] for defining the syntax of
assertions.  Like the delimiters <{ }> used for Imp programs,
we now also have {{ }} delimiters for use with Assertions.

Inside that scope, variables, arithmetic and boolean expressions,
propositions, and function arguments are interpreted in the current
state.  This replaces the need for [ap], [ap2], and explicit lifting
markers.

A raw Lean assertion can also be written directly inside {{ }}.
Notation: Assertionsnamespace Assertion open Lean Elab Term Meta Imp.Elab scoped syntax:max "assn(" ident "; " term ")" : term scoped syntax:lead "{{" term "}}" : term -- `: Assertion` guards that the resulting type is `State → Prop`. macro_rules | `({{ $t }}) => `((fun st : _root_.State => assn(st; $t) : Assertion)) macro_rules | `(assn($st; $t)) => do let result ← match t with | `(($P)) => ``((assn($st; $P))) | `($l = $r) => ``(assn($st; $l) = assn($st; $r)) | `($l + $r) => ``(assn($st; $l) + assn($st; $r)) | `($l - $r) => ``(assn($st; $l) - assn($st; $r)) | `($l * $r) => ``(assn($st; $l) * assn($st; $r)) | `($l ≤ $r) => ``(assn($st; $l) ≤ assn($st; $r)) | `($l < $r) => ``(assn($st; $l) < assn($st; $r)) | `($l ≥ $r) => ``(assn($st; $l) ≥ assn($st; $r)) | `($l > $r) => ``(assn($st; $l) > assn($st; $r)) | `($l ∧ $r) => ``(assn($st; $l) ∧ assn($st; $r)) | `($l ∨ $r) => ``(assn($st; $l) ∨ assn($st; $r)) | `($l → $r) => ``(assn($st; $l) → assn($st; $r)) | `($l ↔ $r) => ``(assn($st; $l) ↔ assn($st; $r)) | `(¬ $p) => ``(¬ assn($st; $p)) | `($f $args*) => do let mut result := f for arg in args do result ← `($result assn($st; $arg)) pure result | _ => Macro.throwUnsupported return withSourceInfoOf t result elab_rules : term | `(assn($st; $t:term)) => do let t ← elabTerm t none let ty ← whnf (← inferType t) tryPostponeIfMVar ty let st ← elabTerm st none match_expr ty with | String => mkAppM ``_root_.MyGetElem.getElem #[st, t] | Aexp => mkAppM ``Aexp.eval #[st, t] | Bexp => mkAppM ``Bexp.eval #[st, t] | _ => match ty with | .forallE _ domain body _ => if body.isProp && (← isDefEq domain (mkConst ``_root_.State)) then pure <| mkApp t st else pure t | _ => pure t
Note to developers (Niklas Halonen)

Mention (don't explain macro hygiene though) why

#check {{ st[X] = st[Y] }}

doesn't work, but instead one should write

#check {{ fun st => st[X] = st[Y] }}

And mention that when inside the brackets, one sees in the infoview

st✝ : State

but outside the brackets, one sees fun st => st[X] = st[X] : State → Prop

Also: should we introduce the terminology "pure" for embedding propositions into assertions that are constant functions?

fun st => 1 = 2 : _root_.State → Prop#check {{ 1 = 2 }} fun st => st[X] = st[X] : _root_.State → Prop#check {{ X = X }} fun st => st[X] = 2 * st[X] : _root_.State → Prop#check {{ X = 2 * X }} -- X is the constant "X" defined in Imp fun st => sorry : _root_.State → Prop#check_failure Type mismatch st✝[X] has type Nat but is expected to have type Prop{{ X }} -- fails as expected fun st => True : _root_.State → Prop#check {{ True }} fun st => (fun st => st[X] = st[Y]) st : _root_.State → Prop#check {{ fun st => st[X] = st[Y] }} variable (a : Aexp) fun st => st[X] = Aexp.eval st a : _root_.State → Prop#check {{ X = a }} variable (b : Bexp) fun st => Bexp.eval st b = true : _root_.State → Prop#check {{ b }} fun st => ¬Bexp.eval st b = true : _root_.State → Prop#check {{ ¬ b }} fun st => Bexp.eval st b = true ∧ Bexp.eval st b = true : _root_.State → Prop#check {{ b ∧ b }} variable (P Q : Assertion) fun st => P st ∧ Q st : _root_.State → Prop#check {{ P ∧ Q }} variable (f : Nat → Nat → Nat → Nat) fun st => f st[X] st[Y] st[X] = 0 : _root_.State → Prop#check {{ f X Y X = 0 }} end Assertion open scoped Assertion

Function applications inside assertions automatically interpret their arguments in the current state:

{{ f e1 ... en }} stands for (fun st => f (e1 st) ... (en st)).

We can place a raw Lean function directly inside assertion notation:

For example: {{ fun st => ∀ x, st[x] = 0 }}

5.1.2. Example Assertions🔗

namespace ExamplePrettyAssertions def assertion1 : Assertion := {{ X = 3 }} def assertion2 : Assertion := {{ True }} def assertion3 : Assertion := {{ False }} def assertion4 : Assertion := {{ True ∨ False }} def assertion5 : Assertion := {{ X ≤ Y }} def assertion6 : Assertion := {{ X = 3 ∨ X ≤ Y }} def assertion7 : Assertion := {{ Z = max X Y }} def assertion8 : Assertion := {{ Z * Z ≤ X ∧ ¬ (((Nat.succ Z) * (Nat.succ Z)) ≤ X) }} def assertion9 : Assertion := {{ Nat.add X Y > max Y X }} variable {xs : List Nat} -- #check {{ xs = X }} /-- info: def ExamplePrettyAssertions.assertion8 : Assertion := fun st => st[Z] * st[Z] ≤ st[X] ∧ ¬st[Z].succ * st[Z].succ ≤ st[X] -/ #guard_msgs in #print assertion8 end ExamplePrettyAssertions

5.1.3. Printing Assertions🔗

Notation encoding: printing assertions backnamespace Assertion.Delab open Lean PrettyPrinter Delaborator SubExpr Imp.Elab Imp.Delab private def getAssn (stx : Term) : Term := withSourceInfoOf (canonical := false) stx <| Unhygienic.run do match stx with | `({{ $P }}) => return P | _ => return stx /-- Rebuild the surface form of an assertion body, undoing the state threading the `assn` elaborator performs: `st[X]` prints as `X`, `Aexp.eval st a` as `a`, `Bexp.eval st b = true` as `b`, an applied assertion `P st` as `P`, and a subterm that does not mention the state prints as itself. -/ partial def delabBody (stId : FVarId) : DelabM Term := do let e ← getExpr if !e.containsFVar stId then delab else match_expr e with | MyGetElem.getElem _ _ _ _ st _ => guard (st == .fvar stId) withAppArg delab | Aexp.eval st _ => guard (st == .fvar stId) withAppArg delab | HAdd.hAdd _ _ _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) + $(← withAppArg (delabBody stId))) | HSub.hSub _ _ _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) - $(← withAppArg (delabBody stId))) | HMul.hMul _ _ _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) * $(← withAppArg (delabBody stId))) | Eq _ l r => -- `Bexp.eval st b = true` is the threaded form of a bare boolean `b` if r.isConstOf ``Bool.true && l.isAppOfArity ``Bexp.eval 2 && l.appFn!.appArg! == .fvar stId then withAppFn <| withAppArg <| withAppArg delab else `($(← withAppFn <| withAppArg (delabBody stId)) = $(← withAppArg (delabBody stId))) | Ne _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) ≠ $(← withAppArg (delabBody stId))) | LE.le _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) ≤ $(← withAppArg (delabBody stId))) | LT.lt _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) < $(← withAppArg (delabBody stId))) | GE.ge _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) ≥ $(← withAppArg (delabBody stId))) | GT.gt _ _ _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) > $(← withAppArg (delabBody stId))) | And _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) ∧ $(← withAppArg (delabBody stId))) | Or _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) ∨ $(← withAppArg (delabBody stId))) | Iff _ _ => `($(← withAppFn <| withAppArg (delabBody stId)) ↔ $(← withAppArg (delabBody stId))) | Not _ => `(¬ $(← withAppArg (delabBody stId))) | _ => if e.isArrow then `($(← withBindingDomain (delabBody stId)) → $(← withBindingBody `h (delabBody stId))) else if let .app f v := e then if v == .fvar stId && !f.containsFVar stId then -- an applied assertion `P st` (or an applied escape lambda) if f.isLambda then withAppFn <| withOptions (pp.notation.set · false) delab else withAppFn delab else `($(← withAppFn (delabBody stId)) $(← withAppArg (delabBody stId))) else failure /-- Print an `Assertion`-valued term as it appears inside `{{ … }}`: a state lambda is un-threaded; a term the printer cannot rebuild falls back to the raw lambda, which is exactly this notation's escape form. -/ partial def delabAssn : DelabM Term := do if (← getExpr).isLambda then (withBindingBody' `st (pure ·.fvarId!) fun stId => delabBody stId) <|> withOptions (pp.notation.set · false) Delaborator.delab else delab /-- Print an assertion-position argument: a state lambda gets the `{{ … }}` notation; any other term (a named assertion, a substitution) already reads well bare. -/ def delabAssnArg (i : Nat) : DelabM Term := do if (← withNaryArg i getExpr).isLambda then `({{ $(← withNaryArg i delabAssn) }}) else withNaryArg i Delaborator.delab /-- Print a bare assertion lambda in `{{ … }}` notation. Keyed on lambdas at large, so the guards bail out cheaply unless the binder is a `State` and the body is a proposition the printer can rebuild. -/ @[delab lam] def delabAssertion : Delab := whenPPOption getPPNotation do let e ← getExpr guard <| e.isLambda && e.bindingDomain!.isConstOf ``_root_.State let P ← withBindingBody' `st (pure ·.fvarId!) fun stId => do guard (← Meta.inferType (← getExpr)).isProp delabBody stId `({{ $P }}) end Assertion.Delab

5.1.4. Assertion Implication🔗

Given two assertions P and Q, we say that P implies Q, written P ->> Q, if, whenever P holds in some state st, Q also holds.

def AssertImplies (P Q : Assertion) : Prop := ∀ st, P st → Q st

Note that the notation for assertion implication is analogous to the "usual" Lean implication →.

notation:26 P:27 " ->> " Q:27 => AssertImplies P Q theorem assertImplies_def {P Q : Assertion} : P ->> Q ↔ ∀ st, P st → Q st := P:AssertionQ:Assertion⊢ P ->> Q ↔ ∀ (st : State), P st → Q st All goals completed! 🐙

We'll also want the "iff" variant of implication between assertions:

notation:26 P:27 " <<->> " Q:27 => AssertImplies P Q ∧ AssertImplies Q P theorem assertIff_def {P Q : Assertion} : P <<->> Q ↔ AssertImplies P Q ∧ AssertImplies Q P := P:AssertionQ:Assertion⊢ (P ->> Q) ∧ (Q ->> P) ↔ (P ->> Q) ∧ (Q ->> P) All goals completed! 🐙
Notation encoding: printing implications backnamespace Assertion.Delab open Lean PrettyPrinter Delaborator SubExpr @[delab app.AssertImplies] def delabAssertImplies : Delab := whenPPOption getPPNotation do guard <| (← getExpr).isAppOfArity ``AssertImplies 2 `($(← delabAssnArg 0) ->> $(← delabAssnArg 1)) /-- `<<->>` abbreviates a conjunction of two `AssertImplies`, so its delaborator is keyed on `∧` and bails out unless the two conjuncts mirror each other. -/ @[delab app.And] def delabAssertIff : Delab := whenPPOption getPPNotation do let e ← getExpr guard <| e.isAppOfArity ``And 2 let l := e.appFn!.appArg! let r := e.appArg! guard <| l.isAppOfArity ``AssertImplies 2 && r.isAppOfArity ``AssertImplies 2 guard <| l.appFn!.appArg! == r.appArg! && l.appArg! == r.appFn!.appArg! `($(← withNaryArg 0 <| delabAssnArg 0) <<->> $(← withNaryArg 0 <| delabAssnArg 1)) end Assertion.Delab

5.2. Hoare Triples, Informally🔗

A Hoare triple is a claim about the state before and after executing a command. A commond notation for Hoare triples, and the one we use in this book, is

{{P}} c {{Q}}

meaning:

  • If command c begins execution in a state satisfying assertion P,

  • and if c eventually terminates in some final state,

  • then that final state will satisfy the assertion Q.

Assertion P is called the precondition of the triple, and Q is the postcondition.

For example,

  • The Hoare triple

{{X = 0}} X := X + 1 {{X = 1}}

states that command X := X + 1 will transform a state in which X = 0 to a state in which X = 1.

  • On the other hand,

∀ m, {{X = m}} X := X + 1 {{X = m + 1}}

is a proposition stating that the Hoare triple {{X = m}} X := X + 1 {{X = m + 1}} is valid for any choice of m. Note that m in the two assertions is a reference to the Lean variable m, which is bound outside the Hoare triple.

Quiz

Paraphrase the following in English.

1) {{True}} c {{X = 5}}

2) ∀ m, {{X = m}} c {{X = m + 5}}

3) {{X ≤ Y}} c {{Y ≤ X}}

4) {{True}} c {{False}}

5) ∀ m,
     {{X = m}}
     c
     {{Y = real_fact m}}

6) ∀ m,
     {{X = m}}
     c
     {{(Z * Z) ≤ m ∧ ¬ ((Z + 1) * (Z + 1) ≤ m)}}
Show solution
  1. If command c terminates starting in an arbitrary state it produces a state where the value of X is equal to 5.

  2. Starting in a state where the value of X is m, if c terminates the value of X is equal to m+5.

  3. Starting in a state where the value of X less or equal than the value of Y, if c terminates then the value of Y is less or equal than the value of X.

  4. c doesn't terminate on any starting state

  5. If c terminates then Y contains as a value the factorial of the initial value of X.

  6. If c terminates starting in a state in which the value of X is equal to, then Z contains the integer square root of the initial value of X.

Quiz

Is the following Hoare triple valid -- i.e., is the claimed relation between P, c, and Q true?

{{True}} X := 5 {{X = 5}}

(A) Yes

(B) No

Quiz

What about this one?

{{X = 2}} X := X + 1 {{X = 3}}

(A) Yes

(B) No

Quiz

What about this one?

{{True}} X := 5; Y := 0 {{X = 5}}

(A) Yes

(B) No

Quiz

What about this one?

{{X = 2 ∧ X = 3}} X := 5 {{X = 0}}

(A) Yes

(B) No

Quiz

What about this one?

{{True}} skip {{False}}

(A) Yes

(B) No

Quiz

What about this one?

{{False}} skip {{True}}

(A) Yes

(B) No

Quiz

What about this one?

{{True}} while true do skip end {{False}}

(A) Yes

(B) No

Quiz

This one?

{{X = 0}}
  while X = 0 do X := X + 1 end
{{X = 1}}

(A) Yes

(B) No

Quiz

This one?

{{X = 1}}
  while X ≠ 0 do X := X + 1 end
{{X = 100}}

(A) Yes

(B) No

5.3. Hoare Triples, Formally🔗

We formalize valid Hoare triples in Lean as follows:

open scoped HasEval def ValidHoareTriple (P : Assertion) (c : Com) (Q : Assertion) : Prop := ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' class HasTriple (Com : Type) where Triple : Assertion → Com → Assertion → Prop namespace HasTriple /-- Hoare triple: `{{ P }} c {{ Q }}` with `imp_com` command syntax -/ scoped syntax:lead "{{" term "}} " imp_com:min " {{" term "}}" : term scoped macro_rules | `({{ $P }} $c:imp_com {{ $Q }}) => ``(HasTriple.Triple ({{ $P }}) (imp { $c }) ({{ $Q }})) end HasTriple instance : HasTriple Com where Triple := ValidHoareTriple
Note to developers (Niklas Halonen @xhalo32)

Something strange is going on in theorem if_example, using apply hoare_consequence_pre followed by · exact hoare_asgn works, but refine hoare_consequence_pre hoare_asgn ?_ or apply hoare_consequence_pre hoare_asgn don't. The only solution I found was to mark ValidHoareTriple irreducible.

It has to do something with apply and refine looking inside the implication in ∀ {st st'}, ...

We make ValidHoareTriple irreducible for "technical reasons", and use it only via validHoareTriple_def in proofs.

open scoped HasTriple theorem validHoareTriple_def {P : Assertion} {c : Com} {Q : Assertion} : {{ P }} c {{ Q }} ↔ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' := P:Assertionc:ComQ:Assertion⊢ HasTriple.Triple ({{P}}) c ({{Q}}) ↔ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' All goals completed! 🐙 attribute [irreducible] ValidHoareTriple
Notation encoding: printing triples back

The delaborator is agnostic to the command type: it prints the command with whatever printer is registered for its constructors and splices the result into the triple, so a language-extension chapter only has to register a printer for its own Com.

Note to developers (Niklas Halonen @xhalo32)

Can we use an unexpander for this? Something like

@[app_unexpander HasTriple.Triple]
def unexpandTriple : Lean.PrettyPrinter.Unexpander
  | `($_ ({{ $P }}) (imp { $c }) ({{ $Q }})) => ``({{ $P }} $c {{ $Q }})
  | _ => throw ()
namespace HasTriple.Delab open Lean PrettyPrinter Delaborator SubExpr Assertion.Delab Imp.Delab @[delab app.HasTriple.Triple] def delabTriple : Delab := whenPPOption getPPNotation do guard <| (← getExpr).isAppOfArity ``HasTriple.Triple 5 let P ← withNaryArg 2 delabAssn let c ← withNaryArg 3 delab let Q ← withNaryArg 4 delabAssn match c with | `(imp { $c:imp_com }) => ``({{ $P }} $c:imp_com {{ $Q }}) | c => ``({{ $P }} ~$c {{ $Q }}) end HasTriple.Delab
Exercise★(hoare_post_true)

Prove that if Q holds in every state, then any triple with Q as its postcondition is valid.

theorem declaration uses `sorry`hoare_post_true {P Q : Assertion} {c : Com} (h : ∀ st, Q st) : {{ P }} c {{ Q }} := P:AssertionQ:Assertionc:Comh:∀ (st : State), Q st⊢ {{P}} ~c {{Q}} All goals completed! 🐙
Exercise★(hoare_pre_false) (Optional)

Prove that if P holds in no state, then any triple with P as its precondition is valid.

theorem declaration uses `sorry`hoare_pre_false {P Q : Assertion} {c : Com} (h : ∀ st, ¬ (P st)) : {{ P }} c {{ Q }} := P:AssertionQ:Assertionc:Comh:∀ (st : State), ¬P st⊢ {{P}} ~c {{Q}} All goals completed! 🐙

5.4. Proof Rules🔗

We want to be able to prove Hoare triples formally.

Here's our plan:

  • introduce one "proof rule" for each Imp syntactic form

  • plus a couple of "structural rules" that help glue proofs together

  • prove these rules correct in terms of the definition of ValidHoareTriple

  • prove programs correct using these proof rules, without ever unfolding the definition of ValidHoareTriple

5.4.1. Skip🔗

Since skip doesn't change the state, it preserves any assertion P:

--------------------  (hoare_skip)
{{ P }} skip {{ P }}
theorem hoare_skip {P : Assertion} : {{ P }} skip {{ P }} := P:Assertion⊢ {{P}} skip {{P}} P:Assertion⊢ ∀ {st st' : State}, (st =[ skip ]=> st') → P st → P st' P:Assertionst:Statest':Stateh:st =[ skip ]=> st'hpre:P st⊢ P st' P:Assertionst:Statehpre:P st⊢ P st All goals completed! 🐙

5.4.2. Sequencing🔗

If command c1 takes any state where P holds to a state where Q holds, and if c2 takes any state where Q holds to one where R holds, then doing c1 followed by c2 will take any state where P holds to one where R holds:

 {{ P }} c1 {{ Q }}
 {{ Q }} c2 {{ R }}
----------------------  (hoare_seq)
{{ P }} c1; c2 {{ R }}
theorem hoare_seq {P Q R : Assertion} {c1 c2 : Com} (h1 : {{ Q }} c2 {{ R }}) (h2 : {{ P }} c1 {{ Q }}) : {{ P }} c1; c2 {{ R }} := P:AssertionQ:AssertionR:Assertionc1:Comc2:Comh1:{{Q}} ~c2 {{R}}h2:{{P}} ~c1 {{Q}}⊢ {{P}} c1; c2 {{R}} P:AssertionQ:AssertionR:Assertionc1:Comc2:Comh1:{{Q}} ~c2 {{R}}h2:{{P}} ~c1 {{Q}}⊢ ∀ {st st' : State}, (st =[ c1; c2 ]=> st') → P st → R st' P:AssertionQ:AssertionR:Assertionc1:Comc2:Comh1:{{Q}} ~c2 {{R}}h2:{{P}} ~c1 {{Q}}st:Statest':Stateh:st =[ c1; c2 ]=> st'hpre:P st⊢ R st' inversion h with | seq st'' hc1 hc2 => P:AssertionQ:AssertionR:Assertionc1:Comc2:Comh1:∀ {st st' : State}, (st =[ c2 ]=> st') → Q st → R st'h2:∀ {st st' : State}, (st =[ c1 ]=> st') → P st → Q st'st:Statest':Statehpre:P stst'':Statehc1:c1.EvalR st st''hc2:c2.EvalR st'' st'⊢ R st' All goals completed! 🐙

5.4.3. Assignment🔗

How can we complete this triple?

{{ ??? }}  X := Y  {{ X = 1 }}

One natural possibility is:

{{ Y = 1 }}  X := Y  {{ X = 1 }}

The precondition is just the postcondition, but with X replaced by Y.

How about this one?

{{ ??? }}  X := X + Y  {{ X = 1 }}

Replace X with X + Y:

{{ X + Y = 1 }}  X := X + Y  {{ X = 1 }}

This works because "equals 1" holding of X is guaranteed by the property "equals 1" holding of whatever is being assigned to X.

In general, the postcondition could be some arbitrary assertion Q, and the right-hand side of the assignment could be some arbitrary arithmetic expression a:

{{ ??? }}  X := a  {{ Q }}

The precondition would then be Q, but with any occurrences of X in it replaced by a.

Let's introduce a notation for this idea of replacing occurrences: Define Q \[X ↦ a] to mean "Q where a is substituted in place of X".

This yields the Hoare logic rule for assignment:

{{ Q [X ↦ a] }}  X := a  {{ Q }}

One way of reading this rule is: If you want statement X := a to terminate in a state that satisfies assertion Q, then it suffices to start in a state that also satisfies Q, except where a is substituted for every occurrence of X.

Here are some valid instances of the assignment rule:

{{ (X ≤ 5) [X ↦ X + 1] }}         (that is, X + 1 ≤ 5)
  X := X + 1
{{ X ≤ 5 }}

{{ (X = 3) [X ↦ 3] }}              (that is, 3 = 3)
  X := 3
{{ X = 3 }}

{{ (0 ≤ X ∧ X ≤ 5) [X ↦ 3] }}.  (that is, 0 ≤ 3 ∧ 3 ≤ 5)
  X := 3
{{ 0 ≤ X ∧ X ≤ 5 }}

To formalize the rule, we must first formalize the idea of "substituting an expression for an Imp variable in an assertion", which we refer to as assertion substitution, or Assertion.subst.

Intuitively, given a proposition P, a variable X, and an arithmetic expression a, we want to derive another proposition P' that is just the same as P except that P' should mention a wherever P mentions X.

This operation is related to the idea of substituting Imp expressions for Imp variables that we saw in Equiv (subst_aexp and friends). The difference is that, here, P is an arbitrary Lean assertion, so we can't directly "edit" its text.

However, we can achieve the same effect by evaluating P in an updated state, defined as follows:

def Assertion.subst (x : Ident) (a : Aexp) (P : Assertion) : Assertion := fun (st : State) => P (x →ₜ a.eval st ; st)
Note to developers (One An @meluge, before next release)

Introduce a notation typeclass for this (e.g. HasSubst)

namespace Assertion /-- Assertion substitution, written inside the braces: `{{ (P) [X ↦ a] }}`. The substituted assertion is re-read with the same notation, so Imp variables in it mean state lookups as usual; a named assertion is passed through directly. -/ scoped syntax:max term:arg " [" ident " ↦ " imp_aexp "]" : term macro_rules | `(assn($st; $P [$x ↦ $a:imp_aexp])) => match P with | `($_:ident) => ``(Assertion.subst $x (aexp { $a }) $P $st) | _ => ``(Assertion.subst $x (aexp { $a }) ({{ $P }}) $st) theorem subst_def {x : Ident} {a : Aexp} {P : Assertion} : Assertion.subst x a P = fun (st : State) => P (x →ₜ a.eval st ; st) := x:Identa:AexpP:Assertion⊢ subst x a P = {{P (((TotalMap.update instBEqOfDecidableEq) x) a)}} All goals completed! 🐙 @[simp] theorem subst_apply {x : Ident} {a : Aexp} {P : Assertion} {st : State} : Assertion.subst x a P st ↔ P (x →ₜ a.eval st ; st) := x:Identa:AexpP:Assertionst:State⊢ subst x a P st ↔ P (x →ₜ Aexp.eval st a ; st) All goals completed! 🐙 end Assertion

This notation allows us to write this operation as:

P [ X ↦ a ]
{{Assertion.subst X (aexp {2 * X}) ({{X ≤ 10}})}} : State → Prop#check (fun st => Assertion.subst X (aexp { 2 * X }) ({{ X ≤ 10 }}) st) {{Assertion.subst X (aexp {2 * X}) ({{X ≤ 10}})}} : State → Prop#check {{ (X ≤ 10) [X ↦ 2 * X] }} ∀ (st : State), ({{Assertion.subst X (aexp {2 * X}) ({{X ≤ 10}})}}) st : Prop#check (∀ st, ({{ (X ≤ 10) [X ↦ 2 * X] }}) st)
Notation encoding: printing substitutions backnamespace Assertion.Delab open Lean PrettyPrinter Delaborator SubExpr Imp.Delab /-- Print an `Assertion.subst` back in `P [x ↦ a]` notation. Emits the bare inside-the-braces form: the generic application case of `delabBody` picks it up inside an assertion body, and the enclosing printer supplies the single pair of braces. -/ @[app_unexpander Assertion.subst] def unexpandSubst : Unexpander | `($_ $x:ident $a $P) => match getAssn P with | `($P:ident) => `($P:ident [$x:ident ↦ $(getAexp a):imp_aexp]) | P => `(($P) [$x:ident ↦ $(getAexp a):imp_aexp]) | _ => throw () end Assertion.Delab

That is, P [X ↦ a] stands for an assertion -- let's call it P' -- that behaves just like P except that, wherever P looks up the variable X in the current state, P' instead uses the value of the expression a.

We can demonstrate formally that we have captured intuitive meaning of "assertion subsitution" by proving some example logical equivalences:

namespace ExampleAssertionSub example : {{ (X ≤ 5) [X ↦ 3] }} <<->> {{ 3 ≤ 5 }} := ⊢ {{(X ≤ 5) [X ↦ 3]}} <<->> {{3 ≤ 5}} ⊢ {{(X ≤ 5) [X ↦ 3]}} <<->> {{3 ≤ 5}} ⊢ (∀ (st : State), (X ≤ 5) [X ↦ 3] st → 3 ≤ 5) ∧ ({{3 ≤ 5}} ->> {{(X ≤ 5) [X ↦ 3]}}) ⊢ ∀ (st : State), (X ≤ 5) [X ↦ 3] st → 3 ≤ 5⊢ {{3 ≤ 5}} ->> {{(X ≤ 5) [X ↦ 3]}} ⊢ ∀ (st : State), (X ≤ 5) [X ↦ 3] st → 3 ≤ 5 st:Statea✝:(X ≤ 5) [X ↦ 3] st⊢ 3 ≤ 5 All goals completed! 🐙 ⊢ {{3 ≤ 5}} ->> {{(X ≤ 5) [X ↦ 3]}} st:Stateh:3 ≤ 5⊢ (X ≤ 5) [X ↦ 3] st All goals completed! 🐙 example : {{ (X ≤ 5) [X ↦ X + 1] }} <<->> {{ (X + 1) ≤ 5 }} := ⊢ {{(X ≤ 5) [X ↦ X + 1]}} <<->> {{X + 1 ≤ 5}} ⊢ {{(X ≤ 5) [X ↦ X + 1]}} <<->> {{X + 1 ≤ 5}} ⊢ {{(X ≤ 5) [X ↦ X + 1]}} ->> {{X + 1 ≤ 5}}⊢ {{X + 1 ≤ 5}} ->> {{(X ≤ 5) [X ↦ X + 1]}} ⊢ {{(X ≤ 5) [X ↦ X + 1]}} ->> {{X + 1 ≤ 5}} ⊢ ∀ (st : State), (X ≤ 5) [X ↦ X + 1] st → st[X] + 1 ≤ 5 st:State⊢ (X ≤ 5) [X ↦ X + 1] st → st[X] + 1 ≤ 5 All goals completed! 🐙 ⊢ {{X + 1 ≤ 5}} ->> {{(X ≤ 5) [X ↦ X + 1]}} ⊢ ∀ (st : State), st[X] + 1 ≤ 5 → (X ≤ 5) [X ↦ X + 1] st st:State⊢ st[X] + 1 ≤ 5 → (X ≤ 5) [X ↦ X + 1] st All goals completed! 🐙 end ExampleAssertionSub

Most of the simp calls rely on Assertion.subst_apply, TotalMap.update_eq plus some Aexp characterizing lemmas like Aexp.eval_num.

Now, using the substitution operation we've just defined, we can give the precise proof rule for assignment:

---------------------------- (hoare_asgn)
{{Q [X ↦ a]}} X := a {{Q}}

We can prove formally that this rule is indeed valid.

theorem hoare_asgn {Q : Assertion} {x : Ident} {a : Aexp} : {{ Q [x ↦ a] }} x := a {{ Q }} := Q:Assertionx:Identa:Aexp⊢ {{Q [x ↦ a]}} x := a {{Q}} Q:Assertionx:Identa:Aexp⊢ ∀ {st st' : State}, (st =[ x := a ]=> st') → Q [x ↦ a] st → Q st' Q:Assertionx:Identa:Aexpst:Statest':StatehE:st =[ x := a ]=> st'hQ:Q [x ↦ a] st⊢ Q st' inversion hE with | asgn n h => Q:Assertionx:Identa:Aexpst:StatehQ:Q [x ↦ a] st⊢ Q (x →ₜ Aexp.eval st a ; st) Q:Assertionx:Identa:Aexpst:StatehQ:Q (x →ₜ Aexp.eval st a ; st)⊢ Q (x →ₜ Aexp.eval st a ; st) All goals completed! 🐙

Here's a first formal proof of a Hoare triple using this rule.

theorem assertion_sub_example : {{ (X < 5) [X ↦ X + 1] }} X := X + 1 {{ X < 5 }} := ⊢ {{(X < 5) [X ↦ X + 1]}} X := X + 1 {{X < 5}} All goals completed! 🐙

Of course, we'd probably prefer to work with this simpler triple:

{{X < 4}} X := X + 1 {{X < 5}}

We will see how to do so in the next section.

Several proofs below use the facts about total-map updates proved in the Typeclasses chapter -- TotalMap.update_eq, TotalMap.update_neq, TotalMap.update_shadow, TotalMap.update_same, and TotalMap.update_permute. Make sure you understand their statements.

5.4.4. Consequence🔗

Sometimes the preconditions and postconditions we get from the Hoare rules won't quite be the ones we want in the particular situation at hand -- they may be logically equivalent but have a different syntactic form that fails to unify with the goal we are trying to prove, or they actually may be logically weaker (for preconditions) or stronger (for postconditions) than what we need.

For instance,

{{(X = 3) [X ↦ 3]}} X := 3 {{X = 3}},

follows directly from the assignment rule, but

{{True}} X := 3 {{X = 3}}

does not. This triple is valid, but it is not an instance of hoare_asgn because True and (X = 3) \[X ↦ 3] are not syntactically equal assertions.

However, they are logically equivalent, so if one triple is valid, then the other must certainly be as well. We can capture this observation with the following rule:

   {{P'}} c {{Q}}
     P <<->> P'
---------------------
   {{P}} c {{Q}}

Taking this line of thought a bit further, we can see that strengthening the precondition or weakening the postcondition of a valid triple always produces another valid triple. This observation is captured by two Rules of Consequence.

       {{P'}} c {{Q}}
          P ->> P'
-----------------------------   (hoare_consequence_pre)
       {{P}} c {{Q}}

       {{P}} c {{Q'}}
         Q' ->> Q
-----------------------------    (hoare_consequence_post)
       {{P}} c {{Q}}

Here are the formal versions:

theorem hoare_consequence_pre {P P' Q : Assertion} {c : Com} (hhoare : {{ P' }} c {{ Q }}) (himp : P ->> P') : {{ P }} c {{ Q }} := P:AssertionP':AssertionQ:Assertionc:Comhhoare:{{P'}} ~c {{Q}}himp:P ->> P'⊢ {{P}} ~c {{Q}} P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'⊢ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'st:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q st' P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'st:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ P' st P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:∀ (st : State), P st → P' stst:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ P' st All goals completed! 🐙 theorem hoare_consequence_post {P Q Q' : Assertion} {c : Com} (hhoare : {{ P }} c {{ Q' }}) (himp : Q' ->> Q) : {{ P }} c {{ Q }} := P:AssertionQ:AssertionQ':Assertionc:Comhhoare:{{P}} ~c {{Q'}}himp:Q' ->> Q⊢ {{P}} ~c {{Q}} P:AssertionQ:AssertionQ':Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st → Q' st'himp:Q' ->> Q⊢ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' P:AssertionQ:AssertionQ':Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st → Q' st'himp:Q' ->> Qst:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q st' P:AssertionQ:AssertionQ':Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st → Q' st'himp:∀ (st : State), Q' st → Q stst:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q st' P:AssertionQ:AssertionQ':Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st → Q' st'himp:∀ (st : State), Q' st → Q stst:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q' st' All goals completed! 🐙

For example, we can use the first consequence rule like this:

{{ True }} ->>
{{ (X = 1) [X ↦ 1] }}
  X := 1
{{ X = 1 }}

Or, formally...

theorem declaration uses `sorry`hoare_asgn_example1 : {{True}} X := 1 {{X = 1}} := ⊢ {{True}} X := 1 {{X = 1}} All goals completed! 🐙

We can also use it to prove the example mentioned earlier.

{{ X < 4 }} ->>
{{ (X < 5)[X ↦ X + 1] }}
  X := X + 1
{{ X < 5 }}

Or, formally ...

theorem declaration uses `sorry`assertion_sub_example2 : {{X < 4}} X := X + 1 {{X < 5}} := ⊢ {{X < 4}} X := X + 1 {{X < 5}} All goals completed! 🐙
Note to developers (Niklas Halonen @xhalo32)

The above proof uses simp_all purely because lia can't see that X and "X" are the same (they are currently marked as @[simp] in Imp).

Finally, here is a combined rule of consequence that allows us to vary both the precondition and the postcondition.

       {{P'}} c {{Q'}}
          P ->> P'
          Q' ->> Q
-----------------------------   (hoare_consequence)
       {{P}} c {{Q}}
Note to developers (Niklas Halonen @xhalo32)

In the following proof, (P' := P') is not necessary, however it avoids having a metavariable in the first goal. Another option is to just write exact hoare_consequence_pre (hoare_consequence_post htriple hpost) hpre.

theorem hoare_consequence {P P' Q Q' : Assertion} {c : Com} (htriple : {{ P' }} c {{ Q' }}) (hpre : P ->> P') (hpost : Q' ->> Q) : {{ P }} c {{ Q }} := P:AssertionP':AssertionQ:AssertionQ':Assertionc:Comhtriple:{{P'}} ~c {{Q'}}hpre:P ->> P'hpost:Q' ->> Q⊢ {{P}} ~c {{Q}} P:AssertionP':AssertionQ:AssertionQ':Assertionc:Comhtriple:{{P'}} ~c {{Q'}}hpre:P ->> P'hpost:Q' ->> Q⊢ {{P'}} ~c {{Q}}P:AssertionP':AssertionQ:AssertionQ':Assertionc:Comhtriple:{{P'}} ~c {{Q'}}hpre:P ->> P'hpost:Q' ->> Q⊢ P ->> P' P:AssertionP':AssertionQ:AssertionQ':Assertionc:Comhtriple:{{P'}} ~c {{Q'}}hpre:P ->> P'hpost:Q' ->> Q⊢ {{P'}} ~c {{Q}} All goals completed! 🐙 P:AssertionP':AssertionQ:AssertionQ':Assertionc:Comhtriple:{{P'}} ~c {{Q'}}hpre:P ->> P'hpost:Q' ->> Q⊢ P ->> P' All goals completed! 🐙

5.4.5. Automation🔗

Many of the proofs we have done so far with Hoare triples can be streamlined using the automation techniques that we introduced in the Automation chapter of Logical Foundations.

Recall that simp rewrites with any lemmas we pass it. The definitions whose meaning we keep needing to expose in this chapter -- ValidHoareTriple, AssertImplies, and Assertion.subst -- each come with a characterizing lemma (validHoareTriple_def, assertImplies_def, Assertion.subst_def) restating the definition as an equation. Passing these lemmas to simp replaces the defined notions by their meanings wherever they appear. We'll do that explicitly below (and shortly package the recipe up as a tactic of our own).

Note to developers (Claude)

The Rocq source here registers Hint Unfold assert_implies assertion_sub t_update : core for auto. That only widens auto's search (unlike the Arguments /. commands, it does not affect simpl), so its Lean counterpart is the assertion_auto tactic's simp list below -- not global @[simp] lemmas as for the notation wrappers, whose folded names carry no meaning in goals the way ->> and Assertion.subst do.

Note to developers (Niklas Halonen @xhalo32, NOW)

The following paragraph is outdated.

Here's a good candidate for automation:

theorem hoare_consequence_pre (P P' Q : Assertion) (c : Com)
    (hhoare : {{ P' }} c {{ Q }}) (himp : P ->> P') :
    {{ P }} c {{ Q }} := by
  rw [validHoareTriple_def] at hhoare ⊢
  intro st st' heval hpre
  apply hhoare heval
  rw [assertImplies_def] at himp
  exact himp _ hpre

Since AssertImplies is not marked irreducible, and assertImplies_def is a proof by definitional equality, we can skip the rw [assertImplies_def] at himp and use P ->> P' like an implication directly.

Note to developers (Niklas Halonen @xhalo32)

This needs a better explanation of when it's okay to use definitions without using their characterizing lemmas.

theorem hoare_consequence_pre' (P P' Q : Assertion) (c : Com) (hhoare : {{ P' }} c {{ Q }}) (himp : P ->> P') : {{ P }} c {{ Q }} := P:AssertionP':AssertionQ:Assertionc:Comhhoare:{{P'}} ~c {{Q}}himp:P ->> P'⊢ {{P}} ~c {{Q}} P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'⊢ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'st:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q st' P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'st:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ P' st All goals completed! 🐙

From now on, we will not usually rewrite assertImplies_def explicitly.

Since, after the rw and intro, the remaining steps just apply hypotheses to the goal (and each other), the remaining proof can be compressed into a single tactic: apply_rules.

theorem hoare_consequence_pre'' (P P' Q : Assertion) (c : Com) (hhoare : {{ P' }} c {{ Q }}) (himp : P ->> P') : {{ P }} c {{ Q }} := P:AssertionP':AssertionQ:Assertionc:Comhhoare:{{P'}} ~c {{Q}}himp:P ->> P'⊢ {{P}} ~c {{Q}} P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'⊢ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' P:AssertionP':AssertionQ:Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P' st → Q st'himp:P ->> P'st:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q st' All goals completed! 🐙

The same trick works for hoare_consequence_post.

theorem hoare_consequence_post' (P Q Q' : Assertion) (c : Com) (hhoare : {{ P }} c {{ Q' }}) (himp : Q' ->> Q) : {{ P }} c {{ Q }} := P:AssertionQ:AssertionQ':Assertionc:Comhhoare:{{P}} ~c {{Q'}}himp:Q' ->> Q⊢ {{P}} ~c {{Q}} P:AssertionQ:AssertionQ':Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st → Q' st'himp:Q' ->> Q⊢ ∀ {st st' : State}, (st =[ c ]=> st') → P st → Q st' P:AssertionQ:AssertionQ':Assertionc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st → Q' st'himp:Q' ->> Qst:Statest':Stateheval:st =[ c ]=> st'hpre:P st⊢ Q st' All goals completed! 🐙

We can also leave a metavariable for P' in hoare_asgn_example1, that we did earlier as an example of using the consequence rule:

theorem hoare_asgn_example1' : {{True}} X := 1 {{X = 1}} := ⊢ {{True}} X := 1 {{X = 1}} ⊢ {{?P'}} X := 1 {{X = 1}}⊢ {{True}} ->> ?P'⊢ Assertion -- not specifying `(P' := ...)` leaves a "hole" `?P'` ⊢ {{?P'}} X := 1 {{X = 1}} -- The goal is `{{?P'}} X := 1 {{X = 1}}` All goals completed! 🐙 -- Assigns `?P'` to `{{ (X = 1) [X ↦ 1] }}` (automatically closing `case P'`) ⊢ {{True}} ->> Assertion.subst "X" (aexp {1}) ({{X = 1}}) st:Statea✝:True⊢ Assertion.subst "X" (aexp {1}) ({{X = 1}}) st -- Since `->>` is an implication, we can just use `intro` directly. All goals completed! 🐙

The final bullet of that proof also looks like a candidate for automation.

theorem hoare_asgn_example1'' : {{True}} X := 1 {{X = 1}} := ⊢ {{True}} X := 1 {{X = 1}} ⊢ {{?P'}} X := 1 {{X = 1}}⊢ {{True}} ->> ?P'⊢ Assertion ⊢ {{?P'}} X := 1 {{X = 1}} All goals completed! 🐙 ⊢ {{True}} ->> Assertion.subst "X" (aexp {1}) ({{X = 1}}) All goals completed! 🐙

Now we have quite a nice proof script: it simply identifies the Hoare rules that need to be used and leaves the remaining low-level details up to Lean to figure out.

The other example of using consequence that we did earlier, hoare_asgn_example2, requires a little more work to automate. simp simplifies the assertion implication in the final bullet, but cannot finish it: the leftover goal is arithmetic, so it needs lia.

theorem assertion_sub_example2' : {{X < 4}} X := X + 1 {{X < 5}} := ⊢ {{X < 4}} X := X + 1 {{X < 5}} ⊢ {{?P'}} X := X + 1 {{X < 5}}⊢ {{X < 4}} ->> ?P'⊢ Assertion ⊢ {{?P'}} X := X + 1 {{X < 5}} All goals completed! 🐙 ⊢ {{X < 4}} ->> Assertion.subst "X" (aexp {X + 1}) ({{X < 5}}) ⊢ ∀ (st : State), st[X] < 4 → st["X"] + 1 < 5 -- an arithmetic goal remains All goals completed! 🐙

Let's introduce our own tactic to handle both that bullet and the bullet from example 1. A macro declaration gives a name to a canned sequence of tactics:

Note to developers (Niklas Halonen @xhalo32)

It's unfortunate that we need to unfold X, Y, Z, W in assertion_auto as simp wouldn't otherwise reduce X == Y to false. Note that Ident is an abbrev. Making it an implicit_reducible def breaks lia for some reason and doesn't resolve the issue.

@[implicit_reducible]
def Ident := String
deriving BEq, ReflBEq, LawfulBEq, DecidableEq
macro "assertion_auto" : tactic => `(tactic| focus (simp +decide [assertImplies_def, assertIff_def, validHoareTriple_def, Assertion.subst_def] at * <;> lia))
theorem assertion_sub_example2'' : {{X < 4}} X := X + 1 {{X < 5}} := ⊢ {{X < 4}} X := X + 1 {{X < 5}} ⊢ {{?P'}} X := X + 1 {{X < 5}}⊢ {{X < 4}} ->> ?P'⊢ Assertion ⊢ {{?P'}} X := X + 1 {{X < 5}} All goals completed! 🐙 ⊢ {{X < 4}} ->> Assertion.subst "X" (aexp {X + 1}) ({{X < 5}}) All goals completed! 🐙
theorem hoare_asgn_example1''' : {{True}} X := 1 {{X = 1}} := ⊢ {{True}} X := 1 {{X = 1}} ⊢ {{?P'}} X := 1 {{X = 1}}⊢ {{True}} ->> ?P'⊢ Assertion ⊢ {{?P'}} X := 1 {{X = 1}} All goals completed! 🐙 ⊢ {{True}} ->> Assertion.subst "X" (aexp {1}) ({{X = 1}}) All goals completed! 🐙

Again, we have quite a nice proof script. All the low-level details of proofs about assertions have been taken care of automatically. Of course, assertion_auto isn't able to prove everything we could possibly want to know about assertions -- there's no magic here! But it's pretty good.

5.4.6. Sequencing + Assignment🔗

Here's an example of a program involving both sequencing and assignment. Note the use of hoare_seq in conjunction with hoare_consequence_pre and apply's metavariables.

theorem hoare_asgn_example3 (a : Aexp) (n : Nat) : {{a = n}} X := a; skip {{X = n}} := a:Aexpn:Nat⊢ {{a = n}} X := a; skip {{X = n}} a:Aexpn:Nat⊢ {{?Q}} skip {{X = n}}a:Aexpn:Nat⊢ {{a = n}} X := a {{?Q}}a:Aexpn:Nat⊢ Assertion a:Aexpn:Nat⊢ {{?Q}} skip {{X = n}} -- right part of seq All goals completed! 🐙 a:Aexpn:Nat⊢ {{a = n}} X := a {{X = n}} -- left part of seq a:Aexpn:Nat⊢ {{?h2.P'}} X := a {{X = n}}a:Aexpn:Nat⊢ {{a = n}} ->> ?h2.P'a:Aexpn:Nat⊢ Assertion a:Aexpn:Nat⊢ {{?h2.P'}} X := a {{X = n}} All goals completed! 🐙 a:Aexpn:Nat⊢ {{a = n}} ->> Assertion.subst "X" a ({{X = n}}) All goals completed! 🐙

Informally, a nice way of displaying a proof using the sequencing rule is as a "decorated program" where the intermediate assertion Q is written between c1 and c2:

         {{ a = n }}
X := a
         {{ X = n }};    <--- decoration for Q
skip
         {{ X = n }}

We'll come back to the idea of decorated programs in much more detail in the next chapter.

5.4.7. Conditionals🔗

What sort of rule do we want for reasoning about conditional commands?

Certainly, if the same assertion Q holds after executing either of the branches, then it holds after the whole conditional. So we might be tempted to write:

        {{P}} c1 {{Q}}
        {{P}} c2 {{Q}}
---------------------------------
{{P}} if b then c1 else c2 {{Q}}

However, this is rather weak. For example, using this rule, we cannot show

{{ True }}
  if X = 0
    then Y := 2
    else Y := X + 1
  end
{{ X ≤ Y }}

since the rule doesn't tell us enough about the state in which the assignments take place in the "then" and "else" branches.

Better:

{{P ∧   b}} c1 {{Q}}
{{P ∧ ¬ b}} c2 {{Q}}
------------------------------------  (hoare_if)
{{P}} if b then c1 else c2 end {{Q}}
Note to developers (Niklas Halonen @xhalo32)

I have removed bassertion as it's an unnecessary abstraction and only adds overhead for the reader.

The following theorem is now unnecessary.

theorem bexp_eval_false (b : Bexp) (st : State) (h : b.eval st = false) : ¬ ({{ b }}) st := b:Bexpst:Stateh:Bexp.eval st b = false⊢ ¬({{b}}) st b:Bexpst:Stateh:Bexp.eval st b = false⊢ ¬Bexp.eval st b = true All goals completed! 🐙
Note to developers (One An @meluge)

The Rocq proof is the single tactic congruence. Using simp seems to work but should we build our own congruence tactic?

Now we can formalize the Hoare proof rule for conditionals and prove it correct.

The statement of the rule reads: given htrue : {{ P ∧ b }} c1 {{Q}} and hfalse : {{ P ∧ ¬b }} c2 {{Q}}, we can conclude {{P}} if (b) { c1 } else { c2 } {{Q}}.

theorem hoare_if {P Q : Assertion} {b : Bexp} {c1 c2 : Com} (htrue : {{ P ∧ b }} c1 {{ Q }}) (hfalse : {{ P ∧ ¬ b }} c2 {{ Q }}) : {{ P }} if (b) { c1 } else { c2 } {{ Q }} := P:AssertionQ:Assertionb:Bexpc1:Comc2:Comhtrue:{{P ∧ b}} ~c1 {{Q}}hfalse:{{P ∧ ¬b}} ~c2 {{Q}}⊢ {{P}} if (b) {c1} else {c2} {{Q}} P:AssertionQ:Assertionb:Bexpc1:Comc2:Comhtrue:∀ {st st' : State}, (st =[ c1 ]=> st') → P st ∧ Bexp.eval st b = true → Q st'hfalse:∀ {st st' : State}, (st =[ c2 ]=> st') → P st ∧ ¬Bexp.eval st b = true → Q st'⊢ ∀ {st st' : State}, (st =[ if (b) {c1} else {c2} ]=> st') → P st → Q st' P:AssertionQ:Assertionb:Bexpc1:Comc2:Comhtrue:∀ {st st' : State}, (st =[ c1 ]=> st') → P st ∧ Bexp.eval st b = true → Q st'hfalse:∀ {st st' : State}, (st =[ c2 ]=> st') → P st ∧ ¬Bexp.eval st b = true → Q st'st:Statest':StatehE:st =[ if (b) {c1} else {c2} ]=> st'hpre:P st⊢ Q st' inversion hE with | ifTrue hb hc1 => All goals completed! 🐙 | ifFalse hb hc => P:AssertionQ:Assertionb:Bexpc1:Comc2:Comhtrue:∀ {st st' : State}, (st =[ c1 ]=> st') → P st ∧ Bexp.eval st b = true → Q st'hfalse:∀ {st st' : State}, (st =[ c2 ]=> st') → P st ∧ ¬Bexp.eval st b = true → Q st'st:Statest':Statehpre:P sthb:¬Bexp.eval st b = truehc:c2.EvalR st st'⊢ Q st' All goals completed! 🐙

5.4.7.1. Example🔗

theorem if_example : {{True}} if (X = 0) { Y := 2 } else { Y := X + 1 } {{X ≤ Y}} := ⊢ {{True}} if (X = 0) {Y := 2} else {Y := X + 1} {{X ≤ Y}} ⊢ {{True ∧ bexp {X = 0} }} Y := 2 {{X ≤ Y}}⊢ {{True ∧ ¬bexp {X = 0} }} Y := X + 1 {{X ≤ Y}} ⊢ {{True ∧ bexp {X = 0} }} Y := 2 {{X ≤ Y}} -- Then ⊢ {{?htrue.P'}} Y := 2 {{X ≤ Y}}⊢ {{True ∧ bexp {X = 0} }} ->> ?htrue.P'⊢ Assertion ⊢ {{?htrue.P'}} Y := 2 {{X ≤ Y}} All goals completed! 🐙 ⊢ {{True ∧ bexp {X = 0} }} ->> Assertion.subst "Y" (aexp {2}) ({{X ≤ Y}}) All goals completed! 🐙 ⊢ {{True ∧ ¬bexp {X = 0} }} Y := X + 1 {{X ≤ Y}} -- Else ⊢ {{?hfalse.P'}} Y := X + 1 {{X ≤ Y}}⊢ {{True ∧ ¬bexp {X = 0} }} ->> ?hfalse.P'⊢ Assertion ⊢ {{?hfalse.P'}} Y := X + 1 {{X ≤ Y}} All goals completed! 🐙 ⊢ {{True ∧ ¬bexp {X = 0} }} ->> Assertion.subst "Y" (aexp {X + 1}) ({{X ≤ Y}}) All goals completed! 🐙

We can even shorten it a little bit more.

theorem if_example' : {{True}} if (X = 0) { Y := 2 } else { Y := X + 1 } {{X ≤ Y}} := ⊢ {{True}} if (X = 0) {Y := 2} else {Y := X + 1} {{X ≤ Y}} ⊢ {{True ∧ bexp {X = 0} }} Y := 2 {{X ≤ Y}}⊢ {{True ∧ ¬bexp {X = 0} }} Y := X + 1 {{X ≤ Y}} ⊢ {{True ∧ bexp {X = 0} }} Y := 2 {{X ≤ Y}}⊢ {{True ∧ ¬bexp {X = 0} }} Y := X + 1 {{X ≤ Y}} apply hoare_consequence_pre hoare_asgn (⊢ {{True ∧ ¬bexp {X = 0} }} ->> Assertion.subst "Y" (aexp {X + 1}) ({{X ≤ Y}}) All goals completed! 🐙)

5.4.7.2. Exercise: One-sided conditionals🔗

Note to developers

HIDE: Question from 2012, Midterm 2. One-sided conditionals.

5.4.8. While Loops🔗

The Hoare rule for while loops is based on the idea of a command invariant (or just invariant): an assertion whose truth is guaranteed after executing a command, assuming it is true before.

That is, an assertion P is a command invariant of c if

{{P}} c {{P}}

holds. Note that the command invariant might temporarily become false in the middle of executing c, but by the end of c it must be restored.

The Hoare while rule combines the idea of a command invariant with information about when guard b does or does not hold.

      {{P ∧ b}} c {{P}}
--------------------------------- (hoare_while)
{{P}} while b do c end {{P ∧ ¬b}}
Note to developers

HIDE: The big comment will not display nicely. But I guess it's folded...

theorem hoare_while {P : Assertion} {b : Bexp} {c : Com} (hhoare : {{P ∧ b}} c {{ P }}) : {{ P }} while (b) { c } {{P ∧ ¬ b}} := P:Assertionb:Bexpc:Comhhoare:{{P ∧ b}} ~c {{P}}⊢ {{P}} while (b) {c} {{P ∧ ¬b}} P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'⊢ ∀ {st st' : State}, (st =[ while (b) {c} ]=> st') → P st → P st' ∧ ¬Bexp.eval st' b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Stateheval:st =[ while (b) {c} ]=> st'hpre:P st⊢ P st' ∧ ¬Bexp.eval st' b = true /- We proceed by induction on `heval`, because, in the "keep looping" case, its hypotheses talk about the whole loop instead of just `c`. We begin by generalizing over an arbitrary command, together with an equation remembering that the command is the original loop. The cases for commands other than `while` are dismissed because their equations are contradictory. -/ P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statehpre:P stcmd:Comheq:imp {while (b) {c} } = cmdheval:st =[ cmd ]=> st'⊢ P st' ∧ ¬Bexp.eval st' b = true induction heval with P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comb0:Bexps0:Statec0:Comhb:Bexp.eval s0 b0 = falsehpre:P s0heq:imp {while (b) {c} } = imp {while (b0) {c0} }⊢ P s0 ∧ ¬Bexp.eval s0 b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comb0:Bexps0:Statec0:Comhb:Bexp.eval s0 b0 = falsehpre:P s0hbeq:b = b0hceq:c = c0⊢ P s0 ∧ ¬Bexp.eval s0 b = true All goals completed! 🐙 P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Coms0:States0':States0'':Stateb0:Bexpc0:Comhb:Bexp.eval s0 b0 = truehc:c0.EvalR s0 s0'hloop:imp {while (b0) {c0} }.EvalR s0' s0''ih1:P s0 → imp {while (b) {c} } = c0 → P s0' ∧ ¬Bexp.eval s0' b = trueih2:P s0' → imp {while (b) {c} } = imp {while (b0) {c0} } → P s0'' ∧ ¬Bexp.eval s0'' b = truehpre:P s0heq:imp {while (b) {c} } = imp {while (b0) {c0} }⊢ P s0'' ∧ ¬Bexp.eval s0'' b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Coms0:States0':States0'':Stateb0:Bexpc0:Comhb:Bexp.eval s0 b0 = truehc:c0.EvalR s0 s0'hloop:imp {while (b0) {c0} }.EvalR s0' s0''ih1:P s0 → imp {while (b) {c} } = c0 → P s0' ∧ ¬Bexp.eval s0' b = trueih2:P s0' → imp {while (b) {c} } = imp {while (b0) {c0} } → P s0'' ∧ ¬Bexp.eval s0'' b = truehpre:P s0hbeq:b = b0hceq:c = c0⊢ P s0'' ∧ ¬Bexp.eval s0'' b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Coms0:States0':States0'':Statehpre:P s0hb:Bexp.eval s0 b = truehc:c.EvalR s0 s0'ih1:P s0 → imp {while (b) {c} } = c → P s0' ∧ ¬Bexp.eval s0' b = truehloop:imp {while (b) {c} }.EvalR s0' s0''ih2:P s0' → imp {while (b) {c} } = imp {while (b) {c} } → P s0'' ∧ ¬Bexp.eval s0'' b = true⊢ P s0'' ∧ ¬Bexp.eval s0'' b = true All goals completed! 🐙 P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statehpre:P st✝heq:imp {while (b) {c} } = imp {skip}⊢ P st✝ ∧ ¬Bexp.eval st✝ b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statea✝:Aexpn✝:Natx✝:Identh✝:Aexp.eval st✝ a✝ = n✝hpre:P st✝heq:imp {while (b) {c} } = imp {x✝ := a✝}⊢ P (x✝ →ₜ n✝ ; st✝) ∧ ¬Bexp.eval (x✝ →ₜ n✝ ; st✝) b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comc₁✝:Comc₂✝:Comst✝:Statest'✝:Statest''✝:Stateh₁✝:c₁✝.EvalR st✝ st'✝h₂✝:c₂✝.EvalR st'✝ st''✝h₁_ih✝:P st✝ → imp {while (b) {c} } = c₁✝ → P st'✝ ∧ ¬Bexp.eval st'✝ b = trueh₂_ih✝:P st'✝ → imp {while (b) {c} } = c₂✝ → P st''✝ ∧ ¬Bexp.eval st''✝ b = truehpre:P st✝heq:imp {while (b) {c} } = imp {c₁✝; c₂✝}⊢ P st''✝ ∧ ¬Bexp.eval st''✝ b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statest'✝:Stateb✝:Bexpc₁✝:Comc₂✝:Comhb✝:Bexp.eval st✝ b✝ = truehc✝:c₁✝.EvalR st✝ st'✝hc_ih✝:P st✝ → imp {while (b) {c} } = c₁✝ → P st'✝ ∧ ¬Bexp.eval st'✝ b = truehpre:P st✝heq:imp {while (b) {c} } = imp {if (b✝) {c₁✝} else {c₂✝} }⊢ P st'✝ ∧ ¬Bexp.eval st'✝ b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statest'✝:Stateb✝:Bexpc₁✝:Comc₂✝:Comhb✝:Bexp.eval st✝ b✝ = falsehc✝:c₂✝.EvalR st✝ st'✝hc_ih✝:P st✝ → imp {while (b) {c} } = c₂✝ → P st'✝ ∧ ¬Bexp.eval st'✝ b = truehpre:P st✝heq:imp {while (b) {c} } = imp {if (b✝) {c₁✝} else {c₂✝} }⊢ P st'✝ ∧ ¬Bexp.eval st'✝ b = true P:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statest'✝:Stateb✝:Bexpc₁✝:Comc₂✝:Comhb✝:Bexp.eval st✝ b✝ = falsehc✝:c₂✝.EvalR st✝ st'✝hc_ih✝:P st✝ → imp {while (b) {c} } = c₂✝ → P st'✝ ∧ ¬Bexp.eval st'✝ b = truehpre:P st✝heq:imp {while (b) {c} } = imp {if (b✝) {c₁✝} else {c₂✝} }⊢ P st'✝ ∧ ¬Bexp.eval st'✝ b = trueP:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statest'✝:Stateb✝:Bexpc₁✝:Comc₂✝:Comhb✝:Bexp.eval st✝ b✝ = truehc✝:c₁✝.EvalR st✝ st'✝hc_ih✝:P st✝ → imp {while (b) {c} } = c₁✝ → P st'✝ ∧ ¬Bexp.eval st'✝ b = truehpre:P st✝heq:imp {while (b) {c} } = imp {if (b✝) {c₁✝} else {c₂✝} }⊢ P st'✝ ∧ ¬Bexp.eval st'✝ b = trueP:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comc₁✝:Comc₂✝:Comst✝:Statest'✝:Statest''✝:Stateh₁✝:c₁✝.EvalR st✝ st'✝h₂✝:c₂✝.EvalR st'✝ st''✝h₁_ih✝:P st✝ → imp {while (b) {c} } = c₁✝ → P st'✝ ∧ ¬Bexp.eval st'✝ b = trueh₂_ih✝:P st'✝ → imp {while (b) {c} } = c₂✝ → P st''✝ ∧ ¬Bexp.eval st''✝ b = truehpre:P st✝heq:imp {while (b) {c} } = imp {c₁✝; c₂✝}⊢ P st''✝ ∧ ¬Bexp.eval st''✝ b = trueP:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statea✝:Aexpn✝:Natx✝:Identh✝:Aexp.eval st✝ a✝ = n✝hpre:P st✝heq:imp {while (b) {c} } = imp {x✝ := a✝}⊢ P (x✝ →ₜ n✝ ; st✝) ∧ ¬Bexp.eval (x✝ →ₜ n✝ ; st✝) b = trueP:Assertionb:Bexpc:Comhhoare:∀ {st st' : State}, (st =[ c ]=> st') → P st ∧ Bexp.eval st b = true → P st'st:Statest':Statecmd:Comst✝:Statehpre:P st✝heq:imp {while (b) {c} } = imp {skip}⊢ P st✝ ∧ ¬Bexp.eval st✝ b = true All goals completed! 🐙
Note to developers (Benjamin Pierce @bcpierce00, before next release, 2021)

This definition / discussion could be clearer.

Note to developers (Benjamin Pierce @bcpierce00, before next release, 2023)
Maja says: The wording of "we will never enter the
loop" could definitely be improved. As is, it suggests a situation
where the loop condition itself can never be satisfied. I suspect that
a previous draft included a discussion that explicitly placed {{ P }}
before the while, perhaps along the lines of "a loop invariant P of
[while b do c end] is also an invariant of [while b do c end]" (which
is, FWIW, a (somewhat obtuse) way of stating a weaker variant of
hoare_while, without the b in the postcondition). Combined with the
fact that it is supposed to justify a somewhat surprising and
unexpected fact — [X = 0] is not what I would intuitively consider an
invariant of this loop — this sentence ends up being quite confusing.
I only understood it when I came back to find this excerpt.

We call P a loop invariant of while b do c end if

{{P ∧ b}} c {{P}}

is a valid Hoare triple.

This means that P will be true at the end of the loop body whenever the loop body executes. If P contradicts b, this holds trivially since the precondition is false.

For instance, X = 0 is a loop invariant of

while X = 2 do X := 1 end

since the program will never enter the loop.

Quiz

Is the assertion

Y = 0

a loop invariant of the following?

while X < 100 do X := X + 1 end

(A) Yes

(B) No

Quiz

Is the assertion

X = 0

a loop invariant of the following?

while X < 100 do X := X + 1 end

(A) Yes

(B) No

Quiz

Is the assertion

X < Y

a loop invariant of the following?

while true do X := X + 1; Y := Y + 1 end

(A) Yes

(B) No

Quiz

Is the assertion

X = Y + Z

a loop invariant of the following?

while Y > 10 do Y := Y - 1; Z := Z + 1 end

(A) Yes

(B) No

Note to developers (before next release)

This last quiz should be turned into a discussion in the text, at least in the full version -- indeed, maybe all these should be turned into a long discussion of what it means to be a loop invariant -- I think that would be pretty helpful.

Note to developers (Benjamin Pierce @bcpierce00, before next release, 2021)

What is this example doing here?? Needs some text.

Note to developers
HIDE: CJC: Maybe also a good place to talk about the structure of
our logic - that we've set up the hoare_* lemmas and they are all
the reasoning about Hoare triples that they should have to use (in
both formal or informal proofs)?  Probably should talk about this
somewhere or else we'll get back lots of proofs that unfold
ValidHoareTriple and reason at a low level everywhere.

BCP 21: I think we do this now?
Quiz

Is the assertion

X > 0

a loop invariant of the following?

while X = 0 do X := X - 1 end

(A) Yes

(B) No

Quiz

Is the assertion

X < 100

a loop invariant of the following?

while X < 100 do X := X + 1 end

(A) Yes

(B) No

Quiz

Is the assertion

X > 10

a loop invariant of the following?

while X > 10 do X := X + 1 end

(A) Yes

(B) No

5.4.8.1. Exercise: repeat🔗

Note to developers

HIDE: I (BCP) think I see a much simpler way to do the 'for' stuff. Instead of for x from a to b do c define for x downfrom a do c that steps from a down to 0. This will be much simpler to specify, though still an interesting challenge. (CJC: This still seemed hard to me, but I'm deleting it for now to get things looking right)

HIDE: Coming up with the precise rule for REPEAT is tricky, and so is proving formally that the precise rule passes the litmus test (at this point we only ask them to convince themselves informally there).

5.5. Summary🔗

The rules of Hoare Logic are:

       --------------------------- (hoare_asgn)
       {{Q [X ↦ a]}} X:=a {{Q}}

       --------------------  (hoare_skip)
       {{ P }} skip {{ P }}

         {{ P }} c1 {{ Q }}
         {{ Q }} c2 {{ R }}
        ----------------------  (hoare_seq)
        {{ P }} c1;c2 {{ R }}

        {{P ∧   b}} c1 {{Q}}
        {{P ∧ ¬ b}} c2 {{Q}}
------------------------------------  (hoare_if)
{{P}} if b then c1 else c2 end {{Q}}

         {{P ∧ b}} c {{P}}
  -----------------------------------  (hoare_while)
  {{P}} while b do c end {{P ∧ ¬ b}}

          {{P'}} c {{Q'}}
             P ->> P'
             Q' ->> Q
   -----------------------------   (hoare_consequence)
          {{P}} c {{Q}}

Our main task in this chapter has been to define the rules of Hoare logic, and prove that the definitions are sound. Having done so, we can go on and work within Hoare logic to prove that particular programs satisfy particular Hoare triples. In the next chapter, we'll see how Hoare logic is can be used to prove that more interesting programs satisfy interesting specifications of their behavior.

Crucially, we will do so without ever again unfolding the definition of Hoare triples -- i.e., we will take the rules of Hoare logic as a closed world for reasoning about programs.

5.6. Additional Exercises🔗

5.6.1. Havoc🔗

5.6.2. Assert and Assume🔗

Source revision: e85fe77, committed 2026-10-06 21:16 UTC