]> git.ipfire.org Git - thirdparty/systemd.git/commit
json: rework JSON_BUILD_XYZ() macros to use compound literals instead of compound...
authorLennart Poettering <lennart@poettering.net>
Mon, 23 Aug 2021 08:48:56 +0000 (10:48 +0200)
committerLuca Boccassi <luca.boccassi@gmail.com>
Mon, 23 Aug 2021 15:07:28 +0000 (16:07 +0100)
commit3e4ca3940d22f0d5f03a88fe44a6e445fca87948
treede4d79c9743485de9df4871af78149bf274e6ffd
parentf95d1ef5fafd96c65a9da57fa2bcdd503fce694c
json: rework JSON_BUILD_XYZ() macros to use compound literals instead of compound statements

Compound statements is this stuff: ({ … })

Compound literals is this stuff: (type) { … }

We use compound statements a lot in macro definitions: they have one
drawback though: they define a code block of their own, hence if macro
invocations are nested within them that use compound literals their
lifetime is limited to the code block, which might be unexpected.

Thankfully, we can rework things from compound statements to compund
literals in the case of json.h: they don't open a new codeblack, and
hence do not suffer by the problem explained above.

The interesting thing about compound statements is that they also work
for simple types, not just for structs/unions/arrays. We can use this
here for a typechecked implicit conversion: we want to superficially
typecheck arguments to the json_build() varargs function, and we do that
by assigning the specified arguments to our compound literals, which
does the minimal amount of typechecks and ensures that types are
propagated on correctly.

We need one special tweak for this: sd_id128_t is not a simple type but
a union. Using compound literals for initialzing that would mean
specifiying the components of the union, not a complete sd_id128_t. Our
hack around that: instead of passing the object directly via the stack
we now take a pointer (and thus a simple type) instead.

Nice side-effect of all this: compound literals is C99, while compound
statements are a GCC extension, hence we move closer to standard C.

Fixes: #20501
Replaces: #20512
src/shared/json.c
src/shared/json.h