0

I'm trying to play with CodeContracts. I'm starting with a little function

public static string MyTrim(string text)
{
    Contract.Requires(text != null);
    Contract.Ensures(Contract.Result<string>().Length == 0 || Contract.Result<string>()[0] != ' ');
    var sCurrent = text;
    while (sCurrent.Length != 0 && sCurrent[0] == ' ')
    {
        sCurrent = sCurrent.Substring(1);
    }
    return sCurrent;
}

Code Contracts says to me that I didn't prove the Ensures. But After the while loop I know that the condition is false. So I know that

Scurrent.Length == 0 || Scurrent[0] != ' '

Which is exactly my ensure condition. What can i do to explain that to Code COntracts ?

  • What is the value of sCurrent? Is it empty? Is `Contract.Result().Length == 0` meant to be `Contract.Result().Length != 0` – Davin Tryon Jun 27 '12 at 14:40
  • I don't really know what there is inside sCurrent, but I know that after a while loop the condition of the while loop is false (otherwiser it will not go outside the loop). – user1485585 Jun 27 '12 at 14:42
  • Very odd - if you change the bit under the `while` loop to: `if (sCurrent.Length == 0) return sCurrent; Contract.Assert(sCurrent[0] != ' '); return sCurrent;`, it's perfectly happy with it. – Damien_The_Unbeliever Jun 27 '12 at 14:47
  • Damien, I tried it. It doesn't accept the Contract.Assert(sCurrent[0] != ' ') Could you show me a complete example ? – user1485585 Jun 27 '12 at 15:01
  • 1
    Formatting is limited in the comments area, but I took exactly your code and inserted 3 lines above the `return` - the `if`, an early `return` and the `Assert`. Those silenced the static checker for me (tried under both VS2010 and VS2012RC). What version of VS and Code Contracts are you using? – Damien_The_Unbeliever Jun 28 '12 at 06:45
  • Today, it works. I dunno what I did wrong yesterday. Thank you for your help. Is there a language for the proof system with i can demonstrate "things" ? – user1485585 Jun 28 '12 at 08:16

1 Answers1

0

I've looked into what is happening in your example and it is just a limitation of the static checker due to the disjunctive loop condition. We'll try to fix this.

Manuel Fahndrich
  • 665
  • 4
  • 12