util/check: Add CHECK_NONFATAL identity function, NONFATAL_UNREACHABLE AND UNREACHABLE macros

This commit is contained in:
Aurèle Oulès
2022-04-09 02:14:02 +02:00
parent e0680bbce8
commit ee02c8bd9a
7 changed files with 49 additions and 39 deletions

View File

@@ -18,8 +18,24 @@ class NonFatalCheckError : public std::runtime_error
using std::runtime_error::runtime_error;
};
#define format_internal_error(msg, file, line, func, report) \
strprintf("Internal bug detected: \"%s\"\n%s:%d (%s)\nPlease report this issue here: %s\n", \
msg, file, line, func, report)
/** Helper for CHECK_NONFATAL() */
template <typename T>
T&& inline_check_non_fatal(T&& val, const char* file, int line, const char* func, const char* assertion)
{
if (!(val)) {
throw NonFatalCheckError(
format_internal_error(assertion, file, line, func, PACKAGE_BUGREPORT));
}
return std::forward<T>(val);
}
/**
* Throw a NonFatalCheckError when the condition evaluates to false
* Identity function. Throw a NonFatalCheckError when the condition evaluates to false
*
* This should only be used
* - where the condition is assumed to be true, not for error handling or validating user input
@@ -29,18 +45,8 @@ class NonFatalCheckError : public std::runtime_error
* asserts or recoverable logic errors. A NonFatalCheckError in RPC code is caught and passed as a string to the RPC
* caller, which can then report the issue to the developers.
*/
#define CHECK_NONFATAL(condition) \
do { \
if (!(condition)) { \
throw NonFatalCheckError( \
strprintf("Internal bug detected: '%s'\n" \
"%s:%d (%s)\n" \
"You may report this issue here: %s\n", \
(#condition), \
__FILE__, __LINE__, __func__, \
PACKAGE_BUGREPORT)); \
} \
} while (false)
#define CHECK_NONFATAL(condition) \
inline_check_non_fatal(condition, __FILE__, __LINE__, __func__, #condition)
#if defined(NDEBUG)
#error "Cannot compile without assertions!"
@@ -80,4 +86,13 @@ T&& inline_assertion_check(T&& val, [[maybe_unused]] const char* file, [[maybe_u
*/
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
/**
* NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code. It throws a NonFatalCheckError.
* This is used to mark code that is not yet implemented or is not yet reachable.
*/
#define NONFATAL_UNREACHABLE() \
throw NonFatalCheckError( \
format_internal_error("Unreachable code reached (non-fatal)", \
__FILE__, __LINE__, __func__, PACKAGE_BUGREPORT))
#endif // BITCOIN_UTIL_CHECK_H