6.S057: 6.S057: Verified Software Engineering

Writing Arrays

This is the introductory reading for classes 20 & 21.

The deadline for exercises in this reading was Sunday, November 22 at 9pm.

Recommended reading in Program Proofs: Chapter 14. Modifying Arrays and Chapter 15. In-situ Sorting.

So far our imperative programs have reassigned plenty of variables (and looped plenty of loops), but we haven’t taken that dangerous step of mutating our mutable arrays. Starting in class 20, things are going to change*!

When we introduced arrays in the previous reading we noted that in an example like this…

dfy
var a := new int[] [10, 9, 8];
var b := a;
var c := a[..];
var d := new array[] [a];

… variable a stores a reference to the array and b is an alias to the same array.

The immutable value types we worked with previously — int, bool, string, seq, multiset, etc. — could be thought of as living entirely on the program stack, passed from function to function by making copies. Arrays (and soon, classes) are reference types where the data objects live on the heap and our variables store references to them.

In 6.101 you drew environment diagrams for a model of Python where all data are on the heap and all variables are references. You can use the same mental model to analyze Dafny programs that use references, but you must keep in mind that immutable value types are not stored or passed with references.

Let’s begin by introducing the additional tools we will use to reason about mutation.

Frames

At the end of the previous reading we presented a version of the following “search” method that does not, in fact, do any searching. It mostly just finds:

dfy
datatype Option<X> = None | Some(value: X)
method MagicSearch(a: array<int>, key: int) returns (r: Option<int>)
  ensures if r == None then key !in a[..]
          else 0 <= r.value < a.Length && a[r.value] == key
{
  if a.Length > 0 {
    a[a.Length/2] := key;
    return Some(a.Length/2);
  }
  return None;
}

The version in that reading was accepted by Dafny whereas this version is not. The crucial difference is that this method does not advertise as part of its specification that it may modify the array, and Dafny therefore will not permit such modification.

In our discussion of loops we described how Dafny infers a loop frame, the set of variables potentially reassigned in a loop*. Now that we’re working with mutable data, we need to understand the frames for functions and methods. And while Dafny could in principle infer these frames as it did with loops, in practice such inference makes the verification problem much harder to modularize, so Dafny requires us to specify them.

Function read frames

The read frame of a function is the set of heap-allocated objects whose fields the function body may access. A field is a component of the object’s state. For now, arrays are our only example of mutable objects — we’ll have more next week. For an array arr:

  • arr[n] uses the special [ ] syntax for accessing its notional nth-element field, and
  • arr.Length accesses the Length field using conventional syntax.

The read frame is specified with reads clauses:

  • If a function accesses the fields of an object obj, its specification must include reads obj.

A function that operates on immutable values, which is 100% of the functions we have written so far, does not need a reads clause.

Method write frames

A method, in order to constrain its possible side effects, has a write frame that specifies the set of objects whose fields the method may modify. The write frame is specified with modifies clauses, and it also automatically includes all the new objects allocated in the body of the method. Therefore:

  • If a method updates the fields of an object o passed in as a parameter, its specification must include modifies o.
  • A method is allowed to make new objects and change their state without mentioning them in a modifies clause.

Old and new

If a method is going to perform mutations, we will need postconditions that relate the method’s post-state — the state of values after the method runs — to the pre-state.

Method postconditions are two-state predicates where by default expressions in the postcondition refer to values in the post-state. That’s why our fake “search” method where the spec says:

dfy
modifies a
ensures ... a[idx] == key

… can simply mutate a to set a[idx] := key: the expression a[idx] refers to the value in the post-state.

To refer to mutable data in the pre-state, use an old expression that causes its argument to be evaluated using the pre-state of the heap. If we write:

dfy
modifies a
ensures ... old(a[idx]) == key

… then our fake “search” no longer verifies: a[idx] has been reassigned to key in the post-state, but it may not have been key in the pre-state.

When writing two-state postconditions, it is important to note that old only affects heap dereferences: in our environment model, interpreting an old expression means finding the value of a field of an object on the heap. Using old does not affect how the method in- and out-parameters are evaluated. So:

  • old(a[idx] == key) is the same as old(a[idx]) == key, because the value of key is unaffected by old.

  • Perhaps surprisingly, old(a)[idx] is not the same as old(a[idx]) — because old(a) just evaluates to a! Then, outside the old(..), we get the value of its notional idxth-element field (using the special [idx] syntax) in the post-state.

    old(a)[idx] is the same as a[idx]. Only accessing fields is affected by old(..).

In addition to relating the pre- and post-states of mutated objects using two-state postconditions, we will want to write methods that create and return new mutable objects. Suppose MyMethod calls MakeCanvas to obtain a new mutable drawing canvas. Is MyMethod then allowed to mutate the returned object? The newly created canvas can’t have been listed in MyMethod’s modifies clause — it didn’t exist yet.

Instead, we need MakeCanvas to certify that the object was newly allocated during its execution and therefore newly allocated inside of MyMethod and available for MyMethod to mutate. This fact is declared with a fresh predicate:

dfy
method MakeCanvas(...) returns (c: Canvas)
  ensures fresh(c) && ...

