Debian Codegraph @

lib/verify.h

raw
1 /* Compile-time assert-like macros.
2
3 Copyright (C) 2005-2006, 2009-2026 Free Software Foundation, Inc.
4
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
9
10 This file 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17
18 /* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */
19
20 #ifndef _GL_VERIFY_H
21 #define _GL_VERIFY_H
22
23
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 by clang 4+.
26
27 Define _GL_HAVE__STATIC_ASSERT1 to 1 if _Static_assert (R) works as
28 per C23. This is supported by GCC 9.1+.
29
30 Support compilers claiming conformance to the relevant standard,
31 and also support GCC when not pedantic. If we were willing to slow
32 'configure' down we could also use it with other compilers, but
33 since this affects only the quality of diagnostics, why bother? */
34 #ifndef __cplusplus
35 # if (201112 <= __STDC_VERSION__ \
36 || (!defined __STRICT_ANSI__ \
37 && ((4 < __GNUC__ + (6 <= __GNUC_MINOR__) && !defined __clang__) \
38 || 5 <= __clang_major__)))
39 # define _GL_HAVE__STATIC_ASSERT 1
40 # endif
41 # if (202311 <= __STDC_VERSION__ \
42 || (!defined __STRICT_ANSI__ && 9 <= __GNUC__ && !defined __clang__))
43 # define _GL_HAVE__STATIC_ASSERT1 1
44 # endif
45 #endif
46
47 /* FreeBSD 9.1 <sys/cdefs.h>, included by <stddef.h> and lots of other
48 system headers, defines a conflicting _Static_assert that is no
49 better than ours; override it. */
50 #ifndef _GL_HAVE__STATIC_ASSERT
51 # include <stddef.h>
52 # undef _Static_assert
53 #endif
54
55 /* Each of these macros verifies that its argument R is nonzero. To
56 be portable, R should be an integer constant expression. Unlike
57 assert (R), there is no run-time overhead.
58
59 If _Static_assert works, verify (R) uses it directly. Similarly,
60 _GL_VERIFY_TRUE works by packaging a _Static_assert inside a struct
61 that is an operand of sizeof.
62
63 The code below uses several ideas for C++ compilers, and for C
64 compilers that do not support _Static_assert:
65
66 * The first step is ((R) ? 1 : -1). Given an expression R, of
67 integral or boolean or floating-point type, this yields an
68 expression of integral type, whose value is later verified to be
69 constant and nonnegative.
70
71 * Next this expression W is wrapped in a type
72 struct _gl_verify_type {
73 unsigned int _gl_verify_error_if_negative: W;
74 }.
75 If W is negative, this yields a compile-time error. No compiler can
76 deal with a bit-field of negative size.
77
78 One might think that an array size check would have the same
79 effect, that is, that the type struct { unsigned int dummy[W]; }
80 would work as well. However, inside a function, some compilers
81 (such as C++ compilers and GNU C) allow local parameters and
82 variables inside array size expressions. With these compilers,
83 an array size check would not properly diagnose this misuse of
84 the verify macro:
85
86 void function (int n) { verify (n < 0); }
87
88 * For the verify macro, the struct _gl_verify_type will need to
89 somehow be embedded into a declaration. To be portable, this
90 declaration must declare an object, a constant, a function, or a
91 typedef name. If the declared entity uses the type directly,
92 such as in
93
94 struct dummy {...};
95 typedef struct {...} dummy;
96 extern struct {...} *dummy;
97 extern void dummy (struct {...} *);
98 extern struct {...} *dummy (void);
99
100 two uses of the verify macro would yield colliding declarations
101 if the entity names are not disambiguated. A workaround is to
102 attach the current line number to the entity name:
103
104 #define _GL_CONCAT0(x, y) x##y
105 #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
106 extern struct {...} * _GL_CONCAT (dummy, __LINE__);
107
108 But this has the problem that two invocations of verify from
109 within the same macro would collide, since the __LINE__ value
110 would be the same for both invocations. (The GCC __COUNTER__
111 macro solves this problem, but is not portable.)
112
113 A solution is to use the sizeof operator. It yields a number,
114 getting rid of the identity of the type. Declarations like
115
116 extern int dummy [sizeof (struct {...})];
117 extern void dummy (int [sizeof (struct {...})]);
118 extern int (*dummy (void)) [sizeof (struct {...})];
119
120 can be repeated.
121
122 * Should the implementation use a named struct or an unnamed struct?
123 Which of the following alternatives can be used?
124
125 extern int dummy [sizeof (struct {...})];
126 extern int dummy [sizeof (struct _gl_verify_type {...})];
127 extern void dummy (int [sizeof (struct {...})]);
128 extern void dummy (int [sizeof (struct _gl_verify_type {...})]);
129 extern int (*dummy (void)) [sizeof (struct {...})];
130 extern int (*dummy (void)) [sizeof (struct _gl_verify_type {...})];
131
132 In the second and sixth case, the struct type is exported to the
133 outer scope; two such declarations therefore collide. GCC warns
134 about the first, third, and fourth cases. So the only remaining
135 possibility is the fifth case:
136
137 extern int (*dummy (void)) [sizeof (struct {...})];
138
139 * GCC warns about duplicate declarations of the dummy function if
140 -Wredundant-decls is used. GCC 4.3 and later have a builtin
141 __COUNTER__ macro that can let us generate unique identifiers for
142 each dummy function, to suppress this warning.
143
144 * This implementation exploits the fact that older versions of GCC,
145 which do not support _Static_assert, also do not warn about the
146 last declaration mentioned above.
147
148 * GCC warns if -Wnested-externs is enabled and 'verify' is used
149 within a function body; but inside a function, you can always
150 arrange to use verify_expr instead.
151
152 * In C++, any struct definition inside sizeof is invalid.
153 Use a template type to work around the problem. */
154
155 /* Concatenate two preprocessor tokens. */
156 #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
157 #define _GL_CONCAT0(x, y) x##y
158
159 /* _GL_COUNTER is an integer, preferably one that changes each time we
160 use it. Use __COUNTER__ if it works (it does so with most compilers,
161 see <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3457.htm>),
162 falling back on __LINE__ otherwise. __LINE__ isn't perfect, but it's
163 better than a constant. */
164 #if defined __COUNTER__ && __COUNTER__ != __COUNTER__
165 # define _GL_COUNTER __COUNTER__
166 #else
167 # define _GL_COUNTER __LINE__
168 #endif
169
170 /* Generate a symbol with the given prefix, making it unique if
171 possible. */
172 #define _GL_GENSYM(prefix) _GL_CONCAT (prefix, _GL_COUNTER)
173
174 /* Verify requirement R at compile-time, as an integer constant expression
175 that returns 1. If R is false, fail at compile-time, preferably
176 with a diagnostic that includes the string-literal DIAGNOSTIC. */
177
178 #define _GL_VERIFY_TRUE(R, DIAGNOSTIC) \
179 (!!sizeof (_GL_VERIFY_TYPE (R, DIAGNOSTIC)))
180
181 #ifdef __cplusplus
182 # if !GNULIB_defined_struct__gl_verify_type
183 template <int w>
184 struct _gl_verify_type {
185 unsigned int _gl_verify_error_if_negative: w;
186 };
187 # define GNULIB_defined_struct__gl_verify_type 1
188 # endif
189 # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
190 _gl_verify_type<(R) ? 1 : -1>
191 #elif defined _GL_HAVE__STATIC_ASSERT
192 # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
193 struct { \
194 _Static_assert (R, DIAGNOSTIC); \
195 int _gl_dummy; \
196 }
197 #else
198 # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
199 struct { unsigned int _gl_verify_error_if_negative: (R) ? 1 : -1; }
200 #endif
201
202 /* Verify requirement R at compile-time, as a declaration without a
203 trailing ';'. If R is false, fail at compile-time.
204
205 This macro requires three or more arguments but uses at most the first
206 two, so that the _Static_assert macro optionally defined below supports
207 both the C11 two-argument syntax and the C23 one-argument syntax.
208
209 Unfortunately, unlike C11, this implementation must appear as an
210 ordinary declaration, and cannot appear inside struct { ... }. */
211
212 #if 202311 <= __STDC_VERSION__ || 200410 <= __cpp_static_assert
213 # define _GL_VERIFY(R, DIAGNOSTIC, ...) static_assert (R, DIAGNOSTIC)
214 #elif defined _GL_HAVE__STATIC_ASSERT
215 # define _GL_VERIFY(R, DIAGNOSTIC, ...) _Static_assert (R, DIAGNOSTIC)
216 #else
217 # define _GL_VERIFY(R, DIAGNOSTIC, ...) \
218 extern int (*_GL_GENSYM (_gl_verify_function) (void)) \
219 [_GL_VERIFY_TRUE (R, DIAGNOSTIC)]
220 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__) && !defined __clang__
221 # pragma GCC diagnostic ignored "-Wnested-externs"
222 # endif
223 #endif
224
225 /* _GL_STATIC_ASSERT_H is defined if this code is copied into assert.h. */
226 #ifdef _GL_STATIC_ASSERT_H
227 /* Define _Static_assert if needed. */
228 /* With clang ≥ 3.8.0 in C++ mode, _Static_assert already works and accepts
229 1 or 2 arguments. We better don't override it, because clang's standard
230 C++ library uses static_assert inside classes in several places, and our
231 replacement via _GL_VERIFY does not work in these contexts. */
232 # if (defined __cplusplus && defined __clang__ \
233 && (4 <= __clang_major__ + (8 <= __clang_minor__)))
234 # if 5 <= __clang_major__
235 /* Avoid "warning: 'static_assert' with no message is a C++17 extension". */
236 # pragma clang diagnostic ignored "-Wc++17-extensions"
237 # else
238 /* Avoid "warning: static_assert with no message is a C++1z extension". */
239 # pragma clang diagnostic ignored "-Wc++1z-extensions"
240 # endif
241 # elif !defined _GL_HAVE__STATIC_ASSERT1 && !defined _Static_assert
242 # if !defined _MSC_VER || defined __clang__
243 # define _Static_assert(...) \
244 _GL_VERIFY (__VA_ARGS__, "static assertion failed", -)
245 # else
246 # if defined __cplusplus && _MSC_VER >= 1910
247 /* In MSVC 14.1 or newer, static_assert accepts one or two arguments,
248 but _Static_assert is not defined. */
249 # define _Static_assert static_assert
250 # else
251 /* Work around MSVC preprocessor incompatibility with ISO C; see
252 <https://stackoverflow.com/questions/5134523/>. */
253 # define _Static_assert(R, ...) \
254 _GL_VERIFY ((R), "static assertion failed", -)
255 # endif
256 # endif
257 # endif
258 /* Define static_assert if needed. */
259 # if defined __cplusplus && defined __clang__ && __clang_major__ < 9
260 /* clang++ before commit 5c739665a8721228cf6143fd4ef95870a59f55ae had a
261 two-arguments static_assert but not the one-argument static_assert. */
262 # undef static_assert
263 # endif
264 # if (!defined static_assert \
265 && __STDC_VERSION__ < 202311 \
266 && (!defined __cplusplus \
267 || (__cpp_static_assert < 201411 \
268 && __GNUG__ < 6 && __clang_major__ < 6 && _MSC_VER < 1910)))
269 # if (defined __cplusplus && defined __GNUG__ && __GNUG__ < 6 \
270 && __cplusplus == 201103L && !defined __clang__)
271 /* g++ >= 4.7, < 6 with option -std=c++11 or -std=gnu++11 supports the
272 two-arguments static_assert but not the one-argument static_assert, and
273 it does not support _Static_assert.
274 We have to play preprocessor tricks to distinguish the two cases. */
275 # define _GL_SA1(a1) static_assert ((a1), "static assertion failed")
276 # define _GL_SA2 static_assert
277 # define _GL_SA3 static_assert
278 # define _GL_SA_PICK(x1,x2,x3,x4,...) x4
279 # define static_assert(...) _GL_SA_PICK(__VA_ARGS__,_GL_SA3,_GL_SA2,_GL_SA1) (__VA_ARGS__)
280 # elif defined __cplusplus && _MSC_VER >= 1900 && !defined __clang__
281 /* MSVC 14 in C++ mode supports the two-arguments static_assert but not
282 the one-argument static_assert, and it does not support _Static_assert.
283 We have to play preprocessor tricks to distinguish the two cases.
284 Since the MSVC preprocessor is not ISO C compliant (see above),
285 the solution is specific to MSVC. */
286 # define _GL_EXPAND(x) x
287 # define _GL_SA1(a1) static_assert ((a1), "static assertion failed")
288 # define _GL_SA2 static_assert
289 # define _GL_SA3 static_assert
290 # define _GL_SA_PICK(x1,x2,x3,x4,...) x4
291 # define static_assert(...) _GL_EXPAND(_GL_SA_PICK(__VA_ARGS__,_GL_SA3,_GL_SA2,_GL_SA1)) (__VA_ARGS__)
292 /* Avoid "fatal error C1189: #error: The C++ Standard Library forbids macroizing keywords." */
293 # define _ALLOW_KEYWORD_MACROS 1
294 # else
295 # define static_assert _Static_assert /* C11 requires this #define. */
296 # endif
297 # endif
298 #endif
299
300 /* @assert.h omit start@ */
301
302 #if defined __clang_major__ && __clang_major__ < 5
303 # define _GL_HAS_BUILTIN_TRAP 0
304 #elif 3 < __GNUC__ + (3 < __GNUC_MINOR__ + (4 <= __GNUC_PATCHLEVEL__))
305 # define _GL_HAS_BUILTIN_TRAP 1
306 #elif defined __has_builtin
307 # define _GL_HAS_BUILTIN_TRAP __has_builtin (__builtin_trap)
308 #else
309 # define _GL_HAS_BUILTIN_TRAP 0
310 #endif
311
312 #ifndef _GL_HAS_BUILTIN_UNREACHABLE
313 # if defined __clang_major__ && __clang_major__ < 5
314 # define _GL_HAS_BUILTIN_UNREACHABLE 0
315 # elif 4 < __GNUC__ + (5 <= __GNUC_MINOR__) && !defined __clang__
316 # define _GL_HAS_BUILTIN_UNREACHABLE 1
317 # elif defined __has_builtin
318 # define _GL_HAS_BUILTIN_UNREACHABLE __has_builtin (__builtin_unreachable)
319 # else
320 # define _GL_HAS_BUILTIN_UNREACHABLE 0
321 # endif
322 #endif
323
324 /* Each of these macros verifies that its argument R is nonzero. To
325 be portable, R should be an integer constant expression. Unlike
326 assert (R), there is no run-time overhead.
327
328 There are two macros, since no single macro can be used in all
329 contexts in C. verify_expr (R, E) is for scalar contexts, including
330 integer constant expression contexts. verify (R) is for declaration
331 contexts, e.g., the top level. */
332
333 /* Verify requirement R at compile-time. Return the value of the
334 expression E. */
335
336 #define verify_expr(R, E) \
337 (_GL_VERIFY_TRUE (R, "verify_expr (" #R ", " #E ")") ? (E) : (E))
338
339 /* Verify requirement R at compile-time, as a declaration without a
340 trailing ';'. verify (R) acts like static_assert (R) except that
341 it is portable to C11/C++14 and earlier, it can issue better
342 diagnostics, and its name is shorter and may be more convenient. */
343
344 #ifdef __PGI
345 /* PGI barfs if R is long. */
346 # define verify(R) _GL_VERIFY (R, "verify (...)", -)
347 #else
348 # define verify(R) _GL_VERIFY (R, "verify (" #R ")", -)
349 #endif
350
351 /* Assume that R always holds. Behavior is undefined if R is false,
352 fails to evaluate, or has side effects.
353
354 'assume (R)' is a directive from the programmer telling the
355 compiler that R is true so the compiler needn't generate code to
356 test R. This is why 'assume' is in verify.h: it's related to
357 static checking (in this case, static checking done by the
358 programmer), not dynamic checking.
359
360 'assume (R)' can affect compilation of all the code, not just code
361 that happens to be executed after the assume (R) is "executed".
362 For example, if the code mistakenly does 'assert (R); assume (R);'
363 the compiler is entitled to optimize away the 'assert (R)'.
364
365 Although assuming R can help a compiler generate better code or
366 diagnostics, performance can suffer if R uses hard-to-optimize
367 features such as function calls not inlined by the compiler.
368
369 Avoid Clang's __builtin_assume, as it breaks GNU Emacs master
370 as of 2020-08-23T21:09:[email protected]; see
371 <https://bugs.gnu.org/43152#71>. It's not known whether this breakage
372 is a Clang bug or an Emacs bug; play it safe for now. */
373
374 #if _GL_HAS_BUILTIN_UNREACHABLE
375 # define assume(R) ((R) ? (void) 0 : __builtin_unreachable ())
376 #elif 1200 <= _MSC_VER
377 # define assume(R) __assume (R)
378 #elif 202311 <= __STDC_VERSION__
379 # include <stddef.h>
380 # define assume(R) ((R) ? (void) 0 : unreachable ())
381 #elif (defined GCC_LINT || defined lint) && _GL_HAS_BUILTIN_TRAP
382 /* Doing it this way helps various packages when configured with
383 --enable-gcc-warnings, which compiles with -Dlint. It's nicer
384 if 'assume' silences warnings with GCC 3.4 through GCC 4.4.7 (2012). */
385 # define assume(R) ((R) ? (void) 0 : __builtin_trap ())
386 #else
387 /* Some older tools grok NOTREACHED, e.g., Oracle Studio 12.6 (2017). */
388 # define assume(R) ((R) ? (void) 0 : /*NOTREACHED*/ (void) 0)
389 #endif
390
391 /* @assert.h omit end@ */
392
393 #endif