Much Ado About Verada

A cheerful guide to programs that keep their promises.

12 · To Have and to Hold

How do I change one seat and preserve the rest of the chart?

Viola's receipt says seat 3 is free. She wants to book it, so Puck needs to mark it taken. Otherwise, the next lookup could offer it again. The curtain department has declined to build another seat 3. Puck will write two operations, one to reserve a seat and one to release it. Each will say whether it succeeded and change only the requested seat if it needs to.

Bring with you. The seating chart, the public contract, and chapter 9's “every.”

Compare the chart before and after

Start with seats 3, 5, and 7 free. Viola books seat 3. Olivia then asks to book the same seat, and finally Viola cancels. Follow seat 3 down the chart below. Each request starts with the flag left by the previous request. The names help us follow the scene. The program stores only the occupancy flags.

Booking trace for seat 3. Viola books it when free. It is taken after her booking. Olivia's request is refused and it stays taken. Viola cancels and it is free again. Every other seat stays as it was.

Three requests. Only seat 3 changes costume.

A writable parameter lets the operation change the chart supplied by its caller. The contract can refer to the entry value, the chart as it was when this call began. For the second request, that's the chart after the first reservation.

For reservation, start with the requested seat. If it was free on entry, the operation accepts. If it was taken, the operation refuses. Either way, that seat is taken when the call returns.

Now look at the rest of the row. For every other slot, its new flag equals its own entry flag. This part of the promise is called the frame. It tells the caller which facts about the chart still hold after the operation. On refusal, the requested seat was taken and stays taken. The frame covers the rest, so the whole row stays the same.

A small reservation tag hangs from seat 3.

Give cancellation the same shape

A cancellation reports whether the seat was taken on entry. On return the seat is free, and every other seat keeps its old flag. A request to release an already free seat leaves it free and reports that nothing was released. In this rehearsal, a successful reservation followed by a cancellation brings the original chart back.

Example 12-1 · Reserve, refuse, release

Copy your example project. Read the three parts of the reservation contract first. Find the decision, the flag after the call, and the promise about all the other flags. The quantified clause lets the chosen slot through and compares old and new values for each other slot. Then see how cancellation mirrors the reservation.

Vada · Ada · Example 12-1

seating.vads · Link to this version

