diff --git a/checkers/rust/avoid_expect.test.rs b/checkers/rust/avoid_expect.test.rs new file mode 100644 index 00000000..e2a396d3 --- /dev/null +++ b/checkers/rust/avoid_expect.test.rs @@ -0,0 +1,27 @@ +fn test_antipattern() { + let some_option: Option = None; + + // + let _ = some_option.expect("failed to get value"); + + let some_result: Result = Err("Error occurred"); + + // + let _ = some_result.expect("failed to process result"); +} + +fn test_safe() { + let some_option: Option = None; + + // Safe error handling with unwrap_or + let _ = some_option.unwrap_or(42); + + // Safe error handling with match + let _ = match some_option { + Some(val) => val, + None => 0, + }; + + // Should not flag string literals containing "expect" + let message = "We expect proper error handling in production code."; +} diff --git a/checkers/rust/avoid_expect.yml b/checkers/rust/avoid_expect.yml new file mode 100644 index 00000000..fe042f75 --- /dev/null +++ b/checkers/rust/avoid_expect.yml @@ -0,0 +1,29 @@ +language: rust +name: avoid_expect +message: "Using expect() can cause runtime panics if an Option is None or Result is Err. Consider handling errors explicitly with match, if let, or the ? operator" +category: antipattern +severity: warning + +pattern: | + ( + (call_expression + function: (field_expression + value: (_) @variable + field: (field_identifier) @method_name + (#eq? @method_name "expect") + ) + arguments: (arguments) + ) @avoid_expect + ) + +exclude: + - "tests/**" + - "vendor/**" + - "**/test_*.rs" + - "**/*_test.rs" + +description: | + Using .expect() in Rust can lead to unexpected panics if the value is None (for Option) or Err (for Result). + While expect() provides a custom error message, uncaught panics in production can crash the application. + Consider handling errors explicitly using match or if let, providing defaults with unwrap_or_else(), + or propagating errors using the ? operator.