6.S057: 6.S057: Verified Software Engineering

Class 23

class23.dfy
dfy
// The coffee machine

// Let's meet Dafny's standard techniques for dealing with class objects that
// "contain" other class objects, through a simplified example of a coffee
// machine.

// The coffee machine contains a grinder...
class Grinder0 {
  var HasBeans: bool
  ghost predicate Valid()
    reads this
  constructor ()
    ensures Valid()
  method AddBeans()
    requires Valid()
    modifies this
    ensures Valid() && HasBeans
  method Grind()
    requires Valid() && HasBeans
    modifies this
    ensures Valid()
}

// ...and a water tank.
class WaterTank0 {
  var Level: nat
  ghost predicate Valid()
    reads this
  constructor ()
    ensures Valid()
  method Fill()
    requires Valid()
    modifies this
    ensures Valid() && Level == 10
  method Use()
    requires Valid() && Level != 0
    modifies this
    ensures Valid() && Level == old(Level) - 1
}

// We'll also have a dummy class representing a cup of coffee.
class Cup {
  constructor ()
}

// The coffee maker itself encapsulates away the details.
class CoffeeMaker0 {
  ghost predicate Valid()
    reads this
  constructor ()
    ensures Valid()
  predicate Ready()
    requires Valid()
    reads this
  method Restock()
    requires Valid()
    modifies this
    ensures Valid() && Ready()
  method Dispense(double: bool) returns (c: Cup)
    requires Valid() && Ready()
    modifies this
    ensures Valid()
}

// Here's our first take at specifying the coffee machine.
class CoffeeMaker1 {
  var g: Grinder0
  var w: WaterTank0
  ghost var Repr: set<object>
  // IMPORTANT HERE: a coffee maker stores a set of "all objects it owns" --
  // those that are encapsulated inside it somehow.

  // The validity predicate captures that the coffee machine, the grinder, and
  // the water tank are all owned by the coffee machine.
  ghost predicate Valid()
    reads this, Repr
  {
    this in Repr &&
      g in Repr && g.Valid() &&
      w in Repr && w.Valid()
  }

  constructor ()
    ensures Valid()
  {
    g := new Grinder0();
    w := new WaterTank0();
    Repr := {this, g, w};
    // Here we know exactly the set of owned objects.
  }

  predicate Ready()
    requires Valid()
    reads Repr
  {
    g.HasBeans && 2 <= w.Level
  }

  method Restock()
    requires Valid()
    modifies Repr
    ensures Valid() && Ready()
  {
    g.AddBeans();
    w.Fill();
  }

  method Dispense(double: bool) returns (c: Cup)
    requires Valid() && Ready()
    modifies Repr
    ensures Valid()
  {
    g.Grind();
    if double {
      w.Use(); w.Use();
    } else {
      w.Use();
    }
    c := new Cup();
  }
}

// However, the following method fails to verify.  We need a number of
// fixes.
/*method CoffeeTestHarness() {
  var cm := new CoffeeMaker1();
  cm.Restock();
  var c := cm.Dispense(true);
}*/

class CoffeeMaker2 {
  var g: Grinder0
  var w: WaterTank0
  ghost var Repr: set<object>

  ghost predicate Valid()
    reads this, Repr
  {
    this in Repr &&
      g in Repr && g.Valid() &&
      w in Repr && w.Valid()
  }

  constructor ()
    ensures Valid()
    ensures fresh(Repr)
    // Fix #1: mark that a newly allocated coffee maker is *fresh*: disjoint
    // from objects that existed when this method was called.
  {
    g := new Grinder0();
    w := new WaterTank0();
    Repr := {this, g, w};
  }

  predicate Ready()
    requires Valid()
    reads Repr
  {
    g.HasBeans && 2 <= w.Level
  }

