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