Derive-C
Loading...
Searching...
No Matches
panic.h
Go to the documentation of this file.
1#pragma once
2#include <assert.h>
3
5
6// JUSTIFY: Disabled under clangd to avoid spurious errors in C code.
7// - We have tests & fuzz tests with panic defined using C++ headers from gtest & rapidcheck
8// - Hence when analysing a header, clangd assumes this is the header as included for these tests
9// - which results in errors for missing macros (e.g. RC_FAIL)
10// Hence for clangd, we just assume the default implementations
11#if !defined PLACEHOLDERS
12 #if defined DC_PANIC_HEADER
13 #include DC_PANIC_HEADER
14 #endif
15#endif
16
17#if !defined DC_STATIC_ASSERT
18 #if defined __cplusplus
19 #define DC_STATIC_ASSERT static_assert
20 #else
21 #define DC_STATIC_ASSERT _Static_assert
22 #endif
23#endif
24
25#if !defined DC_PANIC
26 #include <stdio.h> // NOLINT(misc-include-cleaner) (for default panic implementation)
27 #include <stdlib.h> // NOLINT(misc-include-cleaner) (for default panic implementation)
28 #define DC_PANIC(...) \
29 do { \
30 fprintf(stderr, __VA_ARGS__); \
31 abort(); \
32 } while (0);
33#endif
34
35#if !defined DC_ASSERT
36 #define DC_ASSERT(expr, ...) \
37 if (!(expr)) { \
38 DC_PANIC("assertion " #expr " failed: " __VA_ARGS__); \
39 }
40#endif
41
42#if !defined DC_UNREACHABLE
43 #define DC_UNREACHABLE(...) DC_PANIC("unreachable: " __VA_ARGS__ "\n");
44#endif
45
46#if !defined DC_LIKELY
47 #define DC_LIKELY(x) __builtin_expect(!!(x), 1)
48#endif
49
50#if !defined DC_WHEN
51 #define DC_WHEN(cond, expr) ((cond) ? (expr) : true)
52#endif
53
54#if !defined DC_ASSUME
55 #if !defined NDEBUG
56 #define DC_ASSUME(expr, ...) DC_ASSERT(expr, __VA_ARGS__)
57 #else
58 #if defined(__clang__)
59 #define DC_ASSUME(expr, ...) __builtin_assume(expr)
60 #elif defined(__GNUC__)
61 // GCC doesn't have __builtin_assume, but this pattern has the same effect:
62 #define DC_ASSUME(expr, ...) \
63 do { \
64 if (!(expr)) \
65 __builtin_unreachable(); \
66 } while (0)
67 #else
68 #define DC_ASSUME(expr, ...) ((void)0)
69 #endif
70 #endif
71#endif