  method Restock()
    requires Valid()
    modifies Repr
    ensures Valid() && Ready()
    ensures fresh(Repr - old(Repr))
    // We must also explain freshness of new objects allocated here.
    // Could also: (1) change Repr to const or (1) say Repr == old(Repr).
    // The choices here are on a tradeoff spectrum between simplicity and
    // flexibility to support reasonable implementation strategies that might be
    // substituted in later.
  {
    g.AddBeans();
    w.Fill();
  }

  method Dispense(double: bool) returns (c: Cup)
    requires Valid() && Ready()
    modifies Repr
    ensures Valid()
    ensures fresh(Repr - old(Repr))
  {
    g.Grind();
    if double {
      w.Use(); w.Use();
    } else {
      w.Use();
    }
    c := new Cup();
  }

  // Example of another pattern: having a method internally allocate a new owned
  // object.
  method ChangeGrinder()
    requires Valid()
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr))
  {
    g := new Grinder0();
    Repr := Repr + {g};
  }

  // Example of a further pattern: having a method accept ownership of an object
  // passed in via a parameter.
  method InstallCustomGrinder(grinder: Grinder0)
    requires Valid() && grinder.Valid()
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr) - {grinder})
  {
    g := grinder;
    Repr := Repr + {g};
  }
}

// Now the test harness works!
method CoffeeTestHarness() {
  var cm := new CoffeeMaker2();
  cm.Restock();
  var c := cm.Dispense(true);
}

// OK, but the setup we just used precluded the possibility of the grinder and
// water tank themselves owning more objects.  Let's retrofit to support that
// mode.  We'll leave these two without implementations of methods, etc., though
// they could easily be filled in.

class Grinder {
  var HasBeans: bool
  ghost var Repr: set<object>
  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  constructor ()
    ensures Valid() && fresh(Repr)
  method AddBeans()
    requires Valid()
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr)) && HasBeans
  method Grind()
    requires Valid() && HasBeans
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr))
}

class WaterTank {
  var Level: nat
  ghost var Repr: set<object>
  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  constructor ()
    ensures Valid() && fresh(Repr)
  method Fill()
    requires Valid()
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr)) && Level == 10
  method Use()
    requires Valid() && Level != 0
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr)) && Level == old(Level) - 1
}

// The above two classes just follow the same patterns we introduced for the
// coffee maker itself.  However, the coffee maker now needs to be revised.

class CoffeeMaker {
  var g: Grinder
  var w: WaterTank
  ghost var Repr: set<object>

  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  {
    this in Repr &&
      g in Repr && g.Repr <= Repr && this !in g.Repr && g.Valid() &&
      w in Repr && w.Repr <= Repr && this !in w.Repr && w.Valid() &&
      g.Repr !! w.Repr
      // (Discovered with the help of some assertions below.)
      // So we require: (1) inclusion of Repr sets and (2) disjointness between
      // 'this' and the two Repr sets of subobjects.
      // And we need Valid() constituent objects to be in their own Repr: we
      // include that in the specs for Valid() above and here.
  }

  constructor ()
    ensures Valid()
    ensures fresh(Repr)
  {
    g := new Grinder();
    w := new WaterTank();
    new;
    // Tricky feature here!  Constructors run in two phases: initialize objects
    // to the points where all fields have initial values, then proceed with
    // those objects treated normally.  Writing 'new' indicates the boundary
    // between those phases, allowing us to reference 'this' to stand for a
    // bona-fide (fully initialized) object.
    Repr := {this, g, w} + g.Repr + w.Repr;
  }

  predicate Ready()
    requires Valid()
    reads Repr
  {
    g.HasBeans && 2 <= w.Level
  }

  method Restock()
    requires Valid()
    modifies Repr
    ensures Valid() && Ready()
    ensures fresh(Repr - old(Repr))
  {
    // Here are a few assertions that were helpful in figuring out why the above
    // changes to Repr are necessary.
    assert this !in g.Repr;
    assert g in g.Repr;
    assert w !in g.Repr;
    assert w.Valid();
    assert g.Repr !! w.Repr;
    g.AddBeans();
    assert w.Valid();
    w.Fill();
    Repr := Repr + g.Repr + w.Repr;
    // Don't forget to update Repr after changes.
  }

