verify: use _Static_assert if available
[gnulib.git] / lib / verify.h
1 /* Compile-time assert-like macros.
2
3    Copyright (C) 2005-2006, 2009-2011 Free Software Foundation, Inc.
4
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.
9
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.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert, Bruno Haible, and Jim Meyering.  */
19
20 #ifndef VERIFY_H
21 # define VERIFY_H 1
22
23 /* Define HAVE__STATIC_ASSERT to 1 if _Static_assert works as per the
24    C1X draft N1548 section 6.7.10.  This is supported by GCC 4.6.0 and
25    later, and its use here generates easier-to-read diagnostics when
26    verify (R) fails.
27
28    For now, use this only with GCC.  Eventually whether _Static_assert
29    works should be determined by 'configure'.  */
30 # if 4 < __GNUC__ || (__GNUC__ == 4 && 6 <= __GNUC_MINOR__)
31 #  define HAVE__STATIC_ASSERT 1
32 # endif
33
34 /* Each of these macros verifies that its argument R is nonzero.  To
35    be portable, R should be an integer constant expression.  Unlike
36    assert (R), there is no run-time overhead.
37
38    There are two macros, since no single macro can be used in all
39    contexts in C.  verify_true (R) is for scalar contexts, including
40    integer constant expression contexts.  verify (R) is for declaration
41    contexts, e.g., the top level.
42
43    Symbols ending in "__" are private to this header.
44
45    If _Static_assert works, verify (R) uses it directly.  Similarly,
46    verify_true (R) works by packaging a _Static_assert inside a struct
47    that is an operand of sizeof.
48
49    The code below uses several ideas for C++ compilers, and for C
50    compilers that do not support _Static_assert:
51
52    * The first step is ((R) ? 1 : -1).  Given an expression R, of
53      integral or boolean or floating-point type, this yields an
54      expression of integral type, whose value is later verified to be
55      constant and nonnegative.
56
57    * Next this expression W is wrapped in a type
58      struct verify_type__ { unsigned int verify_error_if_negative_size__: W; }.
59      If W is negative, this yields a compile-time error.  No compiler can
60      deal with a bit-field of negative size.
61
62      One might think that an array size check would have the same
63      effect, that is, that the type struct { unsigned int dummy[W]; }
64      would work as well.  However, inside a function, some compilers
65      (such as C++ compilers and GNU C) allow local parameters and
66      variables inside array size expressions.  With these compilers,
67      an array size check would not properly diagnose this misuse of
68      the verify macro:
69
70        void function (int n) { verify (n < 0); }
71
72    * For the verify macro, the struct verify_type__ will need to
73      somehow be embedded into a declaration.  To be portable, this
74      declaration must declare an object, a constant, a function, or a
75      typedef name.  If the declared entity uses the type directly,
76      such as in
77
78        struct dummy {...};
79        typedef struct {...} dummy;
80        extern struct {...} *dummy;
81        extern void dummy (struct {...} *);
82        extern struct {...} *dummy (void);
83
84      two uses of the verify macro would yield colliding declarations
85      if the entity names are not disambiguated.  A workaround is to
86      attach the current line number to the entity name:
87
88        #define _GL_CONCAT0(x, y) x##y
89        #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
90        extern struct {...} * _GL_CONCAT (dummy, __LINE__);
91
92      But this has the problem that two invocations of verify from
93      within the same macro would collide, since the __LINE__ value
94      would be the same for both invocations.  (The GCC __COUNTER__
95      macro solves this problem, but is not portable.)
96
97      A solution is to use the sizeof operator.  It yields a number,
98      getting rid of the identity of the type.  Declarations like
99
100        extern int dummy [sizeof (struct {...})];
101        extern void dummy (int [sizeof (struct {...})]);
102        extern int (*dummy (void)) [sizeof (struct {...})];
103
104      can be repeated.
105
106    * Should the implementation use a named struct or an unnamed struct?
107      Which of the following alternatives can be used?
108
109        extern int dummy [sizeof (struct {...})];
110        extern int dummy [sizeof (struct verify_type__ {...})];
111        extern void dummy (int [sizeof (struct {...})]);
112        extern void dummy (int [sizeof (struct verify_type__ {...})]);
113        extern int (*dummy (void)) [sizeof (struct {...})];
114        extern int (*dummy (void)) [sizeof (struct verify_type__ {...})];
115
116      In the second and sixth case, the struct type is exported to the
117      outer scope; two such declarations therefore collide.  GCC warns
118      about the first, third, and fourth cases.  So the only remaining
119      possibility is the fifth case:
120
121        extern int (*dummy (void)) [sizeof (struct {...})];
122
123    * GCC warns about duplicate declarations of the dummy function if
124      -Wredundant_decls is used.  GCC 4.3 and later have a builtin
125      __COUNTER__ macro that can let us generate unique identifiers for
126      each dummy function, to suppress this warning.
127
128    * This implementation exploits the fact that older versions of GCC,
129      which do not support _Static_assert, also do not warn about the
130      last declaration mentioned above.
131
132    * In C++, any struct definition inside sizeof is invalid.
133      Use a template type to work around the problem.  */
134
135 /* Concatenate two preprocessor tokens.  */
136 # define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
137 # define _GL_CONCAT0(x, y) x##y
138
139 /* _GL_COUNTER is an integer, preferably one that changes each time we
140    use it.  Use __COUNTER__ if it works, falling back on __LINE__
141    otherwise.  __LINE__ isn't perfect, but it's better than a
142    constant.  */
143 # if defined __COUNTER__ && __COUNTER__ != __COUNTER__
144 #  define _GL_COUNTER __COUNTER__
145 # else
146 #  define _GL_COUNTER __LINE__
147 # endif
148
149 /* Generate a symbol with the given prefix, making it unique if
150    possible.  */
151 # define _GL_GENSYM(prefix) _GL_CONCAT (prefix, _GL_COUNTER)
152
153 /* Verify requirement R at compile-time, as an integer constant expression.
154    Return 1.  */
155
156 # ifdef __cplusplus
157 template <int w>
158   struct verify_type__ { unsigned int verify_error_if_negative_size__: w; };
159 #  define verify_true(R) \
160      (!!sizeof (verify_type__<(R) ? 1 : -1>))
161 # elif HAVE__STATIC_ASSERT
162 #  define verify_true(R) \
163      (!!sizeof \
164       (struct { \
165         _Static_assert (R, "verify_true (" #R ")"); \
166         int verify_dummy__; \
167        }))
168 # else
169 #  define verify_true(R) \
170      (!!sizeof \
171       (struct { unsigned int verify_error_if_negative_size__: (R) ? 1 : -1; }))
172 # endif
173
174 /* Verify requirement R at compile-time, as a declaration without a
175    trailing ';'.  */
176
177 # if HAVE__STATIC_ASSERT
178 #  define verify(R) _Static_assert (R, "verify (" #R ")")
179 # else
180 #  define verify(R) \
181     extern int (* _GL_GENSYM (verify_function) (void)) [verify_true (R)]
182 # endif
183
184 #endif