dafny modeling integer overflow

瘦欲@ 提交于 2021-01-28 10:24:34

问题


Can Dafny model integer overflow? I was surprised when Dafny proved the following:

method overflow(c : int)
{
    if (c > 0)
    {
        assert((c+1) > 0);
    }
}

What am I missing?


回答1:


The type int in Dafny means "mathematical integer". So there is no overflow.

If you want to model machine arithmetic, there are a few ways to do it.

One way is to define something like:

type uint64 = x:int | 0 <= x < 0x10000000000000000

and then when you try to store the result in a uint64 you will get an error:

method overflow(c: uint64) {
  if c > 0 {
    var d: uint64 := c + 1;
    assert d > 0;
  }
}

This technique is primarily useful for proving that your program does not overflow. If instead you want to reason about a program that intentionally uses two's complement arithmetic, you can do that by using bitvectors, like this:

method overflow(c: bv64) {
  if c > 0 {
    assert c + 1 > 0;
  }
}

Bitvectors are a relatively recent addition to Dafny (ok, not that recent, but in the past few years), and in my experience they are not widely used unless you are specifically reasoning about a piece of code that does bitwise operations (eg, crypto). I would recommend staying away from bitvectors if at all possible.



来源:https://stackoverflow.com/questions/63915841/dafny-modeling-integer-overflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!