代码合约失败示例 Graph.Remove(Edge e)

发布于 2024-10-15 09:29:10 字数 797 浏览 2 评论 0原文

这是一个简单的图形操作方法,我用代码契约来装饰它。

确保声明无法证明,但我不明白为什么!我相信它声称在调用 Remove() 后,要么该边不再在边列表中,要么结果为 false。如果结果为真,它不会声明任何有关图状态的信息。静态检查器不喜欢它,而且我还没有让 Pex 告诉我如何使用它(尽管我可能只是不知道如何使用它)。

我相信,对于这个例子来说,锁是无关紧要的,但为了以防万一,我会保留它。另外,OnRemoveEdge 的委托没有任何保证,但我现在隐式假设它不会重新进入图形代码。此外,假设是在它之后。

public bool Remove(E edge)
{
  Contract.Requires(edge != null);
  Contract.Ensures(!Contract.Exists(edges, e => e == edge) || !Contract.Result<bool>());

  lock (sync)
  {
    if (!OnBeforeRemoveEdge(edge)) return false;

    if (!edges.Remove(edge)) return false;
  }

  OnRemoveEdge(edge);

  Contract.Assume(!Contract.Exists(edges, e => e == edge));

  return true;
}

更新:我更改了代码以将事件处理程序 OnRemoveEdge()(但不是委托 OnBeforeRemoveEdge)移出锁定。但是,这对于合约中与线程相关的假设有什么作用呢?代码契约是否采用单线程模型?嗯。

Here's a simple graph manipulation method which I have decorated with Code Contracts.

The ensures claim won't prove but I can't see why! I believe it claims that after calling Remove(), either the edge is no longer in the edges list OR the result is false. It claims nothing about the state of the graph if the result is true. The static checker doesn't like it and I haven't gotten Pex to tell me how (though I probably just don't know how to use it).

The lock is extraneous for this example, I believe, but I'll leave it just in case. Also, the delegate for OnRemoveEdge has no guarantees, but I'll implicitly assume for now that it is not re-entrant into the Graph code. Besides, the Assumption is after it.

public bool Remove(E edge)
{
  Contract.Requires(edge != null);
  Contract.Ensures(!Contract.Exists(edges, e => e == edge) || !Contract.Result<bool>());

  lock (sync)
  {
    if (!OnBeforeRemoveEdge(edge)) return false;

    if (!edges.Remove(edge)) return false;
  }

  OnRemoveEdge(edge);

  Contract.Assume(!Contract.Exists(edges, e => e == edge));

  return true;
}

Update: I changed the code to move the Event handler, OnRemoveEdge(), (but not the delegate, OnBeforeRemoveEdge) out of the lock. But then, what does this do for the contract's assumption related to threads? Does Code Contracts assume a single-threaded model? Hmmm.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轻拂→两袖风尘 2024-10-22 09:29:10

来自Jack Leitch 对类似问题的回答

代码合同用户手册指出,“静态合约检查器尚未处理量词 ForAll 或 Exists。”

真的。真的。

From Jack Leitch's answer to a similar question:

The Code Contracts User Manual states, "The static contract checker does not yet deal with quantifiers ForAll or Exists."

True. true.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文