Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic verification limitations when using pure functions in C# code contracts?
    primarykey
    data
    text
    <p>I'm trying to statically verify the following partial implementation of an array-based stack with code contracts. The method <code>Pop()</code> uses the pure function <code>IsNotEmpty()</code> to ensure that the subsequent array access will be at/above the lower bound. The static verifier fails and suggests that I add the precondition <code>Contract.Requires(0 &lt;= this.top)</code>.</p> <p>Can anyone explain why the verifier cannot prove the array access is valid with respect to the lower bound given the contract <code>IsNotEmpty()</code>?</p> <p>At first I thought the <code>Contract.Requires(IsNotEmpty())</code> approach might be incorrect because a subclass could override <code>IsNotEmpty()</code>. However, the verifier still can't prove the array access is valid if I mark the class as <code>sealed</code>.</p> <p><strong>Update:</strong> If I change <code>IsNotEmpty()</code> to a read-only property, the verification succeeds as expected. This raises the question: <em>how / why are read-only properties and pure functions treated differently?</em> </p> <pre><code>class StackAr&lt;T&gt; { private T[] data; private int capacity; /// &lt;summary&gt; /// the index of the top array element /// &lt;/summary&gt; private int top; [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(data != null); Contract.Invariant(top &lt; capacity); Contract.Invariant(top &gt;= -1); Contract.Invariant(capacity == data.Length); } public StackAr(int capacity) { Contract.Requires(capacity &gt; 0); this.capacity = capacity; this.data = new T[capacity]; top = -1; } [Pure] public bool IsNotEmpty() { return 0 &lt;= this.top; } public T Pop() { Contract.Requires(IsNotEmpty()); //CodeContracts: Suggested precondition: //Contract.Requires(0 &lt;= this.top); T element = data[top]; top--; return element; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload