Skip to content

Commit a80778c

Browse files
committed
Add handling for None.unwrap_or(_else)
1 parent 639c9a2 commit a80778c

File tree

4 files changed

+167
-35
lines changed

4 files changed

+167
-35
lines changed

clippy_lints/src/methods/unnecessary_literal_unwrap.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,24 @@ pub(super) fn check(
7272
};
7373
Some(vec![(expr.span, format!("{default_ty_string}::default()"))])
7474
},
75+
("None", "unwrap_or", _) => Some(vec![
76+
(expr.span.with_hi(args[0].span.lo()), String::new()),
77+
(expr.span.with_lo(args[0].span.hi()), String::new()),
78+
]),
79+
("None", "unwrap_or_else", _) => match args[0].kind {
80+
hir::ExprKind::Closure(hir::Closure {
81+
fn_decl:
82+
hir::FnDecl {
83+
output: hir::FnRetTy::DefaultReturn(span) | hir::FnRetTy::Return(hir::Ty { span, .. }),
84+
..
85+
},
86+
..
87+
}) => Some(vec![
88+
(expr.span.with_hi(span.hi()), String::new()),
89+
(expr.span.with_lo(args[0].span.hi()), String::new()),
90+
]),
91+
_ => None,
92+
},
7593
_ if call_args.is_empty() => None,
7694
(_, _, Some(_)) => None,
7795
("Ok", "unwrap_err", None) | ("Err", "unwrap", None) => Some(vec![

tests/ui/unnecessary_literal_unwrap.fixed

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,23 @@ fn unwrap_option_some() {
1616
1;
1717
}
1818

19+
#[rustfmt::skip] // force rustfmt not to remove braces in `|| { 234 }`
1920
fn unwrap_option_none() {
2021
let _val = panic!();
2122
let _val = panic!("this always happens");
2223
let _val: String = String::default();
24+
let _val: u16 = 234;
25+
let _val: u16 = 234;
26+
let _val: u16 = { 234 };
27+
let _val: u16 = { 234 };
2328

2429
panic!();
2530
panic!("this always happens");
2631
String::default();
32+
234;
33+
234;
34+
{ 234 };
35+
{ 234 };
2736
}
2837

2938
fn unwrap_result_ok() {

tests/ui/unnecessary_literal_unwrap.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,23 @@ fn unwrap_option_some() {
1616
Some(1).expect("this never happens");
1717
}
1818

19+
#[rustfmt::skip] // force rustfmt not to remove braces in `|| { 234 }`
1920
fn unwrap_option_none() {
2021
let _val = None::<()>.unwrap();
2122
let _val = None::<()>.expect("this always happens");
2223
let _val: String = None.unwrap_or_default();
24+
let _val: u16 = None.unwrap_or(234);
25+
let _val: u16 = None.unwrap_or_else(|| 234);
26+
let _val: u16 = None.unwrap_or_else(|| { 234 });
27+
let _val: u16 = None.unwrap_or_else(|| -> u16 { 234 });
2328

2429
None::<()>.unwrap();
2530
None::<()>.expect("this always happens");
2631
None::<String>.unwrap_or_default();
32+
None::<u16>.unwrap_or(234);
33+
None::<u16>.unwrap_or_else(|| 234);
34+
None::<u16>.unwrap_or_else(|| { 234 });
35+
None::<u16>.unwrap_or_else(|| -> u16 { 234 });
2736
}
2837

2938
fn unwrap_result_ok() {

0 commit comments

Comments
 (0)