6.S057: 6.S057: Verified Software Engineering

Class 21

class21.dfy
dfy
// Here is another classic sorting algorithm, quicksort.
//   https://en.wikipedia.org/wiki/Quicksort
// First, we copy a predicate from last time.
  
ghost predicate SplitPoint(a: array<int>, n: int)
  requires 0 <= n <= a.Length
  reads a
{
  forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]
}

// Now, quicksort with the same spec as we used for sorting last time.
method Quicksort(a: array<int>)
  modifies a
  ensures forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
  ensures multiset(a[..]) == old(multiset(a[..]))
{
  QuicksortAux(a, 0, a.Length);
}

// This auxiliary method does most of the work.
method QuicksortAux(a: array<int>, lo: int, hi: int)
  requires 0 <= lo <= hi <= a.Length
  modifies a
  requires SplitPoint(a, lo) && SplitPoint(a, hi)
  ensures forall i, j :: lo <= i < j < hi ==> a[i] <= a[j]
  ensures SwapFrame(a, lo, hi)
  ensures SplitPoint(a, lo) && SplitPoint(a, hi)
  decreases hi - lo
{
  if 2 <= hi - lo {
    var p := Partition(a, lo, hi);
    QuicksortAux(a, lo, p);
    QuicksortAux(a, p + 1, hi);
  }
}

// A *twostate* predicate can use "old"!
// This predicate captures what is not allowed to change during a call.
twostate predicate SwapFrame(a: array<int>, lo: int, hi: int)
  requires 0 <= lo <= hi <= a.Length
  reads a
{
  (forall i :: 0 <= i < lo || hi <= i < a.Length ==> a[i] == old(a[i])) &&
  multiset(a[..]) == old(multiset(a[..]))
}

method Partition(a: array<int>, lo: int, hi: int) returns (p: int)
  requires 0 <= lo < hi <= a.Length
  requires SplitPoint(a, lo) && SplitPoint(a, hi)
  modifies a
  ensures lo <= p < hi
  ensures forall i :: lo <= i < p ==> a[i] < a[p]
  ensures forall i :: p <= i < hi ==> a[p] <= a[i]
  ensures SplitPoint(a, lo) && SplitPoint(a, hi)
  ensures SwapFrame(a, lo, hi)
{
  var pivot := a[lo];
  var m, n := lo + 1, hi;
  while m < n
    invariant lo + 1 <= m <= n <= hi
    invariant a[lo] == pivot
    invariant forall i :: lo + 1 <= i < m ==> a[i] < pivot
    invariant forall i :: n <= i < hi ==> pivot <= a[i]
    invariant SplitPoint(a, lo) && SplitPoint(a, hi)
    invariant SwapFrame(a, lo, hi)
  {
    if a[m] < pivot {
      m := m + 1;
    } else {
      a[m], a[n-1] := a[n-1], a[m];
      n := n - 1;
    }
  }

  a[lo], a[m - 1] := a[m - 1], a[lo];
  return m - 1;
}


// In time remaining after we wrap up sorting, let's take a look at *dynamic
// programming* problems.  Check out this Wikipedia summary of the technique:
//   https://en.wikipedia.org/wiki/Dynamic_programming

// 0-1 knapsack problem

// In this problem, we are given an array of integers and need to find the
// largest subset of the elements that can be added to form a total below some
// limit.  To formalize the elements of correctness one-at-a-time:

// Let's start with an easy one: sum of a sequence.
ghost function Sum(s: seq<nat>): nat {
  if |s| == 0 then
    0
  else
    s[0] + Sum(s[1..])
}

// This predicate characterizes when a chosen sequence represents a legit
// subsequence of another one *and* has a claimed sum total.
ghost predicate PossibleTotalVia(s: seq<nat>, total: nat, chosen: seq<nat>) {
  multiset(chosen) <= multiset(s) && total == Sum(chosen)
}

// The following hides the choice of subsequence, using existential
// quantification.
ghost predicate PossibleTotal(s: seq<nat>, total: nat) {
  exists chosen :: PossibleTotalVia(s, total, chosen)
}

// Now we can characterize what is the maximum possible total that does not
// exceed a limit.
ghost predicate MaxTotal(s: seq<nat>, limit: nat, total: nat) {
  && PossibleTotal(s, total)
  && total <= limit
  && forall total': nat :: PossibleTotal(s, total') && total' <= limit ==> total' <= total
}

function Max(a: nat, b: nat): nat {
  if a < b then
    b
  else
    a
}