  method Dispense(double: bool) returns (c: Cup)
    requires Valid() && Ready()
    modifies Repr
    ensures Valid()
    ensures fresh(Repr - old(Repr))
  {
    g.Grind();
    if double {
      w.Use(); w.Use();
    } else {
      w.Use();
    }
    c := new Cup();
    Repr := Repr + g.Repr + w.Repr;
  }
}

// Linked lists

// Let's now try a more grounded, realistic example: mutable linked lists.
// First we have a class for representing a single node of a linked list.

class LinkedListNode<T> {
  var data: T
  var next: LinkedListNode?<T>
  // Note the question mark to indicate a *nullable* type.
  // We use 'null' to represent an empty list.
  ghost var Repr: set<object>

  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  {
    this in Repr &&
      (next != null ==> next in Repr && next.Repr <= Repr && this !in next.Repr && next.Valid())
      // Same pattern as above, just with a guard for whether 'next' is null.
  }

  // Let's specify linked lists by mapping them to their sequences of data
  // values.
  ghost function Elements(): seq<T>
    reads Repr
    requires Valid()
    // Interesting aspect here: Dafny infers 'decreases Repr' by default, copying a set
    // that we read or modify!
  {
    if next == null then
      [data]
    else
      [data] + next.Elements()
  }

  constructor (data: T, next: LinkedListNode?<T>)
    requires next != null ==> next.Valid()
    ensures Valid()
    ensures next == null ==> Elements() == [data] && fresh(Repr)
    ensures next != null ==> Elements() == [data] + next.Elements() && fresh(Repr - next.Repr)
  {
    this.data := data;
    this.next := next;
    if next == null {
      Repr := {this};
    } else {
      Repr := {this} + next.Repr;
    }
  }

  function Length(): nat
    reads Repr
    requires Valid()
    ensures Length() == |Elements()|
  {
    if next == null then
      1
    else
      1 + next.Length()
  }

  function Get(i: nat): T
    reads Repr
    requires Valid()
    requires i < Length()
    ensures Get(i) == Elements()[i]
  {
    if i == 0 then
      data
    else
      // Dafny figures out that i < Length() and i != 0 imply Length() >= 2, so
      // next is not null.
      next.Get(i - 1)
  }

  method Set(i: nat, v: T)
    modifies Repr
    requires Valid()
    requires i < Length()
    ensures Valid()
    ensures Repr == old(Repr)
    ensures Elements() == old(Elements())[i := v]
    // Note careful use of 'old' to cover complete method calls.
  {
    if i == 0 {
      data := v;
    } else {
      next.Set(i - 1, v);
    }
  }
}

// Now let's wrap all that up into a class for representing sequences,
// hiding our LinkedListNode representation.
class LinkedList<T> {
  var head: LinkedListNode?<T>
  ghost var Repr: set<object>

  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  {
    this in Repr &&
      (head != null ==> head in Repr && head.Repr <= Repr && this !in head.Repr && head.Valid())
  }

  ghost function Elements(): seq<T>
    reads Repr
    requires Valid()
  {
    if head == null then
      []
    else
      head.Elements()
  }

  constructor ()
    ensures Valid()
    ensures Elements() == []
    ensures fresh(Repr)
    // Important: every new linked list is disjoint from those allocated before.
  {
    this.head := null;
    Repr := {this};
  }

  predicate Empty()
    reads Repr
    requires Valid()
    ensures Empty() == (Length() == 0)
  {
    head == null
  }

  function Length(): nat
    reads Repr
    requires Valid()
    ensures Length() == |Elements()|
  {
    if head == null then
      0
    else
      head.Length()
  }

