Derive-C
Loading...
Searching...
No Matches
macros.h
Go to the documentation of this file.
1// JUSTIFY: No guards, just for each macro
2// - allows overriding function attributes
3// - allows overriding panic, differently for each template instantiation
4
5#include <assert.h>
6
7#if !defined INLINE
8 #define INLINE inline __attribute__((always_inline))
9#endif
10
11#if !defined CONST
12 #define CONST __attribute__((const))
13#endif
14
15#if !defined PURE
16 #define PURE __attribute__((pure))
17#endif
18
19#if !defined NODISCARD
20 #define NODISCARD __attribute__((warn_unused_result))
21#endif
22
23#if !defined STATIC_ASSERT
24 #if defined __cplusplus
25 #define STATIC_ASSERT static_assert
26 #else
27 #define STATIC_ASSERT _Static_assert
28 #endif
29#endif
30
31#if !defined PANIC
32 #include <stdio.h> // NOLINT(misc-include-cleaner) (for default panic implementation)
33 #include <stdlib.h> // NOLINT(misc-include-cleaner) (for default panic implementation)
34 #define PANIC(...) \
35 do { \
36 fprintf(stderr, __VA_ARGS__); \
37 abort(); \
38 } while (0);
39#endif
40
41#if !defined ASSERT
42 #define ASSERT(expr, ...) \
43 if (!(expr)) { \
44 PANIC("assertion " #expr " failed: " __VA_ARGS__); \
45 }
46#endif
47
48#if !defined UNREACHABLE
49 #define UNREACHABLE(...) PANIC("unreachable: " __VA_ARGS__ "\n");
50#endif
51
52#if !defined LIKELY
53 #define LIKELY(x) __builtin_expect(!!(x), 1)
54#endif
55
56#if !defined WHEN
57 #define WHEN(cond, expr) ((cond) ? (expr) : true)
58#endif
59
60#if !defined ASSUME
61 #if !defined NDEBUG
62 #define ASSUME(expr, ...) ASSERT(expr, __VA_ARGS__)
63 #else
64 #if defined(__clang__)
65 #define ASSUME(expr, ...) __builtin_assume(expr)
66 #elif defined(__GNUC__)
67 // GCC doesn't have __builtin_assume, but this pattern has the same effect:
68 #define ASSUME(expr, ...) \
69 do { \
70 if (!(expr)) \
71 __builtin_unreachable(); \
72 } while (0)
73 #else
74 #define ASSUME(expr, ...) ((void)0)
75 #endif
76 #endif
77#endif