Skip to content

Commit

Permalink
Add handling for None.unwrap_or(_else)
Browse files Browse the repository at this point in the history
  • Loading branch information
syvb committed Jul 7, 2023
1 parent 639c9a2 commit a80778c
Show file tree
Hide file tree
Showing 4 changed files with 167 additions and 35 deletions.
18 changes: 18 additions & 0 deletions clippy_lints/src/methods/unnecessary_literal_unwrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,24 @@ pub(super) fn check(
};
Some(vec![(expr.span, format!("{default_ty_string}::default()"))])
},
("None", "unwrap_or", _) => Some(vec![
(expr.span.with_hi(args[0].span.lo()), String::new()),
(expr.span.with_lo(args[0].span.hi()), String::new()),
]),
("None", "unwrap_or_else", _) => match args[0].kind {
hir::ExprKind::Closure(hir::Closure {
fn_decl:
hir::FnDecl {
output: hir::FnRetTy::DefaultReturn(span) | hir::FnRetTy::Return(hir::Ty { span, .. }),
..
},
..
}) => Some(vec![
(expr.span.with_hi(span.hi()), String::new()),
(expr.span.with_lo(args[0].span.hi()), String::new()),
]),
_ => None,
},
_ if call_args.is_empty() => None,
(_, _, Some(_)) => None,
("Ok", "unwrap_err", None) | ("Err", "unwrap", None) => Some(vec![
Expand Down
9 changes: 9 additions & 0 deletions tests/ui/unnecessary_literal_unwrap.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,23 @@ fn unwrap_option_some() {
1;
}

#[rustfmt::skip] // force rustfmt not to remove braces in `|| { 234 }`
fn unwrap_option_none() {
let _val = panic!();
let _val = panic!("this always happens");
let _val: String = String::default();
let _val: u16 = 234;
let _val: u16 = 234;
let _val: u16 = { 234 };
let _val: u16 = { 234 };

panic!();
panic!("this always happens");
String::default();
234;
234;
{ 234 };
{ 234 };
}

fn unwrap_result_ok() {
Expand Down
9 changes: 9 additions & 0 deletions tests/ui/unnecessary_literal_unwrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,23 @@ fn unwrap_option_some() {
Some(1).expect("this never happens");
}

#[rustfmt::skip] // force rustfmt not to remove braces in `|| { 234 }`
fn unwrap_option_none() {
let _val = None::<()>.unwrap();
let _val = None::<()>.expect("this always happens");
let _val: String = None.unwrap_or_default();
let _val: u16 = None.unwrap_or(234);
let _val: u16 = None.unwrap_or_else(|| 234);
let _val: u16 = None.unwrap_or_else(|| { 234 });
let _val: u16 = None.unwrap_or_else(|| -> u16 { 234 });

None::<()>.unwrap();
None::<()>.expect("this always happens");
None::<String>.unwrap_or_default();
None::<u16>.unwrap_or(234);
None::<u16>.unwrap_or_else(|| 234);
None::<u16>.unwrap_or_else(|| { 234 });
None::<u16>.unwrap_or_else(|| -> u16 { 234 });
}

fn unwrap_result_ok() {
Expand Down
Loading

0 comments on commit a80778c

Please sign in to comment.