blob: 31eeff9b22868d7e4fd328f379124ffcf2fc4d6d [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
5// NOLINTBEGIN(bugprone-macro-parentheses)
6/**
7 * Require that the given object is of the specified type.
8 *
9 * If the object is not of the required type then a diagnostic will be emitted.
10 *
11 * If you are reading this documentation due to hitting a compilation error
12 * passing through the macro, then you have a type error in your code that must
13 * be fixed. Despite the compiler output, the error is _not_ that some array
14 * is negatively sized, the array is negatively sized _because_ you have a type
15 * error.
16 *
17 * How this works:
18 *
19 * If the type of @p obj is not equivalent to the provided type @p type then
20 * we force the compiler to evaluate sizeof on a negatively-sized array. The
21 * C standard requires that the integer constant expression that specifies
22 * the array length must be greater than zero. Failure to meet this constraint
23 * generally terminates compilation of the translation unit as any other result
24 * cannot be handled in a sensible way. The array size is derived to an integer
25 * constant expression from a type eqivalence evaluated using _Generic()
26 * allowing us to stay within the language standard. The default generic
27 * association, representing a type mismatch, yields -1.
28 *
29 * pldm_require_obj_type() was introduced into the libpldm implementation to
30 * enable use of the pldm_msgbuf_extract*() APIs for objects that may or may not
31 * reside in a packed struct. See src/msgbuf.h for more details.
32 *
33 * @param obj The name of the object to evaluate
34 * @param type The required type of @p obj
35 *
36 * @return The expression either yields 1, or compilation is terminated
37 */
38#define pldm_require_obj_type(obj, type) \
39 ((void)(sizeof( \
40 struct { char buf[_Generic((obj), type: 1, default: -1)]; })))
41// NOLINTEND(bugprone-macro-parentheses)
42
43#endif