Skip to contentSkip to conversation

checkpatch: check for trivial sizeofs

RFC PATCH In review Denis Efremov 2 participants 2 messages May 30, 2020 Checkpatch

lore
Share & tools
lore
#0 lore raw

RFC PATCH 1/1 checkpatch: check for trivial sizeofs

sizeof(char) and its variations in most cases doesn't make code more clear. It only makes code wordy.

---
 scripts/checkpatch.pl | 7 +++++++
 1 file changed, 7 insertions(+)
scripts/checkpatch.pl +7 -0
index eac40f0abd56..9dd338b125d2 100755
@@ -6045,6 +6045,13 @@ sub process {
 			}
 		}
 
+# check for trivial sizeof(char) == 1
+		if ($line =~ /\bsizeof\s*\(\s*((?:(?:un)?signed\s+)?char|(?:__)?u8|u?int8_t|[us]?byte(?:_t)?)\s*\)/) {
+			my $byte = $1;
+			CHK("SIZEOF_TRIVIAL",
+			     "redundant sizeof($byte) == 1 \n" . $herecurr);
+		}
+
 # check for struct spinlock declarations
 		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
 			WARN("USE_SPINLOCK_T",
Signature · 1 line
2.26.2
maintainer
#1 lore raw
Quoted 2 lines · Denis Efremov

sizeof(char) and its variations in most cases doesn't make code more clear. It only makes code wordy.

There are about 1000 of these uses in the kernel.

Not sure I like this though as many/most of the uses seem _less_ readable with a 1 in their place.

$ git grep -P 'sizeof\s*\(\s*(?:(?:unsigned\s+)?char\s*|(?:__)?u8|u?int8_t|[us]?byte(?:_t)?)\s*\)' | wc -l
970

Try the grep without the wc and see if you agree.

And if this is actually going to be used, I'd prefer using a separate $typeChar for the search.

Maybe something like:

---
 scripts/checkpatch.pl | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
scripts/checkpatch.pl +17 -0
index dd750241958b..de2e9242350b 100755
@@ -466,6 +466,13 @@ our $typeTypedefs = qr{(?x:
 	$typeKernelTypedefs\b
 )};
 
+our $typeChar = qr{(?x:
+	(?:(?:un)?signed\s+)?char |
+	(?:__)?u8 |
+	(?:u_|u)?int8_t |
+	[us]?byte(?:_t)?
+)};
+
 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
 
 our $logFunctions = qr{(?x:
@@ -6106,6 +6113,16 @@ sub process {
 			}
 		}
 
+# check for trivial sizeof(char) == 1
+		if ($line =~ /\bsizeof\s*\(\s*($typeChar)\s*\)/) {
+			my $byte = $1;
+			if (CHK("SIZEOF_CHAR",
+				"sizeof($byte) could be the constant 1 instead\n" . $herecurr) &&
+			    $fix) {
+				$fixed[$fixlinenr] =~ s/sizeof\s*\(\s*\Q$byte\E\s*\)/1/;
+			}
+		}
+
 # check for struct spinlock declarations
 		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
 			WARN("USE_SPINLOCK_T",