contract_programming_overview.qbk 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. [/ Copyright (C) 2008-2018 Lorenzo Caminiti]
  2. [/ Distributed under the Boost Software License, Version 1.0 (see accompanying]
  3. [/ file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).]
  4. [/ See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html]
  5. [section Contract Programming Overview]
  6. [:['["It is absurd to make elaborate security checks on debugging runs, when no trust is put in the results, and then remove them in production runs, when an erroneous result could be expensive or disastrous. What would we think of a sailing enthusiast who wears his life-jacket when training on dry land but takes it off as soon as he goes to sea?]]]
  7. [:['-- Charles Antony Richard Hoare (see __Hoare73__)]]
  8. This section gives an overview of contract programming (see __Meyer97__, __Mitchell02__, and __N1613__ for more extensive introductions to contract programming).
  9. Readers that already have a basic understanding of contract programming can skip this section and maybe come back to it after reading the __Tutorial__.
  10. [note
  11. The objective of this library is not to convince programmers to use contract programming.
  12. It is assumed that programmes understand the benefits and trade-offs associated with contract programming and they have already decided to use this methodology in their code.
  13. Then, this library aims to be the best and more complete contract programming library for C++ (without using programs and tools external to the C++ language and its preprocessor).
  14. ]
  15. [section Assertions]
  16. Contract programming is characterized by the following assertion mechanisms:
  17. * /Preconditions/: These are logical conditions that programmers expect to be true when a function is called (e.g., to check constraints on function arguments).
  18. Operations that logically have no preconditions (i.e., that are always well-defined for the entire domain of their inputs) are also referred to as having a /wide contract/.
  19. This is in contrast to operations that have preconditions which are also referred to as having a /narrow contract/ (note that operations with truly narrow contracts are also expected to never throw exceptions because the implementation body of these operations is always expected to succeed after its preconditions are checked to be true).
  20. [footnote
  21. The nomenclature of wide and narrow contracts has gained some popularity in recent years in the C++ community (appearing in a number of more recent proposals to add contract programming to the C++ standard, see __Bibliography__).
  22. This nomenclature is perfectly reasonable but it is not often used in this document just because the authors usually prefer to explicitly say "this operation has no preconditions..." or "this operation has preconditions..." (this is just a matter of taste).
  23. ]
  24. * /Postconditions/: These are logical conditions that programmers expect to be true when a function exits without throwing an exception (e.g., to check the result and any side effect that a function might have).
  25. Postconditions can access the function return value (for non-void functions) and also /old values/ (which are the values that expressions had before the function implementation was executed).
  26. * /Exception guarantees/: These are logical conditions that programmers except to be true when a function exits throwing an exception.
  27. Exception guarantees can access old values (but not the function return value).
  28. [footnote
  29. *Rationale:*
  30. Contract assertions for exception guarantees were first introduced by this library, they are not part of __N1962__ or other references listed in the __Bibliography__ (even if exception safety guarantees have long been part of C++ STL documentation).
  31. ]
  32. * /Class invariants/: These are logical conditions that programmers expect to be true after a constructor exits without throwing an exception, before and after the execution of every non-static public function (even if they throw exceptions), before the destructor is executed (and also after the destructor is executed but only when the destructor throws an exception).
  33. Class invariants define valid states for all objects of a given class.
  34. It is possible to specify a different set of class invariants for volatile public functions, namely /volatile class invariants/.
  35. It is also possible to specify /static class invariants/ which are excepted to be true before and after the execution of any constructor, destructor (even if it does not throw an exception), and public function (even if static).
  36. [footnote
  37. *Rationale:*
  38. Static and volatile class invariants were first introduced by this library (simply to reflect the fact that C++ supports also static and volatile public functions), they are not part of __N1962__ or other references listed in the __Bibliography__.
  39. ]
  40. * /Subcontracting/: This indicates that preconditions cannot be strengthen, while postconditions and class invariants cannot be weaken when a public function in a derived class overrides public functions in one or more of its base classes (this is formally defined according to the __substitution_principle__).
  41. The actual function implementation code, that remains outside of these contract assertions, is often referred to as the /function body/ in contract programming.
  42. Class invariants can also be used to specify /basic/ exception safety guarantees for an object (because they are checked at exit of public functions even when those throw exceptions).
  43. Contract assertions for exception guarantees can be used to specify /strong/ exception safety guarantees for a given operation on the same object.
  44. It is also a common requirement for contract programming to automatically disable contract checking while already checking assertions from another contract (in order to avoid infinite recursion while checking contract assertions).
  45. [note
  46. This library implements this requirement but in order to globally disable assertions while checking another assertion some kind of global arbitrating variable needs to be used by this library implementation.
  47. This library will automatically protect such a global variable from race conditions in multi-threated programs, but this will effectively introduce a global lock in the program (the [macroref BOOST_CONTRACT_DISABLE_THREADS] macro can be defined to disable this global lock but at the risk of incurring in race conditions).
  48. [footnote
  49. *Rationale:*
  50. [macroref BOOST_CONTRACT_DISABLE_THREADS] is named after `BOOST_DISABLE_THREADS`.
  51. ]
  52. ]
  53. In general, it is recommended to specify different contract conditions using separate assertion statements and not to group them together into a single condition using logical operators (`&&`, `||`, etc.).
  54. This is because when contract conditions are programmed together in a single assertion using logical operators, it might not be clear which condition actually failed in case the entire assertion fails at run-time.
  55. [heading C-Style Assertions]
  56. A limited form of contract programming (typically some form of precondition and basic postcondition checking) can be achieved using the C-style `assert` macro.
  57. Using `assert` is common practice for many programmers but it suffers of the following limitations:
  58. * `assert` does not distinguish between preconditions and postconditions.
  59. In well-tested production code, postconditions can usually be disabled trusting the correctness of the implementation while preconditions might still need to remain enabled because of possible changes in the calling code (e.g., postconditions of a given library could be disabled after testing while keeping the library preconditions enabled given that future changes in the user code that calls the library cannot be anticipated).
  60. Using `assert` it is not possible to selectively disable only postconditions and all assertions must be disabled at once.
  61. * `assert` requires to manually program extra code to correctly check postconditions (specifically to handle functions with multiple return statements, to not check postconditions when functions throw exceptions, and to implement old values).
  62. * `assert` requires to manually program extra code to check class invariants (extra member functions, try blocks, etc.).
  63. * `assert` does not support subcontracting.
  64. * `assert` calls are usually scattered within function implementations thus the asserted conditions are not immediately visible in their entirety by programmers (as they are instead when the assertions appear in the function declaration or at least at the very top of the function definition).
  65. Contract programming does not suffer of these limitations.
  66. [endsect]
  67. [section Benefits and Costs]
  68. [heading Benefits]
  69. The main use of contract programming is to improve software quality.
  70. __Meyer97__ discusses how contract programming can be used as the basic tool to write ["correct] software.
  71. __Stroustrup94__ discusses the key importance of class invariants plus advantages and disadvantages of preconditions and postconditions.
  72. The following is a short summary of benefits associated with contract programming inspired mainly by __N1613__:
  73. * Preconditions and postconditions:
  74. Using function preconditions and postconditions, programmers can give a precise semantic description of what a function requires at its entry and what it ensures at its exit (if it does not throw an exception).
  75. In particular, using postcondition old values, contract programming provides a mechanism that allows programmers to compare values of an expression before and after the function body execution.
  76. This mechanism is powerful enough to enable programmers to express many correctness constraints within the code itself, constraints that would otherwise have to be captured at best only informally by documentation.
  77. * Class invariants:
  78. Using class invariants, programmers can describe what to expect from a class and the logic dependencies between the class members.
  79. It is the job of the constructor to ensure that the class invariants are satisfied when the object is first created.
  80. Then the implementation of the member functions can be largely simplified as they can be written knowing that the class invariants are satisfied because contract programming checks them before and after the execution of every public function.
  81. Finally, the destructor makes sure that the class invariants held for the entire life of the object checking the class invariants one last time before the object is destructed.
  82. Class invariants can also be used as a criteria for good abstractions: If it is not possible to specify an invariant, it might be an indication that the design abstraction maybe be poor and it should not have been made into a class (maybe a namespace would have sufficed instead).
  83. * Self-documenting code:
  84. Contracts are part of the source code, they are checked at run-time so they are always up-to-date with the code itself.
  85. Therefore program specifications, as documented by the contracts, can be trusted to always be up-to-date with the implementation.
  86. * Easier debugging:
  87. Contract programming can provide a powerful debugging facility because, if contracts are well-written, bugs will cause contract assertions to fail exactly where the problem first occurs instead than at some later stage of the program execution in an apparently unrelated (and often hard to debug) manner.
  88. Note that a precondition failure points to a bug in the function caller, a postcondition failure points instead to a bug in the function implementation.
  89. [footnote
  90. Of course, if contracts are ill-written then contract programming is of little use.
  91. However, it is less likely to have a bug in both the function body and the contract than in the function body alone.
  92. For example, consider the validation of a result in postconditions.
  93. Validating the return value might seem redundant, but in this case we actually want that redundancy.
  94. When programmers write a function, there is a certain probability that they make a mistake in implementing the function body.
  95. When programmers specify the result of the function in the postconditions, there is also a certain probability that they make a mistake in writing the contract.
  96. However, the probability that programmers make a mistake twice (in both the body /and/ the contract) is in general lower than the probability that the mistake is made only once (in either the body /or/ the contract).
  97. ]
  98. * Easier testing:
  99. Contract programming facilitates testing because a contract naturally specifies what a test should check.
  100. For example, preconditions of a function state which inputs cause the function to fail and postconditions state which outputs are produced by the function on successful exit (contract programming should be seen as a tool to complement and guide, but obviously not to replace, testing).
  101. * Formal design:
  102. Contract programming can serve to reduce the gap between designers and programmers by providing a precise and unambiguous specification language in terms of contract assertions.
  103. Moreover, contracts can make code reviews easier by clarifying some of the semantics and usage of the code.
  104. * Formalize inheritance:
  105. Contract programming formalizes the virtual function overriding mechanism using subcontracting as justified by the __substitution_principle__.
  106. This keeps the base class programmers in control as overriding functions always have to fully satisfy the contracts of their base classes.
  107. * Replace defensive programming:
  108. Contract programming assertions can replace [@http://en.wikipedia.org/wiki/Defensive_programming defensive programming] checks localizing these checks within the contracts and making the code more readable.
  109. Of course, not all formal contract specifications can be asserted in C++.
  110. For example, in C++ is it not possible to assert the validity of an iterator range in the general case (because the only way to check if two iterators form a valid range is to keep incrementing the first iterator until it reaches the second iterator, but if the iterator range is invalid then such a code would render undefined behaviour or run forever instead of failing an assertion).
  111. Nevertheless, a large amount of contract assertions can be successfully programmed in C++ as illustrated by the numerous examples in this documentation and from the literature (for example see how much of STL [link N1962_vector_anchor `vector`] contract assertions can actually be programmed in C++ using this library).
  112. [heading Costs]
  113. In general, contract programming benefits come at the cost of performance as discussed in detail by both __Stroustrup94__ and __Meyer97__.
  114. While performance trade-offs should be carefully considered depending on the specific application domain, software quality cannot be sacrificed: It is difficult to see value in software that quickly and efficiently provides incorrect results.
  115. The run-time performances are negatively impacted by contract programming mainly because of extra time require to:
  116. * Check the asserted conditions.
  117. * Copy old values when these are used in postconditions or exception guarantees.
  118. * Call additional functors that check preconditions, postconditions, exception guarantees, class invariants, etc. (these can add up to many extra calls especially when using subcontracting).
  119. [note
  120. In general, contracts introduce at least three extra functor calls to check preconditions, postconditions, and exception guarantees for any given non-member function call.
  121. Public functions introduce also two more function calls to check class invariants (at entry and at exit).
  122. For subcontracting, these extra calls (some of which become virtual calls) are repeated for the number of functions being overridden from the base classes (possibly deep in the inheritance tree).
  123. In addition to that, this library introduces a number of function calls internal to its implementation in order to properly check the contracts.
  124. ]
  125. To mitigate the run-time performance impact, programmers can selectively disable run-time checking of some of the contract assertions.
  126. Programmers will have to decide based on the performance trade-offs required by their specific applications, but a reasonable approach often is to (see __Disable_Contract_Checking__):
  127. * Always write contracts to clarify the semantics of the design embedding the specifications directly in the code and making the code self-documenting.
  128. * Check preconditions, postconditions, class invariants, and maybe even exception guarantees during initial testing.
  129. * Check only preconditions (and maybe class invariants, but not postconditions and exception guarantees) during release testing and for the final release.
  130. This approach is usually reasonable because in well-tested production code, validating the function body implementation using postconditions is rarely needed since the function has shown itself to be ["correct] during testing.
  131. On the other hand, checking function arguments using preconditions is always needed because of changes that can be made to the calling code (without having to necessarily re-test and re-release the called code).
  132. Furthermore, postconditions and also exception guarantees, with related old value copies, are often computationally more expensive to check than preconditions and class invariants.
  133. [endsect]
  134. [section Function Calls]
  135. [heading Non-Member Functions]
  136. A call to a non-member function with a contract executes the following steps (see [funcref boost::contract::function]):
  137. # Check function preconditions.
  138. # Execute the function body.
  139. # If the body did not throw an exception, check function postconditions.
  140. # Else, check function exception guarantees.
  141. [heading Private and Protected Functions]
  142. Private and protected functions do not have to satisfy class invariants because these functions are part of the class implementation and not of the class public interface.
  143. Furthermore, the __substitution_principle__ does not apply to private and protected functions because these functions are not accessible to the user at the calling site where the __substitution_principle__ applies.
  144. Therefore, calls to private and protected functions with contracts execute the same steps as the ones indicated above for non-member functions (checking only preconditions and postconditions, without checking class invariants and without subcontracting).
  145. [endsect]
  146. [section Public Function Calls]
  147. [heading Overriding Public Functions]
  148. Let's consider a public function in a derived class that overrides public virtual functions declared by its public base classes (because of C++ multiple inheritance, the function could override from more than one of its base classes).
  149. We refer to the function in the derived class as the /overriding function/, and to the set of base classes containing all the /overridden functions/ as /overridden bases/.
  150. When subcontracting, overridden functions are searched (at compile-time) deeply in all public branches of the inheritance tree (i.e., not just the derived class' direct public parents are inspected, but also all its public grandparents, etc.).
  151. In case of multiple inheritance, this search also extends (at compile-time) widely to all public trees of the multiple inheritance forest (multiple public base classes are searched following their order of declaration in the derived class' inheritance list).
  152. As usual with C++ multiple inheritance, this search could result in multiple overridden functions and therefore in subcontracting from multiple public base classes.
  153. Note that only public base classes are considered for subcontracting because private and protected base classes are not accessible to the user at the calling site where the __substitution_principle__ applies.
  154. A call to the overriding public function with a contract executes the following steps (see [funcref boost::contract::public_function]):
  155. # Check static class invariants __AND__ non-static class invariants for all overridden bases, __AND__ then check the derived class static __AND__ non-static invariants.
  156. # Check preconditions of overridden public functions from all overridden bases in __OR__ with each other, __OR__ else check the overriding function preconditions in the derived class.
  157. # Execute the overriding function body.
  158. # Check static class invariants __AND__ non-static class invariants for all overridden bases, __AND__ then check the derived class static __AND__ non-static invariants (even if the body threw an exception).
  159. # If the body did not throw an exception, check postconditions of overridden public functions from all overridden bases in __AND__ with each other, __AND__ then check the overriding function postconditions in the derived class.
  160. # Else, check exception guarantees of overridden public functions from all overridden bases in __AND__ with each other, __AND__ then check the overriding function exception guarantees in the derived class.
  161. Volatile public functions check static class invariants __AND__ volatile class invariants instead.
  162. Preconditions and postconditions of volatile public functions and volatile class invariants access the object as `volatile`.
  163. Class invariants are checked before preconditions and postconditions so programming precondition and postcondition assertions can be simplified assuming that class invariants are satisfied already (e.g., if class invariants assert that a pointer cannot be null then preconditions and postconditions can safety dereference that pointer without additional checking).
  164. Similarly, static class invariants are checked before non-static class invariants so programming non-static class invariant (volatile and non) can be simplified assuming that static class invariants are satisfied already.
  165. Furthermore, subcontracting checks contracts of public base classes before checking the derived class contracts so programming derived class contract assertions can be simplified by assuming that public base class contracts are satisfied already.
  166. [note
  167. [#and_anchor] [#or_anchor]
  168. In this documentation __AND__ and __OR__ indicate the logic /and/ and /or/ operations evaluated in /short-circuit/.
  169. For example: `p` __AND__ `q` is true if and only if both `p` and `q` are true, but `q` is never evaluated when `p` is false; `p` __OR__ `q` is true if and only if either `p` or `q` are true, but `q` is never evaluated when `p` is true.
  170. As indicated by the steps above and in accordance with the __substitution_principle__, subcontracting checks preconditions in __OR__ while class invariants, postconditions, and exceptions guarantees are checked in __AND__ with preconditions, class invariants, postconditions, and exceptions guarantees of base classes respectively.
  171. ]
  172. [heading Non-Overriding Public Functions]
  173. A call to a non-static public function with a contract (that does not override functions from any of its public base classes) executes the following steps (see [funcref boost::contract::public_function]):
  174. # Check class static __AND__ non-static invariants (but none of the invariants from base classes).
  175. # Check function preconditions (but none of the preconditions from functions in base classes).
  176. # Execute the function body.
  177. # Check the class static __AND__ non-static invariants (even if the body threw an exception, but none of the invariants from base classes).
  178. # If the body did not throw an exception, check function postconditions (but none of the postconditions from functions in base classes).
  179. # Else, check function exception guarantees (but none of the exception guarantees from functions in base classes).
  180. Volatile public functions check static class invariants __AND__ volatile class invariants instead.
  181. Preconditions and postconditions of volatile functions and volatile class invariants access the object as `volatile`.
  182. Class invariants are checked because this function is part of the class public interface.
  183. However, none of the contracts of the base classes are checked because this function does not override any functions from any of the public base classes (so the __substitution_principle__ does not require to subcontract in this case).
  184. [heading Static Public Functions]
  185. A call to a static public function with a contract executes the following steps (see [funcref boost::contract::public_function]):
  186. # Check static class invariants (but not the non-static invariants and none of the invariants from base classes).
  187. # Check function preconditions (but none of the preconditions from functions in base classes).
  188. # Execute the function body.
  189. # Check static class invariants (even if the body threw an exception, but not the non-static invariants and none of the invariants from base classes).
  190. # If the body did not throw an exception, check function postconditions (but none of the postconditions from functions in base classes).
  191. # Else, check function exception guarantees (but none of the exception guarantees from functions in base classes).
  192. Class invariants are checked because this function is part of the class public interface, but only static class invariants can be checked (because this is a static function so it cannot access the object that would instead be required to check non-static class invariants, volatile or not).
  193. Furthermore, static functions cannot override any function so the __substitution_principle__ does not apply and they do not subcontract.
  194. Preconditions and postconditions of static functions and static class invariants cannot access the object (because they are checked from `static` member functions).
  195. [endsect]
  196. [section Constructor Calls]
  197. A call to a constructor with a contract executes the following steps (see [classref boost::contract::constructor_precondition] and [funcref boost::contract::constructor]):
  198. # Check constructor preconditions (but these cannot access the object because the object is not constructed yet).
  199. # Execute the constructor member initialization list (if present).
  200. # Construct any base class (public or not) according with C++ construction mechanism and also check the contracts of these base constructors (according with steps similar to the ones listed here).
  201. # Check static class invariants (but not the non-static or volatile class invariants, because the object is not constructed yet).
  202. # Execute the constructor body.
  203. # Check static class invariants (even if the body threw an exception).
  204. # If the body did not throw an exception:
  205. # Check non-static __AND__ volatile class invariants (because the object is now successfully constructed).
  206. # Check constructor postconditions (but these cannot access the object old value [^['oldof]]`(*this)` because the object was not constructed before the execution of the constructor body).
  207. # Else, check constructor exception guarantees (but these cannot access the object old value [^['oldof]]`(*this)` because the object was not constructed before the execution of the constructor body, plus they can only access class' static members because the object has not been successfully constructed given the constructor body threw an exception in this case).
  208. Constructor preconditions are checked before executing the member initialization list so programming these initializations can be simplified assuming the constructor preconditions are satisfied (e.g., constructor arguments can be validated by the constructor preconditions before they are used to initialize base classes and data members).
  209. As indicated in step 2.a. above, C++ object construction mechanism will automatically check base class contracts when these bases are initialized (no explicit subcontracting behaviour is required here).
  210. [endsect]
  211. [section Destructor Calls]
  212. A call to a destructor with a contract executes the following steps (see [funcref boost::contract::destructor]):
  213. # Check static class invariants __AND__ non-static __AND__ volatile class invariants.
  214. # Execute the destructor body (destructors have no parameters and they can be called at any time after object construction so they have no preconditions).
  215. # Check static class invariants (even if the body threw an exception).
  216. # If the body did not throw an exception:
  217. # Check destructor postconditions (but these can only access class' static members and the object old value [^['oldof]]`(*this)` because the object has been destroyed after successful execution of the destructor body).
  218. [footnote
  219. *Rationale:*
  220. Postconditions for destructors are not part of __N1962__ or other references listed in the __Bibliography__ (but with respect to __Meyer97__ it should be noted that Eiffel does not support static data members and that might by why destructors do not have postconditions in Eiffel).
  221. However, in principle there could be uses for destructor postconditions so this library supports postconditions for destructors (e.g., a class that counts object instances could use destructor postconditions to assert that an instance counter stored in a static data member is decreased by `1` because the object has been destructed).
  222. ]
  223. # Destroy any base class (public or not) according with C++ destruction mechanism and also check the contracts of these base destructors (according with steps similar to the ones listed here).
  224. # Else (even if destructors should rarely, if ever, be allowed to throw exceptions in C++):
  225. # Check non-static __AND__ volatile class invariants (because the object was not successfully destructed so it still exists and should satisfy its invariants).
  226. # Check destructor exception guarantees.
  227. As indicated in step 4.b. above, C++ object destruction mechanism will automatically check base class contracts when the destructor exits without throwing an exception (no explicit subcontracting behaviour is required here).
  228. [note
  229. Given that C++ allows destructors to throw, this library handles the case when the destructor body throws an exception as indicated above.
  230. However, in order to comply with STL exception safety guarantees and good C++ programming practices, programmers should implement destructor bodies to rarely, if ever, throw exceptions (in fact destructors are implicitly declared `noexcept` in C++11).
  231. ]
  232. [endsect]
  233. [section Constant-Correctness]
  234. Contracts should not be allowed to modify the program state because they are only responsible to check (and not to change) the program state in order to verify its compliance with the specifications.
  235. Therefore, contracts should only access objects, function arguments, function return values, old values, and all other program variables in `const` context (via `const&`, `const* const`, `const volatile`, etc.).
  236. Whenever possible (e.g., class invariants and postcondition old values), this library automatically enforces this /constant-correctness constraint/ at compile-time using `const`.
  237. However, this library cannot automatically enforce this constraint in all cases (for preconditions and postconditions of mutable member functions, for global variables, etc.).
  238. See __No_Lambda_Functions__ for ways of using this library that enforce the constant-correctness constraint at compile-time (but at the cost of significant boiler-plate code to be programmed manually so not recommended in general).
  239. [note
  240. In general, it is the responsibility of the programmers to code assertions that only check, and do not change, program variables.
  241. [footnote
  242. Note that this is true when using C-style `assert` as well.
  243. ]
  244. ]
  245. [endsect]
  246. [section Specifications vs. Implementation]
  247. Contracts are part of the program specification and not of its implementation.
  248. Therefore, contracts should ideally be programmed within C++ declarations, and not within definitions.
  249. In general, this library cannot satisfy this requirement.
  250. However, even when contracts are programmed together with the body in the function definition, it is still fairly easy for users to identify and read just the contract portion of the function definition (because the contract code must always be programmed at the very top of the function definition).
  251. See __Separate_Body_Implementation__ for ways of using this library to program contract specifications outside of the body implementation (but at the cost of writing one extra function for any given function so not recommended in general).
  252. Furthermore, contracts are most useful when they assert conditions only using public members (in most cases, the need for using non-public members to check contracts, especially in preconditions, indicates an error in the class design).
  253. For example, the caller of a public function cannot in general make sure that the function preconditions are satisfied if the precondition assertions use private members that are not callable by the caller (therefore, a failure in the preconditions will not necessarily indicate a bug in the caller given that the caller was made unable to fully check the preconditions in the first place).
  254. However, given that C++ provides programmers ways around access level restrictions (`friend`, function pointers, etc.), this library leaves it up to programmers to make sure that only public members are used in contract assertions (especially in preconditions). (__N1962__ follows the same approach not restricting contracts to only use public members, Eiffel instead generates a compile-time error if preconditions are asserted using non-public members.)
  255. [footnote
  256. *Rationale:*
  257. Out of curiosity, if C++ [@http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#45 defect 45] had not been fixed, this library could have been implemented to generate a compile-time error when precondition assertions use non-public members more similarly to Eiffel's implementation (but still, not necessary the best approach for C++).
  258. ]
  259. [endsect]
  260. [section On Contract Failures]
  261. If preconditions, postconditions, exception guarantees, or class invariants are either checked to be false or their evaluation throws an exception at run-time then this library will call specific /failure handler functions/.
  262. [footnote
  263. *Rationale:*
  264. If the evaluation of a contract assertion throws an exception, the assertion cannot be checked to be true so the only safe thing to assume is that the assertion failed (indeed the contract assertion checking failed) and call the contract failure handler in this case also.
  265. ]
  266. By default, these failure handler functions print a message to the standard error `std::cerr` (with detailed information about the failure) and then terminate the program calling `std::terminate`.
  267. However, using [funcref boost::contract::set_precondition_failure], [funcref boost::contract::set_postcondition_failure], [funcref boost::contract::set_except_failure], [funcref boost::contract::set_invariant_failure], etc. programmers can define their own failure handler functions that can take any user-specified action (throw an exception, exit the program with an error code, etc., see __Throw_on_Failures__).
  268. [footnote
  269. *Rationale:*
  270. This customizable failure handling mechanism is similar to the one used by C++ `std::terminate` and also to the one proposed in __N1962__.
  271. ]
  272. [note
  273. In C++ there are a number of issues with programming contract failure handlers that throw exceptions instead of terminating the program.
  274. Specifically, destructors check class invariants so they will throw if programmers change class invariant failure handlers to throw instead of terminating the program, but in general destructors should not throw in C++ (to comply with STL exception safety, C++11 implicit `noexcept` declarations for destructors, etc.).
  275. Furthermore, programming a failure handler that throws on exception guarantee failures results in throwing an exception (the one reporting the contract failure) while there is already an active exception (the one that caused the exception guarantees to be checked in the first place), and this will force C++ to terminate the program anyway.
  276. ]
  277. Therefore, it is recommended to terminate the program at least for contract failures from destructors and exception guarantees (if not in all other cases of contract failures as it is done by default by this library).
  278. The contract failure handler functions programmed using this library have information about the failed contract (preconditions, postconditions, etc.) and the operation that was checking the contract (constructor, destructor, etc.) so programmers can granularly distinguish all cases and decide when it is appropriate to terminate, throw, or take some other user-specific action.
  279. [endsect]
  280. [section Feature Summary]
  281. The contract programming features supported by this library are largely based on __N1962__ and on the Eiffel programming language.
  282. The following table compares contract programming features among this library, __N1962__ (unfortunately the C++ standard committee rejected this proposal commenting on a lack of interest in adding contract programming to C++ at that time, even if __N1962__ itself is sound), a more recent proposal __P0380__ (which was accepted in the C++20 standard but unfortunately only supports preconditions and postconditions, while does not support class invariants, old values, and subcontracting), the Eiffel and D programming languages.
  283. Some of the items listed in this summary table will become clear in detail after reading the remaining sections of this documentation.
  284. [table
  285. [
  286. [Feature]
  287. [This Library]
  288. [__N1962__ Proposal (not accepted in C++)]
  289. [C++20 (see __P0380__)]
  290. [ISE Eiffel 5.4 (see __Meyer97__)]
  291. [D (see __Bright04__)]
  292. ][
  293. [['Keywords and specifiers]]
  294. [
  295. Specifiers: `precondition`, `postcondition`, `invariant`, `static_invariant`, and `base_types`.
  296. The last three specifiers appear in user code so their names can be referred to or changed using [macroref BOOST_CONTRACT_INVARIANT], [macroref BOOST_CONTRACT_STATIC_INVARIANT], and [macroref BOOST_CONTRACT_BASES_TYPEDEF] macros respectively to avoid name clashes.
  297. ]
  298. [Keywords: `precondition`, `postcondition`, `oldof`, and `invariant`.]
  299. [Attributes: `[[expects]]` and `[[ensures]]`.]
  300. [Keywords: =require=, =require else=, =ensure=, =ensure then=, =old=, =result=, =do=, and =invariant=.]
  301. [Keywords: =in=, =out=, =do=, =assert=, and =invariant=.]
  302. ][
  303. [['On contract failures]]
  304. [Print an error to `std::cerr` and call `std::terminate` (but can be customized to throw exceptions, exit with an error code, etc.).]
  305. [Call `std::terminate` (but can be customized to throw exceptions, exit with an error code, etc.).]
  306. [Call `std::abort` (but can be customized to throw exceptions, exit with an error code, etc.).]
  307. [Throw exceptions.]
  308. [Throw exceptions.]
  309. ][
  310. [['Return values in postconditions]]
  311. [Yes, captured by or passed as a parameter to (for virtual functions) the postcondition functor.]
  312. [Yes, `postcondition(`[^['result-variable-name]]`)`.]
  313. [Yes, `[[ensures `[^['result-variable-name]]`: ...]]`.]
  314. [Yes, =result= keyword.]
  315. [Yes, `out(`[^['result-variable-name]]`)`.]
  316. ][
  317. [['Old values in postconditions]]
  318. [
  319. Yes, [macroref BOOST_CONTRACT_OLDOF] macro and [classref boost::contract::old_ptr] (but copied before preconditions unless `.old(...)` is used as shown in __Old_Values_Copied_at_Body__).
  320. For templates, [classref boost::contract::old_ptr_if_copyable] skips old value copies for non-copyable types and [funcref boost::contract::condition_if] skips old value copies selectively based on old expression type requirements (on compilers that do not support `if constexpr`).
  321. ]
  322. [
  323. Yes, `oldof` keyword (copied right after preconditions).
  324. (Never skipped, not even in templates for non-copyable types.)
  325. ]
  326. [No.]
  327. [
  328. Yes, =old= keyword (copied right after preconditions).
  329. (Never skipped, but all types are copyable in Eiffel.)
  330. ]
  331. [No.]
  332. ][
  333. [['Class invariants]]
  334. [
  335. Yes, checked at constructor exit, at destructor entry and throw, and at public function entry, exit, and throw.
  336. Same for volatile class invariants.
  337. Static class invariants checked at entry, exit, and throw for constructors, destructors, and any (also `static`) public function.
  338. ]
  339. [
  340. Yes, checked at constructor exit, at destructor entry and throw, and at public function entry, exit, and throw.
  341. (Volatile and static class invariants not supported.)
  342. ]
  343. [No.]
  344. [
  345. Yes, checked at constructor exit, and around public functions.
  346. (Volatile and static class invariants do not apply to Eiffel.)
  347. ]
  348. [
  349. Yes, checked at constructor exit, at destructor entry, and around public functions.
  350. However, invariants cannot call public functions (to avoid infinite recursion because D does not disable contracts while checking other contracts).
  351. (Volatile and static class invariants not supported, `volatile` was deprecated all together in D.)
  352. ]
  353. ][
  354. [['Subcontracting]]
  355. [
  356. Yes, also supports subcontracting for multiple inheritance ([macroref BOOST_CONTRACT_BASE_TYPES], [macroref BOOST_CONTRACT_OVERRIDE], and [classref boost::contract::virtual_] are used to declare base classes, overrides and virtual public functions respectively).
  357. ]
  358. [
  359. Yes, also supports subcontracting for multiple inheritance, but preconditions cannot be subcontracted.
  360. [footnote
  361. *Rationale:*
  362. The authors of __N1962__ decided to forbid derived classes from subcontracting preconditions because they found that such a feature was rarely, if ever, used (see [@http://lists.boost.org/Archives/boost/2010/04/164862.php Re: \[boost\] \[contract\] diff n1962]).
  363. Still, it should be noted that even in __N1962__ if a derived class overrides two functions with preconditions coming from two different base classes via multiple inheritance, the overriding function contract will check preconditions from its two base class functions in __OR__ (so even in __N1962__ preconditions can indirectly subcontract when multiple inheritance is used).
  364. Furthermore, subcontracting preconditions is soundly defined by the __substitution_principle__ so this library allows to subcontract preconditions as Eiffel does (users can always avoid using this feature if they have no need for it).
  365. (This is essentially the only feature on which this library deliberately differs from __N1962__.)
  366. ]
  367. ]
  368. [No.]
  369. [Yes.]
  370. [Yes.]
  371. ][
  372. [['Contracts for pure virtual functions]]
  373. [Yes (programmed via out-of-line functions as always in C++ with pure virtual function definitions).]
  374. [Yes.]
  375. [No (because no subcontracting).]
  376. [Yes (contracts for abstract functions).]
  377. [No.]
  378. ][
  379. [['Arbitrary code in contracts]]
  380. [Yes (but users are generally recommended to only program assertions using [macroref BOOST_CONTRACT_ASSERT] and if-guard statements within contracts to avoid introducing bugs and expensive code in contracts, and also to only use public functions to program preconditions).]
  381. [No, assertions only (use of only public functions to program preconditions is recommended but not prescribed).]
  382. [No, assertions only (in addition contracts of public, protected, and private members can only use other public, public/protected, and public/protected/private members respectively).]
  383. [No, assertions only (in addition only public members can be used in preconditions).]
  384. [Yes.]
  385. ][
  386. [['Constant-correctness]]
  387. [No, enforced only for class invariants and old values (making also preconditions and postconditions constant-correct is possible but requires users to program a fare amount of boiler-plate code).]
  388. [Yes.]
  389. [Yes (side effects in contracts lead to undefined behaviour).]
  390. [Yes.]
  391. [No, enforced only for class invariants.]
  392. ][
  393. [['Contracts in specifications]]
  394. [No, in function definitions instead (unless programmers manually write an extra function for any given function).]
  395. [Yes (in function declarations).]
  396. [Yes (in function declarations).]
  397. [Yes.]
  398. [Yes.]
  399. ][
  400. [['Function code ordering]]
  401. [Preconditions, postconditions, exception guarantees, body.]
  402. [Preconditions, postconditions, body.]
  403. [Preconditions, postconditions, body.]
  404. [Preconditions, body, postconditions.]
  405. [Preconditions, postconditions, body.]
  406. ][
  407. [['Disable assertion checking within assertions checking (to avoid infinite recursion when checking contracts)]]
  408. [
  409. Yes, but use [macroref BOOST_CONTRACT_PRECONDITIONS_DISABLE_NO_ASSERTION] to disable no assertion while checking preconditions (see also [macroref BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION]).
  410. [footnote
  411. *Rationale:*
  412. Technically, it can be shown that an invalid argument can reach the function body when assertion checking is disabled while checking preconditions (that is why __N1962__ does not disable any assertion while checking preconditions, see [@http://lists.boost.org/Archives/boost/2010/04/164862.php Re: \[boost\] \[contract\] diff n1962]).
  413. However, this can only happen while checking contracts when an invalid argument passed to the body, which should results in the body either throwing an exception or returning an incorrect result, will in turn fail the contract assertion being checked by the caller of the body and invoke the related contract failure handler as desired in the first place.
  414. Furthermore, not disabling assertions while checking preconditions (like __N1962__ does) makes it possible to have infinite recursion while checking preconditions.
  415. Therefore, this library by default disables assertion checking also while checking preconditions (like Eiffel does), but it also provides the [macroref BOOST_CONTRACT_PRECONDITIONS_DISABLE_NO_ASSERTION] configuration macro so users can change this behaviour to match __N1962__ if needed.
  416. ]
  417. (In multi-threaded programs this introduces a global lock, see [macroref BOOST_CONTRACT_DISABLE_THREADS].)
  418. ]
  419. [Yes for class invariants and postconditions, but preconditions disable no assertion.]
  420. [No.]
  421. [Yes.]
  422. [No.]
  423. ][
  424. [['Nested member function calls]]
  425. [
  426. Disable nothing.
  427. [footnote
  428. *Rationale:*
  429. Older versions of this library defined a data member in the user class that was automatically used to disable checking of class invariants within nested member function calls (similarly to Eiffel).
  430. This feature was required by older revisions of __N1962__ but it is no longer required by __N1962__ (because it seems to be motivated purely by optimization reasons while similar performances can be achieved by disabling invariants for release builds).
  431. Furthermore, in multi-threaded programs this feature would introduce a lock that synchronizes all member functions calls for a given object.
  432. Therefore, this feature was removed in the current revision of this library.
  433. ]
  434. ]
  435. [Disable nothing.]
  436. [Disable nothing.]
  437. [Disable all contract assertions.]
  438. [Disable nothing.]
  439. ][
  440. [['Disable contract checking]]
  441. [Yes, contract checking can be skipped at run-time by defining combinations of the [macroref BOOST_CONTRACT_NO_PRECONDITIONS], [macroref BOOST_CONTRACT_NO_POSTCONDITIONS], [macroref BOOST_CONTRACT_NO_INVARIANTS], [macroref BOOST_CONTRACT_NO_ENTRY_INVARIANTS], and [macroref BOOST_CONTRACT_NO_EXIT_INVARIANTS] macros (completely removing contract code from compiled object code is also possible but requires using macros as shown in __Disable_Contract_Compilation__).]
  442. [Yes (contract code also removed from compiled object code, but details are compiler-implementation specific).]
  443. [Yes (contract code also removed from compiled object code, but details are compiler-implementation specific).]
  444. [Yes, but only predefined combinations of preconditions, postconditions, and class invariants can be disabled (contract code also removed from compiled object code).]
  445. [Yes.]
  446. ][
  447. [['Assertion levels]]
  448. [Yes, predefined default, audit, and axiom, in addition programmers can also define their own levels.]
  449. [No (but a previous revision of this proposal considered adding assertion levels under the name of "assertion ordering").]
  450. [Yes, predefined default, audit, and axiom.]
  451. [No.]
  452. [No.]
  453. ]
  454. ]
  455. The authors of this library consulted the following references that implement contract programming for C++ (but usually for only a limited set of features, or using preprocessing tools other than the C++ preprocessor and external to the language itself) and for other languages (see __Bibliography__ for a complete list of all references consulted during the design and development of this library):
  456. [table
  457. [ [Reference] [Language] [Notes] ]
  458. [ [__Bright04b__] [Digital Mars C++] [
  459. The Digital Mars C++ compiler extends C++ adding contract programming language support (among many other features).
  460. ] ]
  461. [ [__Maley99__] [C++] [
  462. This supports contract programming including subcontracting but with limitations (e.g., programmers need to manually build an inheritance tree using artificial template parameters), it does not use macros but programmers are required to write by hand a significant amount of boiler-plate code.
  463. (The authors have found this work very inspiring when developing initial revisions of this library especially for its attempt to support subcontracting.)
  464. ] ]
  465. [ [__Lindrud04__] [C++] [
  466. This supports class invariants and old values but it does not support subcontracting (contracts are specified within definitions instead of declarations and assertions are not constant-correct).
  467. ] ]
  468. [ [__Tandin04__] [C++] [
  469. Interestingly, these contract macros automatically generate Doxygen documentation
  470. [footnote
  471. *Rationale:*
  472. Older versions of this library also automatically generated Doxygen documentation from contract definition macros.
  473. This functionality was abandoned for a number of reasons: This library no longer uses macros to program contracts; even before that, the implementation of this library macros became too complex and the Doxygen preprocessor was no longer able to expand them; the Doxygen documentation was just a repeat of the contract code (so programmers could directly look at contracts in the source code); Doxygen might not necessarily be the documentation tool used by all C++ programmers.
  474. ]
  475. but old values, class invariants, and subcontracting are not supported (plus contracts are specified within definitions instead of declarations and assertions are not constant-correct).
  476. ] ]
  477. [ [__Nana__] [GCC C++] [
  478. This uses macros but it only works on GCC (and maybe Clang, but it does not work on MSVC, etc.).
  479. It does not support subcontracting.
  480. It requires extra care to program postconditions for functions with multiple return statements.
  481. It seems that it might not check class invariants when functions throw exceptions (unless the `END` macro does that...).
  482. (In addition, it provides tools for logging and integration with GDB.)
  483. ] ]
  484. [ [__C2__] [C++] [
  485. This uses an external preprocessing tool (the authors could no longer find this project's code to evaluate it).
  486. ] ]
  487. [ [__iContract__] [Java] [
  488. This uses an external preprocessing tool.
  489. ] ]
  490. [ [__Jcontract__] [Java] [
  491. This uses an external preprocessing tool.
  492. ] ]
  493. [ [__CodeContracts__] [.NET] [
  494. Microsoft contract programming for .NET programming languages.
  495. ] ]
  496. [ [__SpecSharp__] [C#] [
  497. This is a C# extension with contract programming language support.
  498. ] ]
  499. [ [__Chrome__] [Object Pascal] [
  500. This is the .NET version of Object Pascal and it has language support for contract programming.
  501. ] ]
  502. [ [__SPARKAda__] [Ada] [
  503. This is an Ada-like programming language with support for contract programming.
  504. ] ]
  505. ]
  506. To the best knowledge of the authors, this the only library that fully supports all contract programming features for C++ (without using preprocessing tools external to the language itself).
  507. In general:
  508. * Implementing preconditions and postconditions in C++ is not difficult (e.g., using some kind of RAII object).
  509. * Implementing postcondition old values is also not too difficult (usually requiring programmers to copy old values into local variables), but it is already somewhat more difficult to ensure such copies are not performed when postconditions are disabled.
  510. [footnote
  511. For example, the following pseudocode attempts to emulate old values in __P0380__:
  512. ``
  513. struct scope_exit { // RAII.
  514. template<typename F>
  515. explicit scope_exit(F f) : f_(f) {}
  516. ~scope_exit() { f_(); }
  517. scope_exit(scope_exit const&) = delete;
  518. scope_exit& operator=(scope_exit const&) = delete;
  519. private:
  520. std::function<void ()> f_;
  521. };
  522. void fswap(file& x, file& y)
  523. [[expects: x.closed()]]
  524. [[expects: y.closed()]]
  525. // Cannot use [[ensures]] for postconditions so to emulate old values.
  526. {
  527. file old_x = x; // Emulate old values with local copies (not disabled).
  528. file old_y = y;
  529. scope_exit ensures([&] { // Check after local objects destroyed.
  530. if(std::uncaught_exceptions() == 0) { // Check only if no throw.
  531. [[assert: x.closed()]]
  532. [[assert: y.closed()]]
  533. [[assert: x == old_y]]
  534. [[assert: y == old_x]]
  535. }
  536. });
  537. x.open();
  538. scope_exit close_x([&] { x.close(); });
  539. y.open();
  540. scope_exit close_y([&] { y.close(); });
  541. file z = file::temp();
  542. z.open;
  543. scope_exit close_z([&] { z.close(); });
  544. x.mv(z);
  545. y.mv(x);
  546. z.mv(y);
  547. }
  548. ``
  549. This requires boiler-plate code to make sure postconditions are correctly checked only if the function did not throw an exception and in a `scope_exit` RAII object after all other local objects have been destroyed (because some of these destructors contribute to establishing the postconditions).
  550. Still, it never disables old value copies (not even if postconditions are disabled in release builds, this would require adding even more boiler-plate code using `#ifdef`, etc.).
  551. ]
  552. * Implementing class invariants is more involved (especially if done automatically, without requiring programmers to manually invoke extra functions to check the invariants).
  553. [footnote
  554. For example, the following pseudocode attempts to emulation of class invariants in __P0380__:
  555. ``
  556. template<typename T>
  557. class vector {
  558. bool invariant() const { // Check invariants at...
  559. [[assert: empty() == (size() == 0)]]
  560. [[assert: size() <= capacity()]]
  561. return true;
  562. }
  563. public:
  564. vector()
  565. [[ensures: invariant()]] // ...constructor exit (only if no throw).
  566. { ... }
  567. ~vector() noexcept
  568. [[expects: invariant()]] // ...destructor entry.
  569. { ... }
  570. void push_back(T const& value)
  571. [[expects: invariant()]] // ...public function entry.
  572. [[ensures: invariant()]] // ...public function exit (if no throw).
  573. try {
  574. ... // Function body.
  575. } catch(...) {
  576. invariant(); // ...public function exit (if throw).
  577. throw;
  578. }
  579. ...
  580. };
  581. ``
  582. This requires boiler-plate code to manually invoke the function that checks the invariants (note that invariants are checked at public function exit regardless of exceptions being thrown while postconditions are not).
  583. In case the destructor can throw (e.g., it is declared `noexcept(false)`), the destructor also requires a `try-catch` statement similar to the one programmed for `push_back` to check class invariants at destructor exit when it throws exceptions.
  584. Still, an outstanding issue remains to avoid infinite recursion if also `empty` and `size` are public functions programmed to check class invariants (because __P0380__ does not automatically disable assertions while checking other assertions).
  585. ]
  586. In addition, all references reviewed by the authors seem to not consider static and volatile functions not supporting static and volatile invariants respectively.
  587. * Implementing subcontracting involves a significant amount of complexity and it seems to not be properly supported by any C++ library other than this one (especially when handling multiple inheritance, correctly copying postcondition old values across all overridden contracts deep in the inheritance tree, and correctly reporting the return value to the postconditions of overridden virtual functions in base classes).
  588. [footnote
  589. For example, it is not really possible to sketch pseudocode based on __P0380__ that emulates subcontracting in the general case.
  590. ]
  591. [endsect]
  592. [endsect]