method MyMethod() {
  var canvas := MakeCanvas(...);
  // canvas was allocated on our behalf and Dafny allows us to mutate it
}

Complete the specifications of MakeExampleArray and Increment so that Dafny proves the correctness of Example as provided:

dfy
method Example(x: int) {
  var a := MakeExampleArray(x);
  Increment(a, 1);
  assert a[1] == 2;
  Increment(a, 3);
  assert a[..] == [ -x, 2, x, x*3 + 1 ];
}

method MakeExampleArray(x: int) returns (ex: array<int>)
  ensures ex[..] == [ -x, 1, x, x*3 ]
{
  ex := new int[] [ -x, 1, x, x*3 ];
}

method Increment(a: array<int>, i: nat)
  requires i < a.Length
{
  a[i] := a[i] + 1;
}
Loading...

Example: Dutch national flag

The Dutch national flag problem 🇳🇱 considers the question of how to sort in-situ an array whose elements are all one of three values: small, medium, and large; or traditionally: red, white, and blue. In this restricted setting, it is straightforward to sort in linear time.

Before we consider how to perform the sort, let’s write the method specification. Add ensures clauses, using old as appropriate, to specify that SortInPlace will modify input a to preserve its elements but put them in LtEq order.

Leave SortInPlace unimplemented. We’ve added the {:axiom} attribute so Dafny ignores the missing body. (You’ll want to take care that your postcondition is satisfiable, since Dafny isn’t going to prove that for us with {:axiom}.)

It will take a few moments, but Dafny should be able to use your spec to prove the correctness of two examples in examples.dfy:

dfy
datatype Color = Red | White | Blue

ghost predicate LtEq(c1: Color, c2: Color) {
  c1 == Red || c1 == c2 || c2 == Blue
}

method {:axiom} SortInPlace(a: array<Color>)
  modifies a
  ensures ???
dfy
method Example1() {
  var a := new Color[2] [ Blue, White ];
  assert a[..] == [ Blue, White ];
  SortInPlace(a);
  assert a[..] == [ White, Blue ];
}

method Example2() {
  var a := new Color[5] [ Blue, Red, Red, Blue, White ];
  assert a[..] == [ Blue, Red, Red, Blue, White ];
  SortInPlace(a);
  assert a[1] == Red || a[1] == a[2] || a[2] == Blue;
  assert a[2] == Red || a[2] == a[3] || a[3] == Blue;
  assert a[0] == Red;
  assert a[1] == Red by { assert a[..] == [Red] + [a[1]] + a[2..]; }
  assert a[4] == Blue;
  assert a[3] == Blue by { assert a[..] == a[..3] + [a[3]] + [Blue]; }
  assert a[2] == White;
  assert a[..] == [ Red, Red, White, Blue, Blue ];
}
Loading...

Here’s the explanation of our sorting algorithm from Program Proofs chapter 15:

The idea behind the algorithm is to structure the given array into four adjacent segments. The first segment will contain only red elements, the next segment only white elements, and the last segment only blue elements. The remaining segment (which I’ll place between the white and blue segments, though another choice would be to place it between the red and white segments) will contain the elements we haven’t yet sorted into its proper segment.

Initially all the elements are in the 3rd segment of unsorted data. The algorithm proceeds by stepping through the elements and performing swaps until every element has been moved out of that segment and into one of the other three.

To keep track of the segment boundaries we’ll use three array indices:

  • r is the upper bound of red elements,
  • w is the upper bound of white elements, and
  • b is the lower bound of blue elements:

What are the initial values of these variables?

r :=
w :=
b :=

And when should our algorithm terminate?

Now you’re ready to implement!

Just kidding, we already wrote the code. Now you’re ready to verify!

Complete the loop invariant so that Dafny accepts this implementation. You will want to encode almost exactly the information conveyed by the figure above! Hint: don’t mention LtEq.

dfy
datatype Color = Red | White | Blue

ghost predicate LtEq(c1: Color, c2: Color) {
  c1 == Red || c1 == c2 || c2 == Blue
}
dfy
method SortInPlace(a: array<Color>)
  modifies a
  ensures forall i, j :: 0 <= i < j < a.Length ==> LtEq(a[i], a[j])
  ensures multiset(a[..]) == multiset(old(a[..]))
{
  var r, w, b := 0, 0, a.Length;
  while w < b
    invariant ???
  {
    match a[w]
    case Red => // swap into red region, white shifts over
      a[w], a[r] := a[r], a[w];
      r, w := r + 1, w + 1;
    case White => // grow white region
      w := w + 1;
    case Blue => // swap into blue region
      b := b - 1;
      a[w], a[b] := a[b], a[w];
  }
}
Loading...

Summary

Dafny supports mutable heap-allocated objects much as do other, more common languages like Python. Familiar bookkeeping challenges around aliasing carry over pretty directly. However, the need to write method specifications and loop invariants forces us to develop a few other features. We use reads and modifies clauses to record rules on method-parameter access, old to let postconditions describe heap contents before and after method calls, and the fresh predicate to promise that an object was allocated during method execution and can’t possible alias any object that existed before the call. With just these new tools, our old patterns of specification and proof can already handle quite a few interesting array-modifying programs.

Copyright 6.S057 course staff.