6.S057: 6.S057: Verified Software Engineering

Classes I

This is the introductory reading for classes 22 & 23.

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

Recommended reading in Program Proofs: Chapter 16. Objects.

After spending two weeks with arrays as the only sort of heap-allocated objects in our programs, it is time to introduce other kinds of objects, objects of our own design.

In class 22 we start writing classes, and in class 23 we start building structures of interrelated class objects.

Object types

As in Python and so many other languages, we define a new object type in Dafny by declaring a class.

Instances of a class are allocated on the heap.

Also as in Python, the class defines the operations we can perform on instances by declaring instance functions and methods that have a this parameter we will see below. Unsurprisingly in Dafny (and unlike in Python), the class also gives static type declarations for the data stored in each instance, called fields.

Abstract object types

Many other proof concerns will start to consume our attention once our classes grow more complicated, so before that happens let’s return for a moment to abstraction and see how, in the event we want to create a mutable abstract data type, we already know how to do it.

Our running example in the first reading on data abstraction was immutable ordered set UniqSeq.

Here is the outline of a mutable ordered set, i.e., an array of unique elements, with a very simple implementation:

dfy
class UniqArray<T(==)> {

  var s: seq<T>

  constructor ()
  {
    this.s := [];
  }

  function Length(): nat
    reads this
  {
    |s|
  }

  function At(i: nat): T
    requires i < Length()
    reads this
  {
    s[i]
  }

  method EnsurePresent(elt: T)
    modifies this
  {
    if elt !in s {
      s := s + [ elt ];
    }
  }
}

Perhaps even more than when we implemented with immutable datatypes, we can clearly distinguish the abstract type UniqArray from its concrete representation s: seq<T>.

Constructor methods are declared with the keyword constructor, and they explain how to initialize a new instance, analogously to Python __init__. In this example we have a single anonymous constructor that sets up an empty UniqArray.

Unlike Python, where a call like obj.operation(x, y) is transformed into a call Class.operation(obj, x, y) and we therefore must declare a first argument — universally named self — to receive the object (the instance) on which operation is being performed, Dafny reserves the keyword this to denote the “current” object. We don’t include this in the parameter list.

And unlike Python, we can omit “this.” when referencing this.field or this.Method() in the specifications and implemementations of class members. So e.g. precondition requires i < Length() means i < this.Length().

Since Length and At do not mutate the UniqArray, we can declare them as functions. We need to specify reads this so that the functions can dereference this heap-allocated UniqArray.

EnsurePresent must declare modifies this in order to reassign this.s (which it does omitting the “this.”).

We can wrap this class up in a module for clients to import:

dfy
module Uniq {
  export
    reveals UniqArray
    provides UniqArray.Length,
             UniqArray.At,
             UniqArray.EnsurePresent

  class UniqArray<T(==)> { ... }
}

reveals UniqArray allows clients to see that UniqArray is a class (so they will need to instantiate it with new) and to see the specifications of its constructor(s). It does not reveal any of the other members of the class.

For members we want clients to use, we can export them with provides in the usual way.

Since our abstract type aims to hide its representation s: seq<T>, field s is not exported at all.

Adding an AF & RI

As we saw previously, these operations as specified are more or less unusable for clients. They won’t be able to prove basic facts about the contents of a UniqArray, nor prove the most important property UniqArray is supposed to guarantee in general:

dfy
import opened Uniq

method UniqArrayTest() {
  var arr := new UniqArray<int>();
  arr.EnsurePresent(5);
  arr.EnsurePresent(10);
  arr.EnsurePresent(5);
  arr.EnsurePresent(10);
  arr.EnsurePresent(20);
  assert arr.Length() == 3;
  assert arr.At(0) == 5;
  assert arr.At(1) == 10;
  assert arr.At(2) == 20;
}

lemma AtHereNotAtThere(ua: UniqArray, i: nat, j: nat)
  requires i < j < ua.Length()
  ensures ua.At(i) != ua.At(j)
{
}
dfy
module Uniq {
  export
    reveals UniqArray
    provides UniqArray.Length,
             UniqArray.At,
             UniqArray.EnsurePresent

  class UniqArray<T(==)> {

    var s: seq<T>

    constructor ()
    {
      this.s := [];
    }

    function Length(): nat
      reads this
    {
      |s|
    }

    function At(i: nat): T
      requires i < Length()
      reads this
    {
      s[i]
    }

