Much Ado About Verada

A cheerful guide to programs that keep their promises.

4 · Measure for Measure

How do caller and function share a precise promise?

Bring with you: assignment, a guarded action, and an assertion worth keeping.

The guard kept the box office from selling a ninth ticket. Now the usher wants to use the same admission rule at the door. Puck needs a calculation the clerk and the usher can each call, with an agreement about who checks for room and what count comes back.

A function takes inputs and returns a result. Our function takes the old number sold and returns the new number. It does not reach into the caller's pocket and secretly replace its count. The caller chooses to store the returned result.

A two-part theatre ticket says Before: sold below 8, and After: result equals sold plus 1. A paper moth carries the input 8, which does not satisfy the entry promise.

“An excellent ticket,” said Puck. “It even says what the ticket seller must do.”

Two halves of one agreement

A precondition states what must be true before a call. The caller has to establish it. A postcondition states what the function promises on normal return. The body has to establish it, using the precondition as a starting fact. Together these promises form the function's contract.

For our eight-seat theatre:

The first half justifies the addition. Together, the two halves also tell us the result cannot exceed eight. A caller that knows these promises can reason about the returned count without reading the function's implementation.

Predict first. What sold count should the function return if the caller starts with 5 tickets sold? What obligation would the caller fail at 8 tickets sold?

Puck holds the two halves of a theatre ticket.

A small company of files

This example introduces a module so the promise can sit at an interface. Copy all files for your chosen syntax, including verada.toml, from its example project into an empty folder. Keep them together.

Vada uses box_office.vads for the public specification, box_office.vadb for its body, and main.vadb for the caller. Varc puts its package interface and body in box_office.va; pub makes the function available outside. Vibe uses a module named box_office.vb. All three have a separate main file. We will return to module design in a later chapter; for now the split lets us see who promises what.

Example 4-1 · One more customer

Vada · Ada · Example 4-1

box_office.vads · Link to this version

package Box_Office is
   function Admit_One (Sold : Natural) return Natural
     with Pre => Sold < 8,
          Post => Admit_One'Result = Sold + 1;
end Box_Office;

box_office.vadb

package body Box_Office is
   function Admit_One (Sold : Natural) return Natural is
   begin
      return Sold + 1;
   end Admit_One;
end Box_Office;

main.vadb

with Ada.Text_IO;
with Box_Office;

procedure Main is
   Sold : Natural := 5;
