Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Exceptions and Contracts

Type Invariants and Predicates

Learn Ada type contracts: Static_Predicate, Dynamic_Predicate and Type_Invariant aspects that keep data valid, when they are checked and how they differ, with C stand-ins.

Subprogram contracts say what a call needs and delivers. But some rules belong to the data itself: a date must have a valid month, a sorted list must stay sorted, a bank account must never be negative. Ada 2012 gives you three aspects for that: Static_Predicate, Dynamic_Predicate and Type_Invariant. They attach the rule to the type, so every object of the type is covered without repeating checks.

The Ada code is read-only on this site (no compiler), and the C stand-ins are runnable models of the same ideas.

Static predicates

A static predicate restricts a subtype to a set known at compile time, typically a list of values or ranges:

ADA
type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);

subtype Weekend is Day
  with Static_Predicate => Weekend in Sat | Sun;

subtype Odd_Digit is Integer range 0 .. 9
  with Static_Predicate => Odd_Digit in 1 | 3 | 5 | 7 | 9;

Because the predicate is static, the compiler can use it in case statements (no "others" is needed if all weekend values are covered), for loops over the subtype (for D in Weekend loop visits Sat then Sun) and membership tests. Assigning an out-of-set value, for example W : Weekend := Mon;, raises Ada.Assertions.Assertion_Error when assertions are on.

Dynamic predicates

A dynamic predicate can use any Boolean expression, including function calls and other variables:

ADA
subtype Even is Integer
  with Dynamic_Predicate => Even mod 2 = 0;

type Int_Array is array (Positive range <>) of Integer;

subtype Sorted_Array is Int_Array
  with Dynamic_Predicate =>
    (for all I in Sorted_Array'First .. Sorted_Array'Last - 1 =>
        Sorted_Array (I) <= Sorted_Array (I + 1));

Sorted_Array is now a subtype of an array type whose values are always in order, and the for all quantified expression says it in one line. A subprogram that takes a Sorted_Array parameter gets the sortedness check on entry for free, and a function returning one gets it checked on exit.

A predicate is checked at specific points: initialization, assignment, conversion, parameter passing in and out, and similar "new value of this subtype" events. It is not checked after you change a single component of an existing object (Arr (3) := 0; can break sortedness without a check), which is the main limitation of predicates.

Three data aspects

Static_Predicate compile-time set
Dynamic_Predicate any Boolean expression
Type_Invariant private type, checked at the boundary

All three raise Assertion_Error when checked and false.

1 / 2

Type invariants

A type invariant applies to a private type and describes what must be true of every object as seen from outside the package. Inside the package, operations may temporarily break it, as long as it is restored when they return to the client.

ADA
package Accounts is
   type Account is private
     with Type_Invariant => Is_Valid (Account);

   function Is_Valid (A : Account) return Boolean;
   function Balance (A : Account) return Integer;
   procedure Deposit  (A : in out Account; Amount : Positive);
   procedure Withdraw (A : in out Account; Amount : Positive)
     with Pre => Amount <= Balance (A);
private
   type Account is record
      Cents    : Integer := 0;
      Overdraft : Natural := 0;
   end record;

   function Is_Valid (A : Account) return Boolean is
     (A.Cents >= -A.Overdraft);
end Accounts;

The invariant is checked after each public operation that creates or modifies an Account (when it returns to the client), and on conversions into the type. Clients can never see an invalid account, and the invariant is written once, next to the type, rather than as a Post on every procedure. Compare this with putting the same rule in each Post: it would be repeated and could be forgotten for a new operation.

Predicate or invariant?

Predicate Type invariant
Applies to any (sub)type private/tagged types only
Checked on new values entering the subtype at the package boundary, after public operations
Component updates not checked checked after the public procedure
Typical use value sets, sortedness consistency of hidden representation

Stand-in: the invariant as a checked boundary (C, runnable)

C has no private types with invariants, but an opaque struct and a check function placed at the end of every public operation behaves the same way. The program shows deposit and withdraw succeeding, and an invalid state being caught at the boundary instead of leaking out.

C C stand-in: invariant checked after each public call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a sorted-array predicate and its blind spot (C, runnable)

This example models Sorted_Array. The check happens when a whole value is accepted. After that, a single-element write slips through unnoticed, just like the component-update limitation of predicates.

C C stand-in: predicate on a whole value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which aspect can only be applied to a private (or tagged) type and is checked at the package boundary?

    Type_Invariant describes the consistency of hidden representations as seen by clients.
  2. 2. What is the main advantage of Static_Predicate over Dynamic_Predicate?

    Static predicates are compile-time sets and are usable as loop ranges and case choices.
  3. 3. Is a predicate checked when you change a single component of an existing array?

    This is a known limitation; whole-value events trigger the check.
  4. 4. What is Dynamic_Predicate => Even mod 2 = 0 on an Integer subtype an example of?

    It restricts the values of the subtype itself.

Summary

  • Predicates restrict a subtype's values; static ones are compile-time sets, dynamic ones are any Boolean.
  • A type invariant keeps the hidden state of a private type consistent at the package boundary.
  • Predicates are checked on whole-value events, not on single-component updates.
  • Put rules about data on the type, not repeated in every contract.

Next: What Is SPARK?