    method EnsurePresent(elt: T)
      modifies this
    {
      if elt !in s {
        s := s + [ elt ];
      }
    }
  }
}

Let’s address those issues by adding an abstraction function and rep invariant we can use in our specifications:

dfy
ghost function Elements(): seq<T>
  reads this
{
  s
}
dfy
ghost predicate Valid()
  reads this
{
  forall i, j ::
    0 <= i < j < |s| ==> s[i] != s[j]
}

The client’s abstract view of the Elements of this array is exactly the stored rep s, because…

… as Valid explains, we made the natural implementation choice only to store unique elements.

Both Elements and Valid are provided (not revealed) to clients.

Now use Elements() to add postconditions to the constructor, Length, At, and HasOrAppend so Dafny can verify the example usage. We have already added pre- and postconditions about this.Valid().

dfy
module UniqAF {
  export
    reveals UniqArray
    provides UniqArray.Valid, UniqArray.Elements, UniqArray.Length, UniqArray.At, UniqArray.EnsurePresent

  class UniqArray<T(==)> {

    var s: seq<T>

    constructor ()
      ensures Valid()
      ensures ???
    {
      this.s := [];
    }

    ghost predicate Valid()
      reads this
    {
      forall i, j ::
        0 <= i < j < |s| ==> s[i] != s[j]
    }

    ghost function Elements(): seq<T>
      reads this
    {
      s
    }

    function Length(): nat
      requires Valid()
      reads this
      ensures ???
    {
      |s|
    }

    function At(i: nat): T
      requires Valid()
      requires i < Length()
      reads this
      ensures ???
    {
      s[i]
    }

    method EnsurePresent(elt: T)
      requires Valid()
      modifies this
      ensures Valid()
      ensures ???
    {
      if elt !in s {
        s := s + [ elt ];
      }
    }
  }
}
dfy
import opened UniqAF

method Main() {
  var arr := new UniqArray<int>();
  arr.EnsurePresent(5);
  arr.EnsurePresent(10);
  arr.EnsurePresent(5);
  arr.EnsurePresent(10);
  arr.EnsurePresent(20);
  assert arr.Length() == 3;
  assert arr.At(0) == 5;
  assert arr.At(1) == 10;
  assert arr.At(2) == 20;
}
Loading...

We also want to address lemma AtHereNotAtThere which says that for any UniqArray, for any valid indices i != j, we know At(i) != At(j). Can we incorporate this invariant about abstract UniqArray behavior into the specification so that it is available to clients without further reasoning?

One place we can do so is as a postcondition of Valid(): any valid UniqArray guarantees this property.

Add a postcondition to Valid that allows Dafny to prove AtHereNotAtThere.

Hint: keep in mind that Valid is a predicate that can return false.
Hint: since At(..) requires Valid(), avoid mentioning At to avoid mutual recursion.

dfy
module UniqRI {
  export
    reveals UniqArray
    provides UniqArray.Valid, UniqArray.Elements, UniqArray.Length, UniqArray.At, UniqArray.EnsurePresent

  class UniqArray<T(==)> {

    var s: seq<T>

    constructor ()
      ensures Valid()
      ensures Elements() == []
    {
      this.s := [];
    }

    ghost predicate Valid()
      reads this
      ensures ???
    {
      forall i, j :: 0 <= i < j < |s| ==> s[i] != s[j]
    }

    ghost function Elements(): seq<T>
      reads this
    {
      s
    }

    function Length(): nat
      requires Valid()
      reads this
      ensures Length() == |Elements()|
    {
      |s|
    }

    function At(i: nat): T
      requires Valid()
      requires i < Length()
      reads this
      ensures At(i) == Elements()[i]
    {
      s[i]
    }

    method EnsurePresent(elt: T)
      requires Valid()
      modifies this
      ensures Valid()
      ensures Elements() == old(Elements()) + if elt in old(Elements()) then [] else [elt]
    {
      if elt !in s {
        s := s + [ elt ];
      }
    }
  }
}
dfy
import opened UniqRI

lemma AtHereNotAtThere(ua: UniqArray, i: nat, j: nat)
  requires ua.Valid()
  requires i < j < ua.Length()
  ensures ua.At(i) != ua.At(j)
{
}

