Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Program Logics

Last class, we introduced IMP; this class, we will discuss how we can use a formal logic to formally verify IMP programs correct on all possible inputs.

Array Maximum

Let’s consider the following program, using our extension to arrays:

i := 0;
max := -1;
while i < n do
    if a[i] > max then 
        max := a[i]
    else skip;
    i := i + 1

The above program computes a maximum over an array. But how do we know that this program is correct? What does “correct” mean? For our purposes, we can define correctness by “what should be true after the program finishes.”

Logical Specifications

To define correctness, we need to invent a specification: a formal definition for what it means for the above program to be correct. Even for the above program, there are many kinds of specifications you can write. In this class, we will explore logical specifications: the ability to assign pre- and post-conditions to code which describes the desired behavior of the code. A precondition is what we assume to be true before the code runs, and a postcondition is what we want to be true after the code runs.

Spec for Array Maximum. For our array maximum, what should the pre- and post-conditions be? Well, we assume that n is the length of the array, so let’s ensure that is positive. In addition, let’s assume the array only holds nonnegative elements, so that we can let \(-1\) be the correct initial value.

\[ n > 0 \wedge (\forall i, a[i] \geq 0) \]

Now, let’s think about a good postcondition. We should ensure that the maximum actually is a maximum, if n is bigger than 0:

\[ \forall i, \text{max} \geq a[i] \] Additionally, we want to ensure the maximum is actually in the array. Thus, our postcondition becomes the following: \[ (\exists i. \text{max} = a[i]) \wedge (\forall i, \text{max} \geq a[i]) \]

The above formulae form a valid specification of our program. If we call our program MAX, then we can say that the following Hoare triple (named after Tony Hoare) is valid:

\[ \{ n > 0 \wedge (\forall i, a[i] \geq 0)\}\ \text{MAX}\ \{ (\exists i. \text{max} = a[i]) \wedge (\forall i, \text{max} \geq a[i])\} \]

A Hoare triple is of the form \( \{P\}\ s\ \{Q\} \), where \(P\) is our precondition, \(s\) is our program, and \(Q\) is our postcondition. Intuitively, validity of a Hoare triple states the following: if our initial state satisfies the precondition, then the final state must satisfy the postcondition.

What is a pre/postcondition? What, formally, are these \(P\)’s and \(Q\)’s? We are writing them as logical formulae, so one could imagine specifying them using formal grammar of logical formulae. However, we instead will think of them more abstractly: a precondition or postcondition is simply a set of states:

\[ P, Q \subseteq \mathsf{States}. \] Above, \(\mathsf{States}\) is the set of all possible program states. We can interpret logical formulas as sets by considering the sets that satisfy the formula.

\[ “n \geq 0” := \{ \sigma \mid \sigma(n) \geq 0 \} \] \[ “x = 4 \land y = 3” := \{ \sigma \mid \sigma(x) = 4 \land y = 3 \} \]

Thus, free variable names in formula, except when otherwise specified, stand for variables in the state. Crucially however, everything else in the logical formula is “just math”. Thus, the greater-than symbol \(\geq\) in the formula is just the greater-than relation on integers, while the greater-than symbol in a program is a formal expression.

Example: Assignment

Before diving into formal properties, let’s take a look at some Hoare triples. First, assignment: \[ \{ x = 3 \land y = 4 \}\ x := y\ \{ x = 4 \land y = 4 \} \] The above states that if \(x\) is equal to \(3\) and \(y\) is equal to \(4\), then after running \(x := y\), we get that \(x\) is equal to \(4\) and \(y\) is still equal to \(4\). Note that if we remove the precondition on \(x\), the triple is still valid: \[ \{ y = 4 \}\ x := y\ \{ x = 4 \land y = 4 \} \] However, if we remove the precondition on \(y\), then it is not valid: \[ \text{INVALID:}\ \{ x = 3 \}\ x := y\ \{ x = 4 \land y = 4 \} \] When we remove conjunctions from the precondition, we are weakening it, meaning that more initial states can apply to it.

On the other hand, if we remove things from the postcondition, that is fine, since it’s a proof obligation, and thus if we make it weaker, we are just proving less: \[ \{ x = 3 \land y = 4 \}\ x := y\ \{ \text{True} \} \]

Example: Swap

Let’s now think about a piece of code that swaps two variables:

\[ \text{Swap}(x, y) := (\text{tmp} := x; x := y; y := \text{tmp}) \]

Let’s think about a good specification for that function. First, if \(x\) is \(6\) and \(y\) is \(7\), then we should get that \(y\) is \(6\) and \(x\) is \(7\):

