Confused by Dafny postcondition messages

扶醉桌前 提交于 2019-12-14 03:19:45

问题


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

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