Re: [PATCH] checkpatch: prefer = {} initializations to = {0}

From: Joe Perches
Date: Thu Aug 05 2021 - 08:27:34 EST


On Thu, 2021-08-05 at 13:43 +0300, Dan Carpenter wrote:
> The "= {};" style empty struct initializer is preferred over = {0}.
> It avoids the situation where the first struct member is a pointer and
> that generates a Sparse warning about assigning using zero instead of
> NULL. Also it's just nicer to look at.
>
> Some people complain that {} is less portable but the kernel has
> different portability requirements from userspace so this is not a
> issue that we care about.
[]
> diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl
[]
> @@ -4029,6 +4029,12 @@ sub process {
>   "Using $1 is unnecessary\n" . $herecurr);
>   }
>
> +# prefer = {}; to = {0};
> + if ($line =~ /= \{ *0 *\}/) {

Have you done a grep and looked at this pattern's actual use in the kernel?
I rather doubt it.

> + WARN("ZERO_INITIALIZER",
> + "= {} is preferred over = {0}\n" . $herecurr);
> + }
> +

To be much more specific to the actual desired match as stated in
the possible commit log, this should probably be something like:

if (defined($stat) &&
$stat =~ /^\+\s+$Declare\s*$Ident\s*=\s*\{\s*0\s*\}\s*;/) {

and maybe it should be a --strict CHK and not WARN.

And I generally avoid using "we" in a commit message.

Maybe something like:
---
scripts/checkpatch.pl | 15 +++++++++++++++
1 file changed, 15 insertions(+)

diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl
index 461d4221e4a4a..e3d4aa5f86c46 100755
--- a/scripts/checkpatch.pl
+++ b/scripts/checkpatch.pl
@@ -6911,6 +6911,21 @@ sub process {
"externs should be avoided in .c files\n" . $herecurr);
}

+# check for non-global single initializers with '= {0};', prefer '= {};'
+# there is already a GLOBAL_INITIALIZERS test so avoid those too with /^\+\s+/
+ if (defined($stat) &&
+ $stat =~ /^\+\s+$Declare\s*$Ident\s*(=\s*\{\s*0\s*\}\s*);/) {
+ my $match = $1;
+ my $cnt = statement_rawlines($stat);
+ my $herectx = get_stat_here($linenr, $cnt, $here);
+ if (WARN("ZERO_INITIALIZER",
+ "Prefer '= {}' over '$match'\n" . $herectx) &&
+ $fix &&
+ $cnt == 1) { # can only --fix single line statements
+ $fixed[$fixlinenr] =~ s/\s*=\s*\{\s*0\s*\}\s*;/ = {};/;
+ }
+ }
+
# check for function declarations that have arguments without identifier names
if (defined $stat &&
$stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&