6.S057: 6.S057: Verified Software Engineering

Class 22

class22.dfy
dfy
// Checksums

// As a first example of classes, let's look at a class to compute checksums
// incrementally.  See this Wikipedia reference on checksums if curious:
//   https://en.wikipedia.org/wiki/Checksum

// We wrap inside a module to do some information hiding.  We'll get to
// explaining these exposed identifiers as they arise.
module Checksums {
  export
    reveals Hash, SumChars, ChecksumMachine
    provides ChecksumMachine.data, ChecksumMachine.Valid, ChecksumMachine.Append, ChecksumMachine.Checksum
  
  // The goal of the class is to compute Hash results of particular strings.
  ghost function Hash(s: string): int {
    SumChars(s) % 137
  }

  ghost function SumChars(s: string): int {
    if |s| == 0 then
      0
    else
      var last := |s| - 1;
      SumChars(s[..last]) + s[last] as int // <-- typecast (conversion)
  }

  // We want our class to meet this interface.
  class ChecksumMachine0 {
    // Store string data enqueued so far.
    var data: string

    // Can initialize with empty data.
    constructor ()
      ensures data == ""

    // Can add new content to the end.
    method Append(d: string)
      modifies this
      ensures data == old(data) + d

    // Can compute the checksum at any time.
    function Checksum(): int
      reads this
      ensures Checksum() == Hash(data)
  }

  // At this point we write ChecksumMachineTestHarness below to exercise the
  // specification, and we wrap ChecksumMachine in a module.

  // Now here's how we actually implement it.
  class ChecksumMachine {
    // First, move "data" to be ghost.
    ghost var data: string
    // Instead, we just store the checksum so far!
    var cs: int

    // We will need a validity predicate, as we used previously for purely
    // functional data structures.  Now, however, it belongs to the class and
    // can reference class fields.
    ghost predicate Valid()
      reads this
    {
      cs == Hash(data)
    }

    constructor ()
      ensures Valid() && data == ""
    {
      data, cs := "", 0;
    }

    // We carefully update the stored checksum, *without* having to repeat
    // processing of all of data (which we don't even store anymore at runtime).
    method Append(d: string)
      requires Valid()
      modifies this
      ensures Valid() && data == old(data) + d
    {
      var i := 0;
      while i != |d|
        invariant 0 <= i <= |d|
        invariant Valid()
        invariant data == old(data) + d[..i]
      {
        cs := (cs + d[i] as int) % 137;
        data := data + [d[i]];
        i := i + 1;
      }
    }

    // This function becomes very easy!
    function Checksum(): int
      requires Valid()
      reads this
      ensures Checksum() == Hash(data)
    {
      cs
    }
  }
}

module ChecksumsTest {
  import opened Checksums

  method ChecksumMachineTestHarness() {
    var m := new ChecksumMachine();
    m.Append("green");
    m.Append("grass");
    var c := m.Checksum();
    print "Checksum is ", c, "\n";
  }
}

// Tokenizer

// We saw this aspect of classic string parsing in the reading.

// We want to break an input string into subsequences of the following kinds:
datatype Category = Identifier | Number | Operator
  | Whitespace | Error | End

// Here is what the categories mean.
predicate Is(ch: char, cat: Category)
  requires cat != End
  decreases cat == Error
  // Weird 'decreases' clause!  It's needed because of the recursive calls
  // below.
{
  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)
}

// Let's explain which characters are legal in strings we can parse.
ghost predicate Parseable(ch: char) {
  Is(ch, Identifier) || Is(ch, Number) || Is(ch, Operator) || Is(ch, Whitespace)
}

// There are awfully many ways to specify this tokenizer.
// In fact, this file adopts a different strategy from the one in Leino's book.
class Tokenizer {
  // What string did we start out parsing?  Note how it's marked 'const' for
  // constant, or immutable, which simplifies reasoning.
  const source: string

  // Which suffix of 'source' remains to tokenize?
  ghost var rest: string

  // How many characters did we already tokenize?
  var n: nat

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

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

  // OK, this method is a doozy even just to specify.
  // It's kind of a kitchen sink of desirable properties.
  // The method is supposed to return the next *token*, a run of characters that
  // belong to the same category.  We also indicate which category that is.
  // Finally, ghost output 'skipped' is present to make the postconditions
  // easier to write.
  method Read() returns (cat: Category, ghost skipped: nat, token: string)
    requires Valid()
    modifies this
    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)..];
  }
}

