using System; using Microsoft.Contracts; namespace SSharpAsst { public class SimpleSet { [SpecPublic] public int[]! contents; [SpecPublic] public int size; invariant size >= 0; invariant size <= contents.Length; [NotDelayed] public SimpleSet(int capacity) requires capacity >0; ensures size == 0; ensures contents.Length == capacity; //ensures isEmpty(); { contents = new int[capacity]; size = 0; base(); assert (size == 0); } [Pure] public bool isEmpty() ensures result == (size == 0); { return size == 0; } public bool add(int i) //ensures size == old(size+1); requires size < contents.Length; ensures exists{int j in (0:size); contents[j]==i }; { if (contains(i)) { assert exists{int j in (0:size); contents[j]==i }; return false; } contents[size]=i; expose(this) { //if (size < contents.Length - 1) size = size + 1; } assert contents[size-1] == i; assert exists{int j in (0:size); contents[j]==i }; return true; } [Pure] public bool contains(int i) ensures result == exists{int j in (0:size); contents[j]==i }; { for (int j = 0; j < size; ++j) invariant forall{int k in (0:j); contents[k]!=i}; { if (contents[j] == i) { return true; } } return false; } [Pure] public bool contains2(int i) ensures result == exists{int j in (0:size); contents[j]==i }; { bool found = false; int j; for (j = 0; j < size; ++j) invariant found == exists{int k in (0:j); contents[k]==i } && j <= size; { if (contents[j] == i) { found = true; } } assert j == size; assert found == exists{int k in (0:size); contents[k]==i }; return found; } static void Main(string![]! args) // The following precondition is redundant with the type // signature for the parameter, but shown here as an example. requires forall{int i in (0:args.Length); args[i] != null}; { Console.WriteLine("Spec# says hello!"); } } class SimpleSetDriver { void testConstructor() { SimpleSet! s = new SimpleSet(2); assert s.size == 0; assert !exists{int j in (0:s.size); s.contents[j]==5 }; //assert !(s.contains(5)); } void testAdd() { SimpleSet! s = new SimpleSet(2); s.add(5); assert !s.contains(4); assert s.contains(5); s.add(4); assert s.contains(4); s.add(4); } } }