// Now we can define our implementation with nested loops.
// There is a lot of detail here!
// We will only comment on a few parts of it.
method ZeroOneKnapsack(weights: array<nat>, limit: nat) returns (total: nat)
  ensures MaxTotal(weights[..], limit, total)
{
  if weights.Length == 0 {
    assert PossibleTotalVia(weights[..], 0, []);
    assert multiset(weights[..]) == multiset{};
    return 0;
  }

  var table := new nat[weights.Length, limit+1];
  // We create a two-dimensional table, where... well, why explain it here in
  // English when we are about to do so in a loop invariant? ;-)

  var i := 0;
  while i < weights.Length
    invariant 0 <= i <= weights.Length
    invariant forall i', j' :: 0 <= i' < i && 0 <= j' <= limit ==> MaxTotal(weights[..i'+1], j', table[i', j'])
    // There you go.  The above invariant explains exactly the intended meaning
    // of every table cell.  Well, it skips cells that haven't been filled in
    // yet, but just imagine i == weights.Length to see the full property.
  {
    var j := 0;
    while j <= limit
      invariant 0 <= j <= limit+1
      invariant forall i', j' :: 0 <= i' < i && 0 <= j' <= limit ==> MaxTotal(weights[..i'+1], j', table[i', j'])
      invariant forall j' :: 0 <= j' < j ==> MaxTotal(weights[..i+1], j', table[i, j'])
      // The invariants here just cover the pattern of filling in cells.
    {
      ghost var i1 := i + 1;
      if i == 0 {
        if weights[i] == 0 || weights[i] > j {
          table[i, j] := 0;
          assert PossibleTotalVia(weights[..i1], table[i, j], []);
          forall total': nat | PossibleTotal(weights[..i1], total') && total' <= j ensures total' <= table[i, j] {
            var s :| PossibleTotalVia(weights[..i1], total', s);
            MultisetLe(multiset(s), multiset(weights[..i1]));
            assert s == [] || s == [weights[i]];
            if s == [weights[i]] {
              assert Sum(s) == weights[i];
            }
          }
        } else {
          table[i, j] := weights[i];
          assert PossibleTotalVia(weights[..i1], table[i, j], [weights[i]]);
          forall total': nat | PossibleTotal(weights[..i1], total') && total' <= j ensures total' <= table[i, j] {
            var s :| PossibleTotalVia(weights[..i1], total', s);
            MultisetLe(multiset(s), multiset(weights[..i1]));
            assert s == [] || s == [weights[i]];
          }
        }
      } else if weights[i] == 0 {
        table[i, j] := table[i-1, j];
        ghost var s :| PossibleTotalVia(weights[..i], table[i-1, j], s);
        assert multiset(s) <= multiset(weights[..i1]);
        assert PossibleTotalVia(weights[..i1], table[i, j], s);
        forall total': nat | PossibleTotal(weights[..i1], total') && total' <= j ensures total' <= table[i, j] {
          var s :| PossibleTotalVia(weights[..i1], total', s);
          if pos :| 0 <= pos < |s| && s[pos] == 0 {
            SumRemove(s, pos);
            assert s == s[..pos] + [0] + s[pos+1..];
            assert multiset(s) == multiset(s[..pos]) + multiset{0} + multiset(s[pos+1..]);
            assert PossibleTotalVia(weights[..i], total', s[..pos] + s[pos+1..]);
            assert PossibleTotal(weights[..i], total');
          } else {
            assert PossibleTotalVia(weights[..i], total', s);
            assert PossibleTotal(weights[..i], total');
          }
        }
      } else if weights[i] > j {
        table[i, j] := table[i-1, j];
        ghost var s :| PossibleTotalVia(weights[..i], table[i-1, j], s);
        assert PossibleTotalVia(weights[..i1], table[i, j], s);
        forall total': nat | PossibleTotal(weights[..i1], total') && total' <= j ensures total' <= table[i, j] {
          ghost var s :| PossibleTotalVia(weights[..i1], total', s);
          assert weights[i] !in s by {
            if pos :| 0 <= pos < |s| && s[pos] == weights[i] {
              SumRemove(s, pos);
            }
          }
          assert PossibleTotalVia(weights[..i], total', s);
          assert PossibleTotal(weights[..i], total');
        }
      } else if table[i-1, j-weights[i]] + weights[i] > limit {
        table[i, j] := table[i-1, j];
      } else {
        // This last case happens to be the straw that break's the timeout camel's back.
        // The main reasoning is factored out into a lemma, which gets a separate timeout limit.
        KnapsackMaxCase(weights, limit, table, i, j);
        table[i, j] := Max(table[i-1, j-weights[i]] + weights[i], table[i-1, j]);
      }
      
      j := j + 1;
    }

    i := i + 1;
  }

  assert weights[..weights.Length] == weights[..];
  return table[weights.Length-1, limit];
}

lemma KnapsackMaxCase(weights: array<nat>, limit: nat, table: array2<nat>, i: nat, j: nat)
  requires weights.Length != 0
  requires 0 < i < weights.Length
  requires 0 <= j < limit+1
  requires table.Length0 == weights.Length
  requires table.Length1 == limit+1
  requires weights[i] != 0
  requires weights[i] <= j
  requires table[i-1, j-weights[i]] + weights[i] <= limit
  requires forall i', j' :: 0 <= i' < i && 0 <= j' <= limit ==> MaxTotal(weights[..i'+1], j', table[i', j'])
  requires forall j' :: 0 <= j' < j ==> MaxTotal(weights[..i+1], j', table[i, j'])
  ensures MaxTotal(weights[..i+1], j, Max(table[i-1, j-weights[i]] + weights[i], table[i-1, j]))
{
  var i1 := i + 1;
  var newCell := Max(table[i-1, j-weights[i]] + weights[i], table[i-1, j]);
  if table[i-1, j-weights[i]] + weights[i] > table[i-1, j] {
    var s :| PossibleTotalVia(weights[..i], table[i-1, j-weights[i]], s);
    assert PossibleTotalVia(weights[..i1], newCell, [weights[i]] + s);
    forall total': nat | PossibleTotal(weights[..i1], total') && total' <= j ensures total' <= newCell {
      var s :| PossibleTotalVia(weights[..i1], total', s);
      if pos :| 0 <= pos < |s| && s[pos] == weights[i] {
        SumRemove(s, pos);
        assert s == s[..pos] + [weights[i]] + s[pos+1..];
        assert multiset(s) == multiset(s[..pos] + [weights[i]] + s[pos+1..]);
        assert PossibleTotalVia(weights[..i], total' - weights[i], s[..pos] + s[pos+1..]);
        assert PossibleTotal(weights[..i], total' - weights[i]);
      } else {
        assert PossibleTotalVia(weights[..i], total', s);
        assert PossibleTotal(weights[..i], total');
      }
    }
  } else {
    var s :| PossibleTotalVia(weights[..i], table[i-1, j], s);
    assert PossibleTotalVia(weights[..i1], newCell, s);
    forall total': nat | PossibleTotal(weights[..i1], total') && total' <= j ensures total' <= newCell {
      var s :| PossibleTotalVia(weights[..i1], total', s);
      if pos :| 0 <= pos < |s| && s[pos] == weights[i] {
        SumRemove(s, pos);
        assert s == s[..pos] + [weights[i]] + s[pos+1..];
        assert multiset(s) == multiset(s[..pos] + [weights[i]] + s[pos+1..]);
        assert PossibleTotalVia(weights[..i], total' - weights[i], s[..pos] + s[pos+1..]);
        assert PossibleTotal(weights[..i], total' - weights[i]);
      } else {
        assert PossibleTotalVia(weights[..i], total', s);
        assert PossibleTotal(weights[..i], total');
      }
    }
  }
}

// Two lemmas that kinda speak for themselves:

lemma SumRemove(s: seq<nat>, i: nat)
  requires 0 <= i < |s|
  ensures Sum(s) == Sum(s[..i] + s[i+1..]) + s[i]
{
  if |s| == 0 {
  } else if i == 0 {
  } else {
    calc {
      Sum(s);
      s[0] + Sum(s[1..]);
      { SumRemove(s[1..], i-1); }
      s[0] + Sum(s[1..][..i-1] + s[1..][i..]) + s[1..][i-1];
      { assert s[1..][..i-1] == s[1..i]; assert s[1..][i..] == s[i+1..]; }
      s[0] + Sum(s[1..i] + s[i+1..]) + s[i];
      { assert s[..i] + s[i+1..] == [s[0]] + (s[1..i] + s[i+1..]); }
      Sum(s[..i] + s[i+1..]) + s[i];
    }
  }
}

lemma MultisetLe<T>(a: multiset<T>, b: multiset<T>)
  requires a <= b
  ensures |a| <= |b|
{
  if x :| x in a {
    MultisetLe(a - multiset{x}, b - multiset{x});
  }
}


// Floyd-Warshall algorithm

// Let's go after another classic:
//   https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm

// Throughout, we represent a graph as a two-dimensional array of weights -- an
// *adjacency matrix*.  Nodes of the graph are natural numbers, corresponding to
// indices within the array.

datatype Option<T> = None | Some(value: T)

// This function computes the length (weight sum) of a *valid* path through the
// graph.  It returns None when the path is invalid.
ghost function PathLength(ws: array2<Option<nat>>, p: seq<nat>): Option<nat>
  reads ws
{
  if |p| <= 1 then
    Some(0)
  else if p[0] >= ws.Length0 || p[1] >= ws.Length1 || ws[p[0], p[1]].None? then
    None
  else
    match PathLength(ws, p[1..])
    case None => None
    case Some(l) => Some(ws[p[0], p[1]].value + l)
}

// And here is what makes a path internally consistent w.r.t. a source and
// destination.
ghost predicate Path(ws: array2<Option<nat>>, src: nat, dst: nat, p: seq<nat>)
  reads ws
{
  && |p| >= 2
  && p[0] == src
  && p[|p|-1] == dst
}

// The above but with a required distance
ghost predicate PathOfDistance(ws: array2<Option<nat>>, src: nat, dst: nat, dist: nat)
  reads ws
{
  exists p: seq<nat> :: Path(ws, src, dst, p) && PathLength(ws, p) == Some(dist)
}

// Now we can characterize what makes a valid shortest-path length.
// A length of None represents "infinity."
ghost predicate ShortestPath(ws: array2<Option<nat>>, src: nat, dst: nat, dist: Option<nat>)
  reads ws
{
  match dist
  case None => forall dist' :: !PathOfDistance(ws, src, dst, dist')
  case Some(dist) =>
    && PathOfDistance(ws, src, dst, dist)
    && forall dist': nat :: PathOfDistance(ws, src, dst, dist') ==> dist' >= dist
}

// Now we redo some of the last few definitions with an extra parameter
// *maxNode*.  We only allow *intermediate* nodes of paths that are *less than*
// this bound.

ghost predicate PathUsing(ws: array2<Option<nat>>, maxNode: nat, src: nat, dst: nat, p: seq<nat>)
  reads ws
{
  && |p| >= 2
  && p[0] == src
  && p[|p|-1] == dst
  && forall i :: 0 < i < |p|-1 ==> p[i] < maxNode
}

ghost predicate PathOfDistanceUsing(ws: array2<Option<nat>>, maxNode: nat, src: nat, dst: nat, dist: nat)
  reads ws
{
  exists p: seq<nat> :: PathUsing(ws, maxNode, src, dst, p) && PathLength(ws, p) == Some(dist)
}

ghost predicate ShortestPathUsing(ws: array2<Option<nat>>, maxNode: nat, src: nat, dst: nat, dist: Option<nat>)
  reads ws
{
  match dist
  case None => forall dist' :: !PathOfDistanceUsing(ws, maxNode, src, dst, dist')
  case Some(dist) =>
    && PathOfDistanceUsing(ws, maxNode, src, dst, dist)
    && forall dist': nat :: PathOfDistanceUsing(ws, maxNode, src, dst, dist') ==> dist' >= dist
}

// OK, this next type will be important for how we state key invariants.  We
// always convert two-dimensional arrays into this type so that we can reason
// about them functionally.
type FuncArray = seq<seq<Option<nat>>>

// Here's the canonical conversion.
ghost function FuncOfArray(ds: array2<Option<nat>>): FuncArray
  reads ds
{
  seq(ds.Length0, i requires 0 <= i < ds.Length0 reads ds =>
    seq(ds.Length1, j requires 0 <= j < ds.Length1 reads ds =>
      ds[i, j]))
  // Sequence comprehensions: neat!
}

// We found that Dafny kept timing out with loop invariants expressed directly
// with quantifiers, so this recursive function function captures the same
// property.
ghost predicate Distances(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1
  requires 0 <= k <= ws.Length0
  requires 0 <= i <= ws.Length0
  requires 0 <= j <= ws.Length1
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  reads ws
  decreases ws.Length0 - src, ws.Length1 - dst
{
  if src == ws.Length0 then
    true
  else if dst == ws.Length1 then
    Distances(ws, ds, k, i, j, src+1, 0)
  else
    0 <= src < |ds| && 0 <= dst < |ds[src]|
    && ShortestPathUsing(ws, if src < i || (src == i && dst < j) then k+1 else k, src, dst, ds[src][dst]) && Distances(ws, ds, k, i, j, src, dst+1)
}

// Finally the Floyd-Warshall implementation!
method AllPairsShortestPaths(ws: array2<Option<nat>>) returns (ds: array2<Option<nat>>)
  requires ws.Length0 == ws.Length1
  ensures ds.Length0 == ds.Length1 == ws.Length0
  ensures forall src, dst :: 0 <= src < ws.Length0 && 0 <= dst < ws.Length1 ==> ShortestPath(ws, src, dst, ds[src, dst])
  // Nice elegant characterization of correctness, huh?
{
  // We mostly won't narrate this method, either, but see a few comments for
  // highlights.
  
  ds := new [ws.Length0, ws.Length1];
  if ws.Length0 == 0 {
    return;
  }
  
  forall u, v | 0 <= u < ws.Length0 && 0 <= v < ws.Length1 {
    ds[u, v] := ws[u, v];
  }
  
  var k := 0;
  AllPairsInit(ws, FuncOfArray(ds), 0, 0);
  while k < ws.Length0
    invariant 0 <= k <= ws.Length0
    invariant Distances(ws, FuncOfArray(ds), k, 0, 0, 0, 0)
  {
    var i := 0;
    while i < ws.Length0
      invariant 0 <= i <= ws.Length0
      invariant Distances(ws, FuncOfArray(ds), k, i, 0, 0, 0)
    {
      var j := 0;
      while j < ws.Length1
        invariant 0 <= j <= ws.Length1
        invariant Distances(ws, FuncOfArray(ds), k, i, j, 0, 0)
      {
        // Trick here!  Save the array values *before* we change them, so we can
        // refer to before-vs.-after versions in assertions.
        ghost var old_ds := FuncOfArray(ds);
        
        match (ds[i, k], ds[k, j]) {
          case (Some(d1), Some(d2)) => {
            match ds[i, j]
            case None =>
              ShortestPathStep1(ws, FuncOfArray(ds), k, i, j);
              ds[i, j] := Some(d1 + d2);
            case Some(d) =>
              if d > d1 + d2 {
                ShortestPathStep2(ws, FuncOfArray(ds), k, i, j);
                ds[i, j] := Some(d1 + d2);
              } else {
                ShortestPathStep3(ws, FuncOfArray(ds), k, i, j);
              }
          }
          case _ => ShortestPathStep4(ws, FuncOfArray(ds), k, i, j);
        }

        // We use the old array values in exactly this lemma call.
        Loop1Next(ws, old_ds, FuncOfArray(ds), k, i, j, 0, 0);
        j := j + 1;
      }

      Loop2Next(ws, FuncOfArray(ds), k, i, 0, 0);
      i := i + 1;
    }

    Loop3Next(ws, FuncOfArray(ds), k, 0, 0);
    k := k + 1;
  }

  AllPairsFinish(ws, FuncOfArray(ds), 0, 0);
  forall src, dst | 0 <= src < ws.Length0 && 0 <= dst < ws.Length1 ensures ShortestPath(ws, src, dst, ds[src, dst]) {
    assert ds[src, dst] == FuncOfArray(ds)[src][dst];
  }
}

// We proved quite a few lemmas, and in general they aren't short.

lemma AllPairsInit(ws: array2<Option<nat>>, ds: FuncArray, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds' :: ds' in ds ==> |ds'| == ws.Length1
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  requires forall i, j :: 0 <= i < ws.Length0 && 0 <= j < ws.Length1 ==> 0 <= i < |ds| && 0 <= j < |ds[i]| && ds[i][j] == ws[i, j]
  ensures Distances(ws, ds, 0, 0, 0, src, dst)
  decreases ws.Length0 - src, ws.Length1 - dst
{
  if src != ws.Length0 && dst != ws.Length1 {
    assert ShortestPathUsing(ws, 0, src, dst, ds[src][dst]) by {
      match ds[src][dst]
      case None =>
      case Some(dist) =>
        var p := [src, dst];
        assert PathUsing(ws, 0, src, dst, p);
        assert PathLength(ws, p) == Some(dist);
    }
  }
}

lemma AllPairsFinish(ws: array2<Option<nat>>, ds: FuncArray, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds' :: ds' in ds ==> |ds'| == ws.Length1
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  requires Distances(ws, ds, ws.Length0, 0, 0, src, dst)
  ensures forall i, j :: src <= i < ws.Length0 && ((i == src && dst <= j < ws.Length1) || (i > src && 0 <= j < ws.Length1)) ==> 0 <= i < |ds| && 0 <= j < |ds[i]| && ShortestPath(ws, i, j, ds[i][j])
  decreases ws.Length0 - src, ws.Length1 - dst
{
  if src != ws.Length0 && dst != ws.Length1 {
    forall i, j | src <= i < ws.Length0 && ((i == src && dst <= j < ws.Length1) || (i > src && 0 <= j < ws.Length1)) ensures ShortestPath(ws, i, j, ds[i][j]) {
      if i == src && j == dst {
        ShortestPathAll(ws, i, j, ds[i][j]);
      }
    }
  }
}

lemma ShortestPathAll(ws: array2<Option<nat>>, src: nat, dst: nat, dist: Option<nat>)
  requires ShortestPathUsing(ws, ws.Length0, src, dst, dist)
  ensures ShortestPath(ws, src, dst, dist)
{
  match dist
  case None =>
    forall dist': nat | PathOfDistance(ws, src, dst, dist') ensures false {
      PathNoLongerUsing(ws, src, dst, dist');
    }
  case Some(dist) =>
    forall dist': nat | PathOfDistance(ws, src, dst, dist') ensures dist' >= dist {
      PathNoLongerUsing(ws, src, dst, dist');
    }
}

lemma PathNoLongerUsing(ws: array2<Option<nat>>, src: nat, dst: nat, dist: nat)
  requires PathOfDistance(ws, src, dst, dist)
  ensures PathOfDistanceUsing(ws, ws.Length0, src, dst, dist)
{
  var p :| Path(ws, src, dst, p) && PathLength(ws, p) == Some(dist);
  assert PathOfDistanceUsing(ws, ws.Length0, src, dst, dist) by {
    forall i | 0 < i < |p|-1 ensures p[i] < ws.Length0 {
      PathLengthBound(ws, p, i, dist);
    }
    assert PathUsing(ws, ws.Length0, src, dst, p);
  }
}

lemma PathLengthBound(ws: array2<Option<nat>>, p: seq<nat>, i: nat, dist: nat)
  requires 0 < i < |p|-1
  requires PathLength(ws, p) == Some(dist)
  ensures p[i] < ws.Length0
{
  if |p| <= 1 {
  } else if p[0] >= ws.Length0 || p[1] >= ws.Length1 || ws[p[0], p[1]].None? {
  } else {
    match PathLength(ws, p[1..])
    case None =>
    case Some(l) =>
      if i > 1 {
        PathLengthBound(ws, p[1..], i-1, dist - ws[p[0], p[1]].value);
      }
  }
}

lemma Loop1Next(ws: array2<Option<nat>>, ds: FuncArray, ds': FuncArray, k: nat, i: nat, j: nat, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1 == |ds| == |ds'|
  requires forall ds0 :: ds0 in ds ==> |ds0| == ws.Length1
  requires forall ds0 :: ds0 in ds' ==> |ds0| == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= i < ws.Length0
  requires 0 <= j < ws.Length0
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  requires Distances(ws, ds, k, i, j, src, dst)
  requires ShortestPathUsing(ws, k+1, i, j, ds'[i][j])
  requires forall i', j' :: 0 <= i' < ws.Length0 && 0 <= j' < ws.Length1 && (i' != i || j' != j) ==> ds'[i'][j'] == ds[i'][j']
  ensures Distances(ws, ds', k, i, j+1, src, dst)
  decreases ws.Length0 - src, ws.Length1 - dst
{
  if src == ws.Length0 {
  } else if dst == ws.Length1 {
    Loop1Next(ws, ds, ds', k, i, j, src+1, 0);
  } else {
    Loop1Next(ws, ds, ds', k, i, j, src, dst+1);
  }
}

lemma Loop2Next(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= i < ws.Length0
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  requires Distances(ws, ds, k, i, ws.Length1, src, dst)
  ensures Distances(ws, ds, k, i+1, 0, src, dst)
  decreases ws.Length0 - src, ws.Length1 - dst
{
}

lemma Loop3Next(ws: array2<Option<nat>>, ds: FuncArray, k: nat, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  requires Distances(ws, ds, k, ws.Length0, 0, src, dst)
  ensures Distances(ws, ds, k+1, 0, 0, src, dst)
  decreases ws.Length0 - src, ws.Length1 - dst
{
}

lemma DistanceCorrect(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat, src: nat, dst: nat, i': nat, j': nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds' :: ds' in ds ==> |ds'| == ws.Length1
  requires 0 <= k <= ws.Length0
  requires 0 <= i <= ws.Length0
  requires 0 <= j <= ws.Length1
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  requires Distances(ws, ds, k, i, j, src, dst)
  requires 0 <= i' < ws.Length0
  requires 0 <= j' < ws.Length1
  requires i' > src || (i' == src && j' >= dst)
  ensures ShortestPathUsing(ws, if i' < i || (i' == i && j' < j) then k + 1 else k, i', j', ds[i'][j'])
  decreases ws.Length0 - src, ws.Length1 - dst
{
}

lemma DistanceCorrectNone(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat, i': nat, j': nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds' :: ds' in ds ==> |ds'| == ws.Length1
  requires 0 <= k <= ws.Length0
  requires 0 <= i <= ws.Length0
  requires 0 <= j <= ws.Length1
  requires Distances(ws, ds, k, i, j, 0, 0)
  requires 0 <= i' < ws.Length0
  requires 0 <= j' < ws.Length1
  requires ds[i'][j'].None?
  ensures forall dist' :: !PathOfDistanceUsing(ws, k, i', j', dist')
{
  DistanceCorrect(ws, ds, k, i, j, 0, 0, i', j');
  if ShortestPathUsing(ws, k, i', j', ds[i'][j']) {
  } else {
    assert ShortestPathUsing(ws, k+1, i', j', ds[i'][j']);
    forall dist' | PathOfDistanceUsing(ws, k, i', j', dist') ensures false {
      assert PathOfDistanceUsing(ws, k+1, i', j', dist');
    }
  }
}

lemma DistanceCorrectSome(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat, i': nat, j': nat, dist: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds' :: ds' in ds ==> |ds'| == ws.Length1
  requires 0 <= k <= ws.Length0
  requires 0 <= i <= ws.Length0
  requires 0 <= j <= ws.Length1
  requires Distances(ws, ds, k, i, j, 0, 0)
  requires 0 <= i' < ws.Length0
  requires 0 <= j' < ws.Length1
  requires ds[i'][j'].Some?
  requires PathOfDistanceUsing(ws, k, i', j', dist)
  ensures dist >= ds[i'][j'].value
{
  var p :| PathUsing(ws, k, i', j', p) && PathLength(ws, p) == Some(dist);
  DistanceCorrect(ws, ds, k, i, j, 0, 0, i', j');
  if ShortestPathUsing(ws, k, i', j', ds[i'][j']) {
  } else {
    assert ShortestPathUsing(ws, k+1, i', j', ds[i'][j']);
    assert PathOfDistanceUsing(ws, k+1, i', j', dist);
  }
}

lemma ShortestPathStep1(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds0 :: ds0 in ds ==> |ds0| == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= i < ws.Length0
  requires 0 <= j < ws.Length0
  requires Distances(ws, ds, k, i, j, 0, 0)
  requires ds[i][k].Some?
  requires ds[k][j].Some?
  requires ds[i][j].None?
  ensures ShortestPathUsing(ws, k+1, i, j, Some(ds[i][k].value + ds[k][j].value))
{
  var dist1 := ds[i][k].value;
  var dist2 := ds[k][j].value;
  var dist := dist1 + dist2;
  assert PathOfDistanceUsing(ws, k+1, i, j, dist) by {
    assert PathOfDistanceUsing(ws, k+1, i, k, dist1) by {
      DistanceCorrect(ws, ds, k, i, j, 0, 0, i, k);
    }
    var p1 :| PathUsing(ws, k+1, i, k, p1) && PathLength(ws, p1) == Some(dist1);
    assert PathOfDistanceUsing(ws, k+1, k, j, dist2) by {
      DistanceCorrect(ws, ds, k, i, j, 0, 0, k, j);
    }
    var p2 :| PathUsing(ws, k+1, k, j, p2) && PathLength(ws, p2) == Some(dist2);
    PathLengthConcat(ws, p1, p2, dist1, dist2);
  }
  ghost var k1 := k + 1;
  forall dist': nat | PathOfDistanceUsing(ws, k1, i, j, dist') ensures dist' >= dist {
    var p :| PathUsing(ws, k+1, i, j, p) && PathLength(ws, p) == Some(dist');
    SplitPathAt(ws, p, k, i, j, dist');
    if PathUsing(ws, k, i, j, p) {
      DistanceCorrectNone(ws, ds, k, i, j, i, j);
      assert PathOfDistanceUsing(ws, k, i, j, dist');
    } else {
      var p1, p2, dist1', dist2' :|
        && PathUsing(ws, k, i, k, p1)
        && PathUsing(ws, k, k, j, p2)
        && PathLength(ws, p1) == Some(dist1')
        && PathLength(ws, p2) == Some(dist2')
        && dist1' + dist2' <= dist';
      DistanceCorrectSome(ws, ds, k, i, j, i, k, dist1');
      DistanceCorrectSome(ws, ds, k, i, j, k, j, dist2');
    }
  }
}

lemma ShortestPathStep2(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds0 :: ds0 in ds ==> |ds0| == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= i < ws.Length0
  requires 0 <= j < ws.Length0
  requires Distances(ws, ds, k, i, j, 0, 0)
  requires ds[i][k].Some?
  requires ds[k][j].Some?
  requires ds[i][j].Some?
  requires ds[i][j].value > ds[i][k].value + ds[k][j].value
  ensures ShortestPathUsing(ws, k+1, i, j, Some(ds[i][k].value + ds[k][j].value))
{
  var dist1 := ds[i][k].value;
  var dist2 := ds[k][j].value;
  var dist := dist1 + dist2;
  assert PathOfDistanceUsing(ws, k+1, i, j, dist) by {
    assert PathOfDistanceUsing(ws, k+1, i, k, dist1) by {
      DistanceCorrect(ws, ds, k, i, j, 0, 0, i, k);
    }
    var p1 :| PathUsing(ws, k+1, i, k, p1) && PathLength(ws, p1) == Some(dist1);
    assert PathOfDistanceUsing(ws, k+1, k, j, dist2) by {
      DistanceCorrect(ws, ds, k, i, j, 0, 0, k, j);
    }
    var p2 :| PathUsing(ws, k+1, k, j, p2) && PathLength(ws, p2) == Some(dist2);
    PathLengthConcat(ws, p1, p2, dist1, dist2);
  }
  ghost var k1 := k + 1;
  forall dist': nat | PathOfDistanceUsing(ws, k1, i, j, dist') ensures dist' >= dist {
    var p :| PathUsing(ws, k+1, i, j, p) && PathLength(ws, p) == Some(dist');
    SplitPathAt(ws, p, k, i, j, dist');
    if PathUsing(ws, k, i, j, p) {
      DistanceCorrectSome(ws, ds, k, i, j, i, j, dist');
      assert PathOfDistanceUsing(ws, k, i, j, dist');
    } else {
      var p1, p2, dist1', dist2' :|
        && PathUsing(ws, k, i, k, p1)
        && PathUsing(ws, k, k, j, p2)
        && PathLength(ws, p1) == Some(dist1')
        && PathLength(ws, p2) == Some(dist2')
        && dist1' + dist2' <= dist';
      DistanceCorrectSome(ws, ds, k, i, j, i, k, dist1');
      DistanceCorrectSome(ws, ds, k, i, j, k, j, dist2');
    }
  }
}

lemma ShortestPathStep3(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds0 :: ds0 in ds ==> |ds0| == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= i < ws.Length0
  requires 0 <= j < ws.Length0
  requires Distances(ws, ds, k, i, j, 0, 0)
  requires ds[i][k].Some?
  requires ds[k][j].Some?
  requires ds[i][j].Some?
  requires ds[i][j].value <= ds[i][k].value + ds[k][j].value
  ensures ShortestPathUsing(ws, k+1, i, j, Some(ds[i][j].value))
{
  var dist1 := ds[i][k].value;
  var dist2 := ds[k][j].value;
  var dist := ds[i][j].value;
  assert PathOfDistanceUsing(ws, k+1, i, j, dist) by {
    DistanceCorrect(ws, ds, k, i, j, 0, 0, i, j);
  }
  ghost var k1 := k + 1;
  forall dist': nat | PathOfDistanceUsing(ws, k1, i, j, dist') ensures dist' >= dist {
    var p :| PathUsing(ws, k+1, i, j, p) && PathLength(ws, p) == Some(dist');
    SplitPathAt(ws, p, k, i, j, dist');
    if PathUsing(ws, k, i, j, p) {
      DistanceCorrectSome(ws, ds, k, i, j, i, j, dist');
      assert PathOfDistanceUsing(ws, k, i, j, dist');
    } else {
      var p1, p2, dist1', dist2' :|
        && PathUsing(ws, k, i, k, p1)
        && PathUsing(ws, k, k, j, p2)
        && PathLength(ws, p1) == Some(dist1')
        && PathLength(ws, p2) == Some(dist2')
        && dist1' + dist2' <= dist';
      DistanceCorrectSome(ws, ds, k, i, j, i, k, dist1');
      DistanceCorrectSome(ws, ds, k, i, j, k, j, dist2');
    }
  }
}

lemma ShortestPathStep4(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat)
  requires ws.Length0 == ws.Length1 == |ds|
  requires forall ds0 :: ds0 in ds ==> |ds0| == ws.Length1
  requires 0 <= k < ws.Length0
  requires 0 <= i < ws.Length0
  requires 0 <= j < ws.Length0
  requires Distances(ws, ds, k, i, j, 0, 0)
  requires ds[i][k].None? || ds[k][j].None?
  ensures ShortestPathUsing(ws, k+1, i, j, ds[i][j])
{
  ghost var k1 := k + 1;
  match ds[i][j]
  case None =>
    forall dist': nat | PathOfDistanceUsing(ws, k1, i, j, dist') ensures false {
      var p :| PathUsing(ws, k+1, i, j, p) && PathLength(ws, p) == Some(dist');
      SplitPathAt(ws, p, k, i, j, dist');
      if PathUsing(ws, k, i, j, p) {
        DistanceCorrectNone(ws, ds, k, i, j, i, j);
        assert PathOfDistanceUsing(ws, k, i, j, dist');
      } else {
        var p1, p2, dist1', dist2' :|
          && PathUsing(ws, k, i, k, p1)
          && PathUsing(ws, k, k, j, p2)
          && PathLength(ws, p1) == Some(dist1')
          && PathLength(ws, p2) == Some(dist2')
          && dist1' + dist2' <= dist';
        if ds[i][k].None? {
          DistanceCorrectNone(ws, ds, k, i, j, i, k);
          assert PathOfDistanceUsing(ws, k, i, k, dist1');
        } else {
          DistanceCorrectNone(ws, ds, k, i, j, k, j);
          assert PathOfDistanceUsing(ws, k, k, j, dist2');
        }
      }
    }
  case Some(dist) =>
    assert PathOfDistanceUsing(ws, k+1, i, j, dist) by {
      DistanceCorrect(ws, ds, k, i, j, 0, 0, i, j);
    }
    forall dist': nat | PathOfDistanceUsing(ws, k1, i, j, dist') ensures dist' >= dist {
      var p :| PathUsing(ws, k+1, i, j, p) && PathLength(ws, p) == Some(dist');
      SplitPathAt(ws, p, k, i, j, dist');
      if PathUsing(ws, k, i, j, p) {
        DistanceCorrectSome(ws, ds, k, i, j, i, j, dist');
      } else {
        var p1, p2, dist1', dist2' :|
          && PathUsing(ws, k, i, k, p1)
          && PathUsing(ws, k, k, j, p2)
          && PathLength(ws, p1) == Some(dist1')
          && PathLength(ws, p2) == Some(dist2')
          && dist1' + dist2' <= dist';
        if ds[i][k].None? {
          DistanceCorrectNone(ws, ds, k, i, j, i, k);
          assert PathOfDistanceUsing(ws, k, i, k, dist1');
        } else {
          DistanceCorrectNone(ws, ds, k, i, j, k, j);
          assert PathOfDistanceUsing(ws, k, k, j, dist2');
        }
      }
    }
}

lemma PathLengthConcat(ws: array2<Option<nat>>, p1: seq<nat>, p2: seq<nat>, len1: nat, len2: nat)
  requires PathLength(ws, p1) == Some(len1)
  requires PathLength(ws, p2) == Some(len2)
  requires |p1| >= 1
  requires |p2| >= 1
  requires p1[|p1|-1] == p2[0]
  ensures PathLength(ws, p1 + p2[1..]) == Some(len1 + len2)
{
  if |p1| <= 1 {
  } else if p1[0] >= ws.Length0 || p1[1] >= ws.Length1 || ws[p1[0], p1[1]].None? {
  } else {
    assert (p1 + p2[1..])[1..] == p1[1..] + p2[1..];
    PathLengthConcat(ws, p1[1..], p2, len1 - ws[p1[0], p1[1]].value, len2);
  }
}

lemma PathLengthUnconcat(ws: array2<Option<nat>>, p1: seq<nat>, p2: seq<nat>, len: nat) returns (len1: nat, len2: nat)
  requires |p1| >= 1
  requires |p2| >= 1
  requires p1[|p1|-1] == p2[0]
  requires PathLength(ws, p1 + p2[1..]) == Some(len)
  ensures PathLength(ws, p1) == Some(len1)
  ensures PathLength(ws, p2) == Some(len2)
  ensures len == len1 + len2
{
  if |p1| <= 1 {
    len1 := 0;
    len2 := len;
  } else if p1[0] >= ws.Length0 || p1[1] >= ws.Length1 || ws[p1[0], p1[1]].None? {
    assert false;
  } else {
    assert (p1 + p2[1..])[1..] == p1[1..] + p2[1..];
    var len1', len2' := PathLengthUnconcat(ws, p1[1..], p2, len - ws[p1[0], p1[1]].value);
    len1 := len1' + ws[p1[0], p1[1]].value;
    len2 := len2';
  }
}

lemma SplitPathAt(ws: array2<Option<nat>>, p: seq<nat>, k: nat, src: nat, dst: nat, dist: nat)
  requires PathUsing(ws, k+1, src, dst, p)
  requires PathLength(ws, p) == Some(dist)
  ensures PathUsing(ws, k, src, dst, p)
    || exists p1, p2, dist1, dist2 ::
        && PathUsing(ws, k, src, k, p1)
        && PathUsing(ws, k, k, dst, p2)
        && PathLength(ws, p1) == Some(dist1)
        && PathLength(ws, p2) == Some(dist2)
        && dist1 + dist2 <= dist
  decreases p
{
  if i :| 0 < i < |p|-1 && p[i] == k && forall i' :: 0 < i' < i ==> p[i'] != k {
    var p1 := p[..i+1];
    assert p == p1 + p[i..][1..];
    var len1, len2 := PathLengthUnconcat(ws, p1, p[i..], dist);
    assert PathUsing(ws, k, src, k, p1);
    assert PathUsing(ws, k+1, k, dst, p[i..]);
    var p', dist' := RemoveForbidden(ws, p[i..], k, dst, len2);
  } else {
    forall i | 0 < i < |p|-1 && p[i] == k ensures false {
      MinimizeMatch(i, p, k);
    }
  }
}

lemma MinimizeMatch(i: nat, p: seq<nat>, k: nat)
  requires forall i :: 0 < i < |p|-1 && p[i] == k ==> exists i' :: 0 < i' < i && p[i'] == k
  requires 0 < i < |p|-1
  requires p[i] == k
  ensures false
{
  var i' :| 0 < i' < i && p[i'] == k;
  MinimizeMatch(i', p, k);
}

lemma RemoveForbidden(ws: array2<Option<nat>>, p: seq<nat>, k: nat, dst: nat, dist: nat) returns (p': seq<nat>, dist': nat)
  requires PathUsing(ws, k+1, k, dst, p)
  requires PathLength(ws, p) == Some(dist)
  ensures PathUsing(ws, k, k, dst, p')
  ensures PathLength(ws, p') == Some(dist')
  ensures dist' <= dist
  decreases p
{
  if i :| 0 < i < |p|-1 && p[i] == k {
    assert p == p[..i+1] + p[i..][1..];
    var len1, len2 := PathLengthUnconcat(ws, p[..i+1], p[i..], dist);
    assert PathUsing(ws, k+1, k, dst, p[i..]);
    p', dist' := RemoveForbidden(ws, p[i..], k, dst, len2);
  } else {
    p', dist' := p, dist;
  }
}

Exercises

class21/quicksort.dfy
dfy
ghost predicate SplitPoint(a: array<int>, n: int)
  requires 0 <= n <= a.Length
  reads a
{
  forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]
}

// Now, quicksort with the same spec as we used for sorting last time.
method Quicksort(a: array<int>)
  modifies a
  ensures forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
  ensures multiset(a[..]) == old(multiset(a[..]))
{
  QuicksortAux(a, 0, a.Length);
}

// This auxiliary method does most of the work.
// Try to fill in a good spec for it.
// The body shouldn't need any proof annotations, either.
method QuicksortAux(a: array<int>, lo: int, hi: int)
{
  if 2 <= hi - lo {
    var p := Partition(a, lo, hi);
    QuicksortAux(a, lo, p);
    QuicksortAux(a, p + 1, hi);
  }
}

// Time permitting, see if you can fill in proof annotations for this method, too.
method Partition(a: array<int>, lo: int, hi: int) returns (p: int)
{
  var pivot := a[lo];
  var m, n := lo + 1, hi;
  while m < n
  {
    if a[m] < pivot {
      m := m + 1;
    } else {
      a[m], a[n-1] := a[n-1], a[m];
      n := n - 1;
    }
  }

  a[lo], a[m - 1] := a[m - 1], a[lo];
  return m - 1;
}
class21/knapsack.dfy
dfy
// Let's start with an easy one: sum of a sequence.
ghost function Sum(s: seq<nat>): nat {
  if |s| == 0 then
    0
  else
    s[0] + Sum(s[1..])
}

// This predicate characterizes when a chosen sequence represents a legit
// subsequence of another one *and* has a claimed sum total.
ghost predicate PossibleTotalVia(s: seq<nat>, total: nat, chosen: seq<nat>) {
  multiset(chosen) <= multiset(s) && total == Sum(chosen)
}

// The following hides the choice of subsequence, using existential
// quantification.
ghost predicate PossibleTotal(s: seq<nat>, total: nat) {
  exists chosen :: PossibleTotalVia(s, total, chosen)
}

// Now we can characterize what is the maximum possible total that does not
// exceed a limit.
ghost predicate MaxTotal(s: seq<nat>, limit: nat, total: nat) {
  && PossibleTotal(s, total)
  && total <= limit
  && forall total': nat :: PossibleTotal(s, total') && total' <= limit ==> total' <= total
}

function Max(a: nat, b: nat): nat {
  if a < b then
    b
  else
    a
}

// Now we can define our implementation with nested loops.
// There won't be time to prove this one fully in an interactive class session,
// but see what you can figure out to fill in proof content.
method ZeroOneKnapsack(weights: array<nat>, limit: nat) returns (total: nat)
  ensures MaxTotal(weights[..], limit, total)
{
  if weights.Length == 0 {
    return 0;
  }

  var table := new nat[weights.Length, limit+1];

  var i := 0;
  while i < weights.Length
  {
    var j := 0;
    while j <= limit
    {
      if i == 0 {
        if weights[i] == 0 || weights[i] > j {
          table[i, j] := 0;
        } else {
          table[i, j] := weights[i];
        }
      } else if weights[i] == 0 {
        table[i, j] := table[i-1, j];
      } else if weights[i] > j {
        table[i, j] := table[i-1, j];
      } else if table[i-1, j-weights[i]] + weights[i] > limit {
        table[i, j] := table[i-1, j];
      } else {
        table[i, j] := Max(table[i-1, j-weights[i]] + weights[i], table[i-1, j]);
      }
      
      j := j + 1;
    }

    i := i + 1;
  }

  return table[weights.Length-1, limit];
}
class21/floydWarshall.dfy
dfy
// Floyd-Warshall algorithm

// Let's go after another classic:
//   https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm

// Throughout, we represent a graph as a two-dimensional array of weights -- an
// *adjacency matrix*.  Nodes of the graph are natural numbers, corresponding to
// indices within the array.

// Here is the implementation, for you to start figuring out in terms of useful proof annotations.
method AllPairsShortestPaths(ws: array2<Option<nat>>) returns (ds: array2<Option<nat>>)
  requires ws.Length0 == ws.Length1
  ensures ds.Length0 == ds.Length1 == ws.Length0
  ensures forall src, dst :: 0 <= src < ws.Length0 && 0 <= dst < ws.Length1 ==> ShortestPath(ws, src, dst, ds[src, dst])
  // Nice elegant characterization of correctness, huh?
{
  ds := new [ws.Length0, ws.Length1];
  if ws.Length0 == 0 {
    return;
  }
  
  forall u, v | 0 <= u < ws.Length0 && 0 <= v < ws.Length1 {
    ds[u, v] := ws[u, v];
  }
  
  var k := 0;
  while k < ws.Length0
  {
    var i := 0;
    while i < ws.Length0
    {
      var j := 0;
      while j < ws.Length1
      {
        match (ds[i, k], ds[k, j]) {
          case (Some(d1), Some(d2)) => {
            match ds[i, j]
            case None =>
              ds[i, j] := Some(d1 + d2);
            case Some(d) =>
              if d > d1 + d2 {
                ds[i, j] := Some(d1 + d2);
              } else {
              }
          }
          case _ =>
        }

        j := j + 1;
      }

      i := i + 1;
    }

    k := k + 1;
  }
}


// Here are all the auxiliary definitions we depend on,
// which we stepped through just before starting this exercise.

datatype Option<T> = None | Some(value: T)

// This function computes the length (weight sum) of a *valid* path through the
// graph.  It returns None when the path is invalid.
ghost function PathLength(ws: array2<Option<nat>>, p: seq<nat>): Option<nat>
  reads ws
{
  if |p| <= 1 then
    Some(0)
  else if p[0] >= ws.Length0 || p[1] >= ws.Length1 || ws[p[0], p[1]].None? then
    None
  else
    match PathLength(ws, p[1..])
    case None => None
    case Some(l) => Some(ws[p[0], p[1]].value + l)
}

// And here is what makes a path internally consistent w.r.t. a source and
// destination.
ghost predicate Path(ws: array2<Option<nat>>, src: nat, dst: nat, p: seq<nat>)
  reads ws
{
  && |p| >= 2
  && p[0] == src
  && p[|p|-1] == dst
}

// The above but with a required distance
ghost predicate PathOfDistance(ws: array2<Option<nat>>, src: nat, dst: nat, dist: nat)
  reads ws
{
  exists p: seq<nat> :: Path(ws, src, dst, p) && PathLength(ws, p) == Some(dist)
}

// Now we can characterize what makes a valid shortest-path length.
// A length of None represents "infinity."
ghost predicate ShortestPath(ws: array2<Option<nat>>, src: nat, dst: nat, dist: Option<nat>)
  reads ws
{
  match dist
  case None => forall dist' :: !PathOfDistance(ws, src, dst, dist')
  case Some(dist) =>
    && PathOfDistance(ws, src, dst, dist)
    && forall dist': nat :: PathOfDistance(ws, src, dst, dist') ==> dist' >= dist
}

// Now we redo some of the last few definitions with an extra parameter
// *maxNode*.  We only allow *intermediate* nodes of paths that are *less than*
// this bound.

ghost predicate PathUsing(ws: array2<Option<nat>>, maxNode: nat, src: nat, dst: nat, p: seq<nat>)
  reads ws
{
  && |p| >= 2
  && p[0] == src
  && p[|p|-1] == dst
  && forall i :: 0 < i < |p|-1 ==> p[i] < maxNode
}

ghost predicate PathOfDistanceUsing(ws: array2<Option<nat>>, maxNode: nat, src: nat, dst: nat, dist: nat)
  reads ws
{
  exists p: seq<nat> :: PathUsing(ws, maxNode, src, dst, p) && PathLength(ws, p) == Some(dist)
}

ghost predicate ShortestPathUsing(ws: array2<Option<nat>>, maxNode: nat, src: nat, dst: nat, dist: Option<nat>)
  reads ws
{
  match dist
  case None => forall dist' :: !PathOfDistanceUsing(ws, maxNode, src, dst, dist')
  case Some(dist) =>
    && PathOfDistanceUsing(ws, maxNode, src, dst, dist)
    && forall dist': nat :: PathOfDistanceUsing(ws, maxNode, src, dst, dist') ==> dist' >= dist
}

// OK, this next type will be important for how we state key invariants.  We
// always convert two-dimensional arrays into this type so that we can reason
// about them functionally.
type FuncArray = seq<seq<Option<nat>>>

// Here's the canonical conversion.
ghost function FuncOfArray(ds: array2<Option<nat>>): FuncArray
  reads ds
{
  seq(ds.Length0, i requires 0 <= i < ds.Length0 reads ds =>
    seq(ds.Length1, j requires 0 <= j < ds.Length1 reads ds =>
      ds[i, j]))
  // Sequence comprehensions: neat!
}

// We found that Dafny kept timing out with loop invariants expressed directly
// with quantifiers, so this recursive function function captures the same
// property.
ghost predicate Distances(ws: array2<Option<nat>>, ds: FuncArray, k: nat, i: nat, j: nat, src: nat, dst: nat)
  requires ws.Length0 == ws.Length1
  requires 0 <= k <= ws.Length0
  requires 0 <= i <= ws.Length0
  requires 0 <= j <= ws.Length1
  requires 0 <= src <= ws.Length0
  requires 0 <= dst <= ws.Length1
  reads ws
  decreases ws.Length0 - src, ws.Length1 - dst
{
  if src == ws.Length0 then
    true
  else if dst == ws.Length1 then
    Distances(ws, ds, k, i, j, src+1, 0)
  else
    0 <= src < |ds| && 0 <= dst < |ds[src]|
    && ShortestPathUsing(ws, if src < i || (src == i && dst < j) then k+1 else k, src, dst, ds[src][dst]) && Distances(ws, ds, k, i, j, src, dst+1)
}
Copyright 6.S057 course staff.