  function Get(i: nat): T
    reads Repr
    requires Valid()
    requires i < Length()
    ensures Get(i) == Elements()[i]
  {
    // Precondition implies head != null!
    head.Get(i)
  }

  method Set(i: nat, v: T)
    modifies Repr
    requires Valid()
    requires i < Length()
    ensures Valid()
    ensures Repr == old(Repr)
    ensures Elements() == old(Elements())[i := v]
  {
    head.Set(i, v);
  }

  // Two more methods, for modifying the list at its front.

  method Push(v: T)
    modifies Repr
    requires Valid()
    ensures Valid()
    ensures fresh(Repr - old(Repr))
    ensures Elements() == [v] + old(Elements())
  {
    head := new LinkedListNode(v, head);
    Repr := {this} + head.Repr;
  }

  method Pop() returns (v: T)
    modifies Repr
    requires Valid()
    requires Length() > 0
    ensures Valid()
    ensures v == old(Elements())[0]
    ensures Elements() == old(Elements())[1..]
    ensures Repr < old(Repr)
    // We might often not bother to shrink Repr sets as elements disappear, but
    // this shrinking set is helpful to support a termination argument below.
  {
    Repr := Repr - {head};
    v := head.data;
    head := head.next;
  }
}

// We'll use the following to specify reversal of linked lists.
ghost function Reverse<T>(s: seq<T>): seq<T> {
  seq(|s|, i requires 0 <= i < |s| => s[|s|-i-1])
}

// Let's do destructive reversal of a linked list.
method ReverseList<T>(ls: LinkedList<T>) returns (ls': LinkedList<T>)
  requires ls.Valid()
  modifies ls.Repr
  ensures ls'.Valid()
  ensures fresh(ls'.Repr)
  ensures ls'.Elements() == Reverse(old(ls.Elements()))
{
  ls' := new LinkedList();
  while !ls.Empty()
    invariant ls.Valid()
    invariant ls'.Valid()
    invariant fresh(ls'.Repr)
    invariant Reverse(ls.Elements()) + ls'.Elements() == Reverse(old(ls.Elements()))
    decreases ls.Repr
  {
    var v := ls.Pop();
    ls'.Push(v);
  }
}

Exercises

class23/coffeemaker.dfy
dfy
// The coffee machine

class Grinder {
  var HasBeans: bool
  ghost predicate Valid()
    reads this
  constructor ()
    ensures Valid()
  method AddBeans()
    requires Valid()
    modifies this
    ensures Valid() && HasBeans
  method Grind()
    requires Valid() && HasBeans
    modifies this
    ensures Valid()
}

class WaterTank {
  var Level: nat
  ghost predicate Valid()
    reads this
  constructor ()
    ensures Valid()
  method Fill()
    requires Valid()
    modifies this
    ensures Valid() && Level == 10
  method Use()
    requires Valid() && Level != 0
    modifies this
    ensures Valid() && Level == old(Level) - 1
}

class Cup {
  constructor ()
}

class CoffeeMaker {

  var g: Grinder
  var w: WaterTank
  ghost var Repr: set<object>

  ghost predicate Valid()
    reads this, Repr
  {
    this in Repr && g in Repr && g.Valid () && w in Repr && w.Valid()
  }

  constructor ()
    ensures Valid()
  {
    g := new Grinder();
    w := new WaterTank();
    Repr := {this, g, w};
  }

  predicate Ready()
    requires Valid()
    reads Repr
  {
    g.HasBeans && 2 <= w.Level
  }

  method Restock()
    requires Valid()
    modifies Repr
    ensures Valid() && Ready()
  {
    g.AddBeans();
    w.Fill();
  }

  method Dispense(double: bool) returns (c: Cup)
    requires Valid() && Ready()
    modifies Repr
    ensures Valid()
  {
    g.Grind();
    if double {
      w.Use(); w.Use();
    } else {
      w.Use();
    }
    c := new Cup();
  }
}

method CoffeeTestHarness() {
  var cm := new CoffeeMaker();
  cm.Restock();
  var c := cm.Dispense(true);
}
class23/dynamicframes.dfy
dfy
class Grinder {
  var HasBeans: bool
  ghost var Repr: set<object>
  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  constructor ()
    ensures Valid() && fresh(Repr)
  method AddBeans()
    requires Valid()
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr)) && HasBeans
}

class WaterTank {
  var Level: nat
  ghost var Repr: set<object>
  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  constructor ()
    ensures Valid() && fresh(Repr)
  method Fill()
    requires Valid()
    modifies Repr
    ensures Valid() && fresh(Repr - old(Repr)) && Level == 10
}

class Cup {
  constructor ()
}

class CoffeeMaker {

  var g: Grinder
  var w: WaterTank
  ghost var Repr: set<object>

  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  {
    && this in Repr
    && g in Repr && g.Valid()
    && w in Repr && w.Valid()
  }

  constructor ()
    ensures Valid()
    ensures fresh(Repr)
  {
    g := new Grinder();
    w := new WaterTank();
    new;
    Repr := {this, g, w} + g.Repr + w.Repr;
  }

  method Restock()
    requires Valid()
    modifies Repr
    ensures Valid()
    ensures fresh(Repr - old(Repr))
  {
    // assert w.Valid();
    g.AddBeans();
    // assert w.Valid();
    w.Fill();
  }
}

method CoffeeTestHarness() {
  var cm := new CoffeeMaker();
  cm.Restock();
  cm.Restock();
}
class23/llnodeA.dfy
dfy
// Implement Valid() and make small adjustments to the constructor and to the specs so
//   that LinkedListNode and the test method are verified.
// Dafny infers `decreases Repr` for recursive functions with `reads Repr`!
// Do *not* override any of the default `decreases` clauses.

class LinkedListNode<T> {
  var data: T
  var next: LinkedListNode?<T>
  ghost var Repr: set<object> // the representation set

  ghost predicate Valid()
    reads this, Repr
    ensures Valid() ==> this in Repr
  {
    true
  }

  constructor (data: T, next: LinkedListNode?<T>)
    ensures Valid()
  {
    this.data := data;
    this.next := next;
  }

  function Length(): nat
    reads Repr
    requires Valid()
  {
    if next == null then
      1
    else
      1 + next.Length()
  }

  function Get(i: nat): T
    reads Repr
    requires Valid()
  {
    if i == 0 then
      data
    else
      next.Get(i - 1)
  }
}

method LinkedListNodeTest1() {
  var one := new LinkedListNode(1, null);
  var two := new LinkedListNode(2, one);
  var i := 0;
  while i < two.Length()
  {
    var elt := two.Get(i);
    i := i + 1;
  }
}
class23/llnodeB.dfy
dfy
{
  // Add this function to LinkedListNode:

  ghost function Elements(): seq<T>
    reads Repr
    requires Valid()
  {
    if next == null then
      [data]
    else
      [data] + next.Elements()
  }

}

// And this new test method at the bottom of the file:

method LinkedListNodeTest2() {
  var one := new LinkedListNode(1, null);
  var two := new LinkedListNode(2, one);
  assert two.Length() == 2;
  assert two.Get(0) == 2;
  assert two.Get(1) == 1;
}
class23/llnodeC.dfy
dfy
{
  // Add this method to LinkedListNode:

  method Set(i: nat, v: T)
    modifies Repr
    requires Valid()
    requires i < Length()
    ensures Valid()
  {
    if i == 0 {
      data := v;
    } else {
      next.Set(i - 1, v);
    }
  }

}

// And this new test method at the bottom of the file:

method LinkedListNodeTest3() {
  var one := new LinkedListNode(1, null);
  var two := new LinkedListNode(2, one);
  two.Set(1, 5);
  assert two.Get(0) == 2;
  assert two.Get(1) == 5;
}
Copyright 6.S057 course staff.