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

HW5: Program Logic via Dafny

  • Due Friday, Dec 11 11:59pm.
  • Upload your submission to Gradescope, starting from this starter file.
  • Only modify the starter file in the places marked with /* MODIFY LINE(s) BELOW */ and /* MODIFY LINE(s) ABOVE */.
  • Be sure to check your solution is valid Dafny code that verifies; otherwise, you will not receive points on that problem.
  • You should complete the assignment as intended, and not use assume statements to bypass verification.

In this homework, you will install and run Dafny. Using Dafny, you will be able to concretely play with the concepts we have learned in class about program logic. The installation instructions show how to run Dafny; the simplest way is to use the VSCode extension, which will automatically download and install Dafny.

Subset of Dafny for this homework

Dafny is a rather large language, so we will only use a particular subset of it for our class, which we describe here. For extra guidance, you will find this tutorial useful. However, we will not be covering arrays in Dafny here, so you can safely ignore that part of the tutorial.

First, Dafny has methods, which contain imperative code:

method Min(x : int, y : int) returns (z : int)
    requires x >= 0
    ensures z <= x && z <= y
    ensures z == x || z == y
    ensures y >= 0 ==> z >= 0
{
    if x <= y {
        z := x;
    }
    else {
        z := y;
    }
    assert z <= x;
    assert z <= y;
}

Each method can have a number of requires and ensures clauses, which are for pre- and post-conditions. Logical predicates in Dafny are simply Booleans; thus, && is AND, || is OR, and ==> is implication.

The body of a method in Dafny is imperative code. In the above example, we have an if-statement, each branch of which has an assignment. Every assignment needs a semicolon at the end. Return values are encoded by giving the method a returns clause, such as returns (z : int); we can then write to z in our code. The subset of Dafny we will use, aside from assert statements and loop invariants (both discussed below), is essentially the same as IMP from class, except that Dafny enforces lexical scope on program variables. Thus, verifying the above method is equivalent to proving the corresponding Hoare triple: \[ \{x \geq 0\}\ \mathsf{Min}(x, y, z)\ \{(z \leq x \land z \leq y \land (z = x \lor z = y) \land (y \geq 0 \implies z \geq 0))\} \] (using three variables for \(\mathsf{Min}\): two for the input arguments and one for the output.)

The above code also has assert statements, like assert z <= x. If the code verifies, Dafny proves that the assert can never fail. Assert statements are useful for debugging and documentation, since they identify intermediate conditions which must be true. Hence, they are analogous to intermediate assertions from a proof outline for Hoare logic.

When you put the above code into Dafny, you will see that it verifies, which is indicated by a green checkmark in the editor to the left of the method. If there is a red error, then there is a goal that Dafny could not prove. For example, try deleting the requires x >= 0 clause and see how Dafny reacts.

You can write while loops in Dafny. Here is a simple example:

method IncrUpTo(x : int) returns (r : int)
    requires x >= 0
    ensures r == x
{
    r := 0;
    assert r == 0;
    while r < x 
        invariant 0 <= r <= x
    {
        r := r + 1;
    }
    assert r == x;
}

We compute the value of x by repeatedly incrementing r until it reaches x, starting from 0. The contract of the method says that x must be at least 0 and that the returned value r will be equal to x. For while loops to guarantee a given postcondition (such as r == x), we need to supply a number of loop invariants. Each loop invariant follows our logic for (R-While) from class: the loop invariant must hold on entry to the loop, be preserved by the loop body (assuming the loop guard is true), and needs to imply the desired postcondition, whenever the loop guard is false. Following (R-While), Dafny will emit the following proof goals, which are all automatically verified:

  • Loop entry: r == 0 && x >= 0 (precondition) implies 0 <= r <= x (loop invariant);
  • Loop iteration: assuming r < x (loop guard) and 0 <= r <= x (loop invariant), after running the loop body, we still have that 0 <= r <= x;
  • Loop exit: if the guard r < x does not hold, but the invariant 0 <= r <= x does, then the postcondition r == x must hold.

(Dafny also ensures that each loop terminates, but the loops considered in this homework are all guaranteed to terminate.)

Problem 1: Designing Postconditions

In this problem, we will give you a pair of Dafny methods A and B, where B calls A and has a specification we wish to prove. However, A’s specification is not strong enough; your job is to modify A’s spec to make B verify. You will know that you succeeded if you never see a red highlight on the method. You can also check to see if your solution is correct by calling dafny verify starter.dfy, which will report all verification errors.

For each problem, we will first present it using the syntax of Hoare triples we have seen in class; then, we will translate it to a problem in Dafny.

1.1. CloseEnough

Find a \(P\) making use of variables x, y, and res such that:

  1. \(\{\text{True}\}\ \mathsf{if}\ x \geq y\ \mathsf{then}\ \mathit{res} := x - y\ \mathsf{else}\ \mathit{res} := y - x\ \{P\}\)
  2. \(\{P\}\ b := (\mathit{res} \leq \mathsf{eps})\ \{b \iff (y - \mathsf{eps} \leq x \leq y + \mathsf{eps})\}\)

