我正在尝试使用代码合同静态验证基于数组的堆栈的以下部分实现。该方法Pop()
使用纯函数IsNotEmpty()
来确保后续数组访问将处于/高于下限。静态验证器失败并建议我添加 precondition Contract.Requires(0 <= this.top)
。
谁能解释为什么验证者不能证明数组访问对于给定合同的下限是有效的IsNotEmpty()
?
起初我认为这种Contract.Requires(IsNotEmpty())
方法可能不正确,因为子类可以覆盖IsNotEmpty()
. 但是,如果我将类标记为sealed
.
更新:如果我更改IsNotEmpty()
为只读属性,则验证按预期成功。这就提出了一个问题:只读属性和纯函数如何/为什么被区别对待?
class StackAr<T>
{
private T[] data;
private int capacity;
/// <summary>
/// the index of the top array element
/// </summary>
private int top;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(data != null);
Contract.Invariant(top < capacity);
Contract.Invariant(top >= -1);
Contract.Invariant(capacity == data.Length);
}
public StackAr(int capacity)
{
Contract.Requires(capacity > 0);
this.capacity = capacity;
this.data = new T[capacity];
top = -1;
}
[Pure]
public bool IsNotEmpty()
{
return 0 <= this.top;
}
public T Pop()
{
Contract.Requires(IsNotEmpty());
//CodeContracts: Suggested precondition:
//Contract.Requires(0 <= this.top);
T element = data[top];
top--;
return element;
}
}