2 use crate::astconv::AstConv;
3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
5 use rustc_ast::util::parser::ExprPrecedence;
6 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
8 use rustc_hir::def::{CtorOf, DefKind};
9 use rustc_hir::lang_items::LangItem;
11 Expr, ExprKind, GenericBound, ItemKind, Node, Path, QPath, Stmt, StmtKind, TyKind,
14 use rustc_infer::infer::{self, TyCtxtInferExt};
15 use rustc_infer::traits;
16 use rustc_middle::lint::in_external_macro;
17 use rustc_middle::ty::subst::GenericArgKind;
18 use rustc_middle::ty::{self, Binder, ToPredicate, Ty};
19 use rustc_span::symbol::{kw, sym};
21 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
25 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26 pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
27 err.span_suggestion_short(
29 "consider using a semicolon here",
31 Applicability::MachineApplicable,
35 /// On implicit return expressions with mismatched types, provides the following suggestions:
37 /// - Points out the method's return type as the reason for the expected type.
38 /// - Possible missing semicolon.
39 /// - Possible missing return type if the return type is the default, and not `fn main()`.
40 pub fn suggest_mismatched_types_on_tail(
43 expr: &'tcx hir::Expr<'tcx>,
48 let expr = expr.peel_drop_temps();
49 // If the expression is from an external macro, then do not suggest
50 // adding a semicolon, because there's nowhere to put it.
52 if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
53 self.suggest_missing_semicolon(err, expr, expected);
55 let mut pointing_at_return_type = false;
56 if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
57 let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
58 pointing_at_return_type = self.suggest_missing_return_type(
66 self.suggest_missing_break_or_return_expr(
67 err, expr, &fn_decl, expected, found, blk_id, fn_id,
70 pointing_at_return_type
73 /// When encountering an fn-like ctor that needs to unify with a value, check whether calling
74 /// the ctor would successfully solve the type mismatch and if so, suggest it:
76 /// fn foo(x: usize) -> usize { x }
77 /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)`
86 let hir = self.tcx.hir();
87 let (def_id, sig) = match *found.kind() {
88 ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)),
89 ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig()),
93 let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0;
94 let sig = self.normalize_associated_types_in(expr.span, sig);
95 if self.can_coerce(sig.output(), expected) {
96 let (mut sugg_call, applicability) = if sig.inputs().is_empty() {
97 (String::new(), Applicability::MachineApplicable)
99 ("...".to_string(), Applicability::HasPlaceholders)
101 let mut msg = "call this function";
102 match hir.get_if_local(def_id) {
104 Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
105 | Node::ImplItem(hir::ImplItem {
106 kind: hir::ImplItemKind::Fn(_, body_id), ..
108 | Node::TraitItem(hir::TraitItem {
109 kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
113 let body = hir.body(*body_id);
117 .map(|param| match ¶m.pat.kind {
118 hir::PatKind::Binding(_, _, ident, None)
119 if ident.name != kw::SelfLower =>
123 _ => "_".to_string(),
128 Some(Node::Expr(hir::Expr {
129 kind: ExprKind::Closure(_, _, body_id, _, _),
130 span: full_closure_span,
133 if *full_closure_span == expr.span {
136 msg = "call this closure";
137 let body = hir.body(*body_id);
141 .map(|param| match ¶m.pat.kind {
142 hir::PatKind::Binding(_, _, ident, None)
143 if ident.name != kw::SelfLower =>
147 _ => "_".to_string(),
152 Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
153 sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
154 match def_id.as_local().map(|def_id| hir.def_kind(def_id)) {
155 Some(DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
156 msg = "instantiate this tuple variant";
158 Some(DefKind::Ctor(CtorOf::Struct, _)) => {
159 msg = "instantiate this tuple struct";
164 Some(Node::ForeignItem(hir::ForeignItem {
165 kind: hir::ForeignItemKind::Fn(_, idents, _),
171 if ident.name != kw::SelfLower {
180 Some(Node::TraitItem(hir::TraitItem {
181 kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
187 if ident.name != kw::SelfLower {
198 err.span_suggestion_verbose(
199 expr.span.shrink_to_hi(),
200 &format!("use parentheses to {}", msg),
201 format!("({})", sugg_call),
209 pub fn suggest_deref_ref_or_into(
211 err: &mut Diagnostic,
212 expr: &hir::Expr<'tcx>,
215 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
217 let expr = expr.peel_blocks();
218 if let Some((sp, msg, suggestion, applicability, verbose)) =
219 self.check_ref(expr, found, expected)
222 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
224 err.span_suggestion(sp, &msg, suggestion, applicability);
226 } else if let (ty::FnDef(def_id, ..), true) =
227 (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
229 if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
230 let sp = self.sess().source_map().guess_head_span(sp);
231 err.span_label(sp, &format!("{} defined here", found));
233 } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
234 let is_struct_pat_shorthand_field =
235 self.maybe_get_struct_pattern_shorthand_field(expr).is_some();
236 let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
237 if !methods.is_empty() {
238 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
239 let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
240 .filter_map(|(receiver, method)| {
241 let method_call = format!(".{}()", method.name);
242 if receiver.ends_with(&method_call) {
243 None // do not suggest code that is already there (#53348)
245 let method_call_list = [".to_vec()", ".to_string()"];
246 let mut sugg = if receiver.ends_with(".clone()")
247 && method_call_list.contains(&method_call.as_str())
249 let max_len = receiver.rfind('.').unwrap();
252 format!("{}{}", &receiver[..max_len], method_call),
255 if expr.precedence().order()
256 < ExprPrecedence::MethodCall.order()
259 (expr.span.shrink_to_lo(), "(".to_string()),
260 (expr.span.shrink_to_hi(), format!("){}", method_call)),
263 vec![(expr.span.shrink_to_hi(), method_call)]
266 if is_struct_pat_shorthand_field {
269 (expr.span.shrink_to_lo(), format!("{}: ", receiver)),
276 if suggestions.peek().is_some() {
277 err.multipart_suggestions(
278 "try using a conversion method",
280 Applicability::MaybeIncorrect,
284 } else if found.to_string().starts_with("Option<")
285 && expected.to_string() == "Option<&str>"
287 if let ty::Adt(_def, subst) = found.kind() {
288 if subst.len() != 0 {
289 if let GenericArgKind::Type(ty) = subst[0].unpack() {
290 let peeled = ty.peel_refs().to_string();
291 if peeled == "String" {
292 let ref_cnt = ty.to_string().len() - peeled.len();
293 let result = format!(".map(|x| &*{}x)", "*".repeat(ref_cnt));
294 err.span_suggestion_verbose(
295 expr.span.shrink_to_hi(),
296 "try converting the passed type into a `&str`",
298 Applicability::MaybeIncorrect,
308 /// When encountering the expected boxed value allocated in the stack, suggest allocating it
309 /// in the heap by calling `Box::new()`.
310 pub(in super::super) fn suggest_boxing_when_appropriate(
312 err: &mut Diagnostic,
313 expr: &hir::Expr<'_>,
317 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
318 // Do not suggest `Box::new` in const context.
321 if !expected.is_box() || found.is_box() {
324 let boxed_found = self.tcx.mk_box(found);
325 if self.can_coerce(boxed_found, expected) {
326 err.multipart_suggestion(
327 "store this in the heap by calling `Box::new`",
329 (expr.span.shrink_to_lo(), "Box::new(".to_string()),
330 (expr.span.shrink_to_hi(), ")".to_string()),
332 Applicability::MachineApplicable,
335 "for more on the distinction between the stack and the heap, read \
336 https://doc.rust-lang.org/book/ch15-01-box.html, \
337 https://doc.rust-lang.org/rust-by-example/std/box.html, and \
338 https://doc.rust-lang.org/std/boxed/index.html",
343 /// When encountering a closure that captures variables, where a FnPtr is expected,
344 /// suggest a non-capturing closure
345 pub(in super::super) fn suggest_no_capture_closure(
347 err: &mut Diagnostic,
351 if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
352 if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
353 // Report upto four upvars being captured to reduce the amount error messages
354 // reported back to the user.
355 let spans_and_labels = upvars
358 .map(|(var_hir_id, upvar)| {
359 let var_name = self.tcx.hir().name(*var_hir_id).to_string();
360 let msg = format!("`{}` captured here", var_name);
363 .collect::<Vec<_>>();
365 let mut multi_span: MultiSpan =
366 spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
367 for (sp, label) in spans_and_labels {
368 multi_span.push_span_label(sp, label);
372 "closures can only be coerced to `fn` types if they do not capture any variables"
378 /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
379 #[instrument(skip(self, err))]
380 pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
382 err: &mut Diagnostic,
383 expr: &hir::Expr<'_>,
389 if self.tcx.hir().is_inside_const_context(expr.hir_id) {
390 // Do not suggest `Box::new` in const context.
393 let pin_did = self.tcx.lang_items().pin_type();
394 // This guards the `unwrap` and `mk_box` below.
395 if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
398 let box_found = self.tcx.mk_box(found);
399 let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
400 let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
401 match expected.kind() {
402 ty::Adt(def, _) if Some(def.did()) == pin_did => {
403 if self.can_coerce(pin_box_found, expected) {
404 debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
406 ty::Adt(def, _) if def.is_box() => {
407 err.help("use `Box::pin`");
410 err.multipart_suggestion(
411 "you need to pin and box this expression",
413 (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
414 (expr.span.shrink_to_hi(), ")".to_string()),
416 Applicability::MaybeIncorrect,
421 } else if self.can_coerce(pin_found, expected) {
423 ty::Adt(def, _) if def.is_box() => {
424 err.help("use `Box::pin`");
433 ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
434 // Check if the parent expression is a call to Pin::new. If it
435 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
436 // can suggest Box::pin.
437 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
438 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
442 ExprKind::Path(QPath::TypeRelative(
444 kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
448 )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
451 "use `Box::pin` to pin and box this expression",
452 "Box::pin".to_string(),
453 Applicability::MachineApplicable,
464 /// A common error is to forget to add a semicolon at the end of a block, e.g.,
468 /// bar_that_returns_u32()
472 /// This routine checks if the return expression in a block would make sense on its own as a
473 /// statement and the return type has been left as default or has been specified as `()`. If so,
474 /// it suggests adding a semicolon.
475 fn suggest_missing_semicolon(
477 err: &mut Diagnostic,
478 expression: &'tcx hir::Expr<'tcx>,
481 if expected.is_unit() {
482 // `BlockTailExpression` only relevant if the tail expr would be
483 // useful on its own.
484 match expression.kind {
486 | ExprKind::MethodCall(..)
489 | ExprKind::Match(..)
490 | ExprKind::Block(..)
491 if expression.can_have_side_effects() =>
494 expression.span.shrink_to_hi(),
495 "consider using a semicolon here",
497 Applicability::MachineApplicable,
505 /// A possible error is to forget to add a return type that is needed:
509 /// bar_that_returns_u32()
513 /// This routine checks if the return type is left as default, the method is not part of an
514 /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
516 pub(in super::super) fn suggest_missing_return_type(
518 err: &mut Diagnostic,
519 fn_decl: &hir::FnDecl<'_>,
526 self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
527 // Only suggest changing the return type for methods that
528 // haven't set a return type at all (and aren't `fn main()` or an impl).
529 match (&fn_decl.output, found.is_suggestable(self.tcx), can_suggest, expected.is_unit()) {
530 (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
531 err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found });
534 (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
535 // FIXME: if `found` could be `impl Iterator` or `impl Fn*`, we should suggest
537 err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
540 (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
541 // `fn main()` must return `()`, do not suggest changing return type
542 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
545 // expectation was caused by something else, not the default return
546 (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
547 (&hir::FnRetTy::Return(ref ty), _, _, _) => {
548 // Only point to return type if the expected type is the return type, as if they
549 // are not, the expectation must have been caused by something else.
550 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
552 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
553 debug!("suggest_missing_return_type: return type {:?}", ty);
554 debug!("suggest_missing_return_type: expected type {:?}", ty);
555 let bound_vars = self.tcx.late_bound_vars(fn_id);
556 let ty = Binder::bind_with_vars(ty, bound_vars);
557 let ty = self.normalize_associated_types_in(span, ty);
558 let ty = self.tcx.erase_late_bound_regions(ty);
559 if self.can_coerce(expected, ty) {
560 err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
561 self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
569 /// check whether the return type is a generic type with a trait bound
570 /// only suggest this if the generic param is not present in the arguments
571 /// if this is true, hint them towards changing the return type to `impl Trait`
573 /// fn cant_name_it<T: Fn() -> u32>() -> T {
577 fn try_suggest_return_impl_trait(
579 err: &mut Diagnostic,
584 // Only apply the suggestion if:
585 // - the return type is a generic parameter
586 // - the generic param is not used as a fn param
587 // - the generic param has at least one bound
588 // - the generic param doesn't appear in any other bounds where it's not the Self type
590 // - Changing the return type to be `impl <all bounds>`
592 debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
594 let ty::Param(expected_ty_as_param) = expected.kind() else { return };
596 let fn_node = self.tcx.hir().find(fn_id);
598 let Some(hir::Node::Item(hir::Item {
601 hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
602 hir::Generics { params, predicates, .. },
606 })) = fn_node else { return };
608 if params.get(expected_ty_as_param.index as usize).is_none() {
612 // get all where BoundPredicates here, because they are used in to cases below
613 let where_predicates = predicates
615 .filter_map(|p| match p {
616 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
621 // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
622 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
627 .map(|(ty, bounds)| match ty.kind() {
628 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
629 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
630 _ => match ty.contains(expected) {
635 .collect::<Result<Vec<_>, _>>();
637 let Ok(where_predicates) = where_predicates else { return };
639 // now get all predicates in the same types as the where bounds, so we can chain them
640 let predicates_from_where =
641 where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
643 // extract all bounds from the source code using their spans
644 let all_matching_bounds_strs = predicates_from_where
645 .filter_map(|bound| match bound {
646 GenericBound::Trait(_, _) => {
647 self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
651 .collect::<Vec<String>>();
653 if all_matching_bounds_strs.len() == 0 {
657 let all_bounds_str = all_matching_bounds_strs.join(" + ");
659 let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
660 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
661 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
664 if ty_param_used_in_fn_params {
670 "consider using an impl return type",
671 format!("impl {}", all_bounds_str),
672 Applicability::MaybeIncorrect,
676 pub(in super::super) fn suggest_missing_break_or_return_expr(
678 err: &mut Diagnostic,
679 expr: &'tcx hir::Expr<'tcx>,
680 fn_decl: &hir::FnDecl<'_>,
686 if !expected.is_unit() {
689 let found = self.resolve_vars_with_obligations(found);
691 let in_loop = self.is_loop(id)
692 || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
694 let in_local_statement = self.is_local_statement(id)
699 .any(|(parent_id, _)| self.is_local_statement(parent_id));
701 if in_loop && in_local_statement {
702 err.multipart_suggestion(
703 "you might have meant to break the loop with this value",
705 (expr.span.shrink_to_lo(), "break ".to_string()),
706 (expr.span.shrink_to_hi(), ";".to_string()),
708 Applicability::MaybeIncorrect,
713 if let hir::FnRetTy::Return(ty) = fn_decl.output {
714 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
715 let bound_vars = self.tcx.late_bound_vars(fn_id);
716 let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
717 let ty = self.normalize_associated_types_in(expr.span, ty);
718 let ty = match self.tcx.asyncness(fn_id.owner) {
719 hir::IsAsync::Async => self
723 infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
725 fn_decl.output.span(),
726 "failed to get output type of async function"
731 hir::IsAsync::NotAsync => ty,
733 if self.can_coerce(found, ty) {
734 err.multipart_suggestion(
735 "you might have meant to return this value",
737 (expr.span.shrink_to_lo(), "return ".to_string()),
738 (expr.span.shrink_to_hi(), ";".to_string()),
740 Applicability::MaybeIncorrect,
746 pub(in super::super) fn suggest_missing_parentheses(
748 err: &mut Diagnostic,
749 expr: &hir::Expr<'_>,
751 let sp = self.tcx.sess.source_map().start_point(expr.span);
752 if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
753 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
754 self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
758 /// Given an expression type mismatch, peel any `&` expressions until we get to
759 /// a block expression, and then suggest replacing the braces with square braces
760 /// if it was possibly mistaken array syntax.
761 pub(crate) fn suggest_block_to_brackets_peeling_refs(
763 diag: &mut Diagnostic,
764 mut expr: &hir::Expr<'_>,
765 mut expr_ty: Ty<'tcx>,
766 mut expected_ty: Ty<'tcx>,
769 match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
771 hir::ExprKind::AddrOf(_, _, inner_expr),
772 ty::Ref(_, inner_expr_ty, _),
773 ty::Ref(_, inner_expected_ty, _),
776 expr_ty = *inner_expr_ty;
777 expected_ty = *inner_expected_ty;
779 (hir::ExprKind::Block(blk, _), _, _) => {
780 self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
788 /// Suggest wrapping the block in square brackets instead of curly braces
789 /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
790 pub(crate) fn suggest_block_to_brackets(
792 diag: &mut Diagnostic,
793 blk: &hir::Block<'_>,
795 expected_ty: Ty<'tcx>,
797 if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
798 if self.can_coerce(blk_ty, *elem_ty)
799 && blk.stmts.is_empty()
800 && blk.rules == hir::BlockCheckMode::DefaultBlock
802 let source_map = self.tcx.sess.source_map();
803 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
804 if snippet.starts_with('{') && snippet.ends_with('}') {
805 diag.multipart_suggestion_verbose(
806 "to create an array, use square brackets instead of curly braces",
811 .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
817 .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
821 Applicability::MachineApplicable,
829 fn is_loop(&self, id: hir::HirId) -> bool {
830 let node = self.tcx.hir().get(id);
831 matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
834 fn is_local_statement(&self, id: hir::HirId) -> bool {
835 let node = self.tcx.hir().get(id);
836 matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
839 /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
840 /// which is a side-effect of autoref.
841 pub(crate) fn note_type_is_not_clone(
843 diag: &mut Diagnostic,
844 expected_ty: Ty<'tcx>,
846 expr: &hir::Expr<'_>,
848 let hir::ExprKind::MethodCall(segment, &[ref callee_expr], _) = expr.kind else { return; };
849 let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
850 let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
851 let results = self.typeck_results.borrow();
852 // First, look for a `Clone::clone` call
853 if segment.ident.name == sym::clone
854 && results.type_dependent_def_id(expr.hir_id).map_or(
857 self.tcx.associated_item(did).container
858 == ty::AssocItemContainer::TraitContainer(clone_trait_did)
861 // If that clone call hasn't already dereferenced the self type (i.e. don't give this
862 // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
863 && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
864 // Check that we're in fact trying to clone into the expected type
865 && self.can_coerce(*pointee_ty, expected_ty)
866 // And the expected type doesn't implement `Clone`
867 && !self.predicate_must_hold_considering_regions(&traits::Obligation {
868 cause: traits::ObligationCause::dummy(),
869 param_env: self.param_env,
871 predicate: ty::Binder::dummy(ty::TraitRef {
872 def_id: clone_trait_did,
873 substs: self.tcx.mk_substs([expected_ty.into()].iter()),
876 .to_predicate(self.tcx),
882 "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"