\[ \{x = 6 \land y = 7\}\ \text{Swap}(x, y)\ \{x = 7 \land y = 6\} \]

More generally, for any \(\mathbf{v}_1\) and \(\mathbf{v}_2\), the corresponding triple should hold:

\[ \forall \mathbf{v}_1, \mathbf{v}_2. \{x = \mathbf{v}_1 \land y = \mathbf{v}_2\}\ \text{Swap}(x, y)\ \{x = \mathbf{v}_2 \land y = \mathbf{v}_1 \} \]

Above, we write \(\mathbf{v}_1/\mathbf{v}_2\) in bold to indicate that they are not variables in the program, but instead logical variables standing in for mathematical integers.

Curiously, there is another implementation of Swap that doesn’t need a temporary variable: \[ \text{Swap2}(x, y) := (x := x + y; y := x - y; x := x - y). \] Can you convince yourself that the same pre and postconditions hold for Swap2 that hold for Swap?

Example: Minimum

Let’s do one more before we dig deeper into the semantics of the program logic: \[ \text{Min}(x, y, m) := (\mathsf{if}\ x <= y\ \mathsf{then}\ m := x\ \mathsf{else}\ m := y) \]

This program won’t need a precondition, so its Hoare triple will look like so:

\[ \{\text{True}\}\ \text{Min}(x, y, m)\ \{Q\} \]

Now, what do we want to be true at the end of the program? Suppose we just required that \(m\) was smaller than \(x\) and \(y\):

\[ Q = (m \leq x) \land (m \leq y). \]

This postcondition is sound, but it is not precise. An imprecise spec is one that can be fulfilled by another program that we did not intend. For example, if we let

\[ \text{FakeMin}(x, y, m) := (m := 0 - (x \times x) - (y \times y)), \] then we will also have that \(m\) is at most \(x\) and \(y\):

\[ \{\text{True}\}\ \text{FakeMin}(x, y, m)\ \{m \leq x \land m \leq y\} \ \]

Whether this spec is good enough depends on our use case. If we are trying to find a lower bound in an array of values, then this version of \(Q\) is sufficient, and we could equally use Min or FakeMin. However, if we need to actually return an element in that array, then this spec is not enough. Thus, we will update the spec to also require that \(m\) is equal to one of the two values:

\[ Q = m \leq x \land m \leq y \land (m = x \lor m = y). \]

We then will be able to derive the following:

\[ \{\text{True}\}\ \text{Min}(x, y, m)\ \{m \leq x \land m \leq y \land (m = x \lor m = y)\} \]

while the below is invalid:

\[ \text{INVALID:}\ \{\text{True}\}\ \text{FakeMin}(x, y, m)\ \{m \leq x \land m \leq y \land (m = x \lor m = y)\} \]

Validity of Hoare Triples

Now, we can investigate what it means to have a valid Hoare triple \( \{P\}\ s\ \{Q\}\). Our earlier intuition was that “if our initial state satisfies the precondition, then the final state must satisfy the postcondition.” Since \(P\) and \(Q\) are just sets of states, a state \(\sigma\) satifies the pre/postcondition exactly when it is in the set: \(\sigma \in P\). Thus, we only need to be able to talk about initial and final states. We can appeal to the stepping semantics of IMP, covered last time. Thus, the triple \( \{P\}\ s\ \{Q\}\) is valid if the following holds:

\[ \forall \sigma, \sigma’. \sigma \in P \wedge \langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in Q. \]

We write \(\vDash \{P\}\ s\ \{Q\} \) if the Hoare triple is valid.

Unwinding the definition for Swap. Let’s now see if it’s the case directly if Swap is correct. By uwinding the definitions for Swap:

\[ \{x = 6 \land y = 7\}\ \text{Swap}(x, y)\ \{x = 7 \land y = 6\} \]

We can see that validity is asking the following:

\[ \forall \sigma, \sigma’. \sigma(x) = 6 \land \sigma(y) = 7 \wedge \langle \sigma, \text{Swap}(x, y) \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’(x) = 7 \land \sigma’(y) = 6. \]

By the definition of how Swap, we can see that whenever \(Swap(x, y)\) terminates under \(\sigma\) to obtain \(\sigma’\), we have that

\[ \sigma’(z) = \begin{cases} \sigma(x) & z = \text{tmp} \\ \sigma(y) & z = x \\ \sigma(x) & z = y \\ \sigma(z) & \text{otherwise.} \end{cases} \]

Thus, if \(\sigma(x) = 6\) and \(\sigma(y) = 7\), then \(\sigma’(x) = \sigma(y) = 7\) and \(\sigma’(y) = \sigma(x) = 6\), as required.

