Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions checkers/rust/avoid_unwrap.test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
fn test_antipattern() {
// These should be flagged
let some_option: Option<i32> = None;

// <expect-error>
let _ = some_option.unwrap();

let some_result: Result<i32, &str> = Err("Error occurred");

// <expect-error>
let _ = some_result.unwrap();

}

fn test_safe() {}
// These are safe and should not be flagged

// Handling Option safely
let _ = some_option.unwrap_or(42); // Providing a default value

// some_option.unwrap();

// Should not flag string literals containing "unwrap"
let message = "Do not use unwrap in production!";
}
28 changes: 28 additions & 0 deletions checkers/rust/avoid_unwrap.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
language: rust
name: avoid_unwrap
message: "Using unwrap() may cause panics if the Option is None or the Result is Err, consider handling errors with match or expect()"
category: antipattern
severity: warning

pattern: |
(
(call_expression
function: (field_expression
value: (_) @variable
field: (field_identifier) @method_name
(#eq? @method_name "unwrap")
)
arguments: (arguments)
) @avoid_unwrap
)

exclude:
- "tests/**"
- "vendor/**"
- "**/test_*.rs"
- "**/*_test.rs"

description: |
The use of .unwrap() in Rust can lead to unexpected panics if the value is None (for Option) or Err (for Result).
This can lead to crashes in production and make debugging harder. Consider handling errors explicitly with match
or use expect() if a panic is acceptable.