begin
   Sold := Box_Office.Admit_One (Sold);
   pragma Assert (Sold = 6);
   Ada.Text_IO.Put_Line ("Sold:" & Natural'Image (Sold));
end Main;
Varc · C-family · Example 4-1

box_office.va · Link to this version

package Box_Office {
    pub fn admit_one(sold: Natural) -> Natural
        requires sold < 8
        ensures result == sold + 1
    {
        return sold + 1;
    }
}

main.va

import Ada.Text_IO;
import Box_Office;

fn Main() {
    var sold: Natural = 5;
    sold = Box_Office.admit_one(sold);
    assert sold == 6;
    Ada.Text_IO.Put_Line("Sold:" ++ Natural::Image(sold));
}
Vibe · Python · Example 4-1

box_office.vb · Link to this version

from verada import Natural, ensures, requires, result


def admit_one(sold: Natural) -> Natural:
    requires(sold < 8)
    ensures(result == sold + 1)
    return sold + 1

main.vb

from verada import Natural
from box_office import admit_one


def main() -> None:
    sold: Natural = 5
    sold = admit_one(sold)
    assert sold == 6
    print("Sold:", sold)


if __name__ == "__main__":
    main()

Syntax note: Vada writes the promises as Pre and Post, Varc as requires and ensures, and Vibe as leading calls to those helpers. The result is Admit_One'Result in Vada and result in Varc/Vibe. These result forms belong in the postcondition; they are not variables to assign in the body. All three examples return a new count instead of changing the caller's, so the call looks the same in every syntax.

From the folder containing the copied project:

veradic prove
veradic run

verada.toml tells Verada where to find the source files, so you can omit the filename. From here on, use the whole example project and run commands from its folder. Once the proof succeeds, run prints:

Sold: 6

The exact proof counts may change between compiler versions. The obligations are the point: the caller supplies a legal starting value, the function safely adds one, the body keeps its postcondition, and the caller's assertion follows.

Follow the promise across the call

The caller starts with 5 tickets sold. That count fits Natural and is below the capacity of 8, so the caller meets the precondition. Inside the function, the parameter is known to be a Natural below eight. Adding one fits both the machine integer arithmetic and the Natural result.

The returned value is exactly the input plus one, so the postcondition holds. Back at the caller, the promised relation makes the new value six. The assertion checks that conclusion.

A contract is more than a comment: Verada generates checks for these obligations. It is also less than a full account of what anyone might want: we chose which property to state.

A theatrical skull rests on a script.

Alas, poor off-by-one.

Exit, pursued by a counterexample

Start from the working project. Prove after each edit to see which obligation fails.

Break the caller. Start its local count at eight rather than five. The caller can no longer establish the precondition. veradic prove reports B5101 for the call's precondition obligation. It is the caller's starting value we should reconsider; the function has not promised to admit somebody to a full theatre.

Break the body. Restore the caller's starting count of five. Make the function return Sold or sold instead of adding one. Now it returns a safe number, but fails its written promise. The expected diagnostic is B5102, a postcondition failure. “The number fits” and “the function did the requested job” are distinct facts.

Weaken the promise. Keep the incorrect return from the previous step. Use a postcondition that promises only a nonnegative result, Admit_One'Result >= 0 or result >= 0. The package's weak promise can now hold while doing no admission at all. The original caller assertion sold == 6 (Vada: Sold = 6) still demands more. Verada reports B5105 at that assertion. Removing it would let the proof succeed while the program leaves the count at five. Restore both the original return and the original postcondition, then prove again.

Forget the entry promise. Now delete only the precondition. In Vada, with Pre => Sold < 8, and the following Post => become a single with Post =>. In Varc, delete the requires sold < 8 line; in Vibe, delete requires(sold < 8). Prove. This report has every part a Verada diagnostic can have, so let's read it from top to bottom. Here is Vada's; Varc's and Vibe's differ in spelling and counts, not in substance.

error[B4101]: overflow check fails
 --> box_office.vadb:4:14
  |
4 |       return Sold + 1;
  |              ^^^^^^^^ might overflow `Integer` (-9223372036854775808 .. 9223372036854775807)
  |
  = note: replaying these values on the program reaches this check and it fails
  = counterexample: fails when Sold = Integer'Last
  = failing inputs: exactly Sold = Integer'Last
  = help: a precondition `Sold <= 9223372036854775806` on `Box_Office.Admit_One` excludes
          exactly the values that fail, and is proved to make this check pass

1 error emitted
proved 7 of 8 checks in 2 subprograms (3 statically, 4 by the solver)

The help is right about arithmetic and wrong about the theatre. Sold <= 9223372036854775806 would let the function admit customer number nine quintillion. Verada knows which numbers fit; only we know there are eight seats. Restore Sold < 8 and prove again before trying the exercises.

Verada may display a counterexample when it can identify inputs witnessing a failure. Which witness it chooses is not part of our contract. Sometimes a proof is unresolved without a confirmed counterexample. We will learn to tell those outcomes apart.

The counterexample moth carries an inconveniently large scroll.

Your cue

  1. Start the caller with 7 tickets sold. Use the precondition and postcondition to predict the new sold count. Set the caller's expected result to your prediction before running it.
  2. Explain who must prove the precondition and who must prove the postcondition.
  3. Why would changing < 8 to < 9 be a wrong repair for admitting a ninth customer?
  4. Design a different API on paper: an admission attempt that accepts a full house and reports refusal. What should it return, and what should remain unchanged? No new syntax required.
Prompter's notes · hints and answers

Seven satisfies the precondition; the postcondition says the result is eight. Change the caller's assertion to eight if you run that variant. Otherwise the original assertion still asks for six and should fail.

The caller establishes the precondition. The body establishes the postcondition under that starting assumption. The caller can then use the promised result relation.

Changing the bound to nine would let the function keep its arithmetic promise while violating the theatre's eight-seat requirement. A repair must preserve the intended rule, not merely silence a diagnostic.

An admission attempt could return an accepted/refused flag alongside the resulting count. On refusal, the count should be unchanged; on acceptance, it should increase by one and remain within capacity. We will learn the data forms needed to express that interface later.

Between shows · Day to day

Puck now has a project and the commands to keep it honest. Three habits make the daily routine easy.

You can now read a contract as a division of responsibility and explain why a safe calculation can still do the wrong job. The box office can keep a count of sales. The next customer asks for a particular seat, and Puck needs a number that can point to it.

← Previous: To Branch, or Not to Branch · Contents · Next: A Seat by Any Other Name →