Library PLF.Hoare2
Set Warnings "-notation-overridden,-parsing,-deprecated-hint-without-locality".
Set Warnings "-intuition-auto-with-star".
From Stdlib Require Import Strings.String.
From PLF Require Import Maps.
From Stdlib Require Import Bool.
From Stdlib Require Import Arith.
From Stdlib Require Import EqNat.
From Stdlib Require Import PeanoNat. Import Nat.
From Stdlib Require Import Lia.
From PLF Require Export Imp.
From PLF Require Import Hoare.
Set Default Goal Selector "!".
Definition FILL_IN_HERE := <{True}>.
Decorated Programs
Example: Swapping
- We begin with the undecorated program (the unnumbered lines).
- We add the specification -- i.e., the outer precondition (1)
and postcondition (5). In the precondition, we use parameters
m and n to remember the initial values of variables X
and Y so that we can refer to them in the postcondition (5).
- We work backwards, mechanically, starting from (5) and proceeding until we get to (2). At each step, we obtain the precondition of the assignment from its postcondition by substituting the assigned variable with the right-hand-side of the assignment. For instance, we obtain (4) by substituting X with X - Y in (5), and we obtain (3) by substituting Y with X - Y in (4).
Example: Simple Conditionals
- We start with the outer precondition (1) and postcondition (8).
- Following the format dictated by the hoare_if rule, we copy the
postcondition (8) to (4) and (7). We conjoin the precondition (1)
with the guard of the conditional to obtain (2). We conjoin (1)
with the negated guard of the conditional to obtain (5).
- In order to use the assignment rule and obtain (3), we substitute
Z by Y - X in (4). To obtain (6) we substitute Z by X - Y
in (7).
- Finally, we verify that (2) implies (3) and (5) implies (6). Both of these implications crucially depend on the ordering of X and Y obtained from the guard. For instance, knowing that X ≤ Y ensures that subtracting X from Y and then adding back X produces Y, as required by the first disjunct of (3). Similarly, knowing that ¬ (X ≤ Y) ensures that subtracting Y from X and then adding back Y produces X, as needed by the second disjunct of (6). Note that n - m + m = n does not hold for arbitrary natural numbers n and m (for example, 3 - 5 + 5 = 5).
Exercise: 2 stars, standard, optional (if_minus_plus_reloaded)
Briefly justify each use of ->>.
☐
Example: Reduce to Zero
- Start with the outer precondition (1) and postcondition (6).
- Following the format dictated by the hoare_while rule, we copy
(1) to (4). We conjoin (1) with the guard to obtain (2). We also
conjoin (1) with the negation of the guard to obtain (5).
- Because the final postcondition (6) does not syntactically match (5),
we add an implication between them.
- Using the assignment rule with assertion (4), we trivially substitute
and obtain assertion (3).
- We add the implication between (2) and (3).
Example: Division
- (1) ->> (2): trivial, by algebra.
- (5) ->> (6): because n ≤ X, we are guaranteed that the subtraction in (6) does not get zero-truncated. We can therefore rewrite (6) as n × Y + n + X - n and cancel the ns, which results in the left conjunct of (5).
- (9) ->> (10): if ¬ (n ≤ X) then X < n. That's straightforward from high-school algebra.
From Decorated Programs to Formal Proofs
Definition reduce_to_zero : com :=
<{ while X ≠ 0 do
X := X - 1
end }>.
Theorem reduce_to_zero_correct' :
{{True}}
reduce_to_zero
{{X = 0}}.
Proof.
unfold reduce_to_zero.
eapply hoare_consequence_post.
- apply hoare_while.
+
eapply hoare_consequence_pre.
× apply hoare_asgn.
×
unfold assertion_sub, "->>". simpl. intros.
exact I.
-
intros st [Inv GuardFalse].
unfold bassertion in GuardFalse. simpl in GuardFalse.
rewrite not_true_iff_false in GuardFalse.
rewrite negb_false_iff in GuardFalse.
apply eqb_eq in GuardFalse.
apply GuardFalse.
Qed.
<{ while X ≠ 0 do
X := X - 1
end }>.
Theorem reduce_to_zero_correct' :
{{True}}
reduce_to_zero
{{X = 0}}.
Proof.
unfold reduce_to_zero.
eapply hoare_consequence_post.
- apply hoare_while.
+
eapply hoare_consequence_pre.
× apply hoare_asgn.
×
unfold assertion_sub, "->>". simpl. intros.
exact I.
-
intros st [Inv GuardFalse].
unfold bassertion in GuardFalse. simpl in GuardFalse.
rewrite not_true_iff_false in GuardFalse.
rewrite negb_false_iff in GuardFalse.
apply eqb_eq in GuardFalse.
apply GuardFalse.
Qed.
In Hoare we introduced a series of tactics named
assertion_auto to automate proofs involving assertions.
The following declaration introduces a more sophisticated tactic
that will help with proving assertions throughout the rest of this
chapter. You don't need to understand the details, but briefly:
it uses split repeatedly to turn all the conjunctions into
separate subgoals, tries to use several theorems about booleans
and (in)equalities, then uses eauto and lia to finish off as
many subgoals as possible. What's left after verify_assertion does
its thing should be just the "interesting parts" of the proof --
which, if we're lucky, might be nothing at all!
Ltac verify_assertion :=
repeat split;
simpl;
unfold assert_implies;
unfold bassertion in *; unfold beval in *; unfold aeval in *;
unfold assertion_sub; intros;
repeat (simpl in *;
rewrite t_update_eq ||
(try rewrite t_update_neq;
[| (intro X; inversion X; fail)]));
simpl in *;
repeat match goal with [H : _ ∧ _ |- _] ⇒
destruct H end;
repeat rewrite not_true_iff_false in *;
repeat rewrite not_false_iff_true in *;
repeat rewrite negb_true_iff in *;
repeat rewrite negb_false_iff in *;
repeat rewrite eqb_eq in *;
repeat rewrite eqb_neq in *;
repeat rewrite leb_iff in *;
repeat rewrite leb_iff_conv in *;
try subst;
simpl in *;
repeat
match goal with
[st : state |- _] ⇒
match goal with
| [H : st _ = _ |- _] ⇒
rewrite → H in *; clear H
| [H : _ = st _ |- _] ⇒
rewrite <- H in *; clear H
end
end;
try eauto;
try lia.
This makes it pretty easy to verify reduce_to_zero:
Theorem reduce_to_zero_correct''' :
{{True}}
reduce_to_zero
{{X = 0}}.
Proof.
unfold reduce_to_zero.
eapply hoare_consequence_post.
- apply hoare_while.
+ eapply hoare_consequence_pre.
× apply hoare_asgn.
× verify_assertion.
- verify_assertion.
Qed.
This example shows that it is conceptually straightforward to read
off the main elements of a formal proof from a decorated program.
Indeed, the process is so straightforward that it can be
automated, as we will see next.
Formal Decorated Programs
Syntax
Module DComFirstTry.
Inductive dcom : Type :=
| DCSkip (P : Assertion)
| DCSeq (P : Assertion) (d1 : dcom) (Q : Assertion)
(d2 : dcom) (R : Assertion)
| DCAsgn (X : string) (a : aexp) (Q : Assertion)
| DCIf (P : Assertion) (b : bexp) (P1 : Assertion) (d1 : dcom)
(P2 : Assertion) (d2 : dcom) (Q : Assertion)
| DCWhile (P : Assertion) (b : bexp)
(P1 : Assertion) (d : dcom) (P2 : Assertion)
(Q : Assertion)
| DCPre (P : Assertion) (d : dcom)
| DCPost (d : dcom) (Q : Assertion).
End DComFirstTry.
But this would result in very verbose decorated programs with a
lot of repeated annotations: even a simple program like
skip;skip would be decorated like this,
P (P skip P) ; (P skip P) P
with pre- and post-conditions around each skip, plus identical
pre- and post-conditions on the semicolon!
In other words, we don't want both preconditions and
postconditions on each command, because a sequence of two commands
would contain redundant decorations--the postcondition of the
first likely being the same as the precondition of the second.
Instead, the formal syntax of decorated commands omits
preconditions whenever possible, trying to embed just the
postcondition.
Putting this all together gives us the formal syntax of decorated
commands:
- The skip command, for example, is decorated only with its
postcondition
skip Qon the assumption that the precondition will be provided by the context.We carry the same assumption through the other syntactic forms: each decorated command is assumed to carry its own postcondition within itself but take its precondition from its context in which it is used.
- Sequences d1 ; d2 need no additional decorations.
Why?Because inside d2 there will be a postcondition; this serves as the postcondition of d1;d2.Similarly, inside d1 there will also be a postcondition, which additionally serves as the precondition for d2.
- An assignment X := a is decorated only with its postcondition:
X := a Q
- A conditional if b then d1 else d2 is decorated with a
postcondition for the entire statement, as well as preconditions
for each branch:
if b then P1 d1 else P2 d2 end Q
- A loop while b do d end is decorated with its postcondition
and a precondition for the body:
while b do P d end QThe postcondition embedded in d serves as the loop invariant.
- Implications ->> can be added as decorations either for a
precondition
- >> P d
d ->> QThe former is waiting for another precondition to be supplied by the context (e.g., {{ P'}} ->> {{ P }} d); the latter relies on the postcondition already embedded in d. - >> P d
Inductive dcom : Type :=
| DCSkip (Q : Assertion)
| DCSeq (d1 d2 : dcom)
| DCAsgn (X : string) (a : aexp) (Q : Assertion)
| DCIf (b : bexp) (P1 : Assertion) (d1 : dcom)
(P2 : Assertion) (d2 : dcom) (Q : Assertion)
| DCWhile (b : bexp) (P : Assertion) (d : dcom)
(Q : Assertion)
| DCPre (P : Assertion) (d : dcom)
| DCPost (d : dcom) (Q : Assertion)
.
To provide the initial precondition that goes at the very top of a
decorated program, we introduce a new type decorated:
To avoid clashing with the existing Notations for ordinary
commands, we introduce these notations in a new grammar scope
called dcom.
Declare Scope dcom_scope.
Notation "'skip' {{ P }}"
:= (DCSkip P)
(in custom com at level 0, P custom assn at level 99) : dcom_scope.
Notation "l ':=' a {{ P }}"
:= (DCAsgn l a P)
(in custom com at level 0, l constr at level 0,
a custom com at level 85, P custom assn at level 99, no associativity)
: dcom_scope.
Notation "'while' b 'do' {{ Pbody }} d 'end' {{ Ppost }}"
:= (DCWhile b Pbody d Ppost)
(in custom com at level 89, b custom com at level 99,
Pbody custom assn at level 99, Ppost custom assn at level 99)
: dcom_scope.
Notation "'if' b 'then' {{ P }} d 'else' {{ P' }} d' 'end' {{ Q }}"
:= (DCIf b P d P' d' Q)
(in custom com at level 89, b custom com at level 99,
P custom assn at level 99, P' custom assn at level 99, Q custom assn at level 99)
: dcom_scope.
Notation "'->>' {{ P }} d"
:= (DCPre P d)
(in custom com at level 12, right associativity, P custom assn at level 99)
: dcom_scope.
Notation "d '->>' {{ P }}"
:= (DCPost d P)
(in custom com at level 10, right associativity, P custom assn at level 99)
: dcom_scope.
Notation " d ; d' "
:= (DCSeq d d')
(in custom com at level 90, right associativity)
: dcom_scope.
Notation "{{ P }} d"
:= (Decorated P d)
(in custom com at level 91, P custom assn at level 99)
: dcom_scope.
Local Open Scope dcom_scope.
Example dec0 : dcom :=
<{ skip {{ True }} }>.
Example dec1 : dcom :=
<{ while true do {{ True }} skip {{ True }} end {{ True }} }>.
Recall that you can Set Printing All to see how all that
notation is desugared.
An example decorated program that decrements X to 0:
Example dec_while : decorated :=
<{
{{ True }}
while X ≠ 0
do
{{ True ∧ (X ≠ 0) }}
X := X - 1
{{ True }}
end
{{ True ∧ X = 0}} ->>
{{ X = 0 }} }>.
It is easy to go from a dcom to a com by erasing all
annotations.
Fixpoint erase (d : dcom) : com :=
match d with
| DCSkip _ ⇒ CSkip
| DCSeq d1 d2 ⇒ CSeq (erase d1) (erase d2)
| DCAsgn X a _ ⇒ CAsgn X a
| DCIf b _ d1 _ d2 _ ⇒ CIf b (erase d1) (erase d2)
| DCWhile b _ d _ ⇒ CWhile b (erase d)
| DCPre _ d ⇒ erase d
| DCPost d _ ⇒ erase d
end.
Definition erase_d (dec : decorated) : com :=
match dec with
| Decorated P d ⇒ erase d
end.
Example erase_while_ex :
erase_d dec_while
= <{while X ≠ 0 do X := X - 1 end}>.
Proof.
unfold dec_while.
reflexivity.
Qed.
It is also straightforward to extract the precondition and
postcondition from a decorated program.
Definition precondition_from (dec : decorated) : Assertion :=
match dec with
| Decorated P d ⇒ P
end.
Fixpoint post (d : dcom) : Assertion :=
match d with
| DCSkip P ⇒ P
| DCSeq _ d2 ⇒ post d2
| DCAsgn _ _ Q ⇒ Q
| DCIf _ _ _ _ _ Q ⇒ Q
| DCWhile _ _ _ Q ⇒ Q
| DCPre _ d ⇒ post d
| DCPost _ Q ⇒ Q
end.
Definition postcondition_from (dec : decorated) : Assertion :=
match dec with
| Decorated P d ⇒ post d
end.
Example precondition_from_while : precondition_from dec_while = True.
Proof. reflexivity. Qed.
Example postcondition_from_while : postcondition_from dec_while = {{ X = 0 }}.
Proof. reflexivity. Qed.
We can then express what it means for a decorated program to be
correct as follows:
Definition outer_triple_valid (dec : decorated) :=
{{$(precondition_from dec)}} erase_d dec {{$(postcondition_from dec)}}.
For example:
Example dec_while_triple_correct :
outer_triple_valid dec_while
=
{{ True }}
while X ≠ 0 do X := X - 1 end
{{ X = 0 }}.
Proof. reflexivity. Qed.
The outer Hoare triple of a decorated program is just a Prop;
thus, to show that it is valid, we need to produce a proof of
this proposition.
We will do this by extracting "proof obligations" from the
decorations sprinkled through the program.
These obligations are often called verification conditions,
because they are the facts that must be verified to see that the
decorations are locally consistent and thus constitute a proof of
validity of the outer triple.
Extracting Verification Conditions
- local consistency checks for each form of command, plus
- uses of ->> to bridge the gap between the assertions found inside a decorated command and the assertions imposed by the precondition from its context; these uses correspond to applications of the consequence rule.
- The decorated command
skip Qis locally consistent with respect to a precondition P if P ->> Q.
- The sequential composition of d1 and d2 is locally consistent with respect to P if d1 is locally consistent with respect to P and d2 is locally consistent with respect to the postcondition of d1.
- An assignment
X := a Qis locally consistent with respect to a precondition P if:P ->> Q X |-> a
- A conditional
if b then P1 d1 else P2 d2 end Qis locally consistent with respect to precondition P if(1) P ∧ b ->> P1(2) P ∧ ¬b ->> P2(3) d1 is locally consistent with respect to P1(4) d2 is locally consistent with respect to P2(5) post d1 ->> Q(6) post d2 ->> Q
- A loop
while b do Q d end Ris locally consistent with respect to precondition P if:(1) P ->> post d(2) post d ∧ b ->> Q(3) post d ∧ ¬b ->> R(4) d is locally consistent with respect to Q
- A command with an extra assertion at the beginning
- -> Q d
(1) P ->> Q(2) d is locally consistent with respect to Q - -> Q d
- A command with an extra assertion at the end
d ->> Qis locally consistent with respect to a precondition P if:(1) d is locally consistent with respect to P(2) post d ->> Q
Fixpoint verification_conditions (P : Assertion) (d : dcom) : Prop :=
match d with
| DCSkip Q ⇒
(P ->> Q)
| DCSeq d1 d2 ⇒
verification_conditions P d1
∧ verification_conditions (post d1) d2
| DCAsgn X a Q ⇒
P ->> {{ Q [X |-> a] }}
| DCIf b P1 d1 P2 d2 Q ⇒
{{ P ∧ b }} ->> P1
∧ {{ P ∧ ¬ b }} ->> P2
∧ (post d1 ->> Q) ∧ (post d2 ->> Q)
∧ verification_conditions P1 d1
∧ verification_conditions P2 d2
| DCWhile b Q d R ⇒
(P ->> post d)
∧ {{ $(post d) ∧ b }} ->> Q
∧ {{ $(post d) ∧ ¬ b }} ->> R
∧ verification_conditions Q d
| DCPre P' d ⇒
(P ->> P')
∧ verification_conditions P' d
| DCPost d Q ⇒
verification_conditions P d
∧ (post d ->> Q)
end.
The following key theorem states that verification_conditions
does its job correctly. Not surprisingly, each of the Hoare Logic
rules gets used at some point in the proof.
Theorem verification_correct : ∀ d P,
verification_conditions P d → {{P}} erase d {{ $(post d) }}.
Proof.
induction d; intros; simpl in ×.
-
eapply hoare_consequence_pre.
+ apply hoare_skip.
+ assumption.
-
destruct H as [H1 H2].
eapply hoare_seq.
+ apply IHd2. apply H2.
+ apply IHd1. apply H1.
-
eapply hoare_consequence_pre.
+ apply hoare_asgn.
+ assumption.
-
destruct H as [HPre1 [HPre2 [Hd1 [Hd2 [HThen HElse] ] ] ] ].
apply IHd1 in HThen. clear IHd1.
apply IHd2 in HElse. clear IHd2.
apply hoare_if.
+ eapply hoare_consequence; eauto.
+ eapply hoare_consequence; eauto.
-
destruct H as [Hpre [Hbody1 [Hpost1 Hd] ] ].
eapply hoare_consequence; eauto.
apply hoare_while.
eapply hoare_consequence_pre; eauto.
-
destruct H as [HP Hd].
eapply hoare_consequence_pre; eauto.
-
destruct H as [Hd HQ].
eapply hoare_consequence_post; eauto.
Qed.
Now that all the pieces are in place, we can define what it means
to verify an entire program.
Definition verification_conditions_from
(dec : decorated) : Prop :=
match dec with
| Decorated P d ⇒ verification_conditions P d
end.
This brings us to the main theorem of this section:
Corollary verification_conditions_correct : ∀ dec,
verification_conditions_from dec →
outer_triple_valid dec.
Proof.
intros [P d]. apply verification_correct.
Qed.
More Automation
Fortunately, our verify_assertion tactic can generally take care of
most or all of them.
To automate the overall process of verification, we can use
verification_correct to extract the verification conditions, use
verify_assertion to verify them as much as it can, and finally tidy
up any remaining bits by hand.
Here's the final, formal proof that dec_while is correct.
Similarly, here is the formal decorated program for the "swapping
by adding and subtracting" example that we saw earlier.
Definition swap_dec (m n:nat) : decorated :=
<{
{{ X = m ∧ Y = n}} ->>
{{ (X + Y) - ((X + Y) - Y) = n ∧ (X + Y) - Y = m }}
X := X + Y
{{ X - (X - Y) = n ∧ X - Y = m }};
Y := X - Y
{{ X - Y = n ∧ Y = m }};
X := X - Y
{{ X = n ∧ Y = m}}
}>.
Theorem swap_correct : ∀ m n,
outer_triple_valid (swap_dec m n).
Proof. verify. Qed.
And here is the formal decorated version of the "positive
difference" program from earlier:
Definition positive_difference_dec :=
<{
{{True}}
if X ≤ Y then
{{True ∧ X ≤ Y}} ->>
{{(Y - X) + X = Y ∨ (Y - X) + Y = X}}
Z := Y - X
{{Z + X = Y ∨ Z + Y = X}}
else
{{True ∧ ¬(X ≤ Y)}} ->>
{{(X - Y) + X = Y ∨ (X - Y) + Y = X}}
Z := X - Y
{{Z + X = Y ∨ Z + Y = X}}
end
{{Z + X = Y ∨ Z + Y = X}}
}>.
Theorem positive_difference_correct :
outer_triple_valid positive_difference_dec.
Proof. verify. Qed.
Exercise: 2 stars, standard, especially useful (if_minus_plus_correct)
Definition if_minus_plus_dec :=
<{
{{True}}
if (X ≤ Y) then
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
Z := Y - X
{{ FILL_IN_HERE }}
else
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
Y := X + Z
{{ FILL_IN_HERE }}
end
{{ Y = X + Z}} }>.
Theorem if_minus_plus_correct :
outer_triple_valid if_minus_plus_dec.
Proof.
Admitted.
☐
Fill in appropriate assertions for the division program from above.
Exercise: 2 stars, standard, optional (div_mod_outer_triple_valid)
Definition div_mod_dec (a b : nat) : decorated :=
<{
{{ True }} ->>
{{ FILL_IN_HERE }}
X := a
{{ FILL_IN_HERE }};
Y := 0
{{ FILL_IN_HERE }};
while b ≤ X do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
X := X - b
{{ FILL_IN_HERE }};
Y := Y + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }} }>.
Theorem div_mod_outer_triple_valid : ∀ a b,
outer_triple_valid (div_mod_dec a b).
Proof.
Admitted.
☐
Finding Loop Invariants
- Strengthening a loop invariant means that you have a stronger
assumption to work with when trying to establish the
postcondition of the loop body, but it also means that the loop
body's postcondition is stronger and thus harder to prove.
- Similarly, strengthening an induction hypothesis means that you have a stronger assumption to work with when trying to complete the induction step of the proof, but it also means that the statement being proved inductively is stronger and thus harder to prove.
Example: Slow Subtraction
- (a) it must be weak enough to be implied by the loop's precondition, i.e., (1) must imply (2);
- (b) it must be strong enough to imply the program's postcondition, i.e., (7) must imply (8);
- (c) it must be preserved by a single iteration of the loop, assuming that the loop guard also evaluates to true, i.e., (3) must imply (4).
Example subtract_slowly_dec (m : nat) (n : nat) : decorated :=
<{
{{ X = m ∧ Y = n }} ->>
{{ Y - X = n - m }}
while X ≠ 0 do
{{ Y - X = n - m ∧ X ≠ 0 }} ->>
{{ (Y - 1) - (X - 1) = n - m }}
Y := Y - 1
{{ Y - (X - 1) = n - m }} ;
X := X - 1
{{ Y - X = n - m }}
end
{{ Y - X = n - m ∧ X = 0 }} ->>
{{ Y = n - m }} }>.
Theorem subtract_slowly_outer_triple_valid : ∀ m n,
outer_triple_valid (subtract_slowly_dec m n).
Proof.
verify. Qed.
Exercise: Slow Assignment
Exercise: 2 stars, standard (slow_assignment)
Example slow_assignment_dec (m : nat) : decorated :=
<{
{{ X = m }}
Y := 0
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }} ;
while X ≠ 0 do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
X := X - 1
{{ FILL_IN_HERE }} ;
Y := Y + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Y = m }}
}>.
Theorem slow_assignment : ∀ m,
outer_triple_valid (slow_assignment_dec m).
Proof. Admitted.
☐
Example: Parity
The postcondition does not hold at the beginning of the loop,
since m = parity m does not hold for an arbitrary m, so we
cannot hope to use that as a loop invariant. To find a loop invariant
that works, let's think a bit about what this loop does. On each
iteration it decrements X by 2, which preserves the parity of X.
So the parity of X does not change, i.e., it is invariant. The initial
value of X is m, so the parity of X is always equal to the
parity of m. Using parity X = parity m as an invariant we
obtain the following decorated program:
X = m ->> (a - OK)
parity X = parity m
while 2 <= X do
parity X = parity m /\ 2 <= X ->> (c - OK)
parity (X-2) = parity m
X := X - 2
parity X = parity m
end
parity X = parity m /\ ~(2 <= X) ->> (b - OK)
X = parity m
With this loop invariant, conditions (a), (b), and (c) are all
satisfied. For verifying (b), we observe that, when X < 2, we
have parity X = X (we can easily see this in the definition of
parity). For verifying (c), we observe that, when 2 ≤ X, we
have parity X = parity (X-2).
Translate the above informal decorated program into a formal one
and prove it correct.
Hint: There are actually several possible loop invariants that all
lead to good proofs; one that leads to a particularly simple proof
is parity X = parity m -- or more formally, using the
ap operator to lift the application of the parity function
into the syntax of assertions, {{ ap parity X = parity m }}.
Exercise: 3 stars, standard, optional (parity)
Definition parity_dec (m:nat) : decorated :=
<{
{{ X = m }} ->>
{{ FILL_IN_HERE }}
while 2 ≤ X do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
X := X - 2
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ X = #parity m }} }>.
If you use the suggested loop invariant, you may find the following
lemmas helpful (as well as leb_complete and leb_correct).
Lemma parity_ge_2 : ∀ x,
2 ≤ x →
parity (x - 2) = parity x.
Proof.
destruct x; intros; simpl.
- reflexivity.
- destruct x; simpl.
+ lia.
+ rewrite sub_0_r. reflexivity.
Qed.
Lemma parity_lt_2 : ∀ x,
¬ 2 ≤ x →
parity x = x.
Proof.
induction x; intros; simpl.
- reflexivity.
- destruct x.
+ reflexivity.
+ lia.
Qed.
Theorem parity_outer_triple_valid : ∀ m,
outer_triple_valid (parity_dec m).
Proof.
Admitted.
☐
Example: Finding Square Roots
Exercise: 3 stars, standard, optional (sqrt)
Definition sqrt_dec (m:nat) : decorated :=
<{
{{ X = m }} ->>
{{ FILL_IN_HERE }}
Z := 0
{{ FILL_IN_HERE }};
while ((Z+1)×(Z+1) ≤ X) do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
Z := Z + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Z×Z≤m ∧ m<(Z+1)×(Z+1) }}
}>.
Theorem sqrt_correct : ∀ m,
outer_triple_valid (sqrt_dec m).
Proof. Admitted.
Example: Squaring
Exercise: Factorial
Exercise: 4 stars, advanced (factorial_correct)
First, write the Imp program factorial that calculates the factorial
of the number initially stored in the variable X and puts it in
the variable Y.
Using your definition factorial and slow_assignment_dec as a
guide, write a formal decorated program factorial_dec that
implements the factorial function. Hint: recall the use of ap
in assertions to apply a function to an Imp variable.
Fill in the blanks and finish the proof of correctness. Bear in mind
that we are working with natural numbers, for which both division
and subtraction can behave differently than with real numbers.
Excluding both operations from your loop invariant is advisable!
Then state a theorem named factorial_correct that says
factorial_dec is correct, and prove the theorem. If all goes
well, verify will leave you with just two subgoals, each of
which requires establishing some mathematical property of fact,
rather than proving anything about your program.
Hint: if those two subgoals become tedious to prove, give some
thought to how you could restate your assertions such that the
mathematical operations are more amenable to manipulation in Coq.
For example, recall that 1 + ... is easier to work with than
... + 1.
Example factorial_dec (m:nat) : decorated
. Admitted.
Theorem factorial_correct: ∀ m,
outer_triple_valid (factorial_dec m).
Proof. Admitted.
☐
Exercise: Minimum
Exercise: 3 stars, standard (minimum_correct)
Definition minimum_dec (a b : nat) : decorated :=
<{
{{ True }} ->>
{{ FILL_IN_HERE }}
X := a
{{ FILL_IN_HERE }};
Y := b
{{ FILL_IN_HERE }};
Z := 0
{{ FILL_IN_HERE }};
while X ≠ 0 && Y ≠ 0 do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
X := X - 1
{{ FILL_IN_HERE }};
Y := Y - 1
{{ FILL_IN_HERE }};
Z := Z + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Z = #min a b }}
}>.
Theorem minimum_correct : ∀ a b,
outer_triple_valid (minimum_dec a b).
Proof. Admitted.
☐
Exercise: Two Loops
Exercise: 3 stars, standard (two_loops)
Definition two_loops_dec (a b c : nat) : decorated :=
<{
{{ True }} ->>
{{ FILL_IN_HERE }}
X := 0
{{ FILL_IN_HERE }};
Y := 0
{{ FILL_IN_HERE }};
Z := c
{{ FILL_IN_HERE }};
while X ≠ a do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
X := X + 1
{{ FILL_IN_HERE }};
Z := Z + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }};
while Y ≠ b do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
Y := Y + 1
{{ FILL_IN_HERE }};
Z := Z + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Z = a + b + c }}
}>.
Theorem two_loops : ∀ a b c,
outer_triple_valid (two_loops_dec a b c).
Proof.
Admitted.
<{
{{ True }} ->>
{{ FILL_IN_HERE }}
X := 0
{{ FILL_IN_HERE }};
Y := 0
{{ FILL_IN_HERE }};
Z := c
{{ FILL_IN_HERE }};
while X ≠ a do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
X := X + 1
{{ FILL_IN_HERE }};
Z := Z + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }};
while Y ≠ b do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
Y := Y + 1
{{ FILL_IN_HERE }};
Z := Z + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Z = a + b + c }}
}>.
Theorem two_loops : ∀ a b c,
outer_triple_valid (two_loops_dec a b c).
Proof.
Admitted.
☐
Exercise: Power Series
Exercise: 4 stars, standard, optional (dpow2)
Fixpoint pow2 n :=
match n with
| 0 ⇒ 1
| S n' ⇒ 2 × (pow2 n')
end.
Definition dpow2_dec (n : nat) :=
<{
{{ True }} ->>
{{ FILL_IN_HERE }}
X := 0
{{ FILL_IN_HERE }};
Y := 1
{{ FILL_IN_HERE }};
Z := 1
{{ FILL_IN_HERE }};
while X ≠ n do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
Z := 2 × Z
{{ FILL_IN_HERE }};
Y := Y + Z
{{ FILL_IN_HERE }};
X := X + 1
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Y = #pow2 (n+1) - 1 }}
}>.
Some lemmas that you may find useful...
Lemma pow2_plus_1 : ∀ n,
pow2 (n+1) = pow2 n + pow2 n.
Proof.
induction n; simpl.
- reflexivity.
- lia.
Qed.
Lemma pow2_le_1 : ∀ n, pow2 n ≥ 1.
Proof.
induction n; simpl; [constructor | lia].
Qed.
The main correctness theorem:
☐
The Fibonacci function is usually written like this:
Fixpoint fib n :=
match n with
| 0 => 1
| 1 => 1
| _ => fib (pred n) + fib (pred (pred n))
end.
This doesn't pass Coq's termination checker, but here is a
slightly clunkier definition that does:
Exercise: 2 stars, advanced, optional (fib_eqn)
Fixpoint fib n :=
match n with
| 0 ⇒ 1
| S n' ⇒ match n' with
| 0 ⇒ 1
| S n'' ⇒ fib n' + fib n''
end
end.
Prove that fib satisfies the following equation. You will need this
as a lemma in the next exercise.
☐
The following Imp program leaves the value of fib n in the
variable Y when it terminates:
X := 1;
Y := 1;
Z := 1;
while X <> 1 + n do
T := Z;
Z := Z + Y;
Y := T;
X := 1 + X
end
Fill in the following definition of dfib and prove that it
satisfies this specification:
True dfib Y = fib n
You will need many uses of ap in your assertions.
If all goes well, your proof will be very brief.
Exercise: 4 stars, advanced, optional (fib)
Definition T : string := "T".
Definition dfib (n : nat) : decorated :=
<{
{{ True }} ->>
{{ FILL_IN_HERE }}
X := 1
{{ FILL_IN_HERE }} ;
Y := 1
{{ FILL_IN_HERE }} ;
Z := 1
{{ FILL_IN_HERE }} ;
while X ≠ 1 + n do
{{ FILL_IN_HERE }} ->>
{{ FILL_IN_HERE }}
T := Z
{{ FILL_IN_HERE }};
Z := Z + Y
{{ FILL_IN_HERE }};
Y := T
{{ FILL_IN_HERE }};
X := 1 + X
{{ FILL_IN_HERE }}
end
{{ FILL_IN_HERE }} ->>
{{ Y = #fib n }}
}>.
Theorem dfib_correct : ∀ n,
outer_triple_valid (dfib n).
Proof.
Admitted.
☐
The formal decorated programs defined in this section are intended
to look as similar as possible to the informal ones defined
earlier. If we drop this requirement, we can eliminate almost all
annotations, just requiring final postconditions and loop
invariants to be provided explicitly. Do this -- i.e., define a
new version of dcom with as few annotations as possible and adapt
the rest of the formal development leading up to the
verification_correct theorem.
Exercise: 5 stars, advanced, optional (improve_dcom)
Weakest Preconditions (Optional)
- P is a precondition, that is, {{P}} c {{Q}}; and
- P is at least as weak as all other preconditions, that is, if {{P'}} c {{Q}} then P' ->> P.
Exercise: 1 star, standard, optional (wp)
Exercise: 3 stars, advanced, optional (is_wp)
☐
Show that the precondition in the rule hoare_asgn is in fact the
weakest precondition.
Exercise: 2 stars, advanced, optional (hoare_asgn_weakest)
☐
Show that your havoc_pre function from the himp_hoare exercise
in the Hoare chapter returns a weakest precondition.
Exercise: 2 stars, advanced, optional (hoare_havoc_weakest)
Module Himp2.
Import Himp.
Lemma hoare_havoc_weakest : ∀ (P Q : Assertion) (X : string),
{{ P }} havoc X {{ Q }} →
P ->> havoc_pre X Q.
Proof.
Admitted.
End Himp2.
Import Himp.
Lemma hoare_havoc_weakest : ∀ (P Q : Assertion) (X : string),
{{ P }} havoc X {{ Q }} →
P ->> havoc_pre X Q.
Proof.
Admitted.
End Himp2.
☐