Presentation is loading. Please wait.

Presentation is loading. Please wait.

K. Rustan M. Leino Microsoft Research, Redmond, WA, USA with Mike Barnett, Robert DeLine, Manuel Fahndrich, and Wolfram Schulte Spec# Writing and checking.

Similar presentations


Presentation on theme: "K. Rustan M. Leino Microsoft Research, Redmond, WA, USA with Mike Barnett, Robert DeLine, Manuel Fahndrich, and Wolfram Schulte Spec# Writing and checking."— Presentation transcript:

1 K. Rustan M. Leino Microsoft Research, Redmond, WA, USA with Mike Barnett, Robert DeLine, Manuel Fahndrich, and Wolfram Schulte Spec# Writing and checking contracts in a.NET language ¨.NET Technologies 2004 Plzeň, Czech Republic 1 June 2004

2 Interoperable pronunciation a == b x = E ; this a = b x := E current “equals” “gets”, “receives” “self” ;

3 Software engineering problem Building and maintaining large systems that are correct

4 Approach Specifications record design decisions – bridge intent and code Tools amplify human effort – manage details – find inconsistencies – ensure quality

5 Design decisions – examples and trends int x; assert(x < a.Length); finite-state protocols SpecStrings Pre- and postconditions, and object invariants Acquire() Release() int strlen(pre notnull char * str); void Copy(int[] a, int start, int count) requires start+count <= a.Length; Contracts

6 StringBuilder.Append Method (Char[], Int32, Int32) Appends the string representation of a specified subarray of Unicode characters to the end of this instance. public StringBuilder Append(char[] value, int startIndex, int charCount); Parameters value A character array. startIndex The starting position in value. charCount The number of characters append. Return Value A reference to this instance after the append operation has occurred. Exceptions Exception TypeCondition ArgumentNullExceptionvalue is a null reference, and startIndex and charCount are not zero. ArgumentOutOfRangeExceptioncharCount is less than zero. -or- startIndex is less than zero. -or- startIndex + charCount is less than the length of value. Contracts today

7 Spec# contracts Precondition Callers are expected to establish precondition before invoking method Implementations can assume precondition holds on entry Postcondition Implementations are expected to establish postcondition on exit Callers can assume postcondition upon return from method invocation public StringBuilder Append( char[] value, int startIndex, int charCount); requires value != null || (charCount == 0 && startIndex == 0); requires 0 <= charCount && 0 <= startIndex; requires startIndex + charCount <= value.Length; ensures result == this;

8 Code + contracts in Spec# Boogie Spec# compiler Compile-time error messages Run-time exceptions Spec# programming system

9 Boogie demo

10 Spec# is C# extended with: Non-null types Preconditions Postconditions Object invariants Checked exceptions...

11 Spec#: Non-null types T x; The value of x is null or a reference to an object whose type is a subtype of T. T! y; The value of y is a reference to an object whose type is a subtype of T, not null.

12 Non-null instance fields class C : B { T! x; public C(T! y) :base() { this.x = y; } public overrides int M() { return x.f; } Is this code type safe? No! The base constructor can invoke the virtual method M and C.M would then find x to be null.

13 Non-null instance fields class C : B { T! x; public C(T! y) :x = y, base() { } public overrides int M() { return x.f; } Need to allow x to be assigned before base constructor is called.

14 requires 0 <= startIndex otherwise ArgumentException; Spec#: Parameter validation public virtual StringBuilder Append(char[] value, int startIndex, int charCount) Parameters … startIndex The starting position in value. … Exceptions Exception TypeCondition ArgumentExceptionstartIndex is less than zero. -or- … ; requires 0 <= startIndex;

15 But what about these parameters? Simplifying today's code public virtual int BinarySearch(int index, int count, object val, IComparer comparer) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException( (index < 0 ? ”index” : ”count”), Environment.GetResourceString( ”ArgumentOutOfRange_NeedNonNegNum”)); }... } requires 0 <= index && 0 <= count otherwise ArgumentOutOfRangeException; supported but discouraged old new

16 Uses of exceptions What do exceptions signal? Domain failures Range failures – Admissible failures – Detected program errors What to do with exceptions? – caller handles – never handled or caught by backstop (ArgumentException, …) (EndOfFileException, …) (IndexOutOfBoundsException, …, OutOfMemoryException, …) checked exceptions unchecked exceptions

17 Spec#: Taming exceptions Introduce checked exceptions An exception is checked if it implements interface ICheckedException JavaSpec# Throwable Exception RuntimeException Error Checked exceptionsUnchecked exceptions ICheckedException CheckedException

18 Spec#: Taming exceptions Methods must declare which checked exceptions they may throw Soundness of throw statement int MyMethod() throws MyException; int MyMethod() throws MyException ensures state==Closed; Exception x = new MyCheckedException(); throw x; If static type of x is not an ICheckedException, then check: !( x is ICheckedException ) at run time.

19 Spec#: Object invariants class C { int x, y; invariant x < y; Joint work also with Peter Müller (ETH Zurich) and David Naumann (Stevens Institute of Technology) Object invariant always holds, except possibly when the object is exposed

20 Spec#: Object invariants class C { int x, y; invariant x < y; public void M(T! o) { … expose (this) { this.x = this.y; o.P(); this.y++; } … } The object invariant may be temporarily violated here The object invariant is checked to hold here Joint work also with Peter Müller (ETH Zurich) and David Naumann (Stevens Institute of Technology)

21 Spec#: Object invariants class C { int x, y; invariant x < y; public void M(T! o) { … expose (this) { this.x = this.y; o.P(); this.y++; } … } The exposed/unexposed state of the object is recorded, so as to detect possible bad re-entrancy Joint work also with Peter Müller (ETH Zurich) and David Naumann (Stevens Institute of Technology)

22 Third-party tools, and debug vs. retail builds All Spec# contracts can have custom attributes int BinarySearch(int[]! a, int lo, int hi) requires 0 <= lo && lo <= hi && hi <= a.Length; [MyToolIgnore] [Conditional(“DEBUG”)] requires IsSorted(a); {... }

23 Compilation void M(int x, out int y) requires 0 <= x; ensures 0 <= y; {... } Spec#: “MSIL”: Contracts are compiled into metadata and specially tagged code [Contract(“requires 0 <= x; ensures 0 <= y;”)] void M(int x, out int y) { if (!(0 <= x)) { throw new RequiresException(); }... if (!(0 <= y)) { throw new EnsuresException(); } }

24 Boogie: Under the hood theorem prover weakest-precondition generator translator MSIL BoogiePL verification condition error messages inference engine Boogie

25 Summary Spec# adds contracts to C# Compiler inserts dynamic checks to enforce contracts Boogie enforces contracts statically Evolution C# managed code  Spec# non-null types, parameter validation  Boogie verification

26 http://research.microsoft.com/~leino new!


Download ppt "K. Rustan M. Leino Microsoft Research, Redmond, WA, USA with Mike Barnett, Robert DeLine, Manuel Fahndrich, and Wolfram Schulte Spec# Writing and checking."

Similar presentations


Ads by Google