File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed
Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ fn test_antipattern ( ) {
2+ // These should be flagged
3+ let some_option: Option < i32 > = None ;
4+
5+ // <expect-error>
6+ let _ = some_option. unwrap ( ) ;
7+
8+ let some_result: Result < i32 , & str > = Err ( "Error occurred" ) ;
9+
10+ // <expect-error>
11+ let _ = some_result. unwrap ( ) ;
12+
13+ // <expect-error>
14+ let _ = some_result. unwrap ( ) ; // Double check on another instance
15+ }
16+
17+ fn test_safe ( ) { }
18+ // These are safe and should not be flagged
19+
20+ // Handling Option safely
21+ let _ = some_option. unwrap_or ( 42 ) ; // Providing a default value
22+
23+ // some_option.unwrap();
24+
25+ // Should not flag string literals containing "unwrap"
26+ let message = "Do not use unwrap in production!" ;
27+ }
Original file line number Diff line number Diff line change 1+ language : rust
2+ name : avoid_unwrap
3+ message : " Using unwrap() may cause panics if the Option is None or the Result is Err, consider handling errors with match or expect()"
4+ category : antipattern
5+ severity : warning
6+
7+ pattern : |
8+ (
9+ (call_expression
10+ function: (field_expression
11+ value: (_) @variable
12+ field: (field_identifier) @method_name (#eq? @method_name "unwrap")
13+ )
14+ arguments: (arguments)
15+ ) @avoid_unwrap
16+ )
17+
18+ exclude :
19+ - " tests/**"
20+ - " vendor/**"
21+ - " **/test_*.rs"
22+ - " **/*_test.rs"
23+
24+ description : |
25+ The use of .unwrap() in Rust can lead to unexpected panics if the value is None (for Option) or Err (for Result).
26+ This can lead to crashes in production and make debugging harder. Consider handling errors explicitly with match
27+ or use expect() if a panic is acceptable.
You can’t perform that action at this time.
0 commit comments