CARLA
Debug.h
Go to the documentation of this file.
1 // Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma
2 // de Barcelona (UAB).
3 //
4 // This work is licensed under the terms of the MIT license.
5 // For a copy, see <https://opensource.org/licenses/MIT>.
6 
7 /// Macro utilities for assertions and debug-only code.
8 ///
9 /// Defines three levels of assertions: debug, development, and release. By
10 /// default, if NDEBUG is defined the level is set to development, otherwise is
11 /// set to debug.
12 ///
13 /// The following macros are defined here:
14 ///
15 /// * DEBUG_ONLY(code) - Code is evaluated only if assertion level is set to
16 /// debug.
17 ///
18 /// * DEVELOPMENT_ONLY(code) - Code is evaluated only if assertion level is
19 /// set to development or higher.
20 ///
21 /// * DEBUG_ASSERT(predicate) - Effectively calls assert(predicate).
22 ///
23 /// * DEVELOPMENT_ASSERT(predicate) - Throws an exception if assertion is
24 /// set to development or higher, and predicate evaluates to false.
25 ///
26 /// * RELEASE_ASSERT(predicate) - Throws an exception if predicate evaluates
27 /// to false.
28 
29 #pragma once
30 
31 #include "carla/Exception.h"
32 
33 #include <stdexcept>
34 
35 #define LIBCARLA_ASSERT_LEVEL_DEBUG 30
36 #define LIBCARLA_ASSERT_LEVEL_DEVELOPMENT 20
37 #define LIBCARLA_ASSERT_LEVEL_RELEASE 10
38 
39 #ifndef LIBCARLA_ASSERT_LEVEL
40 # ifdef NDEBUG
41 # define LIBCARLA_ASSERT_LEVEL LIBCARLA_ASSERT_LEVEL_DEVELOPMENT
42 # else
43 # define LIBCARLA_ASSERT_LEVEL LIBCARLA_ASSERT_LEVEL_DEBUG
44 # endif // NDEBUG
45 #endif // LIBCARLA_ASSERT_LEVEL
46 
47 #if (LIBCARLA_ASSERT_LEVEL >= LIBCARLA_ASSERT_LEVEL_DEBUG)
48 # ifdef NDEBUG
49 # error Cannot have debug asserts with NDEBUG enabled.
50 # endif
51 # include <cassert>
52 #endif // NDEBUG
53 
54 #if (LIBCARLA_ASSERT_LEVEL >= LIBCARLA_ASSERT_LEVEL_DEBUG)
55 # define DEBUG_ONLY(code) code
56 #else
57 # define DEBUG_ONLY(code)
58 #endif
59 
60 #if (LIBCARLA_ASSERT_LEVEL >= LIBCARLA_ASSERT_LEVEL_DEVELOPMENT)
61 # define DEVELOPMENT_ONLY(code) code
62 #else
63 # define DEVELOPMENT_ONLY(code)
64 #endif
65 
66 #define DEBUG_ASSERT(predicate) DEBUG_ONLY(assert(predicate));
67 
68 #define DEBUG_ERROR DEBUG_ASSERT(false);
69 
70 #ifdef LIBCARLA_WITH_GTEST
71 # include <gtest/gtest.h>
72 
73 # define DEBUG_ASSERT_EQ(lhs, rhs) DEBUG_ONLY(EXPECT_EQ(lhs, rhs));DEBUG_ASSERT(lhs == rhs);
74 # define DEBUG_ASSERT_NE(lhs, rhs) DEBUG_ONLY(EXPECT_NE(lhs, rhs));DEBUG_ASSERT(lhs != rhs);
75 #else
76 # define DEBUG_ASSERT_EQ(lhs, rhs) DEBUG_ASSERT((lhs) == (rhs))
77 # define DEBUG_ASSERT_NE(lhs, rhs) DEBUG_ASSERT((lhs) != (rhs))
78 #endif // LIBCARLA_WITH_GTEST
79 
80 #define LIBCARLA_ASSERT_THROW__(pred, msg) if (!(pred)) { ::carla::throw_exception(std::runtime_error(msg)); }
81 
82 #define DEVELOPMENT_ASSERT(pred) DEVELOPMENT_ONLY(LIBCARLA_ASSERT_THROW__(pred, #pred))
83 
84 #define RELEASE_ASSERT(pred) LIBCARLA_ASSERT_THROW__(pred, #pred)