[PATCH v8 2/2] scripts: checkpatch: add RUST_UNWRAP lint

Jason Hall posted 2 patches 1 day, 5 hours ago
There is a newer version of this series
[PATCH v8 2/2] scripts: checkpatch: add RUST_UNWRAP lint
Posted by Jason Hall 1 day, 5 hours ago
Warn against the use of .unwrap() and .expect() unless accompanied by
a '// PANIC:' comment. This enforces safety standards in the Rust-
for-Linux project until upstream Clippy lints are integrated.

Suggested-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://github.com/Rust-for-linux/linux/issues/1191
Signed-off-by: Jason Hall <jason.kei.hall@gmail.com>
---
 scripts/rust_checkpatch.pl | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)

diff --git a/scripts/rust_checkpatch.pl b/scripts/rust_checkpatch.pl
index 56c1bc29d3f2..9a4e256a4ec4 100644
--- a/scripts/rust_checkpatch.pl
+++ b/scripts/rust_checkpatch.pl
@@ -9,7 +9,21 @@ use warnings;
 sub process_rust {
     my ($line, $rawline, $herecurr) = @_;
 
-    # Reserve for future Rust-specific lints
+    # Check for Rust unwrap/expect usage.
+    # We skip lines that are already comments, assert macros (common in tests),
+    # or have a '// PANIC:' justification.
+    if ($line =~ /^\+/) {
+        if ($line =~ /(?:\.|::)(?:unwrap|expect)\s*\(/ &&
+            $rawline !~ /\/\/\s*PANIC:/ &&
+            $line !~ /^\+\s*\/\// &&
+            $line !~ /^\+\s*assert/) {
+            return ("RUST_UNWRAP",
+                    "unwrap() and expect() should generally be avoided in Rust kernel code.\n" .
+                    "If the use is intended, please justify it with a '// PANIC:' comment.\n" .
+                    "See: https://rust.docs.kernel.org/kernel/error/type.Result.html#error-codes-in-c-and-rust\n" .
+                    $herecurr);
+        }
+    }
     return ();
 }
 
-- 
2.43.0