1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
#![feature(lint_reasons)]
#![deny(clippy::panicking_unwrap, clippy::unnecessary_unwrap)]
#![allow(clippy::if_same_then_else, clippy::branches_sharing_code)]
macro_rules! m {
($a:expr) => {
if $a.is_some() {
$a.unwrap(); // unnecessary
}
};
}
macro_rules! checks_in_param {
($a:expr, $b:expr) => {
if $a {
$b;
}
};
}
macro_rules! checks_unwrap {
($a:expr, $b:expr) => {
if $a.is_some() {
$b;
}
};
}
macro_rules! checks_some {
($a:expr, $b:expr) => {
if $a {
$b.unwrap();
}
};
}
fn main() {
let x = Some(());
if x.is_some() {
x.unwrap(); // unnecessary
x.expect("an error message"); // unnecessary
} else {
x.unwrap(); // will panic
x.expect("an error message"); // will panic
}
if x.is_none() {
x.unwrap(); // will panic
} else {
x.unwrap(); // unnecessary
}
m!(x);
checks_in_param!(x.is_some(), x.unwrap()); // ok
checks_unwrap!(x, x.unwrap()); // ok
checks_some!(x.is_some(), x); // ok
let mut x: Result<(), ()> = Ok(());
if x.is_ok() {
x.unwrap(); // unnecessary
x.expect("an error message"); // unnecessary
x.unwrap_err(); // will panic
} else {
x.unwrap(); // will panic
x.expect("an error message"); // will panic
x.unwrap_err(); // unnecessary
}
if x.is_err() {
x.unwrap(); // will panic
x.unwrap_err(); // unnecessary
} else {
x.unwrap(); // unnecessary
x.unwrap_err(); // will panic
}
if x.is_ok() {
x = Err(());
// not unnecessary because of mutation of x
// it will always panic but the lint is not smart enough to see this (it only
// checks if conditions).
x.unwrap();
} else {
x = Ok(());
// not unnecessary because of mutation of x
// it will always panic but the lint is not smart enough to see this (it
// only checks if conditions).
x.unwrap_err();
}
assert!(x.is_ok(), "{:?}", x.unwrap_err()); // ok, it's a common test pattern
}
fn check_expect() {
let x = Some(());
if x.is_some() {
#[expect(clippy::unnecessary_unwrap)]
x.unwrap(); // unnecessary
#[expect(clippy::unnecessary_unwrap)]
x.expect("an error message"); // unnecessary
} else {
#[expect(clippy::panicking_unwrap)]
x.unwrap(); // will panic
#[expect(clippy::panicking_unwrap)]
x.expect("an error message"); // will panic
}
}
|