ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Contract.h File Reference

The contracts of ADS: the preconditions, the postconditions and the invariants of the operations, checked at run time by four macros that mirror the contracts of C++26 (pre, post and contract_assert), so that they can be replaced by them when the compilers support them: More...

#include <concepts>
#include <optional>
#include <stdexcept>
#include <string>

Go to the source code of this file.

Classes

class  ADS::contract_violation
 a contract violated: a bug of the caller (a precondition) or of ADS More...

Namespaces

namespace  ADS

Macros

#define ADS_CONTRACTS   1
 the level of the contracts checked: 0 none, 1 preconditions, 2 postconditions, 3 invariants and audits; 1 by default, 0 with NDEBUG
#define ADS_CONTRACT_CHECK(level, kind, cond)
 the check of the condition cond, a contract of the kind kind, when ADS_CONTRACTS is at least level: contract_violation if it is false
#define ADS_PRE(cond)
 [check]
#define ADS_POST(cond)
 a postcondition, checked from level 2
#define ADS_INVARIANT(cond)
 an invariant, checked from level 3
#define ADS_AUDIT(cond)
 a precondition or a postcondition dearer than the operation, checked from level 3

Detailed description

The contracts of ADS: the preconditions, the postconditions and the invariants of the operations, checked at run time by four macros that mirror the contracts of C++26 (pre, post and contract_assert), so that they can be replaced by them when the compilers support them:

  • ADS_PRE( c ), at the start of an operation, what the caller must ensure (e.g., ! empty() before deleteMin());
  • ADS_POST( c ), at the end, what the operation ensures, when it costs no more than the operation itself;
  • ADS_INVARIANT( c ), at the end of the operations that change a structure, its invariant (e.g., the order of a heap), which usually costs \( O( n ) \) and is meant for the tests;
  • ADS_AUDIT( c ), a precondition or a postcondition that costs more than the operation (e.g., a sorted vector before a binary search), checked with the invariants.

The level ADS_CONTRACTS chooses which are checked: 0 none, 1 the preconditions (the default, 0 when NDEBUG is defined, as for assert), 2 also the postconditions, 3 also the invariants and the audits. A violated contract throws ADS::contract_violation, a std::logic_error whose message names the kind of contract, the condition, the function and the place in the source. The conditions are compiled at every level, so that they stay correct C++, but they are not evaluated above the level chosen; hence they must have no side effects.

See also
J. Berne, T. Doumler, A. Krzemienski et al., Contracts for C++, P2900R14, ISO/IEC JTC1/SC22/WG21, 2025
B. Meyer, Applying "design by contract", Computer 25(10), 40-51, 1992, doi:10.1109/2.161279
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa