diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index b26e6ccb559a6..30411225519c7 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -379,7 +379,19 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } }; if self.can_coerce(ref_ty, expected) { - if let Ok(src) = cm.span_to_snippet(sp) { + let mut sugg_sp = sp; + if let hir::ExprKind::MethodCall(_segment, _sp, args) = &expr.node { + let clone_path = "std::clone::Clone::clone"; + if let ([arg], Some(true)) = (&args[..], self.tables.borrow() + .type_dependent_def_id(expr.hir_id) + .map(|did| self.tcx.def_path_str(did).as_str() == clone_path)) + { + // If this expression had a clone call when suggesting borrowing + // we want to suggest removing it because it'd now be unecessary. + sugg_sp = arg.span; + } + } + if let Ok(src) = cm.span_to_snippet(sugg_sp) { let needs_parens = match expr.node { // parenthesize if needed (Issue #46756) hir::ExprKind::Cast(_, _) | @@ -426,28 +438,16 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - let mut sugg = sugg_expr.as_str(); - if let hir::ExprKind::MethodCall(_segment, _sp, _args) = &expr.node { - let clone_path = "std::clone::Clone::clone"; - if let Some(true) = self.tables.borrow() - .type_dependent_def_id(expr.hir_id) - .map(|did| self.tcx.def_path_str(did).as_str() == clone_path) - { - // If this expression had a clone call when suggesting borrowing - // we want to suggest removing it because it'd now be unecessary. - sugg = sugg_expr.trim_end_matches(".clone()"); - } - } return Some(match mutability { hir::Mutability::MutMutable => ( sp, "consider mutably borrowing here", - format!("{}&mut {}", field_name, sugg), + format!("{}&mut {}", field_name, sugg_expr), ), hir::Mutability::MutImmutable => ( sp, "consider borrowing here", - format!("{}&{}", field_name, sugg), + format!("{}&{}", field_name, sugg_expr), ), }); }