<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Francesco's Blog on CodeContracts, Static analysis, Abstract Interpretation, etc.</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/francesco/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/francesco/feed.xml</link>
    <description>Some tricks to optimize CodeContracts usage, and on static analysis in general</description>
    <lastBuildDate>Wed, 17 Apr 2019 03:23:11 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>False myth: Abstract interpretation can only do "easy" properties as nonnull</title>
      <link>https://docs.microsoft.com/archive/blogs/francesco/false-myth-abstract-interpretation-can-only-do-easy-properties-as-nonnull</link>
      <pubDate>Thu, 13 Nov 2014 17:15:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Logozzo]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/francesco/2014/11/13/false-myth-abstract-interpretation-can-only-do-easy-properties-as-nonnull/</guid>
      <description><![CDATA[When demoing the CodeContracts static checker, often people ask me what's underneath. I tell them...]]></description>
      <content:encoded><![CDATA[<p>When demoing the CodeContracts static checker, often people ask me what's underneath. I tell them that is based on <a title="http://en.wikipedia.org/wiki/Abstract_interpretation" href="http://blogs.msdn.com/controlpanel/blogs/posteditor.aspx/abstract interpretation">abstract interpretation</a>, a theory developed in the late 70s by two French computer scientists, Patrick and Radhia Cousot. According to abstract interpretation, concrete program executions can be observed at different abstraction levels (called abstract semantics). A static analysis is just an abstract semantics which is coarse enough to be computable (and fast!), and precise enough to be useful.</p>
<p>For instance in the program below, instead of considering all the possible input arrays - there are (almost) infinitely many - &nbsp;cccheck only considers an abstraction of them.</p>
<pre><span style="font-family: 'courier new', courier;">public int Max(int[] arr)</span><br /><span style="font-family: 'courier new', courier;">{</span><br /><span style="font-family: 'courier new', courier;"> Contract.Requires(arr != null);</span><br /><span style="font-family: 'courier new', courier;"> Contract.Requires(arr.Length &gt; 0);</span><br /><br /><span style="font-family: 'courier new', courier;"> var max = arr[0];</span><br /><span style="font-family: 'courier new', courier;"> for(var i = 1; i &lt; arr.Length; i++)</span><br /><span style="font-family: 'courier new', courier;"> {</span><br /><span style="font-family: 'courier new', courier;"> if (max &lt; arr[i]) max = arr[i];</span><br /><span style="font-family: 'courier new', courier;"> }</span><br /><br /><span style="font-family: 'courier new', courier;"> return max;</span><br /><span style="font-family: 'courier new', courier;">}</span></pre>
<p>Now the question is which abstraction of the array we should keep?</p>
<p>A very simple abstraction is whether the input array is null or not. This help us to prove the absence of null pointer exceptions &ndash; i.e., in the example, all the array loads are safe.</p>
<p>A more refined abstraction keeps track of the array indexes. In our example, the local variable i is initialized to 1 and always incremented. Therefore we can infer that it always assume values in the interval [1, Int32.MaxValue]. Furthermore, inside the body of the loop we also know that i &lt; arr.Length. As a consequence, we can deduce that is safe to index the array with i, i.e., no out-of-bounds exception is ever thrown, no matter which is the concrete array.</p>
<p>A false myth is that abstract interpretation is good <em>only</em> for those &ldquo;simple&rdquo; properties, and for &ldquo;real&rdquo; verification we need some other technique, as for instance <a href="http://en.wikipedia.org/wiki/Hoare_logic">deductive verification. </a>For instance, in the example below the myth goes as abstract interpretation is unable to infer that Max is effectively computing the max of the array. Let&rsquo;s debunk the myth. &nbsp;We can ask cccheck to tell us which postcondition infers for our program (we use the extra option &ldquo;-suggest methodensures&rdquo;):</p>
<p><span style="font-family: 'courier new', courier;">&hellip;: message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.ForAll(0, arr.Length, __k__ =&gt; arr[__k__] &lt;= Contract.Result&lt;int&gt;()));</span></p>
<p><span style="font-family: 'courier new', courier;">&hellip;: message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.Exists(0, arr.Length, __j__ =&gt; arr[__j__] == Contract.Result&lt;int&gt;()));</span>&nbsp;</p>
<p>The analyzer infers that the returned value is larger or equal to all the elements in the array <em>and</em> that there exists one element in the array that is equal to the returned value, i.e, and the returned value is effectively the maximum element and not a simple upper bound!</p>
<p>To sum up, let me illustrate why we use abstract interpretation and not, e.g., deductive verification in CodeContracts. Using deductive verification, i.e., Hoare-Logic style reasoning, one should provide all the boundary contracts and the loop invariants. Our Max will then look like as this one:</p>
<pre><span style="font-family: 'courier new', courier;">public int Max(int[] arr)</span><span style="font-family: 'courier new', courier;">{</span></pre>
<pre><em><span style="font-family: 'courier new', courier;"> Contract.Requires(arr != null);</span></em><br /><em><span style="font-family: 'courier new', courier;"> Contract.Requires(arr.Length &gt; 0);</span></em><br /><em><span style="font-family: 'courier new', courier;"> Contract.Ensures(Contract.ForAll(arr, el =&gt; el &lt;= Contract.Result&lt;int&gt;()));</span></em><br /><em><span style="font-family: 'courier new', courier;"> Contract.Ensures(Contract.Exists(arr, el =&gt; el == Contract.Result&lt;int&gt;()));</span></em><br /><br /><span style="font-family: 'courier new', courier;"> var max = arr[0];</span><br /><span style="font-family: 'courier new', courier;"> for(var i = 1; i &lt; arr.Length; i++)</span><br /><span style="font-family: 'courier new', courier;"> { // Those below are effectively Loop invariants, CC has no Contract.Invariant(...)</span><br /><em><span style="font-family: 'courier new', courier;"> Contract.Assert(i &gt;= 1); </span></em><br /><em><span style="font-family: 'courier new', courier;"> Contract.Assert(Contract.ForAll(0, i, __j__ =&gt; arr[__j__] &lt;= max)); </span></em><br /><em><span style="font-family: 'courier new', courier;"> Contract.Assert(Contract.Exists(0, i, __j__ =&gt; arr[__j__] == max));</span></em><br /><br /><span style="font-family: 'courier new', courier;"> if (max &lt; arr[i]) max = arr[i];</span><br /><span style="font-family: 'courier new', courier;"> }</span><br /><br /><span style="font-family: 'courier new', courier;"> return max;</span><br /><span style="font-family: 'courier new', courier;">}</span></pre>
<p>Compare it with cccheck, which infers, precondition, postcondition, and loop invariants!</p>
<pre><span style="font-family: 'courier new', courier;">public int Max(int[] arr)</span><br /><span style="font-family: 'courier new', courier;">{ // Precondition &amp; postcondition inferred</span>   <br /><span style="font-family: 'courier new', courier;">&nbsp;</span></pre>
<pre><span style="font-family: 'courier new', courier;"> var max = arr[0];</span><br /><span style="font-family: 'courier new', courier;"> for(var i = 1; i &lt; arr.Length; i++)</span><br /><span style="font-family: 'courier new', courier;"> { // Loop invariant inferred</span><br /><span style="font-family: 'courier new', courier;"> if (max &lt; arr[i]) max = arr[i];</span><br /><span style="font-family: 'courier new', courier;"> }</span><br /><br /><span style="font-family: 'courier new', courier;"> return max;</span><br /><span style="font-family: 'courier new', courier;">}</span></pre>
<p><span style="font-family: 'courier new', courier;">&hellip;: message : CodeContracts: Suggested requires: Contract.Requires(arr != null);</span></p>
<p><span style="font-family: 'courier new', courier;">&hellip;: message : CodeContracts: Suggested requires: Contract.Requires(0 &lt; arr.Length);</span></p>
<p><span style="font-family: 'courier new', courier;">&hellip;: message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.ForAll(0, arr.Length, __k__ =&gt; arr[__k__] &lt;= Contract.Result&lt;System.Int32&gt;()));</span></p>
<p><span style="font-family: 'courier new', courier;">&hellip;: message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.Exists(0, arr.Length, __j__ =&gt; arr[__j__] == Contract.Result&lt;System.Int32&gt;()));</span></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>Inter-procedural inference of conditions to error in cccheck</title>
      <link>https://docs.microsoft.com/archive/blogs/francesco/inter-procedural-inference-of-conditions-to-error-in-cccheck</link>
      <pubDate>Fri, 07 Nov 2014 16:21:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Logozzo]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/francesco/2014/11/07/inter-procedural-inference-of-conditions-to-error-in-cccheck/</guid>
      <description><![CDATA[Today we pushed out a new release of CodeContracts. Among the many improvements, bug fixes, etc. we...]]></description>
      <content:encoded><![CDATA[<p>Today we pushed out a new release of CodeContracts. Among the many improvements, bug fixes, etc. we improved the inference of pre-conditions to errors. The static checker now also provides inter-procedural error traces.</p>
<p>But how it works?</p>
<p>Let me illustrate the inference of preconditions with this example</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">private int Max(int[] a)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; var max = a[0]; </span><br /><span style="font-family: courier new,courier;">&nbsp; for (var i = 1; i &lt; a.Length; i++)</span><br /><span style="font-family: courier new,courier;">&nbsp; {</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; var tmp = a[i];</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; if (tmp &gt; max) max = tmp;</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp; }</span><br /><span style="font-family: courier new,courier;">&nbsp; return max;</span><br /><span style="font-family: courier new,courier;">&nbsp; }</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">private void CreateTheArrayAndDoSomething(int size)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; var array = new int[size];&nbsp; </span><br /><span style="font-family: courier new,courier;">&nbsp; // ... fill the array ...</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp; var arrayMax = Max(array);</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp; // ... do something else ...</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">public void PublicAPI(int size)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; Contract.Requires(size != Int32.MinValue);</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp; if (size &lt; 0) size = -size;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp; CreateTheArrayAndDoSomething(size); </span><br /><span style="font-family: courier new,courier;">}</span></p>
<p>The static checker first analyzes the method Max. It determines that if the input array is null or it is empty, then an error will definitely happen. If we enable the suggestion of requires, it will report (remember to enable "Suggest Requires" to see those messages)</p>
<p><span style="font-family: courier new,courier;">... : CodeContracts: Suggested requires: Contract.Requires(a != null);</span></p>
<p><span style="font-family: courier new,courier;">... : CodeContracts: Suggested requires: Contract.Requires(0 &lt; a.Length);</span></p>
<p>Those preconditions are <em>necessary</em> for Max to be correct: If they are violated Max will cause a runtime exception to occur. The static checker is also smart enough to determine that those preconditions are <em>sufficient</em> for Max to be correct: If satisfied, then the Max will <em>never </em>throw a runtime exception. As a consequence the static checker will not report any warning for Max, but it pushes the condition to the caller.</p>
<p>The caller passes a freshly allocated array of length <span style="font-family: courier new,courier;">size</span> to Max. As a consequence, the first condition (<span style="font-family: courier new,courier;">a != null</span>) is satisfied, but not the second one, which is further propagated to the caller:</p>
<p><span style="font-family: courier new,courier;">... : CodeContracts: Suggested requires: Contract.Requires(0 &lt; size);</span></p>
<p>The caller, PublicAPI, is careful enough to check whether the input values is negative in which case it negates it. Furthermore, it requires the input to be different from the MinValue which will cause an overflow on negation. Nevertheless, it forgot the case when size == 0, which will cause an error downstream. The static analyzer cannot push the condition further up in the call chain, as it reached the public surface. As a consequence it emits a warning as well as the inter-procedural trace that will cause the error</p>
<p><span style="font-family: courier new,courier;">... : CodeContracts: Missing precondition in an externally visible method. Consider adding Contract.Requires(0 != size); for parameter validation. Otherwise the following sequence of method calls may cause an error. Sequence: PublicAPI -&gt; CreateTheArrayAndDoSomething -&gt; Max</span></p>
<p>The precondition inferred by cccheck is <em>by design </em>a condition to the error: if some caller fails to satisfy it, then a runtime error will occur. This makes the cccheck analyzer different from other tools, as all the inferred preconditions are <em>sound.</em></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>How to prove properties of finite state machines with cccheck</title>
      <link>https://docs.microsoft.com/archive/blogs/francesco/how-to-prove-properties-of-finite-state-machines-with-cccheck</link>
      <pubDate>Fri, 19 Sep 2014 16:16:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Logozzo]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/francesco/2014/09/19/how-to-prove-properties-of-finite-state-machines-with-cccheck/</guid>
      <description><![CDATA[In the previous post we saw how to use cccheck to prove that we did not forgot any case in a switch...]]></description>
      <content:encoded><![CDATA[<p>In the <a href="http://blogs.msdn.com/b/francesco/archive/2014/09/12/how-to-use-cccheck-to-prove-no-case-is-forgotten.aspx">previous post</a> we saw how to use cccheck to prove that we did not forgot any case in a switch statement. Some friend in Microsoft product groups asked if we can do more. For instance, if we can prove properties about a finite state machine using the CodeContracts static checker. The answer is yes, and I will illustrate it with our favorite example: cooking pasta!</p>
<p>First, we define a function that tell us if we can move from one state in the (extremely important) process of cooking pasta, to the next one (for theory lovers, we are defining the transition relation of a finite state machine).</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">enum CookPasta { BoilWater, AddSalt, AddPasta, Stir, Strain, Eat }</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">[Pure]</span><br /><span style="font-family: courier new,courier;">static public bool CanTransition(CookPasta from, CookPasta to)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp;switch (from)</span><br /><span style="font-family: courier new,courier;">&nbsp;{</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;case CookPasta.BoilWater:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;return to == CookPasta.AddPasta || to == CookPasta.AddSalt;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;case CookPasta.AddPasta:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;return to == CookPasta.AddSalt || to == CookPasta.Stir;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;case CookPasta.AddSalt:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;return to == CookPasta.AddPasta;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;case CookPasta.Stir:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;return to == CookPasta.Strain;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;case CookPasta.Strain:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;return to == CookPasta.Eat;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;case CookPasta.Eat:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;return false;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;default:</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;throw CodeContractsHelpers.ThrowIfReached("missing case");</span><br /><span style="font-family: courier new,courier;">&nbsp;}</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p>Now we'd love to prove some properties about our state machine. For instance that the first thing to do is to boil water or that once we eat all our pasta we are done. We can do it by defining two methods as below (again for the theory-loving people those acts as lemmas to be proven by the static analyzer).</p>
<p><strong><em>Important.</em> </strong>To repro the examples below, make sure that you have the "Infer ensures" on.</p>
<p>With the first method, BoilWaterIsIntitial,&nbsp;we ask the tool to prove that there is no state from which we can transition <em>into</em> BoilWater:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">static public void BoilWaterIsInitial(CookPasta someState)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; var next = CanTransition(someState, CookPasta.BoilWater);</span><br /><span style="font-family: courier new,courier;">&nbsp; Contract.Assert(<strong>!next</strong>, "there is no way to transition to boiling water");</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p>Similarly, we can ask the tool to prove that there is successor for Eat.</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">static public void EatingIsFinal(CookPasta someOtherState)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; var next = CanTransition(CookPasta.Eat, someOtherState);</span><br /><span style="font-family: courier new,courier;">&nbsp; Contract.Assert(<strong>!next</strong>, "Once you eat your pasta, nothing left to do");</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p>Nevertheless, if we ask whether Strain is final, cccheck will tell that it is not:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">static public void StrainIsFinal(CookPasta someOtherState)</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; var next = CanTransition(CookPasta.Strain, someOtherState);&nbsp; </span><br /><span style="font-family: courier new,courier;">&nbsp; Contract.Assert(<strong>!next</strong>, "We cannot prove it, as it is false");</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">d:\tmp\Pasta\CookPasta.cs(58,9): warning : CodeContracts: <strong>assert unproven</strong></span></p>
<p><strong>What's the magic behind</strong>?&nbsp;There is no magic. The static analyzer will infer the inputs under which <span style="font-family: courier new,courier;">CanTransition</span> returns true, and then it uses this information to prove (or disprove) the assertion. If you are curious to see what the inferred postcondition looks like, add "-infer methodensures" to the extra static checker options box in VS.</p>]]></content:encoded>
    </item>
    <item>
      <title>How to use cccheck to prove no case is forgotten</title>
      <link>https://docs.microsoft.com/archive/blogs/francesco/how-to-use-cccheck-to-prove-no-case-is-forgotten</link>
      <pubDate>Fri, 12 Sep 2014 14:31:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Logozzo]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/francesco/2014/09/12/how-to-use-cccheck-to-prove-no-case-is-forgotten/</guid>
      <description><![CDATA[Today we use the CodeContracts static checker to prove that no case is missing in a switch...]]></description>
      <content:encoded><![CDATA[<p><span style="color: black; font-family: 'Arial','sans-serif'; font-size: 9pt;">Today we use the CodeContracts static checker to prove that no case is missing in a switch statement. This post is inspired by some feedback we had from CodeContracts users in product groups.</span></p>
<p><span style="color: black; font-family: 'Arial','sans-serif'; font-size: 9pt;"><strong>The problem. </strong>Suppose that we want to write a program to cook pasta. Cooking pasta is a simple. First we let the water boil, we add the pasta, we stir, and eventually we strain. We define an enum CookPasta to remember in which state we are and a Next method to tell us what&rsquo;s coming next. The code is straightforward:</span></p>
<p><code class="csharp">enum CookPasta { BoilWater, AddPasta, Stir, Strain, Done&nbsp;}<br /> <br /> public CookPasta Next(CookPasta state)<br />{</code></p>
<p><code class="csharp"></code><code class="csharp">&nbsp; switch(state)<br />&nbsp; {<br />&nbsp;&nbsp;&nbsp; case CookPasta.BoilWater:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return CookPasta.AddPasta;<br /> <br />&nbsp;&nbsp;&nbsp; case CookPasta.AddPasta:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return CookPasta.Stir;<br /><br />&nbsp;&nbsp;&nbsp; case CookPasta.Stir:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return CookPasta.Strain;</code></p>
<p><code class="csharp">&nbsp;&nbsp;&nbsp; case CookPasta.Strain:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return CookPasta.Done;</code></p>
<p><code class="csharp">&nbsp;&nbsp;&nbsp; case CookPasta.Done:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return CookPasta.Done;<br /><br />&nbsp;&nbsp;&nbsp; default:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new Exception("Unknown pasta state!");<br />&nbsp;&nbsp; }<br /> }</code></p>
<p>We added a throw statement&nbsp;to make the C# compiler happy - it would refuse to compile our code otherwise. However, we soon realize that our algorithm to cook pasta is wrong. We forgot a fundamental step: We need to add salt to the boiling water! Therefore we add a case to the enum case:</p>
<p><code class="csharp"></code><code class="csharp">enum CookPasta { BoilWater, AddPasta, <strong>AddSalt,</strong> Stir, Strain, Done&nbsp;}<br /></code>&nbsp;</p>
<p>But now suppose that we forgot to update the Next method (in real code there can be tenths of places to be updated). What is going to happen? An exception ("Unknown pasta state") will be thrown at runtime. But we love compile time analysis, so is there a&nbsp;way to have&nbsp;the static checker warn us that we forgot one case?</p>
<p><strong>The solution</strong>. It is straightforward: All we need is to add an Assert(false) in the default branch:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">default:</span><br /><strong><span style="font-family: courier new,courier;">&nbsp; Contract.Assert(false); // The static checker should prove it unreachable</span></strong><br /><span style="font-family: courier new,courier;">&nbsp; throw new Exception("Unknown pasta state!");</span></p>
<p>We are essentially&nbsp;asking the static checker to prove false, which is of course impossible. In fact, we get:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;warning : CodeContracts: This assert, always leading to an error, may be reachable. Are you missing an enum case?</span></p>
<p>If we fix the code, adding the missing cases</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">case CookPasta.BoilWater:</span><br /><span style="font-family: courier new,courier;">&nbsp; return CookPasta.AddSalt;</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">case CookPasta.AddSalt:</span><br /><span style="font-family: courier new,courier;">&nbsp; return CookPasta.AddPasta;</span></p>
<p>then cccheck will not emit any warning. <em>Why? </em>Did it just proved the impossible (false)? Actually no, it proved that there is no execution reaching the Contract.Assert(false), as we&nbsp;covered all the cases for CookPasta.</p>
<p><strong>The improved solution</strong>. Nevertheless, there is something a little bit ugly about the above solution, as&nbsp;some friend in Microsoft product groups noticed. We should write two lines of code, an assert for the static (and dynamic) checker, and a throw instruction for the C# compiler. Is there&nbsp;a better way of doing it? The trick is to defined an helper class CodeContractsHelpers with an helper function ThrowIfReached.</p>
<p>In the switch statement we write something like</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">default:</span><br /><strong><span style="font-family: courier new,courier;">&nbsp;&nbsp;throw CodeContractsHelpers.ThrowIfReached("Unknown pasta state!");</span></strong></p>
<p>Now it is a matter of defining ThrowIfReached. This is pretty easy:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;public static class CodeContractsHelpers</span><br /><span style="font-family: courier new,courier;">&nbsp; {</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; [ContractVerification(false)]</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; public static Exception ThrowIfReached(string s)</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; {</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Contract.Requires(false);</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return new Exception(s);</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; }</span><br /><span style="font-family: courier new,courier;">&nbsp; }</span></p>
<p>The helper method returns&nbsp;a new exception object. It has a precondition "false", <em>i.e.,</em> it requires to never be called. When analyzing the Next method the static checker will turn the Contract.Requires(false) into a Contract.Assert(false), so that we have the same behavior as above - The static checker will complain if we miss one (or more) case. Finally we use the [ContractVerification(false)]&nbsp;to turn the verification of this&nbsp;helper off.</p>
<p><strong>Is it sound? </strong>Are we 100% guaranteed that our switch case is comprehensive, and as a consequence no execution will ever reach the default branch? In the usual case yes. If the programmer only uses the defined enums, then everything is fine. However, C# allows to <em>forge </em>new enum values like this</p>
<p><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; public const CookPasta AddOil = (CookPasta)(-1);</span></p>
<p>and invoke Next like this (with no type-checking error from C#):</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">var next = Next(AddOil);</span></p>
<p>Luckily the static checker will realize there may be a problem, and it will warn about it:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">warning : CodeContracts: The actual value is not one of those defined for this enum. Forgotten [Flag] in the enum definition?</span></p>
<p>&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>FAQ #1: What is the difference between Assert and Assume?</title>
      <link>https://docs.microsoft.com/archive/blogs/francesco/faq-1-what-is-the-difference-between-assert-and-assume</link>
      <pubDate>Wed, 03 Sep 2014 21:43:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Logozzo]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/francesco/2014/09/03/faq-1-what-is-the-difference-between-assert-and-assume/</guid>
      <description><![CDATA[In CodeContracts, as in&nbsp;most verification systems, we have two APIs to check the validity of an...]]></description>
      <content:encoded><![CDATA[<p>In CodeContracts, as in&nbsp;most verification systems, we have two APIs to check the validity of an expression at a given program point: Contract.Assert and Contract.Assume. People (even very smart Academics with a Ph.D. in computer science!) often get confused by the two concepts. They tend to use Contract.Assert most of the times.</p>
<p>In this first post, I'd like to explain the difference between the two concepts, and guide you in the usage of one or the other kind of contract.</p>
<p>Intuitively, Assert is something that you expect the&nbsp;static checker be able to prove at compile time, whereas Assume is something that&nbsp;the static checker can rely upon, but it will not try to prove. At runtime Assert and Assume behave the same: If the condition is false, then the program fails &ndash; how it fails (<em>e.g., </em>throwing an exception, opening a dialog box, <em>etc</em>. can be completely customized with CodeContracts). &nbsp;</p>
<p>For instance, in the code below we expect that on loop exit that the value of i is 1001, and we ask the static checker to prove it.</p>
<p>&nbsp;&nbsp;<span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;public void Count()</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; {</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var i = 0;</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var j = 1000;</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while (j &gt;= 0)</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i++;</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; j--;</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Contract.Assert(i == 1001);</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; }</span></p>
<p>In fact, the static analyzer infers that after the loop:</p>
<p style="padding-left: 30px;">i + j == 1000 and j == -1</p>
<p>and it deduces that the assertion holds.&nbsp;</p>
<p><strong>Intermezzo:</strong> Try this example with the CodeContracts static checker and you see that it can prove the assertion. Then try to change the assertion, let's say to i == 1000, and it will complain that it is false. How the tool infer the loop invariant? Stay tuned, I will post about it&hellip;</p>
<p>Nevertheless, there is so much that&nbsp;<strong>every </strong>static program analyzer or&nbsp;verifier in the world knows or can infer (do you remember <a href="http://en.wikipedia.org/wiki/Halting_problem">Turing</a>?). There are cases where we need to help the tool by telling &ldquo;<em>please believe me, at this program point this condition is true, so do not try to prove it&rdquo;</em>. In such cases you will use Contract.Assume.</p>
<p>As an example, let us imagine that we have a sensor that reads the room temperature, but it does it using the Kelvin temperature scale. The Kelvin temperature scale is great for science (values are always non-negative, the smallest values is the absolute zero) but not so much for humans (70K may seem very hot, but actually it&rsquo;s extremely cold&hellip;). So, let&rsquo;s write a small function to read from our sensor and convert to Celsius. We are careful programmers, and we also want to document, via a postcondition, the smallest value our implementation can return. Our code looks like</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">// No contract</span><br /><span style="font-family: courier new,courier;">extern double ReadTheTemperatureInKelvinFromSensors();</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">public double GetTemperatureInCelsius()</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp; &nbsp; Contract.Ensures(Contract.Result&lt;double&gt;() &gt;= -273.15);</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; var kelvin = ReadTheTemperatureInKelvinFromSensors();</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; return kelvin - 273.15;</span><br />}</p>
<p>Then, we want to prove it correct. So we run the static checker. Which complains that it cannot&nbsp;prove the postcondition. Why is this? The problem is that the static checker has no knowledge about what &nbsp;ReadTheTemperatureInKelvinFromSensors does, and in particular it does not know that it always returns a non-negative value. We make this assumption explicit, to the static checker, but also to the human who reads the code:</p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">public double GetTemperatureInCelsius()</span><br /><span style="font-family: courier new,courier;">{</span><br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; Contract.Ensures(Contract.Result&lt;double&gt;() &gt;= -273.15);</span></p>
<p style="padding-left: 30px;"><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; var kelvin = ReadTheTemperatureInKelvinFromSensors();</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /><span style="font-family: courier new,courier;"><strong>&nbsp;&nbsp;&nbsp; Contract.Assume(kelvin &gt;= 0, "Physical world assumption - Checked at runtime");</strong></span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /><span style="font-family: courier new,courier;">&nbsp;&nbsp;&nbsp; return kelvin - 273.15;</span><br /><span style="font-family: courier new,courier;">}</span></p>
<p>The static checker will not try to prove that kelvin is non-negative, it will assume it and as a consequence&nbsp;it will prove the postcondition will never be violated. But what happens at runtime if there is a failure in the sensor and it will return a "crazy" value? Well, as we made the assumption explicit, the execution will stop at Assume(kelvin &gt;= 0) immediately pointing out&nbsp;the place where&nbsp;something went wrong...&nbsp;</p>
<p>&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>Welcome to my blog!</title>
      <link>https://docs.microsoft.com/archive/blogs/francesco/welcome-to-my-blog</link>
      <pubDate>Wed, 03 Sep 2014 13:27:12 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Logozzo]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/francesco/2014/09/03/welcome-to-my-blog/</guid>
      <description><![CDATA[Hello. I've decided to start a blog to help CodeContracts users, present some tricks to get the best...]]></description>
      <content:encoded><![CDATA[<p>Hello. I've decided to start a blog to help CodeContracts users, present some tricks to get the best from the tools, in particular the static checker and in general to give some update on what's new and cool in the program analysis and verification environments as well as to explain some of the theory and the concepts that are at the base of static analysis and verification</p>]]></content:encoded>
    </item>
  </channel>
</rss>