How to Validate Hoare Triples?

Now that we know how to specify programs, let’s now show how to prove programs correct against these specifications. How might we show that a Hoare triple \( \{P\}\ s\ \{Q\} \) is valid?

First, we could consider testing: try to run \(s\) on many different, randomly sampled states that satisfy \{P\}, and see if the final states satisfy \{Q\}. This technique is very powerful since it is quite automated, but it has the following limitations:

  • Soundness. While we check that \(s\) is correct on many possible initial states, we don’t get a proof that it is correct on all infinitely many possible states.
  • Completeness. This technique only works if we can efficiently check \{P\} and \{Q\}, but they might have universal quantifiers in them, which we can’t automatically check in general.
  • Performance. This technique requires running the command \(s\) many times, which might have significant performance issues (for example, if \(s\) runs in time exponential in a given input, \(n\).)

In this lecture, we will investigate a different method: program logic (or Hoare logic), which instead provides a collection of inference rules that we can prove sound.

Assumptions about Expressions. For the purpose of this lecture, we will assume that expressions are all total and deterministic, meaning that for every state \(\sigma\), there is a unique value \(n\) such that \(\langle \sigma, e \rangle \Downarrow n.\). Hence, we will not worry about division in this lecture.

Skip, Consequence, and Assignment

First, let’s think about the simple programs.

Program Logic Rule: Skip

Since \(\mathsf{skip}\) doesn’t do anything, the output state is exactly equal to the input state. Thus, for any \(P\), the following inference rule is sound:

\[ \dfrac{}{\{P\}\ \mathsf{skip}\ \{P\}} \text{(R-Skip)} \]

Here, soundness means that the Hoare triple is valid. Let’s prove this rule sound. Unrolling the definition for validity means we want to prove the following:

\[ \forall \sigma, \sigma’. \sigma \in P \land \langle \sigma, \mathsf{skip} \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in P. \]

Since skip does not step, if we have \( \langle \sigma, \mathsf{skip} \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle\) then we have that zero steps have been taken, and thus \(\sigma’ = \sigma\). Hence the above simplifies to this:

\[ \forall \sigma, \sigma’. \sigma \in P \land \sigma’ = \sigma \implies \sigma’ \in P \]

which is of course true.

Program Logic Rule: Consequence

From our examples above, we can see that it is sound to strengthen a precondition — assuming more things — as well as weaken a postcondition — trying to prove fewer things. We can formalize this via the rule of consequence:

\[ \dfrac{P’ \implies P \quad \{P\}\ s\ \{Q\} \quad Q \implies Q’}{\{P’\}\ s\ \{Q’\}} \text{(R-Conseq)} \]

Since \(P\) and \(P’\) are sets of states, the use of implication in the hypothesis (\(P’ \implies P\)) means the same thing as subset: \(P’ \subseteq P\). That is, every state in \(P’\) must also be in \(P\).

For example, if we have

\[ \{ x = 1 \land y = 2 \}\ s\ \{x = 3 \land y = 4\}\] then we can do the following:

  • Weaken the postcondition to just \(x = 3\) (which is a larger set of states). Since we know the final states of \(s\) always satisfy \(x = 3\) and \(y = 4\), it is sound to only require \(x = 3\).
  • Strengthen the precondition to \(x = 1 \land y = 2 \land z = 5\) (which is a smaller set of states). Since we know the initial states of \(s\) want \(x = 1\) and \(y = 2\), also assuming \(z = 5\) does not hurt.

Proof of consequence. We can prove this rule formally. To prove it, we assume the hypotheses and must prove the consequence. Thus, we know:

  • (1) \(P’ \implies P\)
  • (2) \(Q \implies Q’\)
  • (3) \(\forall \sigma, \sigma’. \sigma \in P \land \langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in Q\)

And we need to show:

  • \(\forall \sigma, \sigma’. \sigma \in P’ \land \langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \implies \sigma’ \in Q’\)

Thus, since what we need to show is an implication, we additionally assume a \(\sigma\) and \(\sigma’\), and that:

  • (4) \(\sigma \in P’\)
  • (5) \(\langle \sigma, s \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle \)

And need to show finally that:

  • \(\sigma’ \in Q’\)

To show that \(\sigma’ \in Q’\), it is enough to show that \(\sigma’ \in Q\), by assumption (2). But then we can use assumption (3), which can prove that, as long as: (a) the program runs from \(\sigma\) to \(\sigma’\); and (b) that \(\sigma \in P\). But then, (a) is proven by assumption (5), while (b) is proven by assumption (1) and (4).

