Porytiles
Loading...
Searching...
No Matches
panic.cpp
Go to the documentation of this file.
2
3#include <cstdlib>
4#include <filesystem>
5#include <format>
6#include <iostream>
7
8#include "cpptrace/cpptrace.hpp"
9
10namespace {
11
12bool stacktrace_enabled = true;
13
14void print_stacktrace(std::size_t skip = 0)
15{
16 const auto trace = cpptrace::generate_trace(skip + 1);
17 trace.print();
18}
19
20void print_panic_header(const std::filesystem::path &path, std::uint_least32_t line, std::string_view msg)
21{
22 std::cerr << "---------------------------------" << std::endl;
23 std::cerr << "| PANIC |" << std::endl;
24 std::cerr << "---------------------------------" << std::endl;
25 std::cerr << std::format("{}:{}: {}", path.filename().string(), line, msg) << std::endl;
26 std::cerr << std::endl;
27}
28
29} // namespace
30
31namespace porytiles {
32
33void set_panic_stacktrace_enabled(const bool enabled)
34{
35 stacktrace_enabled = enabled;
36}
37
39{
40 return stacktrace_enabled;
41}
42
44{
45 const std::filesystem::path path{s.loc_.file_name()};
46 print_panic_header(path, s.loc_.line(), s.msg_);
47 if (stacktrace_enabled) {
48 print_stacktrace(1);
49 }
50 std::abort();
51}
52
53void assert_or_panic(const bool condition, const StringViewSourceLoc &s)
54{
55 if (!condition) {
56 const std::filesystem::path path{s.loc_.file_name()};
57 print_panic_header(path, s.loc_.line(), s.msg_);
58 if (stacktrace_enabled) {
59 print_stacktrace(1);
60 }
61 std::abort();
62 }
63}
64
65} // namespace porytiles
void panic(const StringViewSourceLoc &s)
Unconditionally terminates the program with a panic message.
Definition panic.cpp:43
void assert_or_panic(bool condition, const StringViewSourceLoc &s)
Conditionally panics if the given condition is false.
Definition panic.cpp:53
bool is_panic_stacktrace_enabled()
Returns whether stacktrace generation is enabled on panic.
Definition panic.cpp:38
void set_panic_stacktrace_enabled(bool enabled)
Enables or disables stacktrace generation on panic.
Definition panic.cpp:33
A wrapper for std::string_view with a taggable std::source_location.
Definition panic.hpp:17
std::string_view msg_
Definition panic.hpp:37
std::source_location loc_
Definition panic.hpp:38