method TokenizerTestHarness1() {
  var t1 := new Tokenizer("()");
  assert !Parseable(t1.rest[0]);
  var cat, skip, tok := t1.Read();
  assert cat == Error;
}

method TokenizerTestHarness2() {
  var src := "  a";
  var t2 := new Tokenizer(src);
  assert Is(src[0], Whitespace) && Is(src[1], Whitespace) && Is(src[2], Identifier);
  var cat, skip, tok := t2.Read();
  assert skip == 2 by {
    if skip < 2 { assert Is(src[0], cat); assert false; }
    if skip > 2 { assert !Is(src[2], Whitespace); assert false; }
  }
  assert cat == Identifier by { assert tok[0] in tok; }
  assert tok == "a";
}

// Class hierarchies

// A classic example of class hierarchies gets a lot more interesting in Dafny
// with proofs!  Let's verify arithmetic expressions with classes rather than
// datatypes.

datatype Option<T> = None | Some(value: T)
type Var = string
type Env = map<Var, real>

// A Dafny *trait* is like an interface in Java: it expresses a required "shape"
// of classes.  Traits can include required specifications for class methods.
trait Expression {
  // This part was nonobvious to include, as it's needed to prove termination.
  // Intuitively, the size of each class is the number of different class
  // objects contained within it.
  ghost const size: nat

  // A standard object invariant does the trick.  Note we mark this predicate
  // (and most later members) as decreasing size, to support "recursive"
  // definitions.
  ghost predicate Valid()
    decreases size

  // To specify the methods that follow, it helps to know which variables appear
  // in an expression.
  ghost function FreeVars(): set<Var>
    requires Valid()
    decreases size
  
  // We can compute an expression's value, given values for all of its variables.
  function Eval(env: Env): real
    requires Valid()
    requires FreeVars() <= env.Keys
    decreases size

  // We can create a new expression where algebraic simplification rules have
  // been applied.
  method Simplify() returns (e: Expression)
    requires Valid()
    ensures e.Valid()
    ensures e.FreeVars() <= FreeVars()
    ensures forall env: Env :: FreeVars() <= env.Keys ==> e.Eval(env) == Eval(env)
    decreases size

  // Finally, let's check if this expression represents a constant.
  function ConstantOf(): (k: Option<real>)
    requires Valid()
    ensures k.Some? ==> forall env: Env :: FreeVars() <= env.Keys ==> Eval(env) == k.value
}

// The class for constants is pretty straightforward.
class Constant extends Expression {
  const k: real
  
  constructor (k: real)
    ensures Valid()
    ensures this.k == k
  {
    this.k := k;
    this.size := 0;
  }

  ghost predicate Valid()
    decreases size
  {
    size == 0
  }

  ghost function FreeVars(): set<Var>
    decreases size
  {
    {}
  }

  // A twist here: we dropped the precondition!  It is always OK to *drop*
  // preconditions or *add* postconditions, compared to the trait we extend.
  function Eval(env: Env): real
    decreases size
    ensures Eval(env) == k
  {
    k
  }

  method Simplify() returns (e: Expression)
    requires Valid()
    ensures e.Valid()
    ensures e.FreeVars() <= FreeVars()
    ensures forall env: Env :: e.Eval(env) == Eval(env)
    decreases size
  {
    return this;
  }

  function ConstantOf(): (k: Option<real>)
    ensures k.Some? ==> forall env: Env :: FreeVars() <= env.Keys ==> Eval(env) == k.value
  {
    Some(k)
  }
}

class Variable extends Expression {
  const x: Var
  
  constructor (x: Var)
    ensures Valid()
  {
    this.x := x;
    this.size := 0;
  }

  ghost predicate Valid()
    decreases size
  {
    size == 0
  }

  ghost function FreeVars(): set<Var>
    decreases size
  {
    {x}
  }

  function Eval(env: Env): real
    requires FreeVars() <= env.Keys
    decreases size
  {
    env[x]
  }

  method Simplify() returns (e: Expression)
    requires Valid()
    ensures e.Valid()
    ensures e.FreeVars() <= FreeVars()
    ensures forall env: Env :: FreeVars() <= env.Keys ==> e.Eval(env) == Eval(env)
    decreases size
  {
    return this;
  }

  function ConstantOf(): (k: Option<real>)
    ensures k.Some? ==> forall env: Env :: FreeVars() <= env.Keys ==> Eval(env) == k.value
  {
    None
  }
}

class Plus extends Expression {
  const e1: Expression
  const e2: Expression
  
