Skip to content

Commit ce1f87a

Browse files
committed
MP_STATIC_ASSERT: Use _Static_assert.
.. or c++ static_assert where possible. For the same reasons that C++ has trouble with "nonconstexpr" static assertions, _Static_assert rejects such expression as well. So, fall back to the old sizeof-array based implementation in that case. When _Static_assert can be used, the diagnostic quality is improved: ``` ../py/objint.c: In function ‘mp_obj_int_make_new’: ../py/misc.h:67:32: error: static assertion failed: "37 == 42" ../py/objint.c:45:5: note: in expansion of macro ‘MP_STATIC_ASSERT’ ``` As compared to a diagnostic about ``` ../py/misc.h:71:50: error: size of unnamed array is negative ``` Testing on godbolt indicated that this actually works back to gcc 4.5, but it's easier to use GNUC >= 5 as the test; Hypothetical users of 4.5, 4.6, or 4.7 will just get slightly worse diagnostics. Related: micropython#18116 Signed-off-by: Jeff Epler <jepler@unpythonic.net>
1 parent adf6319 commit ce1f87a

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

py/misc.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,14 @@ typedef unsigned int uint;
6363
#define MP_STRINGIFY(x) MP_STRINGIFY_HELPER(x)
6464

6565
// Static assertion macro
66+
#if __cplusplus
67+
#define MP_STATIC_ASSERT(cond) static_assert((cond), #cond)
68+
#elif __GNUC__ >= 5 || __STDC_VERSION__ >= 201112L
69+
#define MP_STATIC_ASSERT(cond) _Static_assert((cond), #cond)
70+
#else
6671
#define MP_STATIC_ASSERT(cond) ((void)sizeof(char[1 - 2 * !(cond)]))
72+
#endif
73+
6774
// In C++ things like comparing extern const pointers are not constant-expressions so cannot be used
6875
// in MP_STATIC_ASSERT. Note that not all possible compiler versions will reject this. Some gcc versions
6976
// do, others only with -Werror=vla, msvc always does.
@@ -72,7 +79,7 @@ typedef unsigned int uint;
7279
#if defined(_MSC_VER) || defined(__cplusplus)
7380
#define MP_STATIC_ASSERT_NONCONSTEXPR(cond) ((void)1)
7481
#else
75-
#define MP_STATIC_ASSERT_NONCONSTEXPR(cond) MP_STATIC_ASSERT(cond)
82+
#define MP_STATIC_ASSERT_NONCONSTEXPR(cond) ((void)sizeof(char[1 - 2 * !(cond)]))
7683
#endif
7784

7885
// Round-up integer division

0 commit comments

Comments
 (0)