From 00cf07b5214d7b072470bb4584737f51242bdd55 Mon Sep 17 00:00:00 2001 From: kraktus Date: Sat, 29 Oct 2022 16:32:11 +0200 Subject: [PATCH] [`option_if_let_else`] do not lint if any arm has guard --- clippy_lints/src/option_if_let_else.rs | 13 ++++++++----- tests/ui/option_if_let_else.fixed | 9 +++++++++ tests/ui/option_if_let_else.rs | 9 +++++++++ 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/clippy_lints/src/option_if_let_else.rs b/clippy_lints/src/option_if_let_else.rs index 4eb42da1fed..472f52380bb 100644 --- a/clippy_lints/src/option_if_let_else.rs +++ b/clippy_lints/src/option_if_let_else.rs @@ -213,11 +213,14 @@ fn try_convert_match<'tcx>( cx: &LateContext<'tcx>, arms: &[Arm<'tcx>], ) -> Option<(&'tcx Pat<'tcx>, &'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> { - if arms.len() == 2 { - return if is_none_or_err_arm(cx, &arms[1]) { - Some((arms[0].pat, arms[0].body, arms[1].body)) - } else if is_none_or_err_arm(cx, &arms[0]) { - Some((arms[1].pat, arms[1].body, arms[0].body)) + if let [first_arm, second_arm] = arms + && first_arm.guard.is_none() + && second_arm.guard.is_none() + { + return if is_none_or_err_arm(cx, second_arm) { + Some((first_arm.pat, first_arm.body, second_arm.body)) + } else if is_none_or_err_arm(cx, first_arm) { + Some((second_arm.pat, second_arm.body, first_arm.body)) } else { None }; diff --git a/tests/ui/option_if_let_else.fixed b/tests/ui/option_if_let_else.fixed index f15ac551bb3..0456005dce4 100644 --- a/tests/ui/option_if_let_else.fixed +++ b/tests/ui/option_if_let_else.fixed @@ -189,3 +189,12 @@ fn main() { let _ = res.map_or(1, |a| a + 1); let _ = res.map_or(5, |a| a + 1); } + +#[allow(dead_code)] +fn issue9742() -> Option<&'static str> { + // should not lint because of guards + match Some("foo ") { + Some(name) if name.starts_with("foo") => Some(name.trim()), + _ => None, + } +} diff --git a/tests/ui/option_if_let_else.rs b/tests/ui/option_if_let_else.rs index 9eeaea12d3b..23b148752cb 100644 --- a/tests/ui/option_if_let_else.rs +++ b/tests/ui/option_if_let_else.rs @@ -230,3 +230,12 @@ fn main() { }; let _ = if let Ok(a) = res { a + 1 } else { 5 }; } + +#[allow(dead_code)] +fn issue9742() -> Option<&'static str> { + // should not lint because of guards + match Some("foo ") { + Some(name) if name.starts_with("foo") => Some(name.trim()), + _ => None, + } +}