BCP 23,25: There are a lot of questions about the flow of this
material. Needs a deep look. In particular:
One feels that it takes a rather circuitous route to get to
formal decorated programs -- there might be a way to just go
straight there.
More importantly, it isn't very clear to me that the
version of decorated programs that we wound up with is really
the right one -- why spend all this time writing annotations
that we then say are unnecessary? Seems like we could define
decorated programs with a lighter annotation burden (as in the
exercise at the end) and just add optional annotations when we
want to, to make particular examples clearer.
The rigidity of the Hoare rules as stated in the last chapter
is also annoying here at many points. Building the rules of
consequence into all the other rules might make a lot of things
smoother. Would be a big change (also to Hoare.v), but definitely
worth a try.
And related...
Note to developers (Michael Clarkson @clarksmr, before next release, 2020)
Here are a bunch of improvements I wanted to make but
didn't have time to get to. Maybe next time if no one else gets to
them first.
This chapter feels largely disconnected from the style of the
rest of the series, which is "100% Rocq script". There's a
significant amount of "just comments" here instead. I think
we could make this much better by introducing formal decorated
programs right after we informally define them. Then in the
examples that follow do each informal decorated program (to
get students to find the right assertions, more or less)
followed immediately by a formal version, instead of delaying
formal so far to the end. The parity exercise is a good
example of one that already almost does this already. (BCP 21:
Done!)
There are several places where we are verifying Imp program
schemas, not actual programs. We're mixing Rocq variables with
Imp variables. That's confusing. One example is two_loops;
I've tried to mark others as I come across them. (BCP: I've
added some quizzes and such to try to clarify the relation
between programs / triples and program/triple schemas.
BCP 25: I think this is a non-issue now.)
Weakest preconditions show up in this chapter as completely
optional, then are revisited (and required) in HoareAsLogic.
Consider moving the entire treatment to that chapter. (BCP
23: Yes, we should do that!)
It seems a shame that the SparseAnnotations section is not
visible in the full version, but only in a solution. It's
fantastic! It would be great to show it off. (BCP 25: Yes!
Indeed, perhaps it should even replace the current treatment!)
Note to developers
HIDE: Some useful theorems about Imp are not being redefined for
the modified versions of Imp. We should either re-prove them or add
hints (or exercises!) about this. BCP 20: Which ones???
Quiz
On a piece of paper (or whatever), write down a Hoare-triple
specification for the following program:
X := 2;
Y := X + X
Quiz
Write down a (useful) specification for the following program:
X := X + 1; Y := X + 1
Quiz
Write down a (useful) specification for the following program:
if X ≤ Y then
skip
else
Z := X;
X := Y;
Y := Z
end
Quiz
Write down a (useful) specification for the following program:
X := m;
Y := X + X
Quiz
Write down a (useful) specification for the following program:
X := m;
Z := 0;
while X ≠ 0 do
X := X - 2;
Z := Z + 1
end
The beauty of Hoare Logic is that it is syntax directed: the
structure of proofs exactly follows the structure of programs.
We can record the essential ideas of a Hoare-logic proof —
omitting low-level calculational details — by "decorating" a
program with appropriate assertions on each of its commands.
Such a decorated program carries within itself an argument for
its own correctness.
For example, consider the program:
X := m;
Z := p;
while X ≠ 0 do
Z := Z - 1;
X := X - 1
end
Here is one possible specification for this program, in the
form of a Hoare triple:
{{ True }}
X := m;
Z := p;
while X ≠ 0 do
Z := Z - 1;
X := X - 1
end
{{ Z = p - m }}
(Note the parametersm and p, which stand for
fixed-but-arbitrary numbers. Formally, they are simply Lean
variables of type Nat.)
Here is a decorated version of this program, embodying a
proof of this specification:
{{ True }} ->>
{{ m = m }}
X := m
{{ X = m }} ->>
{{ X = m ∧ p = p }};
Z := p;
{{ X = m ∧ Z = p }} ->>
{{ Z - X = p - m }}
while X ≠ 0 do
{{ Z - X = p - m ∧ X ≠ 0 }} ->>
{{ (Z - 1) - (X - 1) = p - m }}
Z := Z - 1
{{ Z - (X - 1) = p - m }};
X := X - 1
{{ Z - X = p - m }}
end
{{ Z - X = p - m ∧ ¬ (X ≠ 0) }} ->>
{{ Z = p - m }}
Note to developers
HIDE: MRC'20: It bothers me a little in the proof above (and
similarly throughout the whole file really when it comes to guards)
that when we get to this part:
[[
while X ≠ 0 do {{ Z - X = p - m ∧ X ≠ 0 }} ->>
]]
we are inconsistent about [X ≠ 0] vs. [~(X=0)]. I admit they
evaluate the same (er, sort of---the former is a [bexp] whereas the
latter is an assertion), but they aren't syntactically the same.
Since what we're teaching here (mechanized Hoare logic) is fussy
about syntax, it strikes me as something we ought to be precise
about. But it's an annoying change to propagate through the file,
so I haven't done it. Is it worth a comment, or do others not get
bothered by this? Another way to fix this would be to add the [≠]
operator to Imp, so that we can write the guard in the nicer way.
BCP 20: I think adding in a few more boolean operators at the
outside is the way to go...
BCP 21: ... and I've now done this: ≠ is available in formal
bexps (also >).
Concretely, a decorated program consists of the program's text
interleaved with assertions (sometimes multiple assertions
separated by ->>).
A decorated program can be viewed as a compact representation of a
proof in Hoare Logic: the assertions surrounding each command
specify the Hoare triple to be proved for that part of the program
using one of the Hoare Logic rules, and the structure of the
program itself shows how to assemble all these individual steps
into a proof for the whole program.
Our goal is to verify such decorated programs "mostly
automatically." But, before we can verify anything, we need to be
able to find a proof for a given specification, and for this we
need to discover the right assertions. This can be done in an
almost mechanical way, with the exception of finding loop
invariants. In the remainder of this section, we explain in detail
how to construct decorations for several short programs, all of
which are loop free or have simple loop invariants. We'll return
to finding more interesting loop invariants later in the chapter.
Consider the following program, which swaps the values of two
variables using addition and subtraction, instead of by assigning
to a temporary variable.
X := X + Y;
Y := X - Y;
X := X - Y
We can give a proof, in the form of decorations, that this program is
correct — i.e., it really swaps X and Y — as follows.
(1) {{ X = m ∧ Y = n }} ->>
(2) {{ (X + Y) - ((X + Y) - Y) = n ∧ (X + Y) - Y = m }}
X := X + Y
(3) {{ X - (X - Y) = n ∧ X - Y = m }};
Y := X - Y
(4) {{ X - Y = n ∧ Y = m }};
X := X - Y
(5) {{ X = n ∧ Y = m }}
The decorations can be constructed as follows:
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).
Finally, we verify that (1) logically implies (2) — i.e., that
the step from (1) to (2) is a valid use of the law of
consequence — by doing a bit of high-school algebra.
Note to developers
HIDE: BCP 21: This side comment seems too technical:
(Note that we are working with natural numbers rather than
fixed-width machine integers, so we don't need to worry about
the possibility of arithmetic overflow anywhere in this
argument. This makes life quite a bit simpler!)
HIDE: A quick / optional exercise using just assignment here
would be good.
Here is a simple decorated program using conditionals:
(1) {{ True }}
if X ≤ Y then
(2) {{ True ∧ X ≤ Y }} ->>
(3) {{ (Y - X) + X = Y ∨ (Y - X) + Y = X }}
Z := Y - X
(4) {{ Z + X = Y ∨ Z + Y = X }}
else
(5) {{ True ∧ ¬(X ≤ Y) }} ->>
(6) {{ (X - Y) + X = Y ∨ (X - Y) + Y = X }}
Z := X - Y
(7) {{ Z + X = Y ∨ Z + Y = X }}
end
(8) {{ Z + X = Y ∨ Z + Y = X }}
These decorations can be constructed as follows:
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]).
Note to developers
NOTATION: LATER: The ~ in that paragraph will typeset wrong if
the space after it is removed. Maybe it's better to give up on
all the unicode hacks in the generated HTML...?
N.b.: Although this exercise is marked optional, it is an
excellent warm-up for the (non-optional) if_minus_plus_correct
exercise below!
Fill in valid decorations for the following program:
{{ True }}
if X ≤ Y then
{{ }} ->>
{{ }}
Z := Y - X
{{ }}
else
{{ }} ->>
{{ }}
Y := X + Z
{{ }}
end
{{ Y = X + Z }}
Briefly justify each use of ->>.
{{ True }}
if X ≤ Y then
{{ True ∧ X ≤ Y }} ->>
{{ Y = X + (Y - X) }}
Z := Y - X
{{ Y = X + Z }}
else
{{ True ∧ ¬(X ≤ Y) }} ->>
{{ X + Z = X + Z }}
Y := X + Z
{{ Y = X + Z }}
end
{{ Y = X + Z }}
The second use of consequence is trivial, while the first
crucially depends on the X ≤ Y condition, which ensures that
subtracting X from Y and then adding back X produces Y.
Here is a while loop that is so simple that True suffices
as a loop invariant.
(1) {{ True }}
while X ≠ 0 do
(2) {{ True ∧ X ≠ 0 }} ->>
(3) {{ True }}
X := X - 1
(4) {{ True }}
end
(5) {{ True ∧ ¬(X ≠ 0) }} ->>
(6) {{ X = 0 }}
The decorations can be constructed as follows:
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).
Finally we check that the implications do hold; both are trivial.
Let's do one more example of simple reasoning about a loop.
The following Imp program calculates the integer quotient and
remainder of parameters m and n.
X := m;
Y := 0;
while n ≤ X do
X := X - n;
Y := Y + 1
end;
If we replace m and n by concrete numbers and execute the program, it
will terminate with the variable X set to the remainder when m
is divided by n and Y set to the quotient.
In order to give a specification to this program we need to
remember that dividing m by n produces a remainder X and a
quotient Y such that n * Y + X = m ∧ X < n.
It turns out that we get lucky with this program and don't have to
think very hard about the loop invariant: the loop invariant is just
the first conjunct, n * Y + X = m, and we can use this to
decorate the program.
(1) {{ True }} ->>
(2) {{ n * 0 + m = m }}
X := m;
(3) {{ n * 0 + X = m }}
Y := 0;
(4) {{ n * Y + X = m }}
while n ≤ X do
(5) {{ n * Y + X = m ∧ n ≤ X }} ->>
(6) {{ n * (Y + 1) + (X - n) = m }}
X := X - n;
(7) {{ n * (Y + 1) + X = m }}
Y := Y + 1
(8) {{ n * Y + X = m }}
end
(9) {{ n * Y + X = m ∧ ¬ (n ≤ X) }} ->>
(10) {{ n * Y + X = m ∧ X < n }}
Assertions (4), (5), (8), and (9) are derived mechanically from
the loop invariant and the loop's guard. Assertions (8), (7), and (6)
are derived using the assignment rule going backwards from (8)
to (6). Assertions (4), (3), and (2) are again backwards
applications of the assignment rule.
Now that we've decorated the program it only remains to check that
the uses of the consequence rule are correct — i.e., that (1)
implies (2), that (5) implies (6), and that (9) implies (10). This
is indeed the case:
(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.
So, we have a valid decorated program.
From an informal proof in the form of a decorated program, it is
"easy in principle" to read off a formal proof using the Lean
theorems corresponding to the Hoare Logic rules, but these proofs
can be a bit long and fiddly.
Note that we do not unfold the definition of ValidHoareTriple
anywhere in this proof: the point of the game we're playing now
is to use the Hoare rules as a self-contained logic for reasoning
about programs.
For example...
defreduceToZero:Com:=imp{while(X≠0){X:=X-1}}theoremdeclaration uses `sorry`reduce_to_zero_correct':{{True}}reduceToZero{{X=0}}:=⊢ {{True}}~reduceToZero{{X=0}}-- First put the postcondition into the form expected by-- the while rule.All goals completed! 🐙
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 introduces the available hypotheses, simplifies assertions,
maps, and arithmetic expressions, and then asks lia to solve
linear arithmetic goals. What's left after verify_assertion does
its work should be just the "interesting parts" of the proof
(which, if we're lucky, might be nothing at all!).
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.
Our informal conventions for decorated programs amount to a
way of "displaying" Hoare triples, in which commands are annotated
with enough embedded assertions that checking the validity of a
triple is reduced to simple logical and algebraic calculations
showing that some assertions imply others.
In this section, we show that this presentation style can be made
completely formal — and indeed that checking the validity of
decorated programs can be largely automated.
The first thing we need to do is to formalize a variant of the
syntax of Imp commands that includes embedded assertions, which
we'll call "decorations." We call the new commands decorated
commands, or dcoms.
The choice of exactly where to put assertions in the definition of
dcom is a bit subtle. The simplest thing to do would be to
annotate every dcom with a precondition and postcondition —
something like this...
But this would result in very verbose decorated programs with a
lot of repeated annotations: a simple program like
skip;skip would be decorated like this,
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, our formal syntax of decorated commands will omit
preconditions whenever possible and embed just postconditions.
The skip command, for example, is decorated only with its
postcondition
skip {{ q }}
on the assumption that the precondition will be provided by
somebody else.
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 d₁ ; d₂ need no additional decorations.
Why?
Because inside d₂ there will be a postcondition, which also
serves as the postcondition of d₁;d₂.
Similarly, inside d₁ there will also be a postcondition, which
additionally serves as the precondition for d₂.
An assignment X := a is decorated only with its postcondition:
X := a {{ q }}
A conditional if b then d₁ else d₂ is decorated with a
postcondition for the entire statement, as well as preconditions
for each branch:
if b then {{ p₁ }} d₁ else {{ p₂ }} d₂ end {{ q }}
Note to developers (Benjamin Pierce @bcpierce00, before next release, 2025)
Maybe we need a note here about why we don't just
calculate p₁ and p₂ later, once we know the precondition of the
whole loop. Indeed, we could (and perhaps should, as discussed
elsewhere), but we are doing something simpler for the moment.
A loop while (b) {d} is decorated with its final
postcondition plus a precondition for the body:
while (b) {{ p }} { d } {{ q }}
The postcondition embedded in d serves as the loop invariant.
Implications ->> can be added as decorations either for a
precondition...
->> {{ p }} d
...or for a postcondition:
d ->> {{ q }}
The former is waiting for another precondition to be supplied by
the context; the latter relies on the postcondition already
embedded in d.
Putting this all together gives us the formal syntax of decorated
commands:
Note to developers (Benjamin Pierce @bcpierce00, before next release, 2025)
It would be nice to use <{ ... }> notations
in this definition and the ones below...
| <{ skip {{p}} }> => p
| <{ _; d₂ }> => post d₂
| <{ _ := _ {{q}} }> => q
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 throughout 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.
The function DCom.VerificationConditions takes a decorated command
d together with a precondition p and returns a proposition
that, if it can be proved, implies that the triple
{{p}} d.erase {{d.postcondition}}
is valid.
It does this by walking over d and generating a big conjunction
that includes
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
external precondition; these uses correspond to applications
of the consequence rule.
Local consistency is defined as follows...
The decorated command
skip {{q}}
is locally consistent with respect to a precondition p if
p ->> q.
The sequential composition of d₁ and d₂ is locally
consistent with respect to p if d₁ is locally consistent with
respect to p and d₂ is locally consistent with respect to
the postcondition of d₁.
An assignment
X := a {{q}}
is locally consistent with respect to a precondition p if:
p ->> q [X ↦ a]
A conditional
if b then {{p₁}} d₁ else {{p₂}} d₂ end {{q}}
is locally consistent with respect to precondition p if
(1) p ∧ b ->> p₁
(2) p ∧ b ->> p₂
(3) d₁ is locally consistent with respect to p₁
(4) d₂ is locally consistent with respect to p₂
(5) d₁.postcondition ->> q
(6) d₂.postcondition ->> q
A loop
while (b) {{{q}} d} {{r}}
is locally consistent with respect to precondition p if:
(1) p ->> d.postcondition
(2) d.postcondition ∧ b ->> q
(3) d.postcondition ∧ b ->> r
(4) d is locally consistent with respect to q
A command with an extra assertion at the beginning
->> {{q}} d
is locally consistent with respect to a precondition p if:
(1) p ->> q
(2) d is locally consistent with respect to q
A command with an extra assertion at the end
d ->> {{q}}
is locally consistent with respect to a precondition p if:
(1) d is locally consistent with respect to p
(2) d.postcondition ->> q
With all this in mind, we can write a verification condition
generator that takes a decorated command and reads off a
proposition saying that all its decorations are locally
consistent.
Formally, since a decorated command is "waiting for its
precondition" the main VC generator takes a dcom plus a given
precondition as arguments.
Note to developers
HIDE: There was some discussion in 2016 about whether the VC
generator should should use equivalence or implication in a few
places. I (BCP) believe Phil (Wadler) changed some instances of
the former to the latter.
HIDE: MRC'20: a written explanation of each part of this would be
quite nice. BCP 21: Agreed!! (BCP 23: But it's kind of what's
just above...)
The following key theorem states that DCom.VerificationConditions
does its job correctly. Not surprisingly, each of the Hoare Logic
rules plays a critical role at some point in the proof.
The propositions generated by DCom.VerificationConditions are fairly
big and contain many conjuncts that are essentially trivial.
Note to developers
HIDE: MRC'20: The conditions here used to be just [Eval]ed instead
of being duplicated in a comment. They were actually incorrect
because of changes to notation. Putting them in as an [Example]
will force us to keep them up-to-date. APT20: Yes, but but stating
this an equality completely misses the point about verify_assertion! So I
changed things back.
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 is a skeleton of the formal decorated version of the
if_minus_plus program that we saw earlier. Replace all
occurrences of FILL_IN_HERE with appropriate assertions and fill
in the proof (which should be just as straightforward as in the
examples above).
Once the outermost precondition and postcondition are
chosen, the only creative part of a verifying program using Hoare
Logic is finding the right loop invariants. The reason this is
difficult is the same as the reason that inductive mathematical
proofs are:
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 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 harder to prove.
This section explains how to approach the challenge of finding
loop invariants through a series of examples and exercises.
The following program subtracts the value of X from the value of
Y by repeatedly decrementing both X and Y. We want to verify its
correctness with respect to the pre- and postconditions shown:
{{ X = m ∧ Y = n }}
while X ≠ 0 do
Y := Y - 1;
X := X - 1
end
{{ Y = n - m }}
To verify this program, we need to find an invariant Inv for the
loop. As a first step we can leave Inv as an unknown and build a
skeleton for the proof by applying the rules for local
consistency, working from the end of the program to the beginning,
as usual, and without doing any thinking at all yet.
This leads to the following skeleton:
(1) {{ X = m ∧ Y = n }} ->> (a)
(2) {{ Inv }}
while X ≠ 0 do
(3) {{ Inv ∧ X ≠ 0 }} ->> (c)
(4) {{ Inv [X ↦ X-1] [Y ↦ Y-1] }}
Y := Y - 1;
(5) {{ Inv [X ↦ X-1] }}
X := X - 1
(6) {{ Inv }}
end
(7) {{ Inv ∧ ¬ (X ≠ 0) }} ->> (b)
(8) {{ Y = n - m }}
Examining this skeleton, we can see that any valid Inv will
have to respect three conditions:
(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).
These conditions are actually independent of the particular
program and specification we are considering: every loop
invariant has to satisfy them.
One way to find a loop invariant that simultaneously satisfies these
three conditions is by using an iterative process: start with a
"candidate" invariant (e.g., a guess or a heuristic choice) and
check the three conditions above; if any of the checks fails, try
to use the information that we get from the failure to produce
another — hopefully better — candidate invariant, and repeat.
For instance, in the reduce-to-zero example above, we saw that,
for a very simple loop, choosing True as a loop invariant did the
job. Maybe it will work here too. To find out, let's try
instantiating Inv with True in the skeleton above and
see what we get...
(1) {{ X = m ∧ Y = n }} ->> (a - OK)
(2) {{ True }}
while X ≠ 0 do
(3) {{ True ∧ X ≠ 0 }} ->> (c - OK)
(4) {{ True }}
Y := Y - 1;
(5) {{ True }}
X := X - 1
(6) {{ True }}
end
(7) {{ True ∧ ¬(X ≠ 0) }} ->> (b - WRONG!)
(8) {{ Y = n - m }}
While conditions (a) and (c) are trivially satisfied,
(b) is wrong: it is not the case that True ∧ X = 0 (7)
implies Y = n - m (8). In fact, the two assertions are
completely unrelated, so it is very easy to find a counterexample
to the implication (say, Y = X = m = 0 and n = 1).
If we want (b) to hold, we need to strengthen the loop invariant so
that it implies the postcondition (8). One simple way to do
this is to let the loop invariant be the postcondition. So let's
return to our skeleton, instantiate Inv with Y = n - m, and
try checking conditions (a) to (c) again.
(1) {{ X = m ∧ Y = n }} ->> (a - WRONG!)
(2) {{ Y = n - m }}
while X ≠ 0 do
(3) {{ Y = n - m ∧ X ≠ 0 }} ->> (c - WRONG!)
(4) {{ Y - 1 = n - m }}
Y := Y - 1;
(5) {{ Y = n - m }}
X := X - 1
(6) {{ Y = n - m }}
end
(7) {{ Y = n - m ∧ ¬(X ≠ 0) }} ->> (b - OK)
(8) {{ Y = n - m }}
This time, condition (b) holds trivially, but (a) and (c) are
broken. Condition (a) requires that (1) X = m ∧ Y = n
implies (2) Y = n - m. If we substitute Y by n we have to
show that n = n - m for arbitrary m and n, which is not
the case (for instance, when m = n = 1). Condition (c) requires
that n - m - 1 = n - m, which fails, for instance, for n = 1
and m = 0. So, although Y = n - m holds at the end of the loop,
it does not hold from the start, and it doesn't hold on each
iteration; it is not a correct loop invariant.
This failure is not very surprising: the variable Y changes
during the loop, while m and n are constant, so the assertion
we chose didn't have much chance of being a loop invariant!
To do better, we need to generalize (7) to some statement that is
equivalent to (8) when X is 0, since this will be the case
when the loop terminates, and that "fills the gap" in some
appropriate way when X is nonzero. Looking at how the loop
works, we can observe that X and Y are decremented together
until X reaches 0. So, if X = 2 and Y = 5 initially,
after one iteration of the loop we obtain X = 1 and Y = 4;
after two iterations X = 0 and Y = 3; and then the loop stops.
Notice that the difference between Y and X stays constant
between iterations: initially, Y = n and X = m, and the
difference is always n - m. So let's try instantiating Inv in
the skeleton above with Y - X = n - m.
(1) {{ X = m ∧ Y = n }} ->> (a - OK)
(2) {{ Y - X = n - m }}
while X ≠ 0 do
(3) {{ Y - X = n - m ∧ X ≠ 0 }} ->> (c - OK)
(4) {{ (Y - 1) - (X - 1) = n - m }}
Y := Y - 1;
(5) {{ Y - (X - 1) = n - m }}
X := X - 1
(6) {{ Y - X = n - m }}
end
(7) {{ Y - X = n - m ∧ ¬(X ≠ 0) }} ->> (b - OK)
(8) {{ Y = n - m }}
Success! Conditions (a), (b) and (c) all hold now. (To
verify (c), we need to check that, under the assumption that
X ≠ 0, we have Y - X = (Y - 1) - (X - 1); this holds for all
natural numbers X and Y.)
Here is the final version of the decorated program:
A roundabout way of assigning a number currently stored in X to
the variable Y is to start Y at 0, then decrement X until
it hits 0, incrementing Y at each step. Here is a program that
implements this idea. Fill in decorations and prove the decorated
program correct. (The proof should be very simple.)
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).
Note to developers
HIDE: A more complexly phrased loop invariant for the same program
[[
{{ X = m }} ->> (a - OK)
{{ ev X <-> ev m }}
while 2 ≤ X do
{{ ev X <-> ev m ∧ 2 ≤ X }} ->> (c - OK)
{{ ev (X-2) <-> ev m }}
X := X - 2
{{ ev X <-> ev m }}
end
{{ (ev X <-> ev m) ∧ ~(2 ≤ X) }} ->> (b - OK)
{{ X=0 <-> ev m }}
]]
HIDE: find_parity'_dec; more complicated phrasing of invariant
there is very little resemblance between the invariant and the
postcondition -- the implication is also non-obvious, and the
X ≤ m condition makes the invariant more complicated
[[
{{ X = m }} ->>
{{ X ≤ m ∧ ev (m - X) }}
while 2 ≤ X do
{{ X ≤ m ∧ ev (m - X) ∧ 2 ≤ X }} ->>
{{ X - 2 ≤ m ∧ ev (m - (X - 2)) }}
X := X - 2
{{ X ≤ m ∧ ev (m - X) }}
end
{{ X ≤ m ∧ ev (m - X) ∧ ~(2 ≤ X) }} ->>
{{ X=0 <-> ev m }}
]]
Exercise★★★(parity) (Optional)
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. Ordinary Lean functions can be applied
directly to Imp variables inside assertions, so this can be written
as {{ parity X = parity m }}.
Note to developers (Benjamin Pierce @bcpierce00, before next release, 2023)
Maya: In the parity exercise, I was getting annoyed
by the verify_assertion tactic unfolding the assumption [(2 ≤? st
X) = true] into a match on the first two layers of [st X]. I ended
up digging out the following incantation from the depths of the Rocq
manual:
Arguments leb !n !m.
I'm not sure what level of automated tests you keep for the
exercises, so I wanted to point this struggle out. Perhaps
something changed in the Rocq library at some point.
BCP 23: Worth looking into! (I tried just adding [Arguments leb !n
!m.] to the script, but that broke things.)
If you use the suggested loop invariant, you may find the following
two lemmas helpful.
theorem parity_ge_2 (x : Nat) (h : 2 ≤ x) :
parity (x - 2) = parity x := by
sorry
theorem parity_lt_2 (x : Nat) (h : ¬ 2 ≤ x) :
parity x = x := by
sorry
theorem parity_outer_triple_valid (m : Nat) :
(parityDec m).OuterTripleValid := by
solution!
-- Simplification is too aggressive here; recover the
-- folded guard before proving preservation and exit.
sorry
/- Here is another loop invariant — arguably a more natural
one —
which sadly leads to a rather long proof. -/
inductive Even : Nat → Prop where
| zero : Even 0
| addTwo {n : Nat} : Even n → Even (Nat.succ (Nat.succ n))
def findParityDec (m : Nat) : Decorated where
pre := ({{ X = m }})
body :=
let inv : Assertion :=
fun st => st[X] ≤ m ∧ Even (m - st[X])
let guardedInv : Assertion :=
fun st => (st[X] ≤ m ∧ Even (m - st[X])) ∧ 2 ≤ st[X]
let bodyPre : Assertion :=
fun st => st[X] - 2 ≤ m ∧ Even (m - (st[X] - 2))
let exit : Assertion :=
fun st => (st[X] ≤ m ∧ Even (m - st[X])) ∧ st[X] < 2
let post : Assertion := fun st => st[X] = 0 ↔ Even m
dcom {
->> {{ inv }}
while (2 ≤ X) do
{{ guardedInv }}
->> {{ bodyPre }}
X := X - 2 {{ inv }}
end
{{ exit }}
->> {{ post }}
}
theorem find_parity_correct (m : Nat) :
(findParityDec m).OuterTripleValid := by
-- Simplification is too aggressive here; recover the
-- folded guard before proving preservation and exit.
-- At loop exit, X can only be 0 or 1.
sorry
/- Here is a more intuitive way of writing the loop
invariant. -/
def findParityDec' (m : Nat) : Decorated where
pre := ({{ X = m }})
body :=
let inv : Assertion := fun st => Even st[X] ↔ Even m
let guardedInv : Assertion :=
fun st => (Even st[X] ↔ Even m) ∧ 2 ≤ st[X]
let bodyPre : Assertion :=
fun st => Even (st[X] - 2) ↔ Even m
let exit : Assertion :=
fun st => (Even st[X] ↔ Even m) ∧ ¬ 2 ≤ st[X]
let post : Assertion := fun st => st[X] = 0 ↔ Even m
dcom {
->> {{ inv }}
while (2 ≤ X) do
{{ guardedInv }}
->> {{ bodyPre }}
X := X - 2 {{ inv }}
end
{{ exit }}
->> {{ post }}
}
theorem find_parity_correct' (m : Nat) :
(findParityDec' m).OuterTripleValid := by
-- Simplification is too aggressive here; recover the
-- folded guard before proving preservation and exit.
-- At loop exit, X can only be 0 or 1.
sorry
/- Finally, just for fun, here is an old-style
non-decorated-program proof. -/
theorem parity_correct (m : Nat) :
{{ X = m }}
while (2 ≤ X) {
X := X - 2
}
{{ fun st => st[X] = parity m }} := by
sorry
The following program computes the integer square root of X
by naive iteration:
{{ X=m }}
Z := 0;
while (Z+1)*(Z+1) ≤ X do
Z := Z+1
end
{{ Z*Z≤m ∧ m<(Z+1)*(Z+1) }}
WORK IN CLASS
As we did before, we can try to use the postcondition as a
candidate loop invariant, obtaining the following decorated program:
(1) {{ X=m }} ->> (a - second conjunct of (2) WRONG!)
(2) {{ 0*0 ≤ m ∧ m<(0+1)*(0+1) }}
Z := 0
(3) {{ Z*Z ≤ m ∧ m<(Z+1)*(Z+1) }};
while (Z+1)*(Z+1) ≤ X do
(4) {{ Z*Z≤m ∧ m<(Z+1)*(Z+1)
∧ (Z+1)*(Z+1)≤X }} ->> (c - WRONG!)
(5) {{ (Z+1)*(Z+1)≤m ∧ m<((Z+1)+1)*((Z+1)+1) }}
Z := Z+1
(6) {{ Z*Z≤m ∧ m<(Z+1)*(Z+1) }}
end
(7) {{ Z*Z≤m ∧ m<(Z+1)*(Z+1) ∧ ¬((Z+1)*(Z+1)≤X) }} ->> (b - OK)
(8) {{ Z*Z≤m ∧ m<(Z+1)*(Z+1) }}
This didn't work very well: conditions (a) and (c) both failed.
Looking at condition (c), we see that the second conjunct of (4)
is almost the same as the first conjunct of (5), except that (4)
mentions X while (5) mentions m. But note that X is never
assigned in this program, so we should always have X=m. We
didn't propagate this information from (1) into the loop
invariant, but we could!
Also, we don't need the second conjunct of (8), since we can
obtain it from the negation of the guard — the third conjunct
in (7) — again under the assumption that X=m. This allows
us to simplify a bit.
So we now try X=m ∧ Z*Z ≤ m as the loop invariant:
{{ X=m }} ->> (a - OK)
{{ X=m ∧ 0*0 ≤ m }}
Z := 0
{{ X=m ∧ Z*Z ≤ m }};
while (Z+1)*(Z+1) ≤ X do
{{ X=m ∧ Z*Z≤m ∧ (Z+1)*(Z+1)≤X }} ->> (c - OK)
{{ X=m ∧ (Z+1)*(Z+1)≤m }}
Z := Z + 1
{{ X=m ∧ Z*Z≤m }}
end
{{ X=m ∧ Z*Z≤m ∧ ¬((Z+1)*(Z+1)≤X) }} ->> (b - OK)
{{ Z*Z≤m ∧ m<(Z+1)*(Z+1) }}
This works, since conditions (a), (b), and (c) are now all
rather trivially satisfied.
Very often, when a variable is used in a loop in a read-only
fashion (i.e., it is referred to by the program or by the
specification, and it is not changed by the loop), it is necessary
to record the fact that it doesn't change in the loop invariant.
Exercise★★★(sqrt) (Optional)
Translate the above informal decorated program into a formal one
and prove it correct.
Hint: The loop invariant here must ensure that Z*Z is consistently
less than or equal to X.
HIDE: CH: it might make sense to show all the variants
for future exercise builders, together with some hints on how to
write programs that are easier to verify
Here is a program that squares X by repeated addition:
{{ X = m }}
Y := 0;
Z := 0;
while Y ≠ X do
Z := Z + X;
Y := Y + 1
end
{{ Z = m*m }}
WORK IN CLASS
The first thing to note is that the loop reads X but doesn't
change its value. As we saw in the previous example, it can be a good idea
in such cases to add X = m to the loop invariant. The other thing
that we know is often useful in the loop invariant is the postcondition,
so let's add that too, leading to the candidate loop invariant
Z = m * m ∧ X = m.
{{ X = m }} ->> (a - WRONG)
{{ 0 = m*m ∧ X = m }}
Y := 0
{{ 0 = m*m ∧ X = m }};
Z := 0
{{ Z = m*m ∧ X = m }};
while Y ≠ X do
{{ Z = m*m ∧ X = m ∧ Y ≠ X }} ->> (c - WRONG)
{{ Z+X = m*m ∧ X = m }}
Z := Z + X
{{ Z = m*m ∧ X = m }};
Y := Y + 1
{{ Z = m*m ∧ X = m }}
end
{{ Z = m*m ∧ X = m ∧ ¬(Y ≠ X) }} ->> (b - OK)
{{ Z = m*m }}
Conditions (a) and (c) fail because of the Z = m*m part. While
Z starts at 0 and works itself up to m*m, we can't expect
Z to be m*m from the start. If we look at how Z progresses
in the loop, after the 1st iteration Z = m, after the 2nd
iteration Z = 2*m, and at the end Z = m*m. Since the variable
Y tracks how many times we go through the loop, this leads us to
derive a new loop invariant candidate: Z = Y*m ∧ X = m.
{{ X = m }} ->> (a - OK)
{{ 0 = 0*m ∧ X = m }}
Y := 0
{{ 0 = Y*m ∧ X = m }};
Z := 0
{{ Z = Y*m ∧ X = m }};
while Y ≠ X do
{{ Z = Y*m ∧ X = m ∧ Y ≠ X }} ->> (c - OK)
{{ Z+X = (Y+1)*m ∧ X = m }}
Z := Z + X
{{ Z = (Y+1)*m ∧ X = m }};
Y := Y + 1
{{ Z = Y*m ∧ X = m }}
end
{{ Z = Y*m ∧ X = m ∧ ¬(Y ≠ X) }} ->> (b - OK)
{{ Z = m*m }}
This new loop invariant makes the proof go through: all three
conditions are easy to check.
It is worth comparing the postcondition Z = m*m and the
Z = Y*m conjunct of the loop invariant. It is often the case
that one has to replace parameters with variables — or with
expressions involving both variables and parameters, like
m - Y — when going from postconditions to loop invariants.
Note to developers
HIDE: the more complicated version from 2012's class
Here is a program that squares X by repeated addition:
[[
X := n;
Y := X;
Z := 0;
while Y ≠ 0 do
Z := Z + X;
Y := Y - 1
end
]]
Bob's simpler loop invariant for squaring [square_dec]:
(a very similar invariant given as solution in 2011 final; exercise 3)
[[
{{ True }}
X := n;
{{ X = n }}
Y := X;
{{ X = n ∧ Y = n }}
Z := 0;
{{ X = n ∧ Y = n ∧ Z = 0}} ->>
{{ Z + X * Y = n * n }}
while Y ≠ 0 do
{{ Z + X * Y = n * n ∧ (Y ≠ 0)}} ->>
{{ Z + X + X * (Y - 1) = n * n }}
Z := Z + X;
{{ Z + X * (Y - 1) = n * n }}
Y := Y - 1
{{ Z + X * Y = n * n }}
end
{{ Z + X * Y = n * n ∧ ~(Y ≠ 0)}} ->>
{{ Z = n * n }}
]]
The other loop invariant [square_dec']:
[[
{{ True }}
X := n;
{{ X = n }}
Y := X;
{{ X = n ∧ Y = n }}
Z := 0;
{{ X = n ∧ Y = n ∧ Z = 0}} ->>
{{ Z = X * (X - Y) ∧ X = n ∧ Y ≤ X }}
while Y ≠ 0 do
{{ Z = X * (X - Y) ∧ X = n ∧ Y ≤ X ∧ (Y ≠ 0)}} ->>
{{ Z + X = X * (X - (Y - 1)) ∧ X = n ∧ (Y - 1) ≤ X }}
Z := Z + X;
{{ Z = X * (X - (Y - 1)) ∧ X = n ∧ (Y - 1) ≤ X }}
Y := Y - 1
{{ Z = X * (X - Y) ∧ X = n ∧ Y ≤ X }}
end
{{ Z = X * (X - Y) ∧ X = n ∧ Y ≤ X ∧ ~(Y ≠ 0)}} ->>
{{ Z = n * n }}
]]
Move this later? Might be harder than some of the others.
Note to developers
HIDE: LY: Many are tempted to use division in their propositions here,
with the loop invariant [Y = m!/X!].
Informally, such a decorated program can be correct if we assume
they use real division (in q or r). The issue is that formally in Rocq,
the notation / is also in scope and means integer division, so a pedantic
interpretation would mark those answers wrong, even though that is most
likely *not* what students intended (thus making the grading unfair).
Should we explicitly forbid use of division for this exercise?
(I added a note to that effect in the problem statement).
MRC'20: I strengthened your note so that it explicitly advises
against division (and subtraction).
Exercise★★★★(factorial_correct) (Advanced)
Recall that n! denotes the factorial of n (i.e., n! =
1*2*...*n). We can define the factorial function recursively in
Lean as follows:
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 slowAssignmentDec as a
guide, write a formal decorated program factorialDec that
implements the factorial function. Ordinary Lean functions such as
fact can be applied directly to Imp variables inside assertions.
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
factorialDec 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 Lean.
For example, recall that 1 + ... is easier to work with than
... + 1.
HIDE: MRC'20: That's not really an Imp program though: it is a
schema for an Imp program. m is not an Imp variable nor a
constant. BCP 21: But we do that all over the place, no?
HIDE: LY: I saw one submission for [factorial_dec] use a program
like that instead of the one already given by the informal
exercise. I accepted it because the exercise does not require to
reuse the given program, and we did not strictly define what it
means to "implement" factorial in Imp. This other one "implements"
factorial in the same way two_loops_dec "implements" the sum (a + b
+ c).
Fill in decorations for the following program and prove them
correct. As with factorial, be careful about mathematical
reasoning involving natural numbers, especially subtraction.
Lean functions can be applied directly inside assertions. For
example, the minimum of a and b can be written Nat.min a b.
Note to developers
HIDE: MRC'20: It bothers me a bit that the && in the guard below
becomes a ∧ in the assertion. We've never explained that it's okay
to do a translation like that.
Note to developers (Benjamin Pierce @bcpierce00, before next release, 2025)
HIDE: LY: in this exercise, many end up writing the following implication
after the while line:
{{ Z = min a b - min X Y ∧ ... }} ->>
{{ Z+1 = min a b - min (X-1) (Y-1) ∧ ... }}
that is invalid if you interpret [-] pedantically as [sub : nat ->
nat -> nat], which takes nonnegative values only. But if we are
more generous and interpret these informal proofs in more intuitive
domains (Z, q, or r), then these proofs look fine. I made the
former choice in my grading because I assume at this point they
should know to be careful around [-] with [nat]. BCP 21: Should be
fixed now that the proofs are formal! :-)
Solution:
[[
{{ True }} ->>
{{ c = 0 + c ∧ 0 = 0 }}
X := 0;
{{ c = X + c ∧ 0 = 0 }}
Y := 0;
{{ c = X + c ∧ Y = 0 }}
Z := c;
{{ Z = X + c ∧ Y = 0 }}
while X ≠ a do
{{ Z = X + c ∧ Y = 0 ∧ X ≠ a }} ->>
{{ Z + 1 = X + 1 + c ∧ Y = 0 }}
X := X + 1;
{{ Z + 1 = X + c ∧ Y = 0 }}
Z := Z + 1
{{ Z = X + c ∧ Y = 0 }}
end;
{{ Z = X + c ∧ Y = 0 ∧ ¬(X ≠ a) }} ->>
{{ Z = a + Y + c }}
while Y ≠ b do
{{ Z = a + Y + c ∧ Y ≠ b }} ->>
{{ Z + 1 = a + Y + 1 + c }}
Y := Y + 1;
{{ Z + 1 = a + Y + c }}
Z := Z + 1
{{ Z = a + Y + c }}
end
{{ Z = a + Y + c ∧ ~(Y ≠ b) }} ->>
{{ Z = a + b + c }}
]]
Another solution follows. It doesn't require carrying an additional
[Y = 0] conjunct through the first loop, but instead carries an
additional [ + Y] term through it.
[[
{{ True }} ->>
{{ c = 0 + 0 + c }}
X := 0;
{{ c = X + 0 + c }}
Y := 0;
{{ c = X + Y + c }}
Z := c;
{{ Z = X + Y + c }}
while X ≠ a do
{{ Z = X + Y + c ∧ X ≠ a }} ->>
{{ Z + 1 = (X + 1) + Y + c }}
X := X + 1;
{{ Z + 1 = X + Y + c }}
Z := Z + 1
{{ Z = X + Y + c }}
end;
{{ Z = X + Y + c ∧ ¬(X ≠ a) }} ->>
{{ Z = a + Y + c }}
while Y ≠ b do
{{ Z = a + Y + c ∧ (Y ≠ b) }} ->>
{{ Z + 1 = a + (Y + 1) + c }}
Y := Y + 1;
{{ Z + 1 = a + Y + c }}
Z := Z + 1
{{ Z = a + Y + c }}
end
{{ Z = a + Y + c ∧ ¬(Y ≠ b) }} ->>
{{ Z = a + b + c }}
]]
Note to developers (Michael Clarkson @clarksmr, before next release, 2020)
This is again a program schema rather than a program. Why not...
[[
{{ True }}
X := 0;
Y := 1;
Z := 1;
while X ≠ W do
Z := 2 * Z;
Y := Y + Z;
X := X + 1
end
{{ Y = 2 ^ (W + 1) - 1 }}
]]
...?
BCP 21: Ditto my response above. IMO this is not a problem.
Exercise★★★★(dpow2) (Optional)
Here is a program that computes the series:
1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1
X := 0;
Y := 1;
Z := 1;
while X ≠ m do
Z := 2 * Z;
Y := Y + Z;
X := X + 1
end
Turn this into a decorated program and prove it correct.
HIDE: Another (very) good exercise from 09-mid₂ -- just needs typeset
The notion of weakest precondition has a natural dual : given a
precondition and a command, we can ask what is the strongest
postcondition of the command with respect to the
precondition. Formally, we can define it like this:
q is the strongest postcondition of c for p if:
(a) {{p}} c {{q}}, and
(b) if Q′ is an assertion such that {{p}}c{{Q′}},
then q st implies Q′ st, for all states st.
q is the strongest (most difficult to satisfy) assertion that is
guaranteed to hold after c if p holds before. For example, the
strongest postcondition of the command skip with respect to the
precondition Y = 1 is Y = 1. Similarly, the postcondition in...
{{ Y = y }}
if !Y === A0 then X := A0 else Y := !Y *** A2
{{ (Y = y = X = 0) ∨ (Y = 2*y ∧ y ≠ 0) }}
...is the strongest one.
Complete each of the following Hoare triples with the strongest
postcondition for the given command and precondition.
(a) {{Y=1}} X:=!Y+++A1 {{?}}
(b) {{True}} X:=A5 {{?}}
(c) {{ True }} skip {{ ? }}
(d) {{ True }} while true do skip {{ ? }}
(e) {{ X = x ∧ Y = y }}
while BNot (!X === A0) do (
Y := !Y +++ A2;
X := !X --- A1
)
{{ ? }}
Exercise★★(fib_eqn) (Advanced, Optional)
The Fibonacci function is characterized by the equations
Note to developers (Benjamin Pierce @bcpierce00, before next release, 2021)
This exercise should really be expanded into its
own whole section. Moreover, there is a proposal to make the
decorations in Hoare look more like the decorations earlier in the
present chapter. All three should be aligned.
Exercise★★★★★(improve_dcom) (Advanced, Optional)
The formal decorated programs defined above 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.
namespace SparseAnnotations
/- (This solution also allows optional post-condition
assertions at any point, since these are quite useful in
practice when debugging the results of automated VC
solvers.) -/
inductive DCom where
| skip
| seq (first second : DCom)
| asgn (x : Ident) (a : Aexp)
| cond (b : Bexp) (thenBranch elseBranch : DCom)
| whileDo (b : Bexp) (invariant : Assertion) (body : DCom)
| assert (assertion : Assertion)
structure Decorated where
pre : Assertion
body : DCom
post : Assertion
declare_syntax_cat sparse_dcom
syntax:max "(" sparse_dcom ")" : sparse_dcom
syntax:max "skip" : sparse_dcom
syntax:max ident " := " imp_aexp : sparse_dcom
syntax:20 sparse_dcom:21 ";" ppDedent(ppLine
sparse_dcom:20) : sparse_dcom
syntax:max "if " "(" imp_bexp ")" ppHardSpace "then"
ppLine sparse_dcom ppDedent(ppLine ppDedent("else"))
ppLine sparse_dcom
ppDedent(ppLine ppDedent("end")) : sparse_dcom
syntax:max "while " "(" imp_bexp ")" ppHardSpace "do"
ppLine "{{" term "}}" ppLine sparse_dcom
ppDedent(ppLine ppDedent("end")) : sparse_dcom
syntax:max "assert" " {{" term "}}" : sparse_dcom
syntax:min "sdcom" ppHardSpace "{" ppLine
sparse_dcom ppDedent(ppLine "}") : term
macro_rules
| `(sdcom { $s }) => do
let stx ← match s with
| `(sparse_dcom| ($body:sparse_dcom)) => `(sdcom { $body })
| `(sparse_dcom| skip) => `(DCom.skip)
| `(sparse_dcom| $x:ident := $a:imp_aexp) =>
`(DCom.asgn $x (aexp { $a }))
| `(sparse_dcom| $d₁:sparse_dcom; $d₂:sparse_dcom) =>
`(DCom.seq (sdcom { $d₁ }) (sdcom { $d₂ }))
| `(sparse_dcom|
if ($b:imp_bexp) then
$d₁:sparse_dcom
else
$d₂:sparse_dcom
end) =>
`(DCom.cond (bexp { $b })
(sdcom { $d₁ }) (sdcom { $d₂ }))
| `(sparse_dcom|
while ($b:imp_bexp) do
{{ $inv }}
$body:sparse_dcom
end) =>
`(DCom.whileDo (bexp { $b }) ({{ $inv }})
(sdcom { $body }))
| `(sparse_dcom| assert {{ $p }}) => `(DCom.assert ({{ $p }}))
| _ => Lean.Macro.throwUnsupported
return Imp.Elab.withSourceInfoOf s stx
namespace DCom.Delab
open Lean PrettyPrinter Delaborator SubExpr Parenthesizer Imp.Elab Imp.Delab
@[category_parenthesizer «sparse_dcom»]
def sparse_dcom.parenthesizer : CategoryParenthesizer := fun prec => do
maybeParenthesize `sparse_dcom false wrapParens prec <|
parenthesizeCategoryCore `sparse_dcom prec
where
wrapParens (stx : Syntax) : Syntax := Unhygienic.run do
let stxInfo := SourceInfo.fromRef stx
let stx := stx.setInfo .none
let pstx ← `(sparse_dcom| ($(⟨stx⟩)))
return pstx.raw.setInfo stxInfo
private def getDCom? (stx : Term) : Option (TSyntax `sparse_dcom) :=
match stx with
| `(sdcom { $d:sparse_dcom }) => some <| withSourceInfoOf (canonical := false) stx d
| _ => none
@[app_delab SparseAnnotations.DCom.skip]
def delabSkip : Delab := whenPPOption getPPNotation do
`(sdcom { skip })
@[app_unexpander SparseAnnotations.DCom.asgn]
def unexpandAsgn : Unexpander
| `($_ $x:ident $a) => `(sdcom { $x:ident := $(getAexp a) })
| _ => throw ()
@[app_unexpander SparseAnnotations.DCom.seq]
def unexpandSeq : Unexpander
| `($_ $first $second) => do
let some first := getDCom? first | throw ()
let some second := getDCom? second | throw ()
`(sdcom { $first; $second })
| _ => throw ()
@[app_unexpander SparseAnnotations.DCom.cond]
def unexpandCond : Unexpander
| `($_ $b $thenBranch $elseBranch) => do
let some thenBranch := getDCom? thenBranch | throw ()
let some elseBranch := getDCom? elseBranch | throw ()
`(sdcom {
if ($(getBexp b)) then
$thenBranch
else
$elseBranch
end
})
| _ => throw ()
@[app_unexpander SparseAnnotations.DCom.whileDo]
def unexpandWhileDo : Unexpander
| `($_ $b $invariant $body) => do
let some body := getDCom? body | throw ()
`(sdcom {
while ($(getBexp b)) do
{{ $(_root_.DCom.Delab.getAssnBody invariant) }}
$body
end
})
| _ => throw ()
@[app_unexpander SparseAnnotations.DCom.assert]
def unexpandAssert : Unexpander
| `($_ $assertion) =>
`(sdcom { assert {{ $(_root_.DCom.Delab.getAssnBody assertion) }} })
| _ => throw ()
end DCom.Delab
/- Here's how our decorated programs look now: -/
def decWhile : Decorated where
pre := ({{ True }})
body := sdcom {
while (X ≠ 0) do
{{ True }}
X := X - 1
end
}
post := ({{ X = 0 }})
/- It is easy to go from a `DCom` to a `Com` by erasing all
annotations. -/
def DCom.erase (d : DCom) : Com :=
match d with
| .skip => .skip
| .seq d₁ d₂ => .seq d₁.erase d₂.erase
| .asgn x a => .asgn x a
| .cond b d₁ d₂ => .cond b d₁.erase d₂.erase
| .whileDo b _ body => .whileDo b body.erase
| .assert _ => .skip
/- We can express what it means for a decorated program to
be correct as follows: -/
def Decorated.OuterTripleValid (dec : Decorated) : Prop :=
ValidHoareTriple dec.pre dec.body.erase dec.post
/- This VC generator is derived from Mike Gordon,
"Background reading on Hoare Logic,"
https://www.cl.cam.ac.uk/archive/mjcg/HL/Notes/Notes.pdf -/
def DCom.awp (post : Assertion) (d : DCom) : Assertion :=
match d with
| .skip => post
| .seq d₁ d₂ => d₁.awp (d₂.awp post)
| .asgn x a => {{ post [x ↦ a] }}
| .cond b d₁ d₂ =>
fun st =>
(b.eval st = true ∧ d₁.awp post st) ∨
(b.eval st = false ∧ d₂.awp post st)
| .whileDo _ invariant _ => invariant
| .assert assertion => fun st => assertion st ∧ post st
def DCom.VerificationConditions
(post : Assertion) (d : DCom) : Prop :=
match d with
| .seq d₁ d₂ =>
d₁.VerificationConditions (d₂.awp post) ∧
d₂.VerificationConditions post
| .cond _ d₁ d₂ =>
d₁.VerificationConditions post ∧
d₂.VerificationConditions post
| .whileDo b invariant body =>
(∀ st, invariant st ∧ b.eval st ≠ true → post st) ∧
(∀ st, invariant st ∧ b.eval st = true →
body.awp invariant st) ∧
body.VerificationConditions invariant
| _ => True
theorem vc_correct (d : DCom) (post : Assertion)
(hvc : d.VerificationConditions post) :
ValidHoareTriple (d.awp post) d.erase post := by
sorry
def Decorated.VerificationConditions
(dec : Decorated) : Prop :=
(dec.pre ->> dec.body.awp dec.post) ∧
dec.body.VerificationConditions dec.post
theorem verification_correct (dec : Decorated)
(hvc : dec.VerificationConditions) :
dec.OuterTripleValid := by
sorry
/- Let's redo all the examples to date. -/
/- LATER: Fix indentation. -/
theorem dec_while_correct :
decWhile.OuterTripleValid := by
sorry
def swapDec (m n : Nat) : Decorated where
pre := ({{ X = m ∧ Y = n }})
body := sdcom {
X := X + Y;
Y := X - Y;
X := X - Y
}
post := ({{ X = n ∧ Y = m }})
theorem swap_correct (m n : Nat) :
(swapDec m n).OuterTripleValid := by
sorry
def ifMinusDec : Decorated where
pre := ({{ True }})
body := sdcom {
if (X ≤ Y) then
Z := Y - X
else
Z := X - Y
end
}
post := ({{ Z + X = Y ∨ Z + Y = X }})
theorem if_minus_correct :
ifMinusDec.OuterTripleValid := by
sorry
def ifMinusPlusDec : Decorated where
pre := ({{ True }})
body := sdcom {
if (X ≤ Y) then
Z := Y - X
else
Y := X + Z
end
}
post := ({{ Y = X + Z }})
theorem if_minus_plus_correct :
ifMinusPlusDec.OuterTripleValid := by
sorry
def divModDec (a b : Nat) : Decorated where
pre := ({{ True }})
body := sdcom {
X := ~(Aexp.num a);
Y := 0;
while (~(Aexp.num b) ≤ X) do
{{ b * Y + X = a }}
X := X - ~(Aexp.num b);
Y := Y + 1
end
}
post := ({{ b * Y + X = a ∧ X < b }})
theorem div_mod_outer_triple_valid (a b : Nat) :
(divModDec a b).OuterTripleValid := by
sorry
def parityDec (m : Nat) : Decorated where
pre := ({{ X = m }})
body := sdcom {
while (2 ≤ X) do
{{ parity X = parity m }}
X := X - 2
end
}
post := ({{ X = parity m }})
theorem parity_outer_triple_valid (m : Nat) :
(parityDec m).OuterTripleValid := by
sorry
def sqrtDec (m : Nat) : Decorated where
pre := ({{ X = m }})
body := sdcom {
Z := 0;
while ((Z + 1) * (Z + 1) ≤ X) do
{{ X = m ∧ Z * Z ≤ m }}
Z := Z + 1
end
}
post := ({{ Z * Z ≤ m ∧ m < (Z + 1) * (Z + 1) }})
theorem sqrt_correct (m : Nat) :
(sqrtDec m).OuterTripleValid := by
sorry
def squareDec (m : Nat) : Decorated where
pre := ({{ X = m }})
body := sdcom {
Y := X;
Z := 0;
while (Y ≠ 0) do
{{ Z + X * Y = m * m }}
Z := Z + X;
Y := Y - 1
end
}
post := ({{ Z = m * m }})
theorem square_outer_triple_valid (m : Nat) :
(squareDec m).OuterTripleValid := by
sorry
def squareDec' (n : Nat) : Decorated where
pre := ({{ True }})
body := sdcom {
X := ~(Aexp.num n);
Y := X;
Z := 0;
while (Y ≠ 0) do
{{ Z = X * (X - Y) ∧ X = n ∧ Y ≤ X }}
Z := Z + X;
Y := Y - 1
end
}
post := ({{ Z = n * n }})
theorem square_dec'_correct (n : Nat) :
(squareDec' n).OuterTripleValid := by
sorry
def squareSimplerDec (m : Nat) : Decorated where
pre := ({{ X = m }})
body := sdcom {
Y := 0;
Z := 0;
while (Y ≠ X) do
{{ Z = Y * m ∧ X = m }}
Z := Z + X;
Y := Y + 1
end
}
post := ({{ Z = m * m }})
theorem square_simpler_outer_triple_valid (m : Nat) :
(squareSimplerDec m).OuterTripleValid := by
sorry
def twoLoopsDec (a b c : Nat) : Decorated where
pre := ({{ True }})
body := sdcom {
X := 0;
Y := 0;
Z := ~(Aexp.num c);
(while (X ≠ ~(Aexp.num a)) do
{{ Z = X + c ∧ Y = 0 }}
X := X + 1;
Z := Z + 1
end);
while (Y ≠ ~(Aexp.num b)) do
{{ Z = a + Y + c }}
Y := Y + 1;
Z := Z + 1
end
}
post := ({{ Z = a + b + c }})
theorem two_loops_correct (a b c : Nat) :
(twoLoopsDec a b c).OuterTripleValid := by
sorry
def subtractSlowlyDec (m p : Nat) : Decorated where
pre := ({{ X = m ∧ Z = p }})
body := sdcom {
while (X ≠ 0) do
{{ Z - X = p - m }}
Z := Z - 1;
X := X - 1
end
}
post := ({{ Z = p - m }})
theorem subtract_slowly_correct (m p : Nat) :
(subtractSlowlyDec m p).OuterTripleValid := by
sorry
def dpow2Down (n : Nat) : Decorated where
pre := ({{ True }})
body := sdcom {
X := 0;
Y := 1;
Z := 1;
while (X ≠ ~(Aexp.num n)) do
{{ Y = pow2 (X + 1) - 1 ∧ Z = pow2 X }}
Z := 2 * Z;
Y := Y + Z;
X := X + 1
end
}
post := ({{ Y = pow2 (n + 1) - 1 }})
theorem dpow2_down_correct (n : Nat) :
(dpow2Down n).OuterTripleValid := by
sorry
def factorialDec (m : Nat) : Decorated where
pre := ({{ X = m }})
body := sdcom {
Y := 1;
while (X ≠ 0) do
{{ Y * fact X = fact m }}
Y := Y * X;
X := X - 1
end
}
post := ({{ Y = fact m }})
theorem factorial_outer_triple_valid (m : Nat) :
(factorialDec m).OuterTripleValid := by
sorry
def T : Ident := "T"
def dfib (n : Nat) : Decorated where
pre := ({{ True }})
body := sdcom {
X := 1;
Y := 1;
Z := 1;
while (X ≠ ~(Aexp.num (1 + n))) do
{{ Z = fib X ∧ Y = fib (Nat.pred X) ∧ X > 0 }}
T := Z;
Z := Z + Y;
Y := T;
X := 1 + X
end
}
post := ({{ Y = fib n }})
theorem dfib_correct (n : Nat) :
(dfib n).OuterTripleValid := by
sorry
end SparseAnnotations
HIDE: BCP 21: We talked about moving this stuff to the HoareAsLogic
chapter to lighten this chapter, but it fits awkwardly there, so
I'm leaving it here. It's optional anyway. We might consider
assigning one of the exercises as advanced-only though.
Some preconditions are more interesting than others.
For example, the Hoare triple
{{ False }} X := Y + 1 {{ X ≤ 5 }}
is not very interesting: although it is perfectly valid, it
tells us nothing useful. Since the precondition isn't
satisfied by any state, it doesn't describe any situations where
we can use the command X := Y + 1 to achieve the postcondition
X ≤ 5.
By contrast,
{{ Y ≤ 4 ∧ Z = 0 }} X := Y + 1 {{ X ≤ 5 }}
has a useful precondition: it tells us that, if we can somehow
create a situation in which we know that Y ≤ 4 ∧ Z = 0, then
running this command will produce a state satisfying the
postcondition. However, this precondition is not as useful as it
could be, because the Z = 0 clause in the precondition actually
has nothing to do with the postcondition X ≤ 5.
The most useful precondition for this command is this one:
{{ Y ≤ 4 }} X := Y + 1 {{ X ≤ 5 }}
The assertion Y ≤ 4 is called the weakest precondition of
X := Y + 1 with respect to the postcondition X ≤ 5.
Assertion Y ≤ 4 is a weakest precondition of command
X := Y + 1 with respect to postcondition X ≤ 5. Think of weakest
here as meaning "easiest to satisfy": a weakest precondition is
one that as many states as possible can satisfy.
p is a weakest precondition of command c for postcondition q
if
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.
Note that weakest preconditions need not be unique. For
example, Y ≤ 4 was a weakest precondition above, but so are the
logically equivalent assertions Y < 5, Y ≤ 2 * 2, etc.
It is easy to show that any two weakest preconditions p and p'
of a command c with respect to postcondition q are logically
equivalent; that is, p <<->> p'.
What are weakest preconditions of the following commands
for the following postconditions?
1) {{ ? }} skip {{ X = 5 }}
2) {{ ? }} X := Y + Z {{ X = 5 }}
3) {{ ? }} X := Y {{ X = Y }}
4) {{ ? }}
if X = 0 then Y := Z + 1 else Y := W + 2 end
{{ Y = 5 }}
5) {{ ? }}
X := 5
{{ X = 0 }}
6) {{ ? }}
while (true) {X := 0}
{{ X = 0 }}
1) X = 5
2) Y + Z = 5
3) True
4) (X = 0 ∧ Z = 4) ∨ (X ≠ 0 ∧ W = 3)
5) False
6) True
Exercise★★★(is_wp) (Advanced, Optional)
Prove formally, using the definition of ValidHoareTriple, that Y ≤ 4
is indeed a weakest precondition of X := Y + 1 with respect to
postcondition X ≤ 5.