-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: panic: add
ASSERT
, UNREACHABLE
, UNIMPLEMENTED
, safer env var
Require `SILO_PANIC` env var to be set to `panic` instead of `DEBUG` to be `1` before calling abort, to avoid the risk of accidentally triggering it.
- Loading branch information
Showing
2 changed files
with
83 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,56 @@ | ||
#include "silo/common/panic.h" | ||
|
||
#include <cstdlib> | ||
#include <cstring> | ||
#include <iostream> | ||
|
||
namespace silo::common { | ||
|
||
namespace { | ||
bool is0(const char* str) { | ||
return str[0] == '0' && str[1] == '\0'; | ||
} | ||
} // namespace | ||
|
||
void panic(const std::string& msg, const char* file, int line) { | ||
const char* env = getenv("DEBUG"); | ||
bool debug; | ||
[[noreturn]] void panic( | ||
const std::string& prefix, | ||
const std::string& msg, | ||
const char* file, | ||
int line | ||
) { | ||
const char* env = getenv("SILO_PANIC"); | ||
bool do_abort; | ||
if (env) { | ||
debug = !is0(env); | ||
do_abort = strcmp(env, "abort") == 0; | ||
} else { | ||
debug = false; | ||
do_abort = false; | ||
} | ||
auto full_msg = fmt::format("PANIC: {} at {}:{}", msg, file, line); | ||
if (debug) { | ||
auto full_msg = fmt::format("{}{} at {}:{}", prefix, msg, file, line); | ||
if (do_abort) { | ||
std::cerr << full_msg << "\n" << std::flush; | ||
abort(); | ||
} else { | ||
throw std::runtime_error(full_msg); | ||
} | ||
} | ||
|
||
} // namespace | ||
|
||
[[noreturn]] void panic(const std::string& msg, const char* file, int line) { | ||
panic("PANIC: ", msg, file, line); | ||
} | ||
|
||
[[noreturn]] void unreachable(const char* file, int line) { | ||
panic( | ||
"UNREACHABLE: ", | ||
"Please report this as a bug in SILO: this code should never be reachable", | ||
file, | ||
line | ||
); | ||
} | ||
|
||
[[noreturn]] void unimplemented(const char* file, int line) { | ||
panic("UNIMPLEMENTED: ", "This execution path is not implemented yet", file, line); | ||
} | ||
|
||
[[noreturn]] void assertFailure(const char* msg, const char* file, int line) { | ||
panic("ASSERT failure: ", msg, file, line); | ||
} | ||
|
||
} // namespace silo::common |