Translated to Dafny, we are asking you to fill in the postcondition of Dist below:

// Compute the distance between two integers `x` and `y`.
method Dist(x : int, y : int) returns (res : int)
    ensures 
        /* MODIFY LINE BELOW */
        true 
        /* MODIFY LINE ABOVE */
{
    if x >= y { res := x - y; } else { res := y - x; }
}

// Decide if the distance between x and y is within eps.
method CloseEnough(x : int, y : int, eps : int) returns (b : bool) 
    ensures b <==> (y - eps <= x <= y + eps)
{
    var res := Dist(x, y);
    b := res <= eps;
}

You should ONLY modify the postcondition of Dist so that both methods verify.

1.2: Squaring

Find a \(P\) making use of variables lo, hi, and res such that:

  1. \(\{\mathit{lo} \leq \mathit{hi}\}\ \mathsf{if}\ x < \mathit{lo}\ \mathsf{then}\ \mathit{res} := \mathit{lo}\ \mathsf{else}\ \mathsf{if}\ x > \mathit{hi}\ \mathsf{then}\ \mathit{res} := \mathit{hi}\ \mathsf{else}\ \mathit{res} := x\ \{P\}\)
  2. \(\{P \land \mathit{lo} = 0 \land \mathit{hi} = 12\}\ z := \mathit{res} * \mathit{res}\ \{0 \leq z \leq 144\}\)
// Clamp a value x between lo and hi.
method Clamp(x : int, lo : int, hi : int) returns (res : int)
    requires lo <= hi
    ensures 
        /* MODIFY LINE BELOW */
        true 
        /* MODIFY LINE ABOVE */
{
    if x < lo { res := lo; } else if x > hi { res := hi; } else { res := x; }
}


// Square a value x, but clamp it to ensure the result is not too big.
method SquareNotTooBig(x : int) returns (z : int)
    ensures 0 <= z <= 144
{
    var res := Clamp(x, 0, 12);
    z := res * res;
}

1.3. Comparison

Find a \(P\) making use of variables x, y, and res such that:

  1. \(\{\text{True}\}\ \mathsf{if}\ x > y\ \mathsf{then}\ \mathit{res} := 1\ \mathsf{else}\ \mathsf{if}\ x < y\ \mathsf{then}\ \mathit{res} := -1\ \mathsf{else}\ \mathit{res} := 0\ \{P\}\)
  2. \(\{P\}\ d := \mathit{res} * (x - y)\ \{d \geq 0 \land (d = x - y \lor d = y - x)\}\)
// Compare two integers x and y, returning 1 if x > y, -1 if x < y, and 0 if x == y.
method Compare(x : int, y : int) returns (res : int)
    ensures 
        /* MODIFY LINE BELOW */
        true 
        /* MODIFY LINE ABOVE */
{
    if x > y { res := 1; } else if x < y { res := -1; } else { res := 0; }
}

// Using the comparison method above, compute the distance between x and y.
method Dist2(x : int, y : int) returns (d : int)
    ensures d >= 0
    ensures d == x - y || d == y - x
{
    var res := Compare(x, y);
    d := res * (x - y);
}

Problem 2: Implementing Verified Code

In this problem, rather than inventing a postcondition that’s suitable for a piece of code, you will do the opposite: write a piece of code that fits the given pre/postcondition.

2.1: Min3

Find a statement \(s\) such that:

\[\{\text{True}\}\ s\ \{r \leq x \land r \leq y \land r \leq z \land (r = x \lor r = y \lor r = z)\}\]

For \(s\) to work as valid Dafny code, it can only modify the variable r, and any local variables declared by var.

// Compute the minimum of three integers x, y, and z.
method Min3(x : int, y : int, z : int) returns (r : int)
    ensures r <= x && r <= y && r <= z
    ensures r == x || r == y || r == z

{
    /* MODIFY LINES BELOW */
    // ...
    /* MODIFY LINES ABOVE */
}

2.2: Median3

For this problem, we introduce two auxiliary functions. Unlike methods, which represent imperative code, functions are more similar to functional programs, and are used to represent pure functions which can appear in pre and postconditions.

Find a statement \(s\) such that:

\[\{\text{True}\}\ s\ \{(r = x \lor r = y \lor r = z) \land \mathsf{NumSmaller}(x, y, z, r) \leq 1 \land \mathsf{NumGreater}(x, y, z, r) \leq 1\}\]

// Computes the number of elements among x, y, z that are smaller than r.
function NumSmaller(x : int, y : int, z : int, r : int) : int {
    (if x < r then 1 else 0) + 
    (if y < r then 1 else 0) + 
    (if z < r then 1 else 0) 
}

// Computes the number of elements among x, y, z that are greater than r.
function NumGreater(x : int, y : int, z : int, r : int) : int {
    (if x > r then 1 else 0) + 
    (if y > r then 1 else 0) + 
    (if z > r then 1 else 0) 
}

