timespec_get: New module.
[gnulib.git] / lib / verify.h
blob3cdcdca56715e5a144054f9717c383de18740fbc
1 /* Compile-time assert-like macros.
3 Copyright (C) 2005-2006, 2009-2021 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */
20 #ifndef _GL_VERIFY_H
21 #define _GL_VERIFY_H
24 /* Define _GL_HAVE__STATIC_ASSERT to 1 if _Static_assert (R, DIAGNOSTIC)
25 works as per C11. This is supported by GCC 4.6.0 and later, in C
26 mode, and by clang (also in C++ mode).
28 Define _GL_HAVE__STATIC_ASSERT1 to 1 if _Static_assert (R) works as
29 per C2X. This is supported by GCC 9.1 and later, and by clang in
30 C++1z mode.
32 Define _GL_HAVE_STATIC_ASSERT1 if static_assert (R) works as per
33 C++17. This is supported by GCC 9.1 and later, and by clang in
34 C++1z mode.
36 Support compilers claiming conformance to the relevant standard,
37 and also support GCC when not pedantic. If we were willing to slow
38 'configure' down we could also use it with other compilers, but
39 since this affects only the quality of diagnostics, why bother? */
40 #ifndef __cplusplus
41 # if (201112L <= __STDC_VERSION__ \
42 || (!defined __STRICT_ANSI__ \
43 && (4 < __GNUC__ + (6 <= __GNUC_MINOR__) || 4 <= __clang_major__)))
44 # define _GL_HAVE__STATIC_ASSERT 1
45 # endif
46 # if (202000L <= __STDC_VERSION__ \
47 || (!defined __STRICT_ANSI__ && 9 <= __GNUC__))
48 # define _GL_HAVE__STATIC_ASSERT1 1
49 # endif
50 #else
51 # if 4 <= __clang_major__
52 # define _GL_HAVE__STATIC_ASSERT 1
53 # endif
54 # if 4 <= __clang_major__ && 201411 <= __cpp_static_assert
55 # define _GL_HAVE__STATIC_ASSERT1 1
56 # endif
57 # if 201703L <= __cplusplus \
58 || 9 <= __GNUC__ \
59 || (4 <= __clang_major__ && 201411 <= __cpp_static_assert)
60 # define _GL_HAVE_STATIC_ASSERT1 1
61 # endif
62 #endif
64 /* FreeBSD 9.1 <sys/cdefs.h>, included by <stddef.h> and lots of other
65 system headers, defines a conflicting _Static_assert that is no
66 better than ours; override it. */
67 #ifndef _GL_HAVE__STATIC_ASSERT
68 # include <stddef.h>
69 # undef _Static_assert
70 #endif
72 /* Each of these macros verifies that its argument R is nonzero. To
73 be portable, R should be an integer constant expression. Unlike
74 assert (R), there is no run-time overhead.
76 If _Static_assert works, verify (R) uses it directly. Similarly,
77 _GL_VERIFY_TRUE works by packaging a _Static_assert inside a struct
78 that is an operand of sizeof.
80 The code below uses several ideas for C++ compilers, and for C
81 compilers that do not support _Static_assert:
83 * The first step is ((R) ? 1 : -1). Given an expression R, of
84 integral or boolean or floating-point type, this yields an
85 expression of integral type, whose value is later verified to be
86 constant and nonnegative.
88 * Next this expression W is wrapped in a type
89 struct _gl_verify_type {
90 unsigned int _gl_verify_error_if_negative: W;
92 If W is negative, this yields a compile-time error. No compiler can
93 deal with a bit-field of negative size.
95 One might think that an array size check would have the same
96 effect, that is, that the type struct { unsigned int dummy[W]; }
97 would work as well. However, inside a function, some compilers
98 (such as C++ compilers and GNU C) allow local parameters and
99 variables inside array size expressions. With these compilers,
100 an array size check would not properly diagnose this misuse of
101 the verify macro:
103 void function (int n) { verify (n < 0); }
105 * For the verify macro, the struct _gl_verify_type will need to
106 somehow be embedded into a declaration. To be portable, this
107 declaration must declare an object, a constant, a function, or a
108 typedef name. If the declared entity uses the type directly,
109 such as in
111 struct dummy {...};
112 typedef struct {...} dummy;
113 extern struct {...} *dummy;
114 extern void dummy (struct {...} *);
115 extern struct {...} *dummy (void);
117 two uses of the verify macro would yield colliding declarations
118 if the entity names are not disambiguated. A workaround is to
119 attach the current line number to the entity name:
121 #define _GL_CONCAT0(x, y) x##y
122 #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
123 extern struct {...} * _GL_CONCAT (dummy, __LINE__);
125 But this has the problem that two invocations of verify from
126 within the same macro would collide, since the __LINE__ value
127 would be the same for both invocations. (The GCC __COUNTER__
128 macro solves this problem, but is not portable.)
130 A solution is to use the sizeof operator. It yields a number,
131 getting rid of the identity of the type. Declarations like
133 extern int dummy [sizeof (struct {...})];
134 extern void dummy (int [sizeof (struct {...})]);
135 extern int (*dummy (void)) [sizeof (struct {...})];
137 can be repeated.
139 * Should the implementation use a named struct or an unnamed struct?
140 Which of the following alternatives can be used?
142 extern int dummy [sizeof (struct {...})];
143 extern int dummy [sizeof (struct _gl_verify_type {...})];
144 extern void dummy (int [sizeof (struct {...})]);
145 extern void dummy (int [sizeof (struct _gl_verify_type {...})]);
146 extern int (*dummy (void)) [sizeof (struct {...})];
147 extern int (*dummy (void)) [sizeof (struct _gl_verify_type {...})];
149 In the second and sixth case, the struct type is exported to the
150 outer scope; two such declarations therefore collide. GCC warns
151 about the first, third, and fourth cases. So the only remaining
152 possibility is the fifth case:
154 extern int (*dummy (void)) [sizeof (struct {...})];
156 * GCC warns about duplicate declarations of the dummy function if
157 -Wredundant-decls is used. GCC 4.3 and later have a builtin
158 __COUNTER__ macro that can let us generate unique identifiers for
159 each dummy function, to suppress this warning.
161 * This implementation exploits the fact that older versions of GCC,
162 which do not support _Static_assert, also do not warn about the
163 last declaration mentioned above.
165 * GCC warns if -Wnested-externs is enabled and 'verify' is used
166 within a function body; but inside a function, you can always
167 arrange to use verify_expr instead.
169 * In C++, any struct definition inside sizeof is invalid.
170 Use a template type to work around the problem. */
172 /* Concatenate two preprocessor tokens. */
173 #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
174 #define _GL_CONCAT0(x, y) x##y
176 /* _GL_COUNTER is an integer, preferably one that changes each time we
177 use it. Use __COUNTER__ if it works, falling back on __LINE__
178 otherwise. __LINE__ isn't perfect, but it's better than a
179 constant. */
180 #if defined __COUNTER__ && __COUNTER__ != __COUNTER__
181 # define _GL_COUNTER __COUNTER__
182 #else
183 # define _GL_COUNTER __LINE__
184 #endif
186 /* Generate a symbol with the given prefix, making it unique if
187 possible. */
188 #define _GL_GENSYM(prefix) _GL_CONCAT (prefix, _GL_COUNTER)
190 /* Verify requirement R at compile-time, as an integer constant expression
191 that returns 1. If R is false, fail at compile-time, preferably
192 with a diagnostic that includes the string-literal DIAGNOSTIC. */
194 #define _GL_VERIFY_TRUE(R, DIAGNOSTIC) \
195 (!!sizeof (_GL_VERIFY_TYPE (R, DIAGNOSTIC)))
197 #ifdef __cplusplus
198 # if !GNULIB_defined_struct__gl_verify_type
199 template <int w>
200 struct _gl_verify_type {
201 unsigned int _gl_verify_error_if_negative: w;
203 # define GNULIB_defined_struct__gl_verify_type 1
204 # endif
205 # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
206 _gl_verify_type<(R) ? 1 : -1>
207 #elif defined _GL_HAVE__STATIC_ASSERT
208 # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
209 struct { \
210 _Static_assert (R, DIAGNOSTIC); \
211 int _gl_dummy; \
213 #else
214 # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
215 struct { unsigned int _gl_verify_error_if_negative: (R) ? 1 : -1; }
216 #endif
218 /* Verify requirement R at compile-time, as a declaration without a
219 trailing ';'. If R is false, fail at compile-time.
221 This macro requires three or more arguments but uses at most the first
222 two, so that the _Static_assert macro optionally defined below supports
223 both the C11 two-argument syntax and the C2X one-argument syntax.
225 Unfortunately, unlike C11, this implementation must appear as an
226 ordinary declaration, and cannot appear inside struct { ... }. */
228 #if defined _GL_HAVE__STATIC_ASSERT
229 # define _GL_VERIFY(R, DIAGNOSTIC, ...) _Static_assert (R, DIAGNOSTIC)
230 #else
231 # define _GL_VERIFY(R, DIAGNOSTIC, ...) \
232 extern int (*_GL_GENSYM (_gl_verify_function) (void)) \
233 [_GL_VERIFY_TRUE (R, DIAGNOSTIC)]
234 #endif
236 /* _GL_STATIC_ASSERT_H is defined if this code is copied into assert.h. */
237 #ifdef _GL_STATIC_ASSERT_H
238 # if !defined _GL_HAVE__STATIC_ASSERT1 && !defined _Static_assert
239 # define _Static_assert(...) \
240 _GL_VERIFY (__VA_ARGS__, "static assertion failed", -)
241 # endif
242 # if !defined _GL_HAVE_STATIC_ASSERT1 && !defined static_assert
243 # define static_assert _Static_assert /* C11 requires this #define. */
244 # endif
245 #endif
247 /* @assert.h omit start@ */
249 #if 3 < __GNUC__ + (3 < __GNUC_MINOR__ + (4 <= __GNUC_PATCHLEVEL__))
250 # define _GL_HAS_BUILTIN_TRAP 1
251 #elif defined __has_builtin
252 # define _GL_HAS_BUILTIN_TRAP __has_builtin (__builtin_trap)
253 #else
254 # define _GL_HAS_BUILTIN_TRAP 0
255 #endif
257 #if 4 < __GNUC__ + (5 <= __GNUC_MINOR__)
258 # define _GL_HAS_BUILTIN_UNREACHABLE 1
259 #elif defined __has_builtin
260 # define _GL_HAS_BUILTIN_UNREACHABLE __has_builtin (__builtin_unreachable)
261 #else
262 # define _GL_HAS_BUILTIN_UNREACHABLE 0
263 #endif
265 /* Each of these macros verifies that its argument R is nonzero. To
266 be portable, R should be an integer constant expression. Unlike
267 assert (R), there is no run-time overhead.
269 There are two macros, since no single macro can be used in all
270 contexts in C. verify_expr (R, E) is for scalar contexts, including
271 integer constant expression contexts. verify (R) is for declaration
272 contexts, e.g., the top level. */
274 /* Verify requirement R at compile-time. Return the value of the
275 expression E. */
277 #define verify_expr(R, E) \
278 (_GL_VERIFY_TRUE (R, "verify_expr (" #R ", " #E ")") ? (E) : (E))
280 /* Verify requirement R at compile-time, as a declaration without a
281 trailing ';'. verify (R) acts like static_assert (R) except that
282 it is portable to C11/C++14 and earlier, it can issue better
283 diagnostics, and its name is shorter and may be more convenient. */
285 #ifdef __PGI
286 /* PGI barfs if R is long. */
287 # define verify(R) _GL_VERIFY (R, "verify (...)", -)
288 #else
289 # define verify(R) _GL_VERIFY (R, "verify (" #R ")", -)
290 #endif
292 /* Assume that R always holds. Behavior is undefined if R is false,
293 fails to evaluate, or has side effects.
295 'assume (R)' is a directive from the programmer telling the
296 compiler that R is true so the compiler needn't generate code to
297 test R. This is why 'assume' is in verify.h: it's related to
298 static checking (in this case, static checking done by the
299 programmer), not dynamic checking.
301 'assume (R)' can affect compilation of all the code, not just code
302 that happens to be executed after the assume (R) is "executed".
303 For example, if the code mistakenly does 'assert (R); assume (R);'
304 the compiler is entitled to optimize away the 'assert (R)'.
306 Although assuming R can help a compiler generate better code or
307 diagnostics, performance can suffer if R uses hard-to-optimize
308 features such as function calls not inlined by the compiler.
310 Avoid Clang's __builtin_assume, as it breaks GNU Emacs master
311 as of 2020-08-23T21:09:49Z!eggert@cs.ucla.edu; see
312 <https://bugs.gnu.org/43152#71>. It's not known whether this breakage
313 is a Clang bug or an Emacs bug; play it safe for now. */
315 #if _GL_HAS_BUILTIN_UNREACHABLE
316 # define assume(R) ((R) ? (void) 0 : __builtin_unreachable ())
317 #elif 1200 <= _MSC_VER
318 # define assume(R) __assume (R)
319 #elif (defined GCC_LINT || defined lint) && _GL_HAS_BUILTIN_TRAP
320 /* Doing it this way helps various packages when configured with
321 --enable-gcc-warnings, which compiles with -Dlint. It's nicer
322 when 'assume' silences warnings even with older GCCs. */
323 # define assume(R) ((R) ? (void) 0 : __builtin_trap ())
324 #else
325 /* Some tools grok NOTREACHED, e.g., Oracle Studio 12.6. */
326 # define assume(R) ((R) ? (void) 0 : /*NOTREACHED*/ (void) 0)
327 #endif
329 /* @assert.h omit end@ */
331 #endif