Program Logic Rule: Assignment

Now, let’s think about \(x := e\), which steps in one step to skip with an updated state. Below is the rule for assignment:

\[ \dfrac{}{\{P[e/x]\}\ x := e\ \{P\}} \text{(R-Assign)} \]

Above, we write \(P[e/x]\) for the syntactic substitution of \(e\) for \(x\) in \(P\). Here, we are identifying \(e\) with its mathematical meaning, in addition to its meaning as an IMP expression.

This rule merits a little bit of discussion, as it looks a little backwards. First, let’s see some examples:

\[ \{x = 1\}\ y := x + x\ \{ x = 1 \land y = 2 \} \]

This triple follows from (R-Assign) and (R-Conseq). First, we need the precondition to line up with the postcondition, but with \(e\) substituted for \(y\). Thus, since the postcondition is \[P := x = 1 \land y = 2\], we know that our desired precondition is \[P[e/y] := x = 1 \land (x + x = 2). \] Our desired precondition is a logical consequence of our actual precondition (\(x = 1\)), so we can first use (R-Conseq) to instead prove the following triple:

\[ \{x = 1 \land (x + x = 2)\}\ y := x + x\ \{ x = 1 \land y = 2 \} \]

And now we can use (R-Assign) to finish the proof.

We can write this proof as a derivation tree:

\[ \dfrac{ \dfrac{}{x = 1 \implies x = 1 \land (x + x = 2)} \qquad \dfrac{}{\{x = 1 \land (x + x = 2)\}\ y := x + x\ \{ x = 1 \land y = 2 \}} \text{(R-Assign)} \qquad \dfrac{}{x = 1 \land y = 2 \implies x = 1 \land y = 2} }{ \{x = 1\}\ y := x + x\ \{ x = 1 \land y = 2 \} } \text{(R-Conseq)} \]

While the assignment rule (R-Assign) seems a bit obtuse, we can conceptualize it better as coming up with the best precondition to prove the postcondition. When is it the case that, after we do \(x := e\), we get \(P\)? Well, it’s exactly when \(P\) holds before the assignment, by thinking of the assignment as happening in the precondition instead. In practice, we always use (R-Conseq) to implicitly change our actual precondition to the right shape so that we can call (R-Assign).

Here are some more valid triples:

\[ \{ x = 42\} y := x + 1 \{ y = 43 \} \]

The above holds because we can transform the above precondition, by (R-Conseq), to \( x + 1 = 43 \) (which is logically equivalent). Then, (R-Assign) holds.

\[ \{ x \leq N \} y := x + 2 \{ y \leq N + 2 \} \]

Similarly, we transform the precondition to \( x + 2 \leq N + 2\), and then (R-Assign) applies.

Program Logic Rule: If/then/else

To prove an if/then/else is correct, we need to analyze both sides of the branches. Additionally, we get to assume the branch is equal (or not equal) to zero:

\[ \dfrac{\{P \land e \neq 0\}\ s_1\ \{Q\} \quad \{P \land e = 0\}\ s_2\ \{Q\}}{\{P\}\ \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2\ \{Q\}} \text{(R-If)} \]

This matches the stepping rules from last time.

To show this rule is sound, you can prove the following lemma:

Lemma. If \(\langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle\), then either:

  • \(\sigma(e) \neq 0\) and \(\langle \sigma, s_1 \rangle \to^* \langle \sigma’, \mathsf{skip}\rangle\); or
  • \(\sigma(e) = 0\) and \(\langle \sigma, s_2 \rangle \to^* \langle \sigma’, \mathsf{skip}\rangle\).

This lemma is true because an if/then/else statement can only step in one possible way given a particular state.

Program Logic Rule: Sequencing

Now, how would we prove that Swap is correct? Since Swap only uses assignment and sequencing (\(;\)), we need a rule for sequencing. Here it is:

\[ \dfrac{\{P\}\ s_1\ \{R\} \quad \{R\}\ s_2\ \{Q\}}{\{P\}\ s_1; s_2\ \{Q\}} \text{(R-Seq)} \]

Here, \(R\) is an intermediate condition: it describes the states after \(s_1\) finishes but before \(s_2\) begins. Note that \(R\) does not appear in the conclusion, so when we use (R-Seq), we get to pick \(R\) ourselves.

To show this rule is sound, you can prove the following lemma:

Lemma. If \(\langle \sigma, s_1; s_2 \rangle \to^* \langle \sigma’, \mathsf{skip} \rangle\), then there exists some \(\sigma’’\) such that:

  • \(\langle \sigma, s_1 \rangle \to^* \langle \sigma’’, \mathsf{skip}\rangle\); and
  • \(\langle \sigma’‘, s_2 \rangle \to^* \langle \sigma’, \mathsf{skip}\rangle\).

