add assert with custom runtime fail message

v1
Brett 2024-01-31 17:24:46 -05:00
parent 215a596d21
commit 527595e1cf
2 changed files with 33 additions and 18 deletions

View File

@ -13,22 +13,41 @@ namespace blt
{
void printStacktrace(char** messages, int size, const char* path, int line);
void b_assert_failed(const char* expression, const char* path, int line);
void b_assert_failed(const char* expression, const char* msg, const char* path, int line);
void b_throw(const char* what, const char* path, int line);
bool assert_print(const char* what);
}
// prints error with stack trace if assertion fails. Does not stop execution.
#define blt_assert(expr) do {static_cast<bool>(expr) ? void(0) : blt::b_assert_failed(#expr, __FILE__, __LINE__) } while (0)
// prints error with stack trace then exits with failure.
#define BLT_ASSERT(expr) do { \
if (!static_cast<bool>(expr)) { \
blt::b_assert_failed(#expr, __FILE__, __LINE__); \
std::exit(EXIT_FAILURE); \
} \
/**
* Prints error with stack trace if assertion fails. Does not stop execution.
*/
#define blt_assert(expr) do {static_cast<bool>(expr) ? void(0) : blt::b_assert_failed(#expr, nullptr, __FILE__, __LINE__) } while (0)
/**
* Prints error with stack trace if assertion fails. Will print fail_message after
* the assertion expression but before the stack trace. Does not stop execution.
*/
#define blt_assert_msg(expr, fail_message) do {static_cast<bool>(expr) ? void(0) : blt::b_assert_failed(#expr, fail_message, __FILE__, __LINE__) } while (0)
/**
* Prints error with stack trace then exits with failure.
*/
#define BLT_ASSERT(expr) do { \
if (!static_cast<bool>(expr)) { \
blt::b_assert_failed(#expr, nullptr, __FILE__, __LINE__); \
std::exit(EXIT_FAILURE); \
} \
} while (0)
/**
* Prints the error with stack trace if the assertion fails and stops execution with EXIT_FAILURE. Will print fail_message after
* the assertion expression but before the stack trace.
*/
#define BLT_ASSERT_MSG(expr, fail_message) do { \
if (!static_cast<bool>(expr)) { \
blt::b_assert_failed(#expr, fail_message, __FILE__, __LINE__); \
std::exit(EXIT_FAILURE); \
} \
} while (0)
// prints as error but does not throw the exception.
#define blt_throw(throwable) do {blt::b_throw(throwable.what(), __FILE__, __LINE__);} while (0)
// prints as error with stack trace and throws the exception.

View File

@ -52,12 +52,14 @@ namespace blt {
#endif
}
void b_assert_failed(const char* expression, const char* path, int line)
void b_assert_failed(const char* expression, const char* msg, const char* path, int line)
{
#if defined(__GNUC__) && !defined(__EMSCRIPTEN__)
BLT_STACK_TRACE(50);
BLT_ERROR("The assertion '%s' has failed in file '%s:%d'", expression, path, line);
if (msg != nullptr)
BLT_ERROR(msg);
BLT_ERROR("Stack Trace:");
printStacktrace(messages, size, path, line);
@ -107,11 +109,5 @@ namespace blt {
#endif
}
bool assert_print(const char* what)
{
BLT_ERROR(what);
return true;
}
}