Skip to content

Commit 6e0e09c

Browse files
rsdypksunkara
authored andcommitted
Track init and unwrap of expr
1 parent 7ed7283 commit 6e0e09c

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

clippy_lints/src/methods/unnecessary_literal_unwrap.rs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ use rustc_lint::LateContext;
66
use super::UNNECESSARY_LITERAL_UNWRAP;
77

88
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, name: &str) {
9-
if let hir::ExprKind::Call(call, [arg]) = recv.kind {
9+
let init = clippy_utils::expr_or_init(cx, recv);
10+
11+
if let hir::ExprKind::Call(call, [arg]) = init.kind {
1012
let mess = if is_res_lang_ctor(cx, path_res(cx, call), hir::LangItem::OptionSome) {
1113
Some("Some")
1214
} else if is_res_lang_ctor(cx, path_res(cx, call), hir::LangItem::ResultOk) {
@@ -15,15 +17,19 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr
1517
None
1618
};
1719

18-
if let Some(constructor) = mess {
20+
let Some(constructor) = mess else {
21+
return;
22+
};
23+
24+
if init.span == recv.span {
1925
span_lint_and_then(
2026
cx,
2127
UNNECESSARY_LITERAL_UNWRAP,
2228
expr.span,
2329
&format!("used `{name}()` on `{constructor}` value"),
2430
|diag| {
2531
let suggestions = vec![
26-
(call.span.with_hi(arg.span.lo()), String::new()),
32+
(recv.span.with_hi(arg.span.lo()), String::new()),
2733
(expr.span.with_lo(arg.span.hi()), String::new()),
2834
];
2935

@@ -34,6 +40,16 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr
3440
);
3541
},
3642
);
43+
} else {
44+
span_lint_and_then(
45+
cx,
46+
UNNECESSARY_LITERAL_UNWRAP,
47+
expr.span,
48+
&format!("used `{name}()` on `{constructor}` value"),
49+
|diag| {
50+
diag.span_help(init.span, format!("remove the `{constructor}` and `{name}()`"));
51+
},
52+
);
3753
}
3854
}
3955
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#![warn(clippy::unnecessary_literal_unwrap)]
2+
3+
fn main() {
4+
let val = Some(1);
5+
let _val2 = val.unwrap();
6+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error: used `unwrap()` on `Some` value
2+
--> $DIR/unnecessary_literal_unwrap_unfixable.rs:5:17
3+
|
4+
LL | let _val2 = val.unwrap();
5+
| ^^^^^^^^^^^^
6+
|
7+
help: remove the `Some` and `unwrap()`
8+
--> $DIR/unnecessary_literal_unwrap_unfixable.rs:4:15
9+
|
10+
LL | let val = Some(1);
11+
| ^^^^^^^
12+
= note: `-D clippy::unnecessary-literal-unwrap` implied by `-D warnings`
13+
14+
error: aborting due to previous error
15+

0 commit comments

Comments
 (0)