This lemma states that for \(s_1; s_2\) to step to \(\mathsf{skip}\), we need to first run \(s_1\) all the way down to \(\mathsf{skip}\) before we run \(s_2\). Soundness follows directly from this lemma.

Program Logic Rule: While

Now, let’s think about while loops. These are the most subtle, and where the challenge of program logic proofs comes from. First, let’s see the rule:

\[ \dfrac{P \implies I \quad \{I \land e \neq 0\}\ s\ \{I\} \quad I \land e = 0 \implies Q}{\{P\}\ \mathsf{while}\ e\ \mathsf{do}\ s\ \{Q\}} \text{(R-While)} \]

To prove that \(\{P\}\ \mathsf{while}\ e\ \mathsf{do}\ s \{Q\}\) is valid, we need to come up with an appropriate loop invariant, \(I\). This loop invariant need to have the following properties:

  • It is implied by the precondition, \(P\), which means that it holds before the loop runs;
  • Whenever we have \(I\) and \(e \neq 0\), then \(s\) enforces that the loop invariant still holds after termination; and
  • Whenever we have \(I\) and \(e = 0\), we have that the desired postcondition \(Q\) holds. Thus, when the loop is done, the postcondition holds.

Let’s see an example, where we count up to \(n\) by one each time:

i := 0;
while i < n do 
    i := i + 1

We want to show that, whenever \(n \geq 0\), we have that \(i = n\) at the end of the program. That is, the following Hoare triple should be valid:

\[ \{n \geq 0\}\ i := 0;\ \mathsf{while}\ i < n\ \mathsf{do}\ i := i + 1\ \{i = n\} \]

Now, let’s prove it. First, let’s use (R-Seq), (R-Assign), and (R-Conseq) to get rid of the assignment, and enforce that \(i = 0\) before the loop runs. Using (R-Seq) with intermediate condition \(n \geq 0 \land i = 0\), we need to prove two triples. The first is

\[ \{n \geq 0\}\ i := 0\ \{n \geq 0 \land i = 0\}, \]

which holds since (R-Assign) gives us the precondition \(n \geq 0 \land 0 = 0\), and \(n \geq 0\) implies this by (R-Conseq). The second is the triple for just the while loop:

\[ \{n \geq 0 \land i = 0\}\ \mathsf{while}\ i < n\ \mathsf{do}\ i := i + 1\ \{i = n\} \]

Now, we need to come up with a good loop invariant. It needs to hold on initialization, be maintained by the loop, and imply that \(i = n\) at the end. It turns out that a good loop invariant is that \(i \leq n\). Let’s see why by using (R-While):

\[ \dfrac{ n \geq 0 \land i = 0 \implies i \leq n \quad \{i \leq n \land i < n\}\ i := i + 1\ \{i \leq n\} \quad i \leq n \land \neg(i < n) \implies i = n }{ \{n \geq 0 \land i = 0\}\ \mathsf{while}\ i < n\ \mathsf{do}\ i := i + 1\ \{i = n\} } \text{(R-While)} \]

Above, recall that the guard \(i < n\) is an IMP expression that evaluates to \(1\) or \(0\); thus, \(e \neq 0\) becomes \(i < n\), and \(e = 0\) becomes \(\neg(i < n)\), i.e., \(i \geq n\). Now, we just need to show that our use of (R-While) is valid; that is, the three hypotheses hold.

  • Initialization. If \(i = 0\) and \(n \geq 0\), then \(i \leq n\). Note that this is exactly where we need the precondition \(n \geq 0\): if \(n\) were negative, the loop would never run, and we would end with \(i = 0 \neq n\).
  • Preservation. By (R-Assign), it is enough to show the precondition \((i \leq n)[i + 1/i] = (i + 1 \leq n)\). Since we are working with integers, \(i < n\) implies \(i + 1 \leq n\), so (R-Conseq) finishes the proof.
  • Exit. If \(i \leq n\) and \(i \geq n\), then \(i = n\).

It is worth seeing why other choices of invariant fail. The invariant \(\text{True}\) holds initially and is trivially preserved, but it is too weak: at exit, \(i \geq n\) alone does not give \(i = n\). On the other hand, the invariant \(i = n\) is strong enough at exit, but it does not hold initially (unless \(n = 0\)), nor is it preserved by the loop body. A good loop invariant must be weak enough to hold initially and be preserved, but strong enough to imply the postcondition.