All languages

Spec# languagedormant

Microsoft Research's design-by-contract extension of C#: non-null reference types, method pre- and postconditions, checked exceptions, and object invariants checked by a static verifier that translates to Boogie.

Overview

Spec# is Microsoft Research's extension of C# that puts API contracts into the language itself: non-null types, method pre- and postconditions, object invariants, checked exceptions. It exists to test whether a verifier can check specifications written in the programmer's own language, and that work became Boogie.

Code

string aString = "Hello";                     // non-null by default (/nn)
string? maybe = null;                         // possibly-null: may hold null
int x = 9;
bool inRange = 0 <= x && x < 100;             // conjunction of comparisons
bool big = inRange ==> x > 5;                 // lower precedence than &&
int size = maybe != null ? maybe.Length : 0;  // guarded, so the deref is legal
bool three = exists{int i in (0: x); i == 3};  // half-open integer range
/nn makes string non-null, so string? must be tested before a member is reachable. forall/exists are the quantifiers: they range over a half-open interval, and min/max aggregate a set — neither loops. The clauses are C# expressions, not a separate language. The idiom slot is the payoff: [Rep]ownership plus expose lets an invariant mention a sub-object and still be checked one class frame at a time. Examples follow the tutorial.

Distinctive traits

  • Contracts are syntax: requires, ensures, invariant, and modifies sit between the signature and the body, written in C# itself.
  • Non-null types split references in two: string cannot be null, string? may be, and only the first is dereferenceable without a guard or cast.
  • An object invariant holds for every valid object; expose opens a scoped region in which a multi-field update may break it.
  • [Rep] marks a component of an aggregate, and ownership lets an invariant mention a sub-object while still checking each frame modularly.
  • The static verifier is sound but not complete: Boogie plus a solver may reject correct methods until specifications are strengthened.
  • A checked exception is part of the contract: throws names it, and an ensures after it constrains what holds when it is raised.

Status

Research project, not a product: the last CodePlex release was 1.0.21125 in 2009, licensed for non-commercial use only, and Code Contracts carried the contract idea into .NET 4. A community fork moved the compiler and libraries to .NET Framework 4.x.

Sources & references