// Compute the median of three integers x, y, and z.
method Median3(x : int, y : int, z : int) returns (r : int)
    ensures (r == x) || (r == y) || (r == z)
    ensures NumSmaller(x, y, z, r) <= 1
    ensures NumGreater(x, y, z, r) <= 1
{
    /* MODIFY LINES BELOW */
    // ...
    /* MODIFY LINES ABOVE */

}

Problem 3: Creating Loop Invariants

Finally, in this problem, we will look at how to verify loops by inventing loop invariants.

3.1: Triple

In this program, you will verify a method which computes \(3x\) by repeatedly adding \(3\) to a running total. Below is the Dafny code:

// Compute 3 * x by repeatedly adding 3 to a running total.
method Triple(x : int) returns (r : int)
    requires 0 <= x
    ensures r == 3 * x
{
    var i := 0;
    r := 0;
    assert 0 <= x && i == 0 && r == 0;
    while i < x
        invariant 
            /* MODIFY LINE BELOW */
            true
            /* MODIFY LINE ABOVE */
    {
        i := i + 1;
        r := r + 3;
    }
    assert r == 3 * x;
}

Hence, you need to find a loop invariant \(P\) which makes the above method verify. You can only modify the loop invariant. Your loop invariant must be chosen to satisfy the three conditions of (R-While):

  • Loop Entry: \(0 \leq x \land i = 0 \land r = 0 \implies P\)
  • Loop Body: \(\{P \land i < x\}\ i := i + 1;\ r := r + 3\ \{P\}\)
  • Loop Exit: \(P \land \neg (i < x) \implies r = 3 * x\)

(Hint: you need to ensure that 0 <= i <= x, and tie the value of r to x and i. You can use multiple loop invariants across multiple lines if you wish.)

3.2: Div2

We now will verify the method Div2, which repeatedly adds 2 to a running total until it reaches x, and records how many times the loop ran.

method Div2(x:int) returns (r : int)
    requires 0 <= x
    ensures r == x / 2
{
    var i := 0;
    var j := 0;
    assert 0 <= x && i == 0 && j == 0;
    while i + 2 <= x
        invariant 
            /* MODIFY LINE BELOW */
            true
            /* MODIFY LINE ABOVE */
    {
        i := i + 2;
        j := j + 1;
    }
    r := j;
    assert r == x / 2;
}

You must find a loop invariant \(P\) so that:

  • Loop Entry: \(0 \leq x \land i = 0 \land j = 0 \implies P\)
  • Loop Body: \(\{P \land i + 2 \leq x\}\ i := i + 2;\ j := j + 1\ \{P\}\)
  • Loop Exit: \(P \land \neg (i + 2 \leq x) \implies j = x / 2\) (where \(/\) denotes integer division)

(Hint: Just like the previous problem, you need to come up with a bound for i, and tie the value of i to j).

3.3: Integer Square Root

Given a non-negative integer x, this method computes the greatest integer r such that r * r <= x. We will do so via a linear search, where we check each integer r ascending from 0 until we find the largest r such that \(r * r <= x\) but \(x < (r + 1) * (r + 1)\).

However, we can employ a clever arithmetic trick to avoid multiplication. Notice that \[ (r + 1)^2 = r^2 + 2r + 1,\] and hence the gap between consecutive squares \(r^2\) and \((r + 1)^2\) is \(2r + 1\). Thus, alongside the candidate r, the code keeps track of the next square, nextSq, and the gap from nextSq to the square after it, gap. Each time we increment r, we compute the new next square by adding gap to nextSq, and the new gap by adding \(2\) to gap.

method ISqrt(x : int) returns (r : int)
    requires x >= 0
    ensures r * r <= x < (r + 1) * (r + 1)
{
    r := 0;
    var nextSq := 1;
    var gap := 3;
    assert x >= 0 && r == 0 && nextSq == 1 && gap == 3;
    while nextSq <= x
        /* MODIFY LINE BELOW */
        invariant true
        /* MODIFY LINE ABOVE */
    {
        nextSq := nextSq + gap;
        gap := gap + 2;
        r := r + 1;
    }
    assert r * r <= x < (r + 1) * (r + 1);
}

Hence, you will need to find a loop invariant \(P\) so that:

  • Loop Entry: \(x \geq 0 \land r = 0 \land \mathit{nextSq} = 1 \land \mathit{gap} = 3 \implies P\)
  • Loop Body: \(\{P \land \mathit{nextSq} \leq x\}\ \mathit{nextSq} := \mathit{nextSq} + \mathit{gap};\ \mathit{gap} := \mathit{gap} + 2;\ r := r + 1\ \{P\}\)
  • Loop Exit: \(P \land \neg (\mathit{nextSq} \leq x) \implies r * r \leq x < (r + 1) * (r + 1)\)

(This problem, similarly, requires you to come up with a bound for r, and tie the values of nextSq and gap to r.)