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

From: Andres Freund <andres(at)2ndquadrant(dot)com>
To: pgsql-committers(at)postgresql(dot)org
Cc: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Subject: Re: pgsql: Provide some static-assertion functionality on all compilers.
Date: 2012-10-16 13:08:38
Message-ID: 201210161508.39052.andres@2ndquadrant.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Responses

Browse pgsql-committers by date

  From Date Subject
Next Message Bruce Momjian 2012-10-16 16:38:10 pgsql: When outputting the session id in log_line_prefix (%c) or in CSV
Previous Message Tom Lane 2012-10-15 16:19:25 pgsql: alter_generic regression test cannot run concurrently with privi