From 4580c8a9b7f61d2e9968ae1aaab08cfa2a5eb221 Mon Sep 17 00:00:00 2001 From: Max Baumann Date: Sun, 20 Mar 2022 23:54:04 +0100 Subject: [PATCH] refactor: use is_lang_ctor() --- clippy_lints/src/methods/or_then_unwrap.rs | 31 +++++++++------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/clippy_lints/src/methods/or_then_unwrap.rs b/clippy_lints/src/methods/or_then_unwrap.rs index a0f6d80c19b..28b1bfe8fb5 100644 --- a/clippy_lints/src/methods/or_then_unwrap.rs +++ b/clippy_lints/src/methods/or_then_unwrap.rs @@ -1,9 +1,8 @@ -use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_type_diagnostic_item; -use if_chain::if_chain; +use clippy_utils::{diagnostics::span_lint_and_sugg, is_lang_ctor}; use rustc_errors::Applicability; -use rustc_hir::{Expr, ExprKind, QPath}; +use rustc_hir::{lang_items::LangItem, Expr, ExprKind}; use rustc_lint::LateContext; use rustc_span::{sym, Span}; @@ -22,14 +21,14 @@ pub(super) fn check<'tcx>( if is_type_diagnostic_item(cx, ty, sym::Option) { title = "found `.or(Some(…)).unwrap()`"; - if let Some(content) = get_content_if_is(or_arg, "Some") { + if let Some(content) = get_content_if_ctor_matches(cx, or_arg, LangItem::OptionSome) { or_arg_content = content; } else { return; } } else if is_type_diagnostic_item(cx, ty, sym::Result) { title = "found `.or(Ok(…)).unwrap()`"; - if let Some(content) = get_content_if_is(or_arg, "Ok") { + if let Some(content) = get_content_if_ctor_matches(cx, or_arg, LangItem::ResultOk) { or_arg_content = content; } else { return; @@ -64,19 +63,13 @@ pub(super) fn check<'tcx>( ); } -/// is expr a Call to name? if so, return what it's wrapping -/// name might be "Some", "Ok", "Err", etc. -fn get_content_if_is<'a>(expr: &Expr<'a>, name: &str) -> Option { - if_chain! { - if let ExprKind::Call(some_expr, [arg]) = expr.kind; - if let ExprKind::Path(QPath::Resolved(_, path)) = &some_expr.kind; - if let Some(path_segment) = path.segments.first(); - if path_segment.ident.name.as_str() == name; - then { - Some(arg.span) - } - else { - None - } +fn get_content_if_ctor_matches(cx: &LateContext<'_>, expr: &Expr<'_>, item: LangItem) -> Option { + if let ExprKind::Call(some_expr, [arg]) = expr.kind + && let ExprKind::Path(qpath) = &some_expr.kind + && is_lang_ctor(cx, qpath, item) + { + Some(arg.span) + } else { + None } }