ExpectsAndEnsures.hpp
Go to the documentation of this file.
1 // Distributed under the MIT License.
2 // See LICENSE.txt for details.
3 
4 /// \file
5 /// Defines macros Expects and Ensures
6 
7 #pragma once
8 
10 
11 // part of GSL, but GSL depends on Expects and Ensures...
12 #ifndef UNLIKELY
13 #if defined(__clang__) || defined(__GNUC__)
14 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
15 #else
16 #define UNLIKELY(x) (x)
17 #endif
18 #endif
19 
20 /*!
21  * \ingroup ErrorHandlingGroup
22  * \brief check expectation of pre-conditions of a function
23  *
24  * The Expects macro sets the preconditions to a function's arguments, it is a
25  * contract (C++20) that must be satisfied. See the CppCoreGuidelines for
26  * details.
27  * \param cond the expression that is expected to be true
28  */
29 #if defined(SPECTRE_DEBUG) || defined(EXPECTS_ENSURES)
30 #define Expects(cond) \
31  if (UNLIKELY(!(cond))) { \
32  CERROR("Expects violated: "s + #cond); \
33  } else \
34  static_cast<void>(0)
35 #else
36 #define Expects(cond) \
37  if (false) { \
38  static_cast<void>(cond); \
39  } else \
40  static_cast<void>(0)
41 #endif
42 
43 /*!
44  * \ingroup ErrorHandlingGroup
45  * \brief Check that a post-condition of a function is true
46  *
47  * The Ensures macro sets the postconditions of function, it is a contract
48  * (C++20) that must be satisfied. See the CppCoreGuidelines for details.
49  * \param cond the expression that is expected to be true
50  */
51 #if defined(SPECTRE_DEBUG) || defined(EXPECTS_ENSURES)
52 #define Ensures(cond) \
53  if (UNLIKELY(!(cond))) { \
54  CERROR("Ensures violated: "s + #cond); \
55  } else \
56  static_cast<void>(0)
57 #else
58 #define Ensures(cond) \
59  if (false) { \
60  static_cast<void>(cond); \
61  } else \
62  static_cast<void>(0)
63 #endif
Defines macro ERROR.