Reduce unnecessary work in cmp_owned

This commit is contained in:
Jason Newcomb 2022-05-09 11:41:25 -04:00
parent c3f3c588b0
commit 0f1544f15e

View file

@ -20,8 +20,8 @@ use rustc_span::symbol::sym;
use clippy_utils::consts::{constant, Constant}; use clippy_utils::consts::{constant, Constant};
use clippy_utils::sugg::Sugg; use clippy_utils::sugg::Sugg;
use clippy_utils::{ use clippy_utils::{
get_item_name, get_parent_expr, in_constant, is_diag_trait_item, is_integer_const, iter_input_pats, get_item_name, get_parent_expr, in_constant, is_integer_const, iter_input_pats, last_path_segment,
last_path_segment, match_any_def_paths, path_def_id, paths, unsext, SpanlessEq, match_any_def_paths, path_def_id, paths, unsext, SpanlessEq,
}; };
declare_clippy_lint! { declare_clippy_lint! {
@ -569,33 +569,30 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left:
}) })
} }
let (arg_ty, snip) = match expr.kind { let typeck = cx.typeck_results();
ExprKind::MethodCall(.., args, _) if args.len() == 1 => { let (arg, arg_span) = match expr.kind {
if_chain!( ExprKind::MethodCall(.., [arg], _)
if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if typeck
if is_diag_trait_item(cx, expr_def_id, sym::ToString) .type_dependent_def_id(expr.hir_id)
|| is_diag_trait_item(cx, expr_def_id, sym::ToOwned); .and_then(|id| cx.tcx.trait_of_item(id))
then { .map_or(false, |id| {
(cx.typeck_results().expr_ty(&args[0]), snippet(cx, args[0].span, "..")) matches!(cx.tcx.get_diagnostic_name(id), Some(sym::ToString | sym::ToOwned))
} else { }) =>
return; {
} (arg, arg.span)
)
}, },
ExprKind::Call(path, [arg]) => { ExprKind::Call(path, [arg])
if path_def_id(cx, path) if path_def_id(cx, path)
.and_then(|id| match_any_def_paths(cx, id, &[&paths::FROM_STR_METHOD, &paths::FROM_FROM])) .and_then(|id| match_any_def_paths(cx, id, &[&paths::FROM_STR_METHOD, &paths::FROM_FROM]))
.is_some() .is_some() =>
{ {
(cx.typeck_results().expr_ty(arg), snippet(cx, arg.span, "..")) (arg, arg.span)
} else {
return;
}
}, },
_ => return, _ => return,
}; };
let other_ty = cx.typeck_results().expr_ty(other); let arg_ty = typeck.expr_ty(arg);
let other_ty = typeck.expr_ty(other);
let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default(); let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default();
let with_deref = arg_ty let with_deref = arg_ty
@ -627,13 +624,14 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left:
return; return;
} }
let arg_snip = snippet(cx, arg_span, "..");
let expr_snip; let expr_snip;
let eq_impl; let eq_impl;
if with_deref.is_implemented() { if with_deref.is_implemented() {
expr_snip = format!("*{}", snip); expr_snip = format!("*{}", arg_snip);
eq_impl = with_deref; eq_impl = with_deref;
} else { } else {
expr_snip = snip.to_string(); expr_snip = arg_snip.to_string();
eq_impl = without_deref; eq_impl = without_deref;
}; };