guanaqo 1.0.0-alpha.25
Utilities for scientific software
Loading...
Searching...
No Matches
assume.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file
4/// @ingroup macros
5/// Assertion and assumption macros with debug/release semantics.
6
7#include <guanaqo/stringify.h>
8#include <stdexcept>
9
10/// @def GUANAQO_ASSUME(x)
11/// @ingroup macros
12/// Invokes undefined behavior if the expression @p x does not evaluate to true.
13/// @throws std::logic_error in debug mode if @p x is false.
14
15/// @def GUANAQO_DEBUG_ASSERT(x)
16/// @ingroup macros
17/// Check the expression @p x (in debug mode only).
18/// @throws std::logic_error in debug mode if @p x is false.
19
20/// @def GUANAQO_ASSERT(x)
21/// @ingroup macros
22/// Check the expression @p x (regardless of debug or release mode).
23/// @throws std::logic_error if @p x is false.
24
25#if defined(NDEBUG) && !GUANAQO_VERIFY_ASSUMPTIONS
26#if __has_cpp_attribute(assume) >= 202207L
27#define GUANAQO_ASSUME(x) [[assume(x)]]
28#else
29#include <utility>
30#if __cpp_lib_unreachable >= 202202L
31#define GUANAQO_ASSUME(x) \
32 do { \
33 if (!(x)) \
34 std::unreachable(); \
35 } while (false)
36#elif defined(__GNUC__) // GCC, Clang
37#define GUANAQO_ASSUME(x) \
38 do { \
39 if (!(x)) \
40 __builtin_unreachable(); \
41 } while (false)
42#elif defined(_MSC_VER) // MSVC
43#define GUANAQO_ASSUME(x) __assume(x)
44#endif // __cpp_lib_unreachable >= 202202L
45#endif // __has_cpp_attribute(assume)
46#define GUANAQO_DEBUG_ASSERT(x) \
47 do { \
48 (void)sizeof(x); \
49 } while (false)
50#endif // defined(NDEBUG) && !GUANAQO_VERIFY_ASSUMPTIONS
51
52#ifndef GUANAQO_DEBUG_ASSERT
53#define GUANAQO_DEBUG_ASSERT(x) \
54 do { \
55 if (!(x)) \
56 throw std::logic_error("Assertion " #x " failed (" __FILE__ \
57 ":" GUANAQO_STRINGIFY(__LINE__) ")"); \
58 } while (false)
59#endif
60
61#define GUANAQO_ASSERT(x) \
62 do { \
63 if (!(x)) \
64 throw std::logic_error("Assertion " #x " failed (" __FILE__ \
65 ":" GUANAQO_STRINGIFY(__LINE__) ")"); \
66 } while (false)
67
68#ifndef GUANAQO_ASSUME
69#define GUANAQO_ASSUME(x) GUANAQO_ASSERT(x)
70#endif
Stringify and token concatenation helpers.