blob: 3657471f11dc2abb90624e721a27763c4d5f30e0 [file] [log] [blame]
Andrew Jeffery66c77232024-04-24 11:42:02 +09301/* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */
2#ifndef PLDM_COMPILER_H
3#define PLDM_COMPILER_H
4
Andrew Jeffery860a43d2024-08-23 01:21:58 +00005#ifndef __has_attribute
6#error The libpldm implementation requires __has_attribute
7#endif
8
9#include <assert.h>
10
11static struct {
Andrew Jefferycb569bc2024-09-01 09:38:09 +030012 static_assert(__has_attribute(always_inline),
13 "`always_inline` attribute is required");
Andrew Jeffery860a43d2024-08-23 01:21:58 +000014 static_assert(__has_attribute(unused),
15 "`unused` attribute is required");
16 int compliance;
17} pldm_required_attributes __attribute__((unused));
18
Andrew Jefferycb569bc2024-09-01 09:38:09 +030019#define LIBPLDM_CC_ALWAYS_INLINE __attribute__((always_inline)) static inline
20#define LIBPLDM_CC_UNUSED __attribute__((unused))
Andrew Jeffery860a43d2024-08-23 01:21:58 +000021
Andrew Jeffery66c77232024-04-24 11:42:02 +093022// NOLINTBEGIN(bugprone-macro-parentheses)
23/**
24 * Require that the given object is of the specified type.
25 *
26 * If the object is not of the required type then a diagnostic will be emitted.
27 *
28 * If you are reading this documentation due to hitting a compilation error
29 * passing through the macro, then you have a type error in your code that must
30 * be fixed. Despite the compiler output, the error is _not_ that some array
31 * is negatively sized, the array is negatively sized _because_ you have a type
32 * error.
33 *
34 * How this works:
35 *
36 * If the type of @p obj is not equivalent to the provided type @p type then
37 * we force the compiler to evaluate sizeof on a negatively-sized array. The
38 * C standard requires that the integer constant expression that specifies
39 * the array length must be greater than zero. Failure to meet this constraint
40 * generally terminates compilation of the translation unit as any other result
41 * cannot be handled in a sensible way. The array size is derived to an integer
42 * constant expression from a type eqivalence evaluated using _Generic()
43 * allowing us to stay within the language standard. The default generic
44 * association, representing a type mismatch, yields -1.
45 *
46 * pldm_require_obj_type() was introduced into the libpldm implementation to
47 * enable use of the pldm_msgbuf_extract*() APIs for objects that may or may not
48 * reside in a packed struct. See src/msgbuf.h for more details.
49 *
50 * @param obj The name of the object to evaluate
51 * @param type The required type of @p obj
52 *
53 * @return The expression either yields 1, or compilation is terminated
54 */
55#define pldm_require_obj_type(obj, type) \
56 ((void)(sizeof( \
57 struct { char buf[_Generic((obj), type: 1, default: -1)]; })))
58// NOLINTEND(bugprone-macro-parentheses)
59
60#endif