  constructor (e1: Expression, e2: Expression)
    requires e1.Valid() && e2.Valid()
    ensures Valid() && this.e1 == e1 && this.e2 == e2
  {
    this.e1 := e1;
    this.e2 := e2;
    this.size := 1 + e1.size + e2.size;
  }

  ghost predicate Valid()
    decreases size
  {
    size == 1 + e1.size + e2.size && e1.Valid() && e2.Valid()
  }

  ghost function FreeVars(): set<Var>
    requires Valid()
    ensures FreeVars() == e1.FreeVars() + e2.FreeVars()
    decreases size
  {
    e1.FreeVars() + e2.FreeVars()
  }

  function Eval(env: Env): real
    requires Valid()
    requires FreeVars() <= env.Keys
    decreases size
  {
    e1.Eval(env) + e2.Eval(env)
  }

  method Simplify() returns (e: Expression)
    requires Valid()
    ensures e.Valid()
    ensures e.FreeVars() <= FreeVars()
    ensures forall env: Env :: FreeVars() <= env.Keys ==> e.Eval(env) == Eval(env)
    decreases size
  {
    var e1' := e1.Simplify();
    var e2' := e2.Simplify();
    match e1'.ConstantOf()
    case Some(0.0) => return e2';
    case _ =>
      match e2'.ConstantOf()
      case Some(0.0) => return e1';
      case _ => return new Plus(e1', e2');
  }

  function ConstantOf(): (k: Option<real>)
    requires Valid()
    ensures k.Some? ==> forall env: Env :: FreeVars() <= env.Keys ==> Eval(env) == k.value
  {
    None
  }
}

class Times extends Expression {
  const e1: Expression
  const e2: Expression
  
  constructor (e1: Expression, e2: Expression)
    requires e1.Valid() && e2.Valid()
    ensures Valid() && this.e1 == e1 && this.e2 == e2
  {
    this.e1 := e1;
    this.e2 := e2;
    this.size := 1 + e1.size + e2.size;
  }

  ghost predicate Valid()
    decreases size
  {
    size == 1 + e1.size + e2.size && e1.Valid() && e2.Valid()
  }

  ghost function FreeVars(): set<Var>
    requires Valid()
    ensures FreeVars() == e1.FreeVars() + e2.FreeVars()
    decreases size
  {
    e1.FreeVars() + e2.FreeVars()
  }

  function Eval(env: Env): real
    requires Valid()
    requires FreeVars() <= env.Keys
    decreases size
  {
    e1.Eval(env) * e2.Eval(env)
  }

  method Simplify() returns (e: Expression)
    requires Valid()
    ensures e.Valid()
    ensures e.FreeVars() <= FreeVars()
    ensures forall env: Env :: FreeVars() <= env.Keys ==> e.Eval(env) == Eval(env)
    decreases size
  {
    var e1' := e1.Simplify();
    var e2' := e2.Simplify();
    match e1'.ConstantOf()
    case Some(0.0) => return new Constant(0.0);
    case Some(1.0) => return e2';
    case _ =>
      match e2'.ConstantOf()
      case Some(0.0) => return new Constant(0.0);
      case Some(1.0) => return e1';
      case _ => return new Times(e1', e2');
  }

  function ConstantOf(): (k: Option<real>)
    requires Valid()
    ensures k.Some? ==> forall env: Env :: FreeVars() <= env.Keys ==> Eval(env) == k.value
  {
    None
  }
}

// We can test the above interface by building a generic check for whether an
// expression is known to be zero.
method ProvablyZero(e: Expression) returns (b: bool)
  requires e.Valid()
  ensures b ==> forall env: Env :: e.FreeVars() <= env.Keys ==> e.Eval(env) == 0.0
{
  var e' := e.Simplify();
  match e'.ConstantOf()
  case Some(0.0) => return true;
  case _ => return false;
}

// This example shows why it is important that Dafny made us work to prove
// termination above: in general, the graph of objects can include cycles!
// That means a method calling itself on "child" objects may not terminate.
class Tricky {
  var r: Tricky

  constructor ()
  {
    r := this;
  }

  method Uhoh()
    requires false
    // Remove this precondition and termination checking justifiably fails.
  {
    r.Uhoh();
  }
}

Exercises

class22/checksum.dfy
dfy
module Checksums {

  export
    reveals Hash, SumChars, ChecksumMachine
    provides ChecksumMachine.data, ChecksumMachine.Valid, ChecksumMachine.Append, ChecksumMachine.Checksum

