
(* Traversing a tree inorder, filling an array with the elements
   (from Rustan Leino's tutorial on Dafny at VSTTE 2012)

   Author: Jean-Christophe Filliatre (CNRS)
*)

module Fill

  use int.Int
  use array.Array

  type elt
  type tree = Null | Node tree elt tree

  predicate contains (t: tree) (x: elt) = match t with
    | Null       -> false
    | Node l y r -> contains l x || x = y || contains r x
  end

  let rec fill (t: tree) (a: array elt) (start: int) : int
    requires { 0 <= start <= length a }
    ensures  { start <= result <= length a }
    ensures  { forall i: int. 0 <= i < start -> a[i] = (old a)[i] }
    ensures  { forall i: int. start <= i < result -> contains t a[i] }
    variant  { t }
  = match t with
    | Null ->
        start
    | Node l x r ->
        let res = fill l a start in
        if res <> length a then begin
          a[res] <- x;
          fill r a (res + 1)
        end else
          res
     end

end