method Main() {
  var arr := new UniqArray<int>();
  arr.EnsurePresent(5);
  arr.EnsurePresent(10);
  arr.EnsurePresent(5);
  arr.EnsurePresent(10);
  arr.EnsurePresent(20);
  assert arr.Length() == 3;
  assert arr.At(0) == 5;
  assert arr.At(1) == 10;
  assert arr.At(2) == 20;
}
Loading...

Probably the headline from the reading up to now is that the ideas we studied for data abstraction with functional programs adapt very smoothly to imperative classes. Let’s see them in action next on a moderately larger example.

Example: tokenizer

As part of your 6.101 LISP interpreter you implemented two functions to process input strings like "((lambda (x) (+ x x)) 16)" into a tree-structured representation that could be recursively evaluated:

  • tokenize splits the input string into a sequence of syntactically valid tokens, where a token might be a single character like ( or + or a sequence of characters like lambda or 16, and
  • parse constructs a tree representation from the token sequence.

In practice these components are very often built using a parser generator that takes a grammar for the language we wish to parse and produces the code for a parser that tokenizes and parses the language according to the grammar. For example, you can look at the grammar for Dafny that is used to generate Dafny’s parser.

Let’s build a simple tokenizer that can be used to read out the sequence of tokens from an input string. The tokenizer is mutable, updating its internal state to reflect its current position in the input.

You can find an alternative version of this tokenizer in Program Proofs section 16.1: take a look at both and decide which specification you prefer!

Tokens

We define the kinds of tokens, including End to denote the end of the input and Error for anything that doesn’t match another category. Then we explain what the categories mean (except for End) with predicate Is:

dfy
datatype Category = Identifier | Number | Operator | Whitespace | Error | End

predicate Is(ch: char, cat: Category)
  requires cat != End
  decreases cat == Error
{
  match cat
  case Whitespace => ch in " \t\r\n"
  case Identifier => 'A' <= ch <= 'Z' || 'a' <= ch <= 'z'
  case Number => '0' <= ch <= '9'
  case Operator => ch in "+-*/%!=><~^&|"
  case Error => !Is(ch, Identifier) && !Is(ch, Number) &&
                !Is(ch, Operator) && !Is(ch, Whitespace)
}

We need to prove termination of the recursive definition of Is, which we do by showing that recursive calls only occur from cat == Error to cat != Error.

We also explain which of these categories represent legal input we can parse: all of them except Error and End.

dfy
ghost predicate Parseable(ch: char) {
  Is(ch, Identifier) || Is(ch, Number) || Is(ch, Operator) || Is(ch, Whitespace)
}

A token returned by our tokenizer will be a run of characters that belong to the same category, skipping Whitespace. So:

text
foo => foo + 123

 should be tokenized as: 

foo
Ident

, 

=>
Oper

, 

foo
Ident

, 

+
Oper

, 

123
Num

.

State

We declare three fields in class Tokenizer:

dfy
class Tokenizer {

  const source: string

  ghost var rest: string

  var n: nat

  // ...
  • source is the string this Tokenizer was created to parse. We make it unreassignable with keyword const which can simplify our reasoning: we never have to show that source is unchanged.

  • rest is the suffix of source that remains to be tokenized. This ghost field, like other ghost variables, is only for the purpose of writing specs and proofs: it does not exist at runtime.

  • n is our position in source, the number of characters already tokenized.

A representation invariant to relate source, n, and rest:

dfy
ghost predicate Valid()
  reads this
{
  n <= |source| && rest == source[n..]
}

And the constructor for making a new tokenizer:

dfy
constructor (input: string)
  ensures Valid() && rest == input
{
  source, rest, n := input, input, 0;
}

Operations

Our tokenizer has only one operation, but its specification is a kind of kitchen sink of desirable properties. The operation returns the next token in the input: the one (after skipping whitespace) at index n; the one sitting (after skipping whitespace) at the front of rest. In addition to the token itself, we output:

  • its Category, and
  • ghost skipped, the number of Whitespace characters that were skipped, again for the purpose of specification.
dfy
method Read() returns (cat: Category, ghost skipped: nat, token: string)
  requires Valid()
  modifies this

So far so good.

dfy
  ensures cat == Error || Valid()
  ensures cat != Whitespace

Either the tokenizer remains Valid or we return an Error token. And we never return a Whitespace token.

dfy
  ensures skipped <= |old(rest)|
  ensures forall ch :: ch in old(rest)[..skipped] ==> Is(ch, Whitespace)

All of the skipped characters are Whitespace at the front of rest.

dfy
  ensures cat == Error ==> skipped < |old(rest)| && !Parseable(old(rest)[skipped])
  ensures cat != Error ==> old(rest) == old(rest)[..skipped] + token + rest

Returning an Error means that we encountered an unparseable character after skipping whitespace. Otherwise:

  • the skipped whitespace concatenated with the returned token are a prefix of the old value of rest,
  • and the new value of rest is the remaining suffix.
dfy
  ensures cat == End ==> rest == "" && token == ""
  ensures cat != End && cat != Error ==> token != ""
  ensures cat != End && cat != Error ==> forall ch :: ch in token ==> Is(ch, cat)
  ensures cat != End && cat != Error ==> rest == "" || !Is(rest[0], cat)

Returning End means that we reached the end of the input. Otherwise, if we’re returning one of the Parseable categories:

  • the token is a nonempty string of characters in that category,
  • and the next character in the input is not in that category (or there is no more input).

Implementation

With our conveniently disjoint categories of characters, the implementation is just as straightforward as it was in the 6.101 LISP interpreter — but now Dafny will prove our kitchen sink is water-tight.

Step 1: skip initial whitespace. The interesting work is in the loop invariant, which we can pronounce as (1) the loop-iteration variable n increases through the loop, with an upper bound of the source length; (2) field skipped is kept up-to-date as the extent to which n has increased; (3) all characters we are skipping truly are whitespace; and (4) field rest is not modified.

dfy
skipped := 0;
while n != |source| && Is(source[n], Whitespace)
  invariant old(n) <= n <= |source|
  invariant skipped == n - old(n)
  invariant forall i :: old(n) <= i < n ==> Is(source[i], Whitespace)
  invariant rest == old(rest)
{
  n := n + 1;
  skipped := skipped + 1;
}

One quick note on this example: we previously saw how Dafny generally does not require us to use loop invariants to declare all cases of variables not modified by loops. Instead, the handy feature of frames makes that information available to proofs automatically. So why do we need rest == old(rest) here? The difference is that rest is a field, which doesn’t get the same treatment as local variables. The loop’s enclosing method modifies this, so we need to specify that this.rest is not reassigned.

Step 2: identify the token category.

dfy
if n == |source| {
  cat := End;
  token := "";
  rest := "";
  return;
} else if Is(source[n], Identifier) {
  cat := Identifier;
} else if Is(source[n], Number) {
  cat := Number;
} else if Is(source[n], Operator) {
  cat := Operator;
} else {
  cat := Error;
  token := "";
  return;
}

Step 3: find all the adjacent characters in that category to form the token. We need an invariant to show that n is in bounds and an invariant so that we can prove the postcondition about characters in token.

dfy
var start := n;
n := n + 1;
while n != |source| && Is(source[n], cat)
  invariant old(n) + skipped <= n <= |source|
  invariant forall i :: old(n) + skipped <= i < n ==> Is(source[i], cat)
  invariant rest == old(rest)
{
  n := n + 1;
}
token := source[start..n];
rest := rest[n-old(n)..];

Test harness

Dafny proves the implementation above correct. We can also validate that our specification will be effective for clients by trying to use it in a test harness. In this case, the specification ought to fully determinize the behavior of Tokenizer, and we ought to be able to prove its the exact behavior on small examples. And indeed we can:

dfy
method Main() {
  var input := "foo + 123";
  var tokenizer := new Tokenizer(input);
  ghost var rest := input;
  ghost var cat, skipped, tok;

  // First token is Identifier "foo"
  cat, skipped, tok := tokenizer.Read();
  assert (cat, skipped, tok) == (Identifier, 0, "foo") by {
    assert skipped == 0 by { assert !Is(rest[0], Whitespace); }
    assert tok[0] == rest[0];
    assert cat == Identifier by { assert tok[0] in tok && Is(tok[0], Identifier); }
    assert tok[..3] == rest[..3] && rest[3] !in tok;
    assert tok == "foo";
  }
  rest := " + 123";
  assert tokenizer.rest == rest;

  // Second token is Operator "+"
  cat, skipped, tok := tokenizer.Read();
  assert (cat, skipped, tok) == (Operator, 1, "+") by {
    assert skipped == 1 by { assert !Is(rest[1], Whitespace) && rest[0] in rest && Is(rest[0], Whitespace); }
    assert tok[0] == rest[1];
    assert cat == Operator by { assert tok[0] in tok && Is(tok[0], Operator); }
    assert rest[2] !in tok;
    assert tok == "+";
  }
  rest := " 123";
  assert tokenizer.rest == rest;

  // Third token is Number "123"
  cat, skipped, tok := tokenizer.Read();
  assert (cat, skipped, tok) == (Number, 1, "123") by {
    assert skipped == 1 by { assert !Is(rest[1], Whitespace) && rest[0] in rest && Is(rest[0], Whitespace); }
    assert tok[0] == rest[1];
    assert cat == Number by { assert tok[0] in tok && Is(tok[0], Number); }
    assert tok[..3] == rest[1..4];
    assert tok == "123";
  }
  rest := "";
  assert tokenizer.rest == rest;

  // Final token is End
  cat, skipped, tok := tokenizer.Read();
  assert (cat, skipped, tok) == (End, 0, "");
}
dfy
class Tokenizer {

  const source: string

  ghost var rest: string

  var n: nat


  ghost predicate Valid()
    reads this
  {
    n <= |source| && rest == source[n..]
  }

  constructor (input: string)
    ensures Valid() && rest == input
  {
    source, rest, n := input, input, 0;
  }

  method Read() returns (cat: Category, ghost skipped: nat, token: string)
    requires Valid()
    modifies this
  // use of `` below is a hack to fix the indentation of these snippets :(
    ensures cat == Error || Valid()
    ensures cat != Whitespace
    ensures skipped <= |old(rest)|
    ensures forall ch :: ch in old(rest)[..skipped] ==> Is(ch, Whitespace)
    ensures cat == Error ==> skipped < |old(rest)| && !Parseable(old(rest)[skipped])
    ensures cat != Error ==> old(rest) == old(rest)[..skipped] + token + rest
    ensures cat == End ==> rest == "" && token == ""
    ensures cat != End && cat != Error ==> token != ""
    ensures cat != End && cat != Error ==> forall ch :: ch in token ==> Is(ch, cat)
    ensures cat != End && cat != Error ==> rest == "" || !Is(rest[0], cat)
  {
    // Step 1: skip initial whitespace.
    skipped := 0;
    while n != |source| && Is(source[n], Whitespace)
      invariant old(n) <= n <= |source|
      invariant skipped == n - old(n)
      invariant forall i :: old(n) <= i < n ==> Is(source[i], Whitespace)
      invariant rest == old(rest)
    {
      n := n + 1;
      skipped := skipped + 1;
    }

    // Step 2: decide the token category.
    if n == |source| {
      cat := End;
      token := "";
      rest := "";
      return;
    } else if Is(source[n], Identifier) {
      cat := Identifier;
    } else if Is(source[n], Number) {
      cat := Number;
    } else if Is(source[n], Operator) {
      cat := Operator;
    } else {
      cat := Error;
      token := "";
      return;
    }

    // Step 3: find all remaining adjacent characters in that category.
    var start := n;
    n := n + 1;
    while n != |source| && Is(source[n], cat)
      invariant old(n) + skipped <= n <= |source|
      invariant forall i :: old(n) + skipped <= i < n ==> Is(source[i], cat)
      invariant rest == old(rest)
    {
      n := n + 1;
    }
    token := source[start..n];
    rest := rest[n-old(n)..];
  }
}
dfy
datatype Category = Identifier | Number | Operator | Whitespace | Error | End

predicate Is(ch: char, cat: Category)
  requires cat != End
  decreases cat == Error
{
  match cat
  case Whitespace => ch in " \t\r\n"
  case Identifier => 'A' <= ch <= 'Z' || 'a' <= ch <= 'z'
  case Number => '0' <= ch <= '9'
  case Operator => ch in "+-*/%!=><~^&|"
  case Error => !Is(ch, Identifier) && !Is(ch, Number) &&
                !Is(ch, Operator) && !Is(ch, Whitespace)
}

ghost predicate Parseable(ch: char) {
  Is(ch, Identifier) || Is(ch, Number) || Is(ch, Operator) || Is(ch, Whitespace)
}

Summary

Dafny’s classes are a natural step up from modules of functional code. The same concepts of representation invariants and abstraction functions help structure proofs. We mix in constructs like old that we had studied in connection with loops that modify arrays. Crucially, old can be applied to a call to an abstraction function, and we often use that pattern to characterize the abstract effect of a class method.

Copyright 6.S057 course staff.