userver: userver/utils/assert.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
assert.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/assert.hpp
4/// @brief Assertion macros UASSERT, UASSERT_MSG, UINVARIANT and AbortWithStacktrace() function
5/// @ingroup userver_universal
6
7#include <string_view>
8
9#include <userver/utils/impl/source_location.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utils {
14
15namespace impl {
16
17[[noreturn]] void UASSERT_failed(
18 std::string_view expr,
19 const char* file,
20 unsigned int line,
21 const char* function,
22 std::string_view msg
23) noexcept;
24
25[[noreturn]] void LogAndThrowInvariantError(
26 std::string_view condition,
27 std::string_view message,
28 utils::impl::SourceLocation source_location
29);
30
31#ifdef NDEBUG
32inline constexpr bool kEnableAssert = false;
33#else
34inline constexpr bool kEnableAssert = true;
35#endif
36
37extern bool dump_stacktrace_on_assert_failure;
38
39} // namespace impl
40
41/// @brief Function that prints the stacktrace with message and aborts the program execution.
42///
43/// Mostly useful for placing in dead code branches or in 'should-never-happen-and-theres-no-way-to-restore' places.
44[[noreturn]] void AbortWithStacktrace(std::string_view message) noexcept;
45
46} // namespace utils
47
48USERVER_NAMESPACE_END
49
50/// @brief Assertion macro for that aborts execution in DEBUG builds with a
51/// message `msg` and does nothing in release builds
52///
53/// @hideinitializer
54// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
55#define UASSERT_MSG(expr, msg)
56 do {
57 if (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
58 if (expr) {
59 } else {
60 USERVER_NAMESPACE::utils::impl::UASSERT_failed(#expr, __FILE__, __LINE__, __func__, msg);
61 }
62 }
63 } while (0)
64
65/// @brief Assertion macro that aborts execution in DEBUG builds and does
66/// nothing in release builds
67///
68/// @hideinitializer
69// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
70#define UASSERT(expr) UASSERT_MSG(expr, std::string_view{})
71
72/// @brief Asserts in debug builds, throws utils::InvariantError in release
73///
74/// @hideinitializer
75// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
76#define UINVARIANT(condition, message)
77 do {
78 if (condition) {
79 } else {
80 if constexpr (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
81 USERVER_NAMESPACE::utils::impl::UASSERT_failed(#condition, __FILE__, __LINE__, __func__, message);
82 } else {
83 USERVER_NAMESPACE::utils::impl::LogAndThrowInvariantError(
84 #condition, message, USERVER_NAMESPACE::utils::impl::SourceLocation::Current()
85 );
86 }
87 }
88 } while (0)