siplasplas
A library for C++ reflection and introspection
assert.hpp
1 #ifndef SIPLASPLAS_UTILITY_ASSERT_HPP
2 #define SIPLASPLAS_UTILITY_ASSERT_HPP
3 
4 #include <stdexcept>
5 #include <functional>
6 #include "preprocessor.hpp"
7 #include "exception.hpp"
8 #include <siplasplas/utility/export.hpp>
9 
10 namespace cpp
11 {
12 
26 class SIPLASPLAS_UTILITY_EXPORT AssertException : public std::logic_error
27 {
28 public:
29  using std::logic_error::logic_error;
30 };
31 
43 class SIPLASPLAS_UTILITY_EXPORT AssertExpression
44 {
45 public:
55  AssertExpression(bool expressionResult,
56  const std::string& message,
57  const std::string& file,
58  std::size_t line);
59 
69  ~AssertExpression() noexcept(false);
70 
99  AssertExpression& onFailure(const std::function<void()>& callback);
100 
101 private:
102  std::string _message;
103  std::string _file;
104  std::size_t _line;
105  std::function<void()> _onFailureCallback;
106  bool _assertionFailed;
107 };
108 
116 class SIPLASPLAS_UTILITY_EXPORT DummyAssertExpression
117 {
118 public:
130  template<typename Function>
132  {
133  return *this;
134  }
135 };
136 
137 }
138 
139 #ifndef NDEBUG
140 #define SIPLASPLAS_ASSERT_IMPL(MESSAGE, ...) ::cpp::AssertExpression((__VA_ARGS__), MESSAGE, __FILE__, __LINE__)
141 #else
142 #define SIPLASPLAS_ASSERT_IMPL(MESSAGE, ...) ::cpp::DummyAssertExpression()
143 #endif
144 
159 #define SIPLASPLAS_ASSERT(...) SIPLASPLAS_ASSERT_IMPL(SIPLASPLAS_PP_STR((__VA_ARGS__)), __VA_ARGS__)
160 
199 #define SIPLASPLAS_ASSERT_COMP_IMPL(a, b, op, wording) SIPLASPLAS_ASSERT_IMPL(::fmt::format( \
200  "Expected '{}' ({}) {} '{}' ({})", \
201  SIPLASPLAS_PP_STR(a), \
202  a, \
203  wording, \
204  SIPLASPLAS_PP_STR(b), \
205  b \
206  ), (a op b))
207 
226 #define SIPLASPLAS_ASSERT_EQ(a, b) SIPLASPLAS_ASSERT_COMP_IMPL(a, b, ==, "equal to")
227 
228 
247 #define SIPLASPLAS_ASSERT_NE(a, b) SIPLASPLAS_ASSERT_COMP_IMPL(a, b, !=, "not equal to")
248 
249 
268 #define SIPLASPLAS_ASSERT_BT(a, b) SIPLASPLAS_ASSERT_COMP_IMPL(a, b, > , "bigger than")
269 
270 
289 #define SIPLASPLAS_ASSERT_LT(a, b) SIPLASPLAS_ASSERT_COMP_IMPL(a, b, < , "less than")
290 
291 
310 #define SIPLASPLAS_ASSERT_BE(a, b) SIPLASPLAS_ASSERT_COMP_IMPL(a, b, >=, "bigger or equal to")
311 
312 
331 #define SIPLASPLAS_ASSERT_LE(a, b) SIPLASPLAS_ASSERT_COMP_IMPL(a, b, <=, "less or equal to")
332 
333 #endif // SIPLASPLAS_UTILITY_ASSERT_HPP
DummyAssertExpression & onFailure(Function)
Does nothing.
Definition: assert.hpp:131
Definition: canary_allocator.hpp:7
Represents an assertion error.
Definition: assert.hpp:26
Represents an assert expression when SIPLASPLAS_ASSERT() macros are disabled.
Definition: assert.hpp:116
Implements a siplasplas assertion.
Definition: assert.hpp:43