package Seating is
   type Seat_Number is range 1 .. 8;
   subtype Row_Offset is Natural range 0 .. 7;
   type Seat_Row is array (Row_Offset) of Boolean;

   function To_Offset (Seat : Seat_Number) return Row_Offset is
     (Integer (Seat) - 1);

   function At_Offset (Taken : Seat_Row; Slot : Row_Offset) return Boolean is
     (Taken (Slot));

   procedure Reserve (Taken : in out Seat_Row; Seat : Seat_Number;
                      Accepted : out Boolean)
     with Post => Accepted = (not At_Offset (Taken'Old, To_Offset (Seat)))
       and Taken (To_Offset (Seat))
       and (for all Slot in Row_Offset =>
         Slot = To_Offset (Seat) or else Taken (Slot) = At_Offset (Taken'Old, Slot));

   procedure Cancel (Taken : in out Seat_Row; Seat : Seat_Number;
                     Released : out Boolean)
     with Post => Released = At_Offset (Taken'Old, To_Offset (Seat))
       and not Taken (To_Offset (Seat))
       and (for all Slot in Row_Offset =>
         Slot = To_Offset (Seat) or else Taken (Slot) = At_Offset (Taken'Old, Slot));
end Seating;

seating.vadb

package body Seating is
   procedure Reserve (Taken : in out Seat_Row; Seat : Seat_Number;
                      Accepted : out Boolean)
   is
      Slot : constant Row_Offset := To_Offset (Seat);
   begin
      Accepted := not Taken (Slot);
      if Accepted then
         Taken (Slot) := True;
      end if;
   end Reserve;

   procedure Cancel (Taken : in out Seat_Row; Seat : Seat_Number;
                     Released : out Boolean)
   is
      Slot : constant Row_Offset := To_Offset (Seat);
   begin
      Released := Taken (Slot);
      if Released then
         Taken (Slot) := False;
      end if;
   end Cancel;
end Seating;

main.vadb

with Ada.Text_IO; use Ada.Text_IO;
with Seating; use Seating;

procedure Main is
   Original : constant Seat_Row :=
     [True, True, False, True, False, True, False, True];
   Taken : Seat_Row := Original;
   After_Reserve : Seat_Row;
   Accepted, Released : Boolean;
begin
   Reserve (Taken, 3, Accepted);
   pragma Assert (Accepted and Taken (2));
   pragma Assert (Taken (3) and not Taken (4));
   Put_Line ("Seat 3 reserved.");

   After_Reserve := Taken;
   Reserve (Taken, 3, Accepted);
   pragma Assert (not Accepted);
   pragma Assert (for all Slot in Row_Offset => Taken (Slot) = After_Reserve (Slot));
   Put_Line ("Seat 3 already taken.");

   Cancel (Taken, 3, Released);
   pragma Assert (Released);
   pragma Assert (for all Slot in Row_Offset => Taken (Slot) = Original (Slot));
   Put_Line ("Seat 3 released.");
end Main;
Varc · C-family · Example 12-1

seating.va · Link to this version

package Seating {
    pub type Seat_Number = range 1...8;
    pub subtype Row_Offset = Natural range 0...7;
    pub type Seat_Row = [Row_Offset]Boolean;

    pub fn to_offset(seat: Seat_Number) -> Row_Offset = Integer(seat) - 1;

    pub fn reserve(taken: inout Seat_Row, seat: Seat_Number, accepted: out Boolean)
        ensures accepted == !old(taken)[to_offset(seat)]
        ensures taken[to_offset(seat)]
        ensures forall slot in Row_Offset =>
            slot == to_offset(seat) || taken[slot] == old(taken)[slot]
    {
        let slot: Row_Offset = to_offset(seat);
        accepted = !taken[slot];
        if accepted {
            taken[slot] = True;
        }
    }

    pub fn cancel(taken: inout Seat_Row, seat: Seat_Number, released: out Boolean)
        ensures released == old(taken)[to_offset(seat)]
        ensures !taken[to_offset(seat)]
        ensures forall slot in Row_Offset =>
            slot == to_offset(seat) || taken[slot] == old(taken)[slot]
    {
        let slot: Row_Offset = to_offset(seat);
        released = taken[slot];
        if released {
            taken[slot] = False;
        }
    }
}

main.va

import Ada.Text_IO; use Ada.Text_IO;
import Seating; use Seating;

fn Main() {
    let original: Seat_Row = [True, True, False, True, False, True, False, True];
    var taken: Seat_Row = original;
    var accepted, released: Boolean;
    reserve(&taken, 3, &accepted);
    assert accepted && taken[2];
    assert taken[3] && !taken[4];
    Put_Line("Seat 3 reserved.");

    let after_reserve: Seat_Row = taken;
    reserve(&taken, 3, &accepted);
    assert !accepted;
    assert forall slot in Row_Offset => taken[slot] == after_reserve[slot];
    Put_Line("Seat 3 already taken.");

    cancel(&taken, 3, &released);
    assert released;
    assert forall slot in Row_Offset => taken[slot] == original[slot];
    Put_Line("Seat 3 released.");
}
Vibe · Python · Example 12-1

seating.vb · Link to this version

from verada import Annotated, Array, Interval, RangeInt, ensures, old, result


class Seat_Number(RangeInt, ge=1, le=8):
    pass


type Row_Offset = Annotated[int, Interval(ge=0, le=7)]


class Seat_Row(Array[bool], size=8):
    pass


def to_offset(seat: Seat_Number) -> Row_Offset:
    return int(seat) - 1


def reserve(taken: Seat_Row, seat: Seat_Number) -> bool:
    ensures(result == (not old(taken)[to_offset(seat)]))
    ensures(taken[to_offset(seat)])
    ensures(all(slot == to_offset(seat) or taken[slot] == old(taken)[slot]
                for slot in range(8)))
    slot = to_offset(seat)
    if not taken[slot]:
        taken[slot] = True
        return True
    return False


def cancel(taken: Seat_Row, seat: Seat_Number) -> bool:
    ensures(result == old(taken)[to_offset(seat)])
    ensures(not taken[to_offset(seat)])
    ensures(all(slot == to_offset(seat) or taken[slot] == old(taken)[slot]
                for slot in range(8)))
    slot = to_offset(seat)
    if taken[slot]:
        taken[slot] = False
        return True
    return False

main.vb

from seating import Seat_Row, cancel, reserve


def main() -> None:
    taken = Seat_Row([True, True, False, True, False, True, False, True])
    original: Seat_Row = taken
    accepted: bool = reserve(taken, 3)
    assert accepted and taken[2]
    assert taken[3] and not taken[4]
    print("Seat 3 reserved.")

    after_reserve: Seat_Row = taken
    accepted = reserve(taken, 3)
    assert not accepted
    assert all(taken[slot] == after_reserve[slot] for slot in range(8))
    print("Seat 3 already taken.")

    released: bool = cancel(taken, 3)
    assert released
    assert all(taken[slot] == original[slot] for slot in range(8))
    print("Seat 3 released.")


if __name__ == "__main__":
    main()

Syntax note. Vada uses in out for the chart and out for the status. Its At_Offset helper reads a flag from the entry chart named by Taken'Old. Varc marks those parameters inout and out, marks the writable arguments with &, and reads the entry chart with old(taken). Vibe also uses old(taken). Verada infers the chart write from the function body, and the client assigns the Boolean result from the call.

The client saves a copy of the chart before the refusal and compares flags slot by slot afterward. In this example all three routes save a separate array value. Vibe's read-only after_reserve saves the flags as they were before the call, even though the assignment looks like ordinary Python. The comparisons reuse chapter 9's “every.” Run veradic prove and veradic run to check the sequence.

Seat 3 reserved.
Seat 3 already taken.
Seat 3 released.

A chalk eraser sweeps away one mark.

Your cue

  1. Find Olivia's refused request in the booking trace. Which part of the contract covers seat 3? Which part preserves seat 5?
  2. In the final call, try to cancel seat 5 instead of seat 3. Seat 5 is already free. Expect a false status and compare with the chart saved after Viola booked seat 3. Change the final line to Seat 5 already free. Prove and run.
  3. Restore the original project. Inside the successful reservation branch, add an assignment making offset 4 taken as well. Which promise does this break when the customer reserves seat 3?
Prompter's notes

The status and the selected-seat promise tell us that seat 3 was taken and is still taken. The frame preserves seat 5 because it is outside the requested slot.

Cancelling seat 5 reports false. Its flag stays free and the frame preserves every other flag, including the reservation of seat 3.

Offset 4 is seat 5. The extra write can change it even though the request is for seat 3. The reservation's frame fails with B5102. Restore the single intended write.

Puck can make a booking and undo it. At the last rehearsal, he tries a couple of edits to see what the checks catch. He brings an eraser. The moth brings a noticeboard.

← Previous: The Play Within the Package · Contents · Next: Exit, Pursued by a Counterexample →