  ghost function Hash(s: string): int {
    SumChars(s) % 137
  }

  ghost function SumChars(s: string): int {
    if |s| == 0 then
      0
    else
      var last := |s| - 1;
      SumChars(s[..last]) + s[last] as int
  }

  class ChecksumMachine {

    // Don't store the data!
    ghost var data: string

    var cs: int // Just store the checksum so far

    ghost predicate Valid()
      reads this
    {
      cs == Hash(data)
    }

    constructor ()
      ensures Valid() && data == ""
    {
      data, cs := "", 0;
    }

    method Append(d: string)
      requires Valid()
      modifies this
      ensures Valid() && data == old(data) + d
    {
      // Use `d[i] as int` to convert the character d[i] to its numeric value
    }

    function Checksum(): int
      requires Valid()
      reads this
      ensures Checksum() == Hash(data)
    {
      cs
    }
  }
}

import opened Checksums

method ChecksumMachineTestHarness() {
  var m := new ChecksumMachine();
  m.Append("green");
  m.Append("grass");
  var c := m.Checksum();
  print "Checksum is ", c, "\n";
}
class22/expression.dfy
dfy
// Expression trait

// Write specifications for Eval, Simplify, & ConstantOf:
// Eval needs a precondition?
// Simplify needs a postcondition, the result should be correct w.r.t. Eval?
// ConstantOf needs a postcondition, maybe the result is a conservative estimate?

datatype Option<T> = None | Some(value: T)
type Var = string
type Env = map<Var, real>

trait Expression {

  ghost predicate Valid()

  ghost function FreeVars(): set<Var>
    requires Valid()

  // Compute an expression's value, given values for all of its variables.
  function Eval(env: Env): real

  // Create a new expression where algebraic simplification rules have been applied.
  method Simplify() returns (e: Expression)

  // Check if this expression represents a constant.
  function ConstantOf(): (k: Option<real>)
}
class22/plus.dfy
dfy
// Adding a recursive concrete subtype of Expression

// Prove termination.
// Suggestion: add a `ghost` field that associates each Expression object with a
// value that decreases for recursive calls.

datatype Option<T> = None | Some(value: T)
type Var = string
type Env = map<Var, real>

trait Expression {

  ghost predicate Valid()

  ghost function FreeVars(): set<Var>
    requires Valid()

  // Compute an expression's value, given values for all of its variables.
  function Eval(env: Env): real
    requires Valid()
    requires FreeVars() <= env.Keys

  // Create a new expression where algebraic simplification rules have been applied.
  method Simplify() returns (e: Expression)

  // Check if this expression represents a constant.
  function ConstantOf(): (k: Option<real>)
}

class Constant extends Expression {
  const k: real

  constructor (k: real)
    ensures Valid()
    ensures this.k == k
  {
    this.k := k;
  }

  ghost predicate Valid()
  {
    true
  }

  ghost function FreeVars(): set<Var>
  {
    {}
  }

  function Eval(env: Env): real
  {
    k
  }

  method Simplify() returns (e: Expression)
  {
    return this;
  }

  function ConstantOf(): (k: Option<real>)
  {
    Some(k)
  }
}

class Variable extends Expression {
  const x: Var

  constructor (x: Var)
    ensures Valid()
  {
    this.x := x;
  }

  ghost predicate Valid()
  {
    true
  }

  ghost function FreeVars(): set<Var>
  {
    {x}
  }

  function Eval(env: Env): real
    requires FreeVars() <= env.Keys
  {
    env[x]
  }

  method Simplify() returns (e: Expression)
  {
    return this;
  }

  function ConstantOf(): (k: Option<real>)
  {
    None
  }
}

class Plus extends Expression {
  const e1: Expression
  const e2: Expression

  constructor (e1: Expression, e2: Expression)
    requires e1.Valid() && e2.Valid()
    ensures Valid() && this.e1 == e1 && this.e2 == e2
  {
    this.e1 := e1;
    this.e2 := e2;
  }

  ghost predicate Valid()
  {
    e1.Valid() && e2.Valid()
  }

  ghost function FreeVars(): set<Var>
    requires Valid()
  {
    e1.FreeVars() + e2.FreeVars()
  }

  function Eval(env: Env): real
    requires Valid()
    requires FreeVars() <= env.Keys
  {
    e1.Eval(env) + e2.Eval(env)
  }

  method Simplify() returns (e: Expression)
  {
    return this;
  }

  function ConstantOf(): (k: Option<real>)
  {
    None
  }
}
Copyright 6.S057 course staff.