TorchCraftAI
A bot for machine learning research on StarCraft: Brood War
assert.h
1 #pragma once
2 
3 #include <backward/backward.hpp>
4 #include <gflags/gflags.h>
5 #include <stdexcept>
6 #include <string>
7 #include <string_view>
8 
9 DECLARE_bool(continue_on_assert);
10 
11 namespace common {
12 
13 class Exception : public std::runtime_error {
14  public:
15  Exception(
16  std::string_view what,
17  const char* file = "unknown_file",
18  int line = 0);
19  Exception(
20  std::string_view what,
21  const char* file,
22  int line,
23  backward::StackTrace st);
24 
25  const char* file;
26  int line;
27  backward::StackTrace stackTrace;
28 
29  void print();
30 
31  protected:
32  static std::string
33  formatErrorMessage(std::string_view message, const char* file, int line);
34 };
35 
36 class AssertionFailure : public Exception {
37  public:
39  std::string_view condition,
40  std::string_view message,
41  const char* file,
42  int line,
43  backward::StackTrace const& st);
44 
45  std::string_view condition;
46 
47  protected:
48  static std::string formatErrorMessage(
49  std::string_view condition,
50  std::string_view message);
51 };
52 
53 // Returns a StackTrace that starts in the caller function
54 backward::StackTrace createStackTrace();
55 
56 } // namespace common
57 
58 #define ASSERT_MAKE_STR(s) #s
59 #define ASSERT_2(condition, message) \
60  { \
61  if (!(condition)) { \
62  throw common::AssertionFailure( \
63  ASSERT_MAKE_STR(condition), \
64  message, \
65  __FILE__, \
66  __LINE__, \
67  common::createStackTrace()); \
68  } \
69  }
70 #define ASSERT_1(condition) ASSERT_2(condition, "")
71 
72 // The trick below allows the user to specify either 1 or 2 arguments
73 // to the ASSERT macro, without having to use explicitely ASSERT_1 or ASSERT_2
74 // https://stackoverflow.com/questions/3046889/optional-parameters-with-c-macros
75 #define GET_3RD_ARG(arg1, arg2, arg3, ...) arg3
76 #define ASSERT_MACRO_CHOOSER(...) GET_3RD_ARG(__VA_ARGS__, ASSERT_2, ASSERT_1, )
77 
78 // Takes 1 or 2 arguments: the condition, and an optional message
79 #define ASSERT(...) ASSERT_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)
Definition: assert.h:13
const char * file
Definition: assert.h:25
Exception(std::string_view what, const char *file="unknown_file", int line=0)
Definition: assert.cpp:9
int line
Definition: assert.h:26
std::string_view condition
Definition: assert.h:45
Definition: assert.h:36
void print()
Definition: assert.cpp:29
General utilities.
Definition: assert.cpp:7
backward::StackTrace stackTrace
Definition: assert.h:27
static std::string formatErrorMessage(std::string_view message, const char *file, int line)
Definition: assert.cpp:22
backward::StackTrace createStackTrace()
Definition: assert.cpp:59