Skip to content

4. Contracts

A type says what values can exist. A contract says what a subprogram needs and what it promises. This chapter reads missile guidance, the code that decides what a heat-seeker chases. It is where the engine's contracts first start to say something about the game, not just about numbers.

Preconditions

Guidance needs to ask where a target is. A target is a number (chapter 3), and only some numbers name something that exists right now:

engine/src/adawars-guidance.ads
   --  Whether target T exists: a flying jet, or a burning flare.
   function Exists (Jets : Jet_Array; Flares : Flare_Table; T : Target)
     return Boolean
   is (case T is
          when No_Target    => False,
          when Jet_Target   =>
            T in Jets'Range and then Jets (T).State = Flying,
          when Flare_Target =>
            Flare_Owner (T) in Flares'Range
            and then Flares (Flare_Owner (T)) (Flare_Slot_Of (T)).Active);

   --  Where target T is.
   function Position (Jets : Jet_Array; Flares : Flare_Table; T : Target)
     return Point
   is (if T in Jet_Target then Jets (T).Pos
       else Flares (Flare_Owner (T)) (Flare_Slot_Of (T)).Pos)
   with Pre => Exists (Jets, Flares, T);

A case can branch on subtypes: each when names a range of values, and together they must cover them all.

Position has a precondition, Pre. It is the caller's side of the bargain: call Position only for a target that exists. In return, Position need not check. Its body indexes Jets (T) without testing that T is a jet in this match, because the precondition already says so.

That is the alternative to defensive if statements. Instead of every function checking its inputs and inventing something to do when they are wrong, the requirement is written down once, as part of the interface, and it is checked at every call.

Postconditions that specify

Here is the heart of a heat-seeker. First, what it may lock onto:

engine/src/adawars-guidance.ads
   --  Whether the missile may lock onto T: something its seeker detects,
   --  never its owner's own jet or flares.
   function Is_Candidate
     (M : Missile; Owner : Player_Id; Jets : Jet_Array; Flares : Flare_Table;
      T : Target) return Boolean
   is (Exists (Jets, Flares, T)
       and then Detects (Weapons (M.Kind).Seeker, M.Pos, M.Heading,
                         Position (Jets, Flares, T))
       and then Owner_Of (T) /= Owner);

and then matters here. Position may only be called when Exists is true, and and then evaluates its right-hand side only if the left is true. With plain and, the call to Position could happen for a target that does not exist, and the precondition would fail.

Then the choice:

engine/src/adawars-guidance.ads
   function Lock_On
     (M : Missile; Owner : Player_Id; Jets : Jet_Array; Flares : Flare_Table)
      return Target
   with
     Post =>
       (if Lock_On'Result = No_Target
        then
          (for all T in Target =>
             not Is_Candidate (M, Owner, Jets, Flares, T))
        else
          Is_Candidate (M, Owner, Jets, Flares, Lock_On'Result)
          and then (for all T in Target =>
                      (if Is_Candidate (M, Owner, Jets, Flares, T)
                       then Heat_Of (Jets, Flares, T)
                            <= Heat_Of (Jets, Flares, Lock_On'Result))));

This postcondition is a complete specification of the heat-seeker's choice. In English:

  • if it locks onto nothing, there was nothing it could lock onto;
  • otherwise it locked onto a candidate, and no candidate is hotter.

The body, a loop over every target, is in the next chapter but one. What matters here is that the contract says what the heat-seeker does without saying how. Anyone reading the spec knows how the missile behaves. And since a flare burns hotter than any jet, it follows that a flare in the seeker always wins.

A contract can also be a bound rather than a full definition:

engine/src/adawars-guidance.ads
   function Steer
     (M : Missile; Lock : Target; Jets : Jet_Array; Flares : Flare_Table)
      return Offset
   is (if Lock = No_Target then 0
       else Limit (Diff (Bearing (M.Pos, Position (Jets, Flares, Lock)),
                         M.Heading),
                   Weapons (M.Kind).Turn))
   with
     Pre  => Lock = No_Target or else Exists (Jets, Flares, Lock),
     Post => abs Steer'Result <= Weapons (M.Kind).Turn;

Steer's body is its definition, pure pursuit: turn towards the target as far as the turn rate allows. The postcondition adds the one property callers care about: a missile never turns faster than its weapon can.

Contracts at run time

Contracts are Ada, not comments, so they can be executed. The engine is compiled with -gnata, which turns every Pre, Post, predicate and pragma Assert into a run-time check. (It is the contracts = "Yes" line in engine/alire.toml.) A failed check raises Assertion_Error, naming the contract that failed.

Proof makes those checks redundant inside the engine: GNATprove has shown they never fail. They stay on anyway, as a second line of defence, and because the code calling the engine (the tests, the server) is not proved. For that code, the checks are what catch a broken promise.

Try it

Call a function out of contract. Survivor finds the one jet left flying, and its precondition says there must be one:

engine/src/adawars-worlds.ads
   function Survivor (Jets : Jet_Array) return Player_Id
   with
     Pre  => Has_Survivor (Jets),
     Post => Sole_Survivor (Jets, Survivor'Result);

Call it in a test at the start of a match, when every jet is flying:

Try: engine/tests/test_simulation.adb
    --  A new match.
    Check (Fresh.Result.Kind = Running, "new match runs");
+   Check (Survivor (Fresh.Jets) = 1, "a survivor at the start");

The test does not get a wrong answer. It gets no answer: the precondition fails at the call.

Expect: test fails
raised ADA.ASSERTIONS.ASSERTION_ERROR : failed precondition from adawars-worlds.ads

Prove the wrong thing. Take the owner rule out of Is_Candidate, so a heat-seeker may lock onto the jet that fired it:

Try: engine/src/adawars-guidance.ads
        and then Detects (Weapons (M.Kind).Seeker, M.Pos, M.Heading,
-                         Position (Jets, Flares, T))
-       and then Owner_Of (T) /= Owner);
+                         Position (Jets, Flares, T)));

Now prove guidance:

Expect: prove adawars-guidance.adb passes
warning: unused variable "Owner"

It still proves! Lock_On's postcondition is stated in terms of Is_Candidate, so when the definition of a candidate changes, the proof follows it. The only hint is a warning that Owner is no longer used. The tests know better, because one of them states the rule directly:

Expect: test fails
FAIL no lock on the jet that fired it

This is the most important lesson about proof: a proof shows that the code meets its specification, not that the specification is what you meant. Specifications must be read, and checked against the rules, as carefully as code. Tests that state the rules a second way are still worth having.

Recap

  • Pre is what the caller must ensure; Post is what the subprogram then guarantees.
  • A precondition replaces defensive checks inside the subprogram with a requirement on its callers.
  • A postcondition can define a result completely, or bound it.
  • and then guards the right-hand side, which matters when it has a precondition of its own.
  • With -gnata, contracts are run-time checks too, raising Assertion_Error.
  • A proof is only as good as its specification.