问题
A very simple multiplication code:
method Product1 (m: nat, n: nat) returns (res:nat)
ensures res == m * n;
{
var m1: nat := 0;
var n1: nat := 0;
res := 0;
while (m1 < m)
{
n1 := 0;
while (n1 < n)
{
res := res + 1;
n1 := n1 + 1;
}
m1 := m1 + 1;
}
}
When I verify it with dafny, it says:
Description Line Column
1 A postcondition might not hold on this return path. 8 4
2 This is the postcondition that might not hold. 2 16
I get it says under some conditions, res != m*n, but I can't figure it out.
回答1:
Updated!
Tried dafny in the online website, looks like it is bug?
method Test(m: nat) returns (r: nat)
{
var m1: nat := 0;
while (m1 < m) {
m1 := m1 + 1;
}
assert m == m1; // fail assert
}
more try:
method Test(m: nat) returns (r: nat)
{
var m1: nat := 0;
while (m1 < m) {
assert m1 < m;
m1 := m1 + 1;
}
assert !(m1 < m); // pass
assert m1 == m || m1 > m; // pass
assert m1 == m; // fail
}
After some deep understand, I know that it should use Loop Invariants
for dafny to address this question.
My modified code:
method Product1 (m: nat, n: nat) returns (res:nat)
ensures res == m * n;
{
var m1: nat := 0;
var n1: nat := 0;
res := 0;
while (m1 < m)
invariant 0 <= m1 <= m
invariant res == m1 * n
{
var temp: nat := res;
n1 := 0;
while (n1 < n)
invariant 0 <= n1 <= n
invariant res == temp+n1
{
res := res + 1;
n1 := n1 + 1;
}
m1 := m1 + 1;
}
assert m1 == m; // success
}
Then remove the tmp var:
method Product1 (m: nat, n: nat) returns (res:nat)
ensures res == m * n;
{
var m1: nat := 0;
var n1: nat := 0;
res := 0;
while (m1 < m)
invariant 0 <= m1 <= m
invariant res == m1 * n
{
n1 := 0;
while (n1 < n)
invariant 0 <= n1 <= n
invariant res == n1 + m1*n
{
res := res + 1;
n1 := n1 + 1;
}
m1 := m1 + 1;
}
assert m1 == m; // success
}
回答2:
Your loops don't have any loop invariants. At a minimum, you'll need invariants on both loops. Otherwise, Dafny won't be able to figure out what holds after the loops...
来源:https://stackoverflow.com/questions/39484196/confused-by-dafny-postcondition-messages