Re: pgsql: Provide some static-assertion functionality on all compilers. - Mailing list pgsql-committers

From Andres Freund
Subject Re: pgsql: Provide some static-assertion functionality on all compilers.
Date
Msg-id 201210161508.39052.andres@2ndquadrant.com
Whole thread Raw
In response to pgsql: Provide some static-assertion functionality on all compilers.  (Tom Lane <tgl@sss.pgh.pa.us>)
Responses Re: pgsql: Provide some static-assertion functionality on all compilers.
List pgsql-committers
On Monday, October 01, 2012 04:46:41 AM Tom Lane wrote:
> Provide some static-assertion functionality on all compilers.
>
> On reflection (especially after noticing how many buildfarm critters have
> __builtin_types_compatible_p but not _Static_assert), it seems like we
> ought to try a bit harder to make these macros do something everywhere.
> The initial cut at it would have been no help to code that is compiled only
> on platforms without _Static_assert, for instance; and in any case not all
> our contributors do their initial coding on the latest gcc version.
>
> Some googling about static assertions turns up quite a bit of prior art
> for making it work in compilers that lack _Static_assert.  The method
> that seems closest to our needs involves defining a struct with a bit-field
> that has negative width if the assertion condition fails.  There seems no
> reliable way to get the error message string to be output, but throwing a
> compile error with a confusing message is better than missing the problem
> altogether.

The current method used here doesn't allow the macro to be used in file scope
which imo would be rather useful. What about adding something like:

#ifdef !HAVE__STATIC_ASSERT
#define StaticAssertTop(condition, errmessage) \
    _Static_assert(condition, errmessage)
#else /* !HAVE__STATIC_ASSERT */
#define StaticAssertLine2(condition, line) \
    typedef struct { int static_assert_failure_in_line##line : \
        (condition) ? 1 : -1; } static_assert_failure_in_line##line
#define StaticAssertLine1(condition, line, errmsg) \
        StaticAssertLine2(condition, line)
#define StaticAssertTop(condition, errmessage) \
        StaticAssertLine1(condition, __LINE__, errmessage)
#endif /* HAVE__STATIC_ASSERT */

Annoyingly that would mean you cannot have two errors in the same line in two
files that are in one translation unit if your compiler doesn't allow repeated
typedefs. Not sure if thats a realistic problem?

Independently from this it might be worthwile to add the __LINE__ hackery to
the existing fallback for StaticAssertStmt?

Greetings,

Andres
--
 Andres Freund                       http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


pgsql-committers by date:

Previous
From: Bruce Momjian
Date:
Subject: pgsql: When outputting the session id in log_line_prefix (%c) or in CSV
Next
From: Tom Lane
Date:
Subject: Re: pgsql: Provide some static-assertion functionality on all compilers.