rustc_hir_typeck/method/
suggest.rs

1//! Give useful errors and suggestions to users when an item can't be
2//! found or is otherwise invalid.
3
4// ignore-tidy-filelength
5
6use core::ops::ControlFlow;
7use std::borrow::Cow;
8use std::path::PathBuf;
9
10use hir::Expr;
11use rustc_ast::ast::Mutability;
12use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
13use rustc_data_structures::sorted_map::SortedMap;
14use rustc_data_structures::unord::UnordSet;
15use rustc_errors::codes::*;
16use rustc_errors::{
17    Applicability, Diag, DiagStyledString, MultiSpan, StashKey, pluralize, struct_span_code_err,
18};
19use rustc_hir::attrs::AttributeKind;
20use rustc_hir::def::{CtorKind, DefKind, Res};
21use rustc_hir::def_id::DefId;
22use rustc_hir::intravisit::{self, Visitor};
23use rustc_hir::lang_items::LangItem;
24use rustc_hir::{self as hir, ExprKind, HirId, Node, PathSegment, QPath, find_attr};
25use rustc_infer::infer::{BoundRegionConversionTime, RegionVariableOrigin};
26use rustc_middle::bug;
27use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type};
28use rustc_middle::ty::print::{
29    PrintTraitRefExt as _, with_crate_prefix, with_forced_trimmed_paths,
30    with_no_visible_paths_if_doc_hidden,
31};
32use rustc_middle::ty::{self, GenericArgKind, IsSuggestable, Ty, TyCtxt, TypeVisitableExt};
33use rustc_span::def_id::DefIdSet;
34use rustc_span::{
35    DUMMY_SP, ErrorGuaranteed, ExpnKind, FileName, Ident, MacroKind, Span, Symbol, edit_distance,
36    kw, sym,
37};
38use rustc_trait_selection::error_reporting::traits::DefIdOrName;
39use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedNote;
40use rustc_trait_selection::infer::InferCtxtExt;
41use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
42use rustc_trait_selection::traits::{
43    FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, supertraits,
44};
45use tracing::{debug, info, instrument};
46
47use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
48use super::{CandidateSource, MethodError, NoMatchData};
49use crate::errors::{self, CandidateTraitNote, NoAssociatedItem};
50use crate::{Expectation, FnCtxt};
51
52impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
53    fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
54        self.autoderef(span, ty)
55            .silence_errors()
56            .any(|(ty, _)| matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
57    }
58
59    fn impl_into_iterator_should_be_iterator(
60        &self,
61        ty: Ty<'tcx>,
62        span: Span,
63        unsatisfied_predicates: &Vec<(
64            ty::Predicate<'tcx>,
65            Option<ty::Predicate<'tcx>>,
66            Option<ObligationCause<'tcx>>,
67        )>,
68    ) -> bool {
69        fn predicate_bounds_generic_param<'tcx>(
70            predicate: ty::Predicate<'_>,
71            generics: &'tcx ty::Generics,
72            generic_param: &ty::GenericParamDef,
73            tcx: TyCtxt<'tcx>,
74        ) -> bool {
75            if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
76                predicate.kind().as_ref().skip_binder()
77            {
78                let ty::TraitPredicate { trait_ref: ty::TraitRef { args, .. }, .. } = trait_pred;
79                if args.is_empty() {
80                    return false;
81                }
82                let Some(arg_ty) = args[0].as_type() else {
83                    return false;
84                };
85                let ty::Param(param) = *arg_ty.kind() else {
86                    return false;
87                };
88                // Is `generic_param` the same as the arg for this trait predicate?
89                generic_param.index == generics.type_param(param, tcx).index
90            } else {
91                false
92            }
93        }
94
95        let is_iterator_predicate = |predicate: ty::Predicate<'tcx>| -> bool {
96            if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
97                predicate.kind().as_ref().skip_binder()
98            {
99                self.tcx.is_diagnostic_item(sym::Iterator, trait_pred.trait_ref.def_id)
100                    // ignore unsatisfied predicates generated from trying to auto-ref ty (#127511)
101                    && trait_pred.trait_ref.self_ty() == ty
102            } else {
103                false
104            }
105        };
106
107        // Does the `ty` implement `IntoIterator`?
108        let Some(into_iterator_trait) = self.tcx.get_diagnostic_item(sym::IntoIterator) else {
109            return false;
110        };
111        let trait_ref = ty::TraitRef::new(self.tcx, into_iterator_trait, [ty]);
112        let obligation = Obligation::new(self.tcx, self.misc(span), self.param_env, trait_ref);
113        if !self.predicate_must_hold_modulo_regions(&obligation) {
114            return false;
115        }
116
117        match *ty.peel_refs().kind() {
118            ty::Param(param) => {
119                let generics = self.tcx.generics_of(self.body_id);
120                let generic_param = generics.type_param(param, self.tcx);
121                for unsatisfied in unsatisfied_predicates.iter() {
122                    // The parameter implements `IntoIterator`
123                    // but it has called a method that requires it to implement `Iterator`
124                    if predicate_bounds_generic_param(
125                        unsatisfied.0,
126                        generics,
127                        generic_param,
128                        self.tcx,
129                    ) && is_iterator_predicate(unsatisfied.0)
130                    {
131                        return true;
132                    }
133                }
134            }
135            ty::Slice(..) | ty::Adt(..) | ty::Alias(ty::Opaque, _) => {
136                for unsatisfied in unsatisfied_predicates.iter() {
137                    if is_iterator_predicate(unsatisfied.0) {
138                        return true;
139                    }
140                }
141            }
142            _ => return false,
143        }
144        false
145    }
146
147    #[instrument(level = "debug", skip(self))]
148    pub(crate) fn report_method_error(
149        &self,
150        call_id: HirId,
151        rcvr_ty: Ty<'tcx>,
152        error: MethodError<'tcx>,
153        expected: Expectation<'tcx>,
154        trait_missing_method: bool,
155    ) -> ErrorGuaranteed {
156        // NOTE: Reporting a method error should also suppress any unused trait errors,
157        // since the method error is very possibly the reason why the trait wasn't used.
158        for &import_id in
159            self.tcx.in_scope_traits(call_id).into_iter().flatten().flat_map(|c| &c.import_ids)
160        {
161            self.typeck_results.borrow_mut().used_trait_imports.insert(import_id);
162        }
163
164        let (span, expr_span, source, item_name, args) = match self.tcx.hir_node(call_id) {
165            hir::Node::Expr(&hir::Expr {
166                kind: hir::ExprKind::MethodCall(segment, rcvr, args, _),
167                span,
168                ..
169            }) => {
170                (segment.ident.span, span, SelfSource::MethodCall(rcvr), segment.ident, Some(args))
171            }
172            hir::Node::Expr(&hir::Expr {
173                kind: hir::ExprKind::Path(QPath::TypeRelative(rcvr, segment)),
174                span,
175                ..
176            })
177            | hir::Node::PatExpr(&hir::PatExpr {
178                kind: hir::PatExprKind::Path(QPath::TypeRelative(rcvr, segment)),
179                span,
180                ..
181            })
182            | hir::Node::Pat(&hir::Pat {
183                kind:
184                    hir::PatKind::Struct(QPath::TypeRelative(rcvr, segment), ..)
185                    | hir::PatKind::TupleStruct(QPath::TypeRelative(rcvr, segment), ..),
186                span,
187                ..
188            }) => {
189                let args = match self.tcx.parent_hir_node(call_id) {
190                    hir::Node::Expr(&hir::Expr {
191                        kind: hir::ExprKind::Call(callee, args), ..
192                    }) if callee.hir_id == call_id => Some(args),
193                    _ => None,
194                };
195                (segment.ident.span, span, SelfSource::QPath(rcvr), segment.ident, args)
196            }
197            node => unreachable!("{node:?}"),
198        };
199
200        // Try to get the span of the identifier within the expression's syntax context
201        // (if that's different).
202        let within_macro_span = span.within_macro(expr_span, self.tcx.sess.source_map());
203
204        // Avoid suggestions when we don't know what's going on.
205        if let Err(guar) = rcvr_ty.error_reported() {
206            return guar;
207        }
208
209        match error {
210            MethodError::NoMatch(mut no_match_data) => self.report_no_match_method_error(
211                span,
212                rcvr_ty,
213                item_name,
214                call_id,
215                source,
216                args,
217                expr_span,
218                &mut no_match_data,
219                expected,
220                trait_missing_method,
221                within_macro_span,
222            ),
223
224            MethodError::Ambiguity(mut sources) => {
225                let mut err = struct_span_code_err!(
226                    self.dcx(),
227                    item_name.span,
228                    E0034,
229                    "multiple applicable items in scope"
230                );
231                err.span_label(item_name.span, format!("multiple `{item_name}` found"));
232                if let Some(within_macro_span) = within_macro_span {
233                    err.span_label(within_macro_span, "due to this macro variable");
234                }
235
236                self.note_candidates_on_method_error(
237                    rcvr_ty,
238                    item_name,
239                    source,
240                    args,
241                    span,
242                    &mut err,
243                    &mut sources,
244                    Some(expr_span),
245                );
246                err.emit()
247            }
248
249            MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
250                let kind = self.tcx.def_kind_descr(kind, def_id);
251                let mut err = struct_span_code_err!(
252                    self.dcx(),
253                    item_name.span,
254                    E0624,
255                    "{} `{}` is private",
256                    kind,
257                    item_name
258                );
259                err.span_label(item_name.span, format!("private {kind}"));
260                let sp =
261                    self.tcx.hir_span_if_local(def_id).unwrap_or_else(|| self.tcx.def_span(def_id));
262                err.span_label(sp, format!("private {kind} defined here"));
263                if let Some(within_macro_span) = within_macro_span {
264                    err.span_label(within_macro_span, "due to this macro variable");
265                }
266                self.suggest_valid_traits(&mut err, item_name, out_of_scope_traits, true);
267                self.suggest_unwrapping_inner_self(&mut err, source, rcvr_ty, item_name);
268                err.emit()
269            }
270
271            MethodError::IllegalSizedBound { candidates, needs_mut, bound_span, self_expr } => {
272                let msg = if needs_mut {
273                    with_forced_trimmed_paths!(format!(
274                        "the `{item_name}` method cannot be invoked on `{rcvr_ty}`"
275                    ))
276                } else {
277                    format!("the `{item_name}` method cannot be invoked on a trait object")
278                };
279                let mut err = self.dcx().struct_span_err(span, msg);
280                if !needs_mut {
281                    err.span_label(bound_span, "this has a `Sized` requirement");
282                }
283                if let Some(within_macro_span) = within_macro_span {
284                    err.span_label(within_macro_span, "due to this macro variable");
285                }
286                if !candidates.is_empty() {
287                    let help = format!(
288                        "{an}other candidate{s} {were} found in the following trait{s}",
289                        an = if candidates.len() == 1 { "an" } else { "" },
290                        s = pluralize!(candidates.len()),
291                        were = pluralize!("was", candidates.len()),
292                    );
293                    self.suggest_use_candidates(
294                        candidates,
295                        |accessible_sugg, inaccessible_sugg, span| {
296                            let suggest_for_access =
297                                |err: &mut Diag<'_>, mut msg: String, sugg: Vec<_>| {
298                                    msg += &format!(
299                                        ", perhaps add a `use` for {one_of_them}:",
300                                        one_of_them =
301                                            if sugg.len() == 1 { "it" } else { "one_of_them" },
302                                    );
303                                    err.span_suggestions(
304                                        span,
305                                        msg,
306                                        sugg,
307                                        Applicability::MaybeIncorrect,
308                                    );
309                                };
310                            let suggest_for_privacy =
311                                |err: &mut Diag<'_>, mut msg: String, suggs: Vec<String>| {
312                                    if let [sugg] = suggs.as_slice() {
313                                        err.help(format!("\
314                                            trait `{}` provides `{item_name}` is implemented but not reachable",
315                                            sugg.trim(),
316                                        ));
317                                    } else {
318                                        msg += &format!(" but {} not reachable", pluralize!("is", suggs.len()));
319                                        err.span_suggestions(
320                                            span,
321                                            msg,
322                                            suggs,
323                                            Applicability::MaybeIncorrect,
324                                        );
325                                    }
326                                };
327                            if accessible_sugg.is_empty() {
328                                // `inaccessible_sugg` must not be empty
329                                suggest_for_privacy(&mut err, help, inaccessible_sugg);
330                            } else if inaccessible_sugg.is_empty() {
331                                suggest_for_access(&mut err, help, accessible_sugg);
332                            } else {
333                                suggest_for_access(&mut err, help.clone(), accessible_sugg);
334                                suggest_for_privacy(&mut err, help, inaccessible_sugg);
335                            }
336                        },
337                    );
338                }
339                if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind() {
340                    if needs_mut {
341                        let trait_type =
342                            Ty::new_ref(self.tcx, *region, *t_type, mutability.invert());
343                        let msg = format!("you need `{trait_type}` instead of `{rcvr_ty}`");
344                        let mut kind = &self_expr.kind;
345                        while let hir::ExprKind::AddrOf(_, _, expr)
346                        | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind
347                        {
348                            kind = &expr.kind;
349                        }
350                        if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = kind
351                            && let hir::def::Res::Local(hir_id) = path.res
352                            && let hir::Node::Pat(b) = self.tcx.hir_node(hir_id)
353                            && let hir::Node::Param(p) = self.tcx.parent_hir_node(b.hir_id)
354                            && let Some(decl) = self.tcx.parent_hir_node(p.hir_id).fn_decl()
355                            && let Some(ty) = decl.inputs.iter().find(|ty| ty.span == p.ty_span)
356                            && let hir::TyKind::Ref(_, mut_ty) = &ty.kind
357                            && let hir::Mutability::Not = mut_ty.mutbl
358                        {
359                            err.span_suggestion_verbose(
360                                mut_ty.ty.span.shrink_to_lo(),
361                                msg,
362                                "mut ",
363                                Applicability::MachineApplicable,
364                            );
365                        } else {
366                            err.help(msg);
367                        }
368                    }
369                }
370                err.emit()
371            }
372
373            MethodError::ErrorReported(guar) => guar,
374
375            MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
376        }
377    }
378
379    fn suggest_missing_writer(
380        &self,
381        rcvr_ty: Ty<'tcx>,
382        rcvr_expr: &hir::Expr<'tcx>,
383        mut long_ty_path: Option<PathBuf>,
384    ) -> Diag<'_> {
385        let mut err = struct_span_code_err!(
386            self.dcx(),
387            rcvr_expr.span,
388            E0599,
389            "cannot write into `{}`",
390            self.tcx.short_string(rcvr_ty, &mut long_ty_path),
391        );
392        *err.long_ty_path() = long_ty_path;
393        err.span_note(
394            rcvr_expr.span,
395            "must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method",
396        );
397        if let ExprKind::Lit(_) = rcvr_expr.kind {
398            err.span_help(
399                rcvr_expr.span.shrink_to_lo(),
400                "a writer is needed before this format string",
401            );
402        };
403        err
404    }
405
406    fn suggest_use_shadowed_binding_with_method(
407        &self,
408        self_source: SelfSource<'tcx>,
409        method_name: Ident,
410        ty: Ty<'tcx>,
411        err: &mut Diag<'_>,
412    ) {
413        #[derive(Debug)]
414        struct LetStmt {
415            ty_hir_id_opt: Option<hir::HirId>,
416            binding_id: hir::HirId,
417            span: Span,
418            init_hir_id: hir::HirId,
419        }
420
421        // Used for finding suggest binding.
422        // ```rust
423        // earlier binding for suggesting:
424        // let y = vec![1, 2];
425        // now binding:
426        // if let Some(y) = x {
427        //     y.push(y);
428        // }
429        // ```
430        struct LetVisitor<'a, 'tcx> {
431            // Error binding which don't have `method_name`.
432            binding_name: Symbol,
433            binding_id: hir::HirId,
434            // Used for check if the suggest binding has `method_name`.
435            fcx: &'a FnCtxt<'a, 'tcx>,
436            call_expr: &'tcx Expr<'tcx>,
437            method_name: Ident,
438            // Suggest the binding which is shallowed.
439            sugg_let: Option<LetStmt>,
440        }
441
442        impl<'a, 'tcx> LetVisitor<'a, 'tcx> {
443            // Check scope of binding.
444            fn is_sub_scope(&self, sub_id: hir::ItemLocalId, super_id: hir::ItemLocalId) -> bool {
445                let scope_tree = self.fcx.tcx.region_scope_tree(self.fcx.body_id);
446                if let Some(sub_var_scope) = scope_tree.var_scope(sub_id)
447                    && let Some(super_var_scope) = scope_tree.var_scope(super_id)
448                    && scope_tree.is_subscope_of(sub_var_scope, super_var_scope)
449                {
450                    return true;
451                }
452                false
453            }
454
455            // Check if an earlier shadowed binding make `the receiver` of a MethodCall has the method.
456            // If it does, record the earlier binding for subsequent notes.
457            fn check_and_add_sugg_binding(&mut self, binding: LetStmt) -> bool {
458                if !self.is_sub_scope(self.binding_id.local_id, binding.binding_id.local_id) {
459                    return false;
460                }
461
462                // Get the earlier shadowed binding'ty and use it to check the method.
463                if let Some(ty_hir_id) = binding.ty_hir_id_opt
464                    && let Some(tyck_ty) = self.fcx.node_ty_opt(ty_hir_id)
465                {
466                    if self
467                        .fcx
468                        .lookup_probe_for_diagnostic(
469                            self.method_name,
470                            tyck_ty,
471                            self.call_expr,
472                            ProbeScope::TraitsInScope,
473                            None,
474                        )
475                        .is_ok()
476                    {
477                        self.sugg_let = Some(binding);
478                        return true;
479                    } else {
480                        return false;
481                    }
482                }
483
484                // If the shadowed binding has an itializer expression,
485                // use the initializer expression's ty to try to find the method again.
486                // For example like:  `let mut x = Vec::new();`,
487                // `Vec::new()` is the itializer expression.
488                if let Some(self_ty) = self.fcx.node_ty_opt(binding.init_hir_id)
489                    && self
490                        .fcx
491                        .lookup_probe_for_diagnostic(
492                            self.method_name,
493                            self_ty,
494                            self.call_expr,
495                            ProbeScope::TraitsInScope,
496                            None,
497                        )
498                        .is_ok()
499                {
500                    self.sugg_let = Some(binding);
501                    return true;
502                }
503                return false;
504            }
505        }
506
507        impl<'v> Visitor<'v> for LetVisitor<'_, '_> {
508            type Result = ControlFlow<()>;
509            fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
510                if let hir::StmtKind::Let(&hir::LetStmt { pat, ty, init, .. }) = ex.kind
511                    && let hir::PatKind::Binding(_, binding_id, binding_name, ..) = pat.kind
512                    && let Some(init) = init
513                    && binding_name.name == self.binding_name
514                    && binding_id != self.binding_id
515                {
516                    if self.check_and_add_sugg_binding(LetStmt {
517                        ty_hir_id_opt: ty.map(|ty| ty.hir_id),
518                        binding_id,
519                        span: pat.span,
520                        init_hir_id: init.hir_id,
521                    }) {
522                        return ControlFlow::Break(());
523                    }
524                    ControlFlow::Continue(())
525                } else {
526                    hir::intravisit::walk_stmt(self, ex)
527                }
528            }
529
530            // Used for find the error binding.
531            // When the visitor reaches this point, all the shadowed bindings
532            // have been found, so the visitor ends.
533            fn visit_pat(&mut self, p: &'v hir::Pat<'v>) -> Self::Result {
534                match p.kind {
535                    hir::PatKind::Binding(_, binding_id, binding_name, _) => {
536                        if binding_name.name == self.binding_name && binding_id == self.binding_id {
537                            return ControlFlow::Break(());
538                        }
539                    }
540                    _ => {
541                        let _ = intravisit::walk_pat(self, p);
542                    }
543                }
544                ControlFlow::Continue(())
545            }
546        }
547
548        if let SelfSource::MethodCall(rcvr) = self_source
549            && let hir::ExprKind::Path(QPath::Resolved(_, path)) = rcvr.kind
550            && let hir::def::Res::Local(recv_id) = path.res
551            && let Some(segment) = path.segments.first()
552        {
553            let body = self.tcx.hir_body_owned_by(self.body_id);
554
555            if let Node::Expr(call_expr) = self.tcx.parent_hir_node(rcvr.hir_id) {
556                let mut let_visitor = LetVisitor {
557                    fcx: self,
558                    call_expr,
559                    binding_name: segment.ident.name,
560                    binding_id: recv_id,
561                    method_name,
562                    sugg_let: None,
563                };
564                let _ = let_visitor.visit_body(&body);
565                if let Some(sugg_let) = let_visitor.sugg_let
566                    && let Some(self_ty) = self.node_ty_opt(sugg_let.init_hir_id)
567                {
568                    let _sm = self.infcx.tcx.sess.source_map();
569                    let rcvr_name = segment.ident.name;
570                    let mut span = MultiSpan::from_span(sugg_let.span);
571                    span.push_span_label(sugg_let.span,
572                            format!("`{rcvr_name}` of type `{self_ty}` that has method `{method_name}` defined earlier here"));
573
574                    let ty = self.tcx.short_string(ty, err.long_ty_path());
575                    span.push_span_label(
576                        self.tcx.hir_span(recv_id),
577                        format!("earlier `{rcvr_name}` shadowed here with type `{ty}`"),
578                    );
579                    err.span_note(
580                        span,
581                        format!(
582                            "there's an earlier shadowed binding `{rcvr_name}` of type `{self_ty}` \
583                             that has method `{method_name}` available"
584                        ),
585                    );
586                }
587            }
588        }
589    }
590
591    fn report_no_match_method_error(
592        &self,
593        mut span: Span,
594        rcvr_ty: Ty<'tcx>,
595        item_ident: Ident,
596        expr_id: hir::HirId,
597        source: SelfSource<'tcx>,
598        args: Option<&'tcx [hir::Expr<'tcx>]>,
599        sugg_span: Span,
600        no_match_data: &mut NoMatchData<'tcx>,
601        expected: Expectation<'tcx>,
602        trait_missing_method: bool,
603        within_macro_span: Option<Span>,
604    ) -> ErrorGuaranteed {
605        let mode = no_match_data.mode;
606        let tcx = self.tcx;
607        let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
608        let mut ty_file = None;
609        let is_method = mode == Mode::MethodCall;
610        let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
611        let similar_candidate = no_match_data.similar_candidate;
612        let item_kind = if is_method {
613            "method"
614        } else if rcvr_ty.is_enum() {
615            "variant or associated item"
616        } else {
617            match (item_ident.as_str().chars().next(), rcvr_ty.is_fresh_ty()) {
618                (Some(name), false) if name.is_lowercase() => "function or associated item",
619                (Some(_), false) => "associated item",
620                (Some(_), true) | (None, false) => "variant or associated item",
621                (None, true) => "variant",
622            }
623        };
624
625        // We could pass the file for long types into these two, but it isn't strictly necessary
626        // given how targeted they are.
627        if let Err(guar) =
628            self.report_failed_method_call_on_range_end(tcx, rcvr_ty, source, span, item_ident)
629        {
630            return guar;
631        }
632        if let Err(guar) = self.report_failed_method_call_on_numerical_infer_var(
633            tcx,
634            rcvr_ty,
635            source,
636            span,
637            item_kind,
638            item_ident,
639            &mut ty_file,
640        ) {
641            return guar;
642        }
643        span = item_ident.span;
644
645        let is_write = sugg_span.ctxt().outer_expn_data().macro_def_id.is_some_and(|def_id| {
646            tcx.is_diagnostic_item(sym::write_macro, def_id)
647                || tcx.is_diagnostic_item(sym::writeln_macro, def_id)
648        }) && item_ident.name == sym::write_fmt;
649        let mut err = if is_write && let SelfSource::MethodCall(rcvr_expr) = source {
650            self.suggest_missing_writer(rcvr_ty, rcvr_expr, ty_file)
651        } else {
652            // Don't show expanded generic arguments when the method can't be found in any
653            // implementation (#81576).
654            let mut ty = rcvr_ty;
655            if let ty::Adt(def, generics) = rcvr_ty.kind() {
656                if generics.len() > 0 {
657                    let mut autoderef = self.autoderef(span, rcvr_ty).silence_errors();
658                    let candidate_found = autoderef.any(|(ty, _)| {
659                        if let ty::Adt(adt_def, _) = ty.kind() {
660                            self.tcx
661                                .inherent_impls(adt_def.did())
662                                .into_iter()
663                                .any(|def_id| self.associated_value(*def_id, item_ident).is_some())
664                        } else {
665                            false
666                        }
667                    });
668                    let has_deref = autoderef.step_count() > 0;
669                    if !candidate_found && !has_deref && unsatisfied_predicates.is_empty() {
670                        ty = self.tcx.at(span).type_of(def.did()).instantiate_identity();
671                    }
672                }
673            }
674
675            let mut err = self.dcx().create_err(NoAssociatedItem {
676                span,
677                item_kind,
678                item_ident,
679                ty_prefix: if trait_missing_method {
680                    // FIXME(mu001999) E0599 maybe not suitable here because it is for types
681                    Cow::from("trait")
682                } else {
683                    rcvr_ty.prefix_string(self.tcx)
684                },
685                ty,
686                trait_missing_method,
687            });
688
689            if is_method {
690                self.suggest_use_shadowed_binding_with_method(
691                    source, item_ident, rcvr_ty, &mut err,
692                );
693            }
694
695            // Check if we wrote `Self::Assoc(1)` as if it were a tuple ctor.
696            if let SelfSource::QPath(ty) = source
697                && let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind
698                && let Res::SelfTyAlias { alias_to: impl_def_id, .. } = path.res
699                && let DefKind::Impl { .. } = self.tcx.def_kind(impl_def_id)
700                && let Some(candidate) = tcx.associated_items(impl_def_id).find_by_ident_and_kind(
701                    self.tcx,
702                    item_ident,
703                    ty::AssocTag::Type,
704                    impl_def_id,
705                )
706                && let Some(adt_def) = tcx.type_of(candidate.def_id).skip_binder().ty_adt_def()
707                && adt_def.is_struct()
708                && adt_def.non_enum_variant().ctor_kind() == Some(CtorKind::Fn)
709            {
710                let def_path = tcx.def_path_str(adt_def.did());
711                err.span_suggestion(
712                    sugg_span,
713                    format!("to construct a value of type `{}`, use the explicit path", def_path),
714                    def_path,
715                    Applicability::MachineApplicable,
716                );
717            }
718
719            err
720        };
721
722        if tcx.sess.source_map().is_multiline(sugg_span) {
723            err.span_label(sugg_span.with_hi(span.lo()), "");
724        }
725        if let Some(within_macro_span) = within_macro_span {
726            err.span_label(within_macro_span, "due to this macro variable");
727        }
728
729        if rcvr_ty.references_error() {
730            err.downgrade_to_delayed_bug();
731        }
732
733        if matches!(source, SelfSource::QPath(_)) && args.is_some() {
734            self.find_builder_fn(&mut err, rcvr_ty, expr_id);
735        }
736
737        if tcx.ty_is_opaque_future(rcvr_ty) && item_ident.name == sym::poll {
738            let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
739            err.help(format!(
740                "method `poll` found on `Pin<&mut {ty_str}>`, \
741                see documentation for `std::pin::Pin`"
742            ));
743            err.help("self type must be pinned to call `Future::poll`, \
744                see https://rust-lang.github.io/async-book/04_pinning/01_chapter.html#pinning-in-practice"
745            );
746        }
747
748        if let Mode::MethodCall = mode
749            && let SelfSource::MethodCall(cal) = source
750        {
751            self.suggest_await_before_method(
752                &mut err,
753                item_ident,
754                rcvr_ty,
755                cal,
756                span,
757                expected.only_has_type(self),
758            );
759        }
760        if let Some(span) =
761            tcx.resolutions(()).confused_type_with_std_module.get(&span.with_parent(None))
762        {
763            err.span_suggestion(
764                span.shrink_to_lo(),
765                "you are looking for the module in `std`, not the primitive type",
766                "std::",
767                Applicability::MachineApplicable,
768            );
769        }
770
771        // on pointers, check if the method would exist on a reference
772        if let SelfSource::MethodCall(rcvr_expr) = source
773            && let ty::RawPtr(ty, ptr_mutbl) = *rcvr_ty.kind()
774            && let Ok(pick) = self.lookup_probe_for_diagnostic(
775                item_ident,
776                Ty::new_ref(tcx, ty::Region::new_error_misc(tcx), ty, ptr_mutbl),
777                self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id)),
778                ProbeScope::TraitsInScope,
779                None,
780            )
781            && let ty::Ref(_, _, sugg_mutbl) = *pick.self_ty.kind()
782            && (sugg_mutbl.is_not() || ptr_mutbl.is_mut())
783        {
784            let (method, method_anchor) = match sugg_mutbl {
785                Mutability::Not => {
786                    let method_anchor = match ptr_mutbl {
787                        Mutability::Not => "as_ref",
788                        Mutability::Mut => "as_ref-1",
789                    };
790                    ("as_ref", method_anchor)
791                }
792                Mutability::Mut => ("as_mut", "as_mut"),
793            };
794            err.span_note(
795                tcx.def_span(pick.item.def_id),
796                format!("the method `{item_ident}` exists on the type `{ty}`", ty = pick.self_ty),
797            );
798            let mut_str = ptr_mutbl.ptr_str();
799            err.note(format!(
800                "you might want to use the unsafe method `<*{mut_str} T>::{method}` to get \
801                an optional reference to the value behind the pointer"
802            ));
803            err.note(format!(
804                "read the documentation for `<*{mut_str} T>::{method}` and ensure you satisfy its \
805                safety preconditions before calling it to avoid undefined behavior: \
806                https://doc.rust-lang.org/std/primitive.pointer.html#method.{method_anchor}"
807            ));
808        }
809
810        let mut ty_span = match rcvr_ty.kind() {
811            ty::Param(param_type) => {
812                Some(param_type.span_from_generics(self.tcx, self.body_id.to_def_id()))
813            }
814            ty::Adt(def, _) if def.did().is_local() => Some(tcx.def_span(def.did())),
815            _ => None,
816        };
817
818        if let SelfSource::MethodCall(rcvr_expr) = source {
819            self.suggest_fn_call(&mut err, rcvr_expr, rcvr_ty, |output_ty| {
820                let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id));
821                let probe = self.lookup_probe_for_diagnostic(
822                    item_ident,
823                    output_ty,
824                    call_expr,
825                    ProbeScope::AllTraits,
826                    expected.only_has_type(self),
827                );
828                probe.is_ok()
829            });
830            self.note_internal_mutation_in_method(
831                &mut err,
832                rcvr_expr,
833                expected.to_option(self),
834                rcvr_ty,
835            );
836        }
837
838        let mut custom_span_label = false;
839
840        let static_candidates = &mut no_match_data.static_candidates;
841
842        // `static_candidates` may have same candidates appended by
843        // inherent and extension, which may result in incorrect
844        // diagnostic.
845        static_candidates.dedup();
846
847        if !static_candidates.is_empty() {
848            err.note(
849                "found the following associated functions; to be used as methods, \
850                 functions must have a `self` parameter",
851            );
852            err.span_label(span, "this is an associated function, not a method");
853            custom_span_label = true;
854        }
855        if static_candidates.len() == 1 {
856            self.suggest_associated_call_syntax(
857                &mut err,
858                static_candidates,
859                rcvr_ty,
860                source,
861                item_ident,
862                args,
863                sugg_span,
864            );
865            self.note_candidates_on_method_error(
866                rcvr_ty,
867                item_ident,
868                source,
869                args,
870                span,
871                &mut err,
872                static_candidates,
873                None,
874            );
875        } else if static_candidates.len() > 1 {
876            self.note_candidates_on_method_error(
877                rcvr_ty,
878                item_ident,
879                source,
880                args,
881                span,
882                &mut err,
883                static_candidates,
884                Some(sugg_span),
885            );
886        }
887
888        let mut bound_spans: SortedMap<Span, Vec<String>> = Default::default();
889        let mut restrict_type_params = false;
890        let mut suggested_derive = false;
891        let mut unsatisfied_bounds = false;
892        if item_ident.name == sym::count && self.is_slice_ty(rcvr_ty, span) {
893            let msg = "consider using `len` instead";
894            if let SelfSource::MethodCall(_expr) = source {
895                err.span_suggestion_short(span, msg, "len", Applicability::MachineApplicable);
896            } else {
897                err.span_label(span, msg);
898            }
899            if let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) {
900                let iterator_trait = self.tcx.def_path_str(iterator_trait);
901                err.note(format!(
902                    "`count` is defined on `{iterator_trait}`, which `{rcvr_ty}` does not implement"
903                ));
904            }
905        } else if self.impl_into_iterator_should_be_iterator(rcvr_ty, span, unsatisfied_predicates)
906        {
907            err.span_label(span, format!("`{rcvr_ty}` is not an iterator"));
908            if !span.in_external_macro(self.tcx.sess.source_map()) {
909                err.multipart_suggestion_verbose(
910                    "call `.into_iter()` first",
911                    vec![(span.shrink_to_lo(), format!("into_iter()."))],
912                    Applicability::MaybeIncorrect,
913                );
914            }
915            return err.emit();
916        } else if !unsatisfied_predicates.is_empty() && matches!(rcvr_ty.kind(), ty::Param(_)) {
917            // We special case the situation where we are looking for `_` in
918            // `<TypeParam as _>::method` because otherwise the machinery will look for blanket
919            // implementations that have unsatisfied trait bounds to suggest, leading us to claim
920            // things like "we're looking for a trait with method `cmp`, both `Iterator` and `Ord`
921            // have one, in order to implement `Ord` you need to restrict `TypeParam: FnPtr` so
922            // that `impl<T: FnPtr> Ord for T` can apply", which is not what we want. We have a type
923            // parameter, we want to directly say "`Ord::cmp` and `Iterator::cmp` exist, restrict
924            // `TypeParam: Ord` or `TypeParam: Iterator`"". That is done further down when calling
925            // `self.suggest_traits_to_import`, so we ignore the `unsatisfied_predicates`
926            // suggestions.
927        } else if !unsatisfied_predicates.is_empty() {
928            let mut type_params = FxIndexMap::default();
929
930            // Pick out the list of unimplemented traits on the receiver.
931            // This is used for custom error messages with the `#[rustc_on_unimplemented]` attribute.
932            let mut unimplemented_traits = FxIndexMap::default();
933            let mut unimplemented_traits_only = true;
934            for (predicate, _parent_pred, cause) in unsatisfied_predicates {
935                if let (ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)), Some(cause)) =
936                    (predicate.kind().skip_binder(), cause.as_ref())
937                {
938                    if p.trait_ref.self_ty() != rcvr_ty {
939                        // This is necessary, not just to keep the errors clean, but also
940                        // because our derived obligations can wind up with a trait ref that
941                        // requires a different param_env to be correctly compared.
942                        continue;
943                    }
944                    unimplemented_traits.entry(p.trait_ref.def_id).or_insert((
945                        predicate.kind().rebind(p),
946                        Obligation {
947                            cause: cause.clone(),
948                            param_env: self.param_env,
949                            predicate: *predicate,
950                            recursion_depth: 0,
951                        },
952                    ));
953                }
954            }
955
956            // Make sure that, if any traits other than the found ones were involved,
957            // we don't report an unimplemented trait.
958            // We don't want to say that `iter::Cloned` is not an iterator, just
959            // because of some non-Clone item being iterated over.
960            for (predicate, _parent_pred, _cause) in unsatisfied_predicates {
961                match predicate.kind().skip_binder() {
962                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))
963                        if unimplemented_traits.contains_key(&p.trait_ref.def_id) => {}
964                    _ => {
965                        unimplemented_traits_only = false;
966                        break;
967                    }
968                }
969            }
970
971            let mut collect_type_param_suggestions =
972                |self_ty: Ty<'tcx>, parent_pred: ty::Predicate<'tcx>, obligation: &str| {
973                    // We don't care about regions here, so it's fine to skip the binder here.
974                    if let (ty::Param(_), ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))) =
975                        (self_ty.kind(), parent_pred.kind().skip_binder())
976                    {
977                        let node = match p.trait_ref.self_ty().kind() {
978                            ty::Param(_) => {
979                                // Account for `fn` items like in `issue-35677.rs` to
980                                // suggest restricting its type params.
981                                Some(self.tcx.hir_node_by_def_id(self.body_id))
982                            }
983                            ty::Adt(def, _) => def
984                                .did()
985                                .as_local()
986                                .map(|def_id| self.tcx.hir_node_by_def_id(def_id)),
987                            _ => None,
988                        };
989                        if let Some(hir::Node::Item(hir::Item { kind, .. })) = node
990                            && let Some(g) = kind.generics()
991                        {
992                            let key = (
993                                g.tail_span_for_predicate_suggestion(),
994                                g.add_where_or_trailing_comma(),
995                            );
996                            type_params
997                                .entry(key)
998                                .or_insert_with(UnordSet::default)
999                                .insert(obligation.to_owned());
1000                            return true;
1001                        }
1002                    }
1003                    false
1004                };
1005            let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
1006                let msg = format!("`{}`", if obligation.len() > 50 { quiet } else { obligation });
1007                match self_ty.kind() {
1008                    // Point at the type that couldn't satisfy the bound.
1009                    ty::Adt(def, _) => {
1010                        bound_spans.get_mut_or_insert_default(tcx.def_span(def.did())).push(msg)
1011                    }
1012                    // Point at the trait object that couldn't satisfy the bound.
1013                    ty::Dynamic(preds, _, _) => {
1014                        for pred in preds.iter() {
1015                            match pred.skip_binder() {
1016                                ty::ExistentialPredicate::Trait(tr) => {
1017                                    bound_spans
1018                                        .get_mut_or_insert_default(tcx.def_span(tr.def_id))
1019                                        .push(msg.clone());
1020                                }
1021                                ty::ExistentialPredicate::Projection(_)
1022                                | ty::ExistentialPredicate::AutoTrait(_) => {}
1023                            }
1024                        }
1025                    }
1026                    // Point at the closure that couldn't satisfy the bound.
1027                    ty::Closure(def_id, _) => {
1028                        bound_spans
1029                            .get_mut_or_insert_default(tcx.def_span(*def_id))
1030                            .push(format!("`{quiet}`"));
1031                    }
1032                    _ => {}
1033                }
1034            };
1035            let mut format_pred = |pred: ty::Predicate<'tcx>| {
1036                let bound_predicate = pred.kind();
1037                match bound_predicate.skip_binder() {
1038                    ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
1039                        let pred = bound_predicate.rebind(pred);
1040                        // `<Foo as Iterator>::Item = String`.
1041                        let projection_term = pred.skip_binder().projection_term;
1042                        let quiet_projection_term = projection_term
1043                            .with_replaced_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
1044
1045                        let term = pred.skip_binder().term;
1046
1047                        let obligation = format!("{projection_term} = {term}");
1048                        let quiet = with_forced_trimmed_paths!(format!(
1049                            "{} = {}",
1050                            quiet_projection_term, term
1051                        ));
1052
1053                        bound_span_label(projection_term.self_ty(), &obligation, &quiet);
1054                        Some((obligation, projection_term.self_ty()))
1055                    }
1056                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
1057                        let p = poly_trait_ref.trait_ref;
1058                        let self_ty = p.self_ty();
1059                        let path = p.print_only_trait_path();
1060                        let obligation = format!("{self_ty}: {path}");
1061                        let quiet = with_forced_trimmed_paths!(format!("_: {}", path));
1062                        bound_span_label(self_ty, &obligation, &quiet);
1063                        Some((obligation, self_ty))
1064                    }
1065                    _ => None,
1066                }
1067            };
1068
1069            // Find all the requirements that come from a local `impl` block.
1070            let mut skip_list: UnordSet<_> = Default::default();
1071            let mut spanned_predicates = FxIndexMap::default();
1072            for (p, parent_p, cause) in unsatisfied_predicates {
1073                // Extract the predicate span and parent def id of the cause,
1074                // if we have one.
1075                let (item_def_id, cause_span) = match cause.as_ref().map(|cause| cause.code()) {
1076                    Some(ObligationCauseCode::ImplDerived(data)) => {
1077                        (data.impl_or_alias_def_id, data.span)
1078                    }
1079                    Some(
1080                        ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1081                        | ObligationCauseCode::WhereClause(def_id, span),
1082                    ) if !span.is_dummy() => (*def_id, *span),
1083                    _ => continue,
1084                };
1085
1086                // Don't point out the span of `WellFormed` predicates.
1087                if !matches!(
1088                    p.kind().skip_binder(),
1089                    ty::PredicateKind::Clause(
1090                        ty::ClauseKind::Projection(..) | ty::ClauseKind::Trait(..)
1091                    )
1092                ) {
1093                    continue;
1094                }
1095
1096                match self.tcx.hir_get_if_local(item_def_id) {
1097                    // Unmet obligation comes from a `derive` macro, point at it once to
1098                    // avoid multiple span labels pointing at the same place.
1099                    Some(Node::Item(hir::Item {
1100                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
1101                        ..
1102                    })) if matches!(
1103                        self_ty.span.ctxt().outer_expn_data().kind,
1104                        ExpnKind::Macro(MacroKind::Derive, _)
1105                    ) || matches!(
1106                        of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
1107                        Some(ExpnKind::Macro(MacroKind::Derive, _))
1108                    ) =>
1109                    {
1110                        let span = self_ty.span.ctxt().outer_expn_data().call_site;
1111                        let entry = spanned_predicates.entry(span);
1112                        let entry = entry.or_insert_with(|| {
1113                            (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1114                        });
1115                        entry.0.insert(span);
1116                        entry.1.insert((
1117                            span,
1118                            "unsatisfied trait bound introduced in this `derive` macro",
1119                        ));
1120                        entry.2.push(p);
1121                        skip_list.insert(p);
1122                    }
1123
1124                    // Unmet obligation coming from an `impl`.
1125                    Some(Node::Item(hir::Item {
1126                        kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
1127                        span: item_span,
1128                        ..
1129                    })) => {
1130                        let sized_pred =
1131                            unsatisfied_predicates.iter().any(|(pred, _, _)| {
1132                                match pred.kind().skip_binder() {
1133                                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
1134                                        self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
1135                                            && pred.polarity == ty::PredicatePolarity::Positive
1136                                    }
1137                                    _ => false,
1138                                }
1139                            });
1140                        for param in generics.params {
1141                            if param.span == cause_span && sized_pred {
1142                                let (sp, sugg) = match param.colon_span {
1143                                    Some(sp) => (sp.shrink_to_hi(), " ?Sized +"),
1144                                    None => (param.span.shrink_to_hi(), ": ?Sized"),
1145                                };
1146                                err.span_suggestion_verbose(
1147                                    sp,
1148                                    "consider relaxing the type parameter's implicit `Sized` bound",
1149                                    sugg,
1150                                    Applicability::MachineApplicable,
1151                                );
1152                            }
1153                        }
1154                        if let Some(pred) = parent_p {
1155                            // Done to add the "doesn't satisfy" `span_label`.
1156                            let _ = format_pred(*pred);
1157                        }
1158                        skip_list.insert(p);
1159                        let entry = spanned_predicates.entry(self_ty.span);
1160                        let entry = entry.or_insert_with(|| {
1161                            (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1162                        });
1163                        entry.2.push(p);
1164                        if cause_span != *item_span {
1165                            entry.0.insert(cause_span);
1166                            entry.1.insert((cause_span, "unsatisfied trait bound introduced here"));
1167                        } else {
1168                            if let Some(of_trait) = of_trait {
1169                                entry.0.insert(of_trait.trait_ref.path.span);
1170                            }
1171                            entry.0.insert(self_ty.span);
1172                        };
1173                        if let Some(of_trait) = of_trait {
1174                            entry.1.insert((of_trait.trait_ref.path.span, ""));
1175                        }
1176                        entry.1.insert((self_ty.span, ""));
1177                    }
1178                    Some(Node::Item(hir::Item {
1179                        kind: hir::ItemKind::Trait(_, rustc_ast::ast::IsAuto::Yes, ..),
1180                        span: item_span,
1181                        ..
1182                    })) => {
1183                        self.dcx().span_delayed_bug(
1184                            *item_span,
1185                            "auto trait is invoked with no method error, but no error reported?",
1186                        );
1187                    }
1188                    Some(
1189                        Node::Item(hir::Item {
1190                            kind:
1191                                hir::ItemKind::Trait(_, _, _, ident, ..)
1192                                | hir::ItemKind::TraitAlias(ident, ..),
1193                            ..
1194                        })
1195                        // We may also encounter unsatisfied GAT or method bounds
1196                        | Node::TraitItem(hir::TraitItem { ident, .. })
1197                        | Node::ImplItem(hir::ImplItem { ident, .. })
1198                    ) => {
1199                        skip_list.insert(p);
1200                        let entry = spanned_predicates.entry(ident.span);
1201                        let entry = entry.or_insert_with(|| {
1202                            (FxIndexSet::default(), FxIndexSet::default(), Vec::new())
1203                        });
1204                        entry.0.insert(cause_span);
1205                        entry.1.insert((ident.span, ""));
1206                        entry.1.insert((cause_span, "unsatisfied trait bound introduced here"));
1207                        entry.2.push(p);
1208                    }
1209                    _ => {
1210                        // It's possible to use well-formedness clauses to get obligations
1211                        // which point arbitrary items like ADTs, so there's no use in ICEing
1212                        // here if we find that the obligation originates from some other
1213                        // node that we don't handle.
1214                    }
1215                }
1216            }
1217            let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
1218            spanned_predicates.sort_by_key(|(span, _)| *span);
1219            for (_, (primary_spans, span_labels, predicates)) in spanned_predicates {
1220                let mut preds: Vec<_> = predicates
1221                    .iter()
1222                    .filter_map(|pred| format_pred(**pred))
1223                    .map(|(p, _)| format!("`{p}`"))
1224                    .collect();
1225                preds.sort();
1226                preds.dedup();
1227                let msg = if let [pred] = &preds[..] {
1228                    format!("trait bound {pred} was not satisfied")
1229                } else {
1230                    format!("the following trait bounds were not satisfied:\n{}", preds.join("\n"),)
1231                };
1232                let mut span: MultiSpan = primary_spans.into_iter().collect::<Vec<_>>().into();
1233                for (sp, label) in span_labels {
1234                    span.push_span_label(sp, label);
1235                }
1236                err.span_note(span, msg);
1237                unsatisfied_bounds = true;
1238            }
1239
1240            let mut suggested_bounds = UnordSet::default();
1241            // The requirements that didn't have an `impl` span to show.
1242            let mut bound_list = unsatisfied_predicates
1243                .iter()
1244                .filter_map(|(pred, parent_pred, _cause)| {
1245                    let mut suggested = false;
1246                    format_pred(*pred).map(|(p, self_ty)| {
1247                        if let Some(parent) = parent_pred
1248                            && suggested_bounds.contains(parent)
1249                        {
1250                            // We don't suggest `PartialEq` when we already suggest `Eq`.
1251                        } else if !suggested_bounds.contains(pred)
1252                            && collect_type_param_suggestions(self_ty, *pred, &p)
1253                        {
1254                            suggested = true;
1255                            suggested_bounds.insert(pred);
1256                        }
1257                        (
1258                            match parent_pred {
1259                                None => format!("`{p}`"),
1260                                Some(parent_pred) => match format_pred(*parent_pred) {
1261                                    None => format!("`{p}`"),
1262                                    Some((parent_p, _)) => {
1263                                        if !suggested
1264                                            && !suggested_bounds.contains(pred)
1265                                            && !suggested_bounds.contains(parent_pred)
1266                                            && collect_type_param_suggestions(
1267                                                self_ty,
1268                                                *parent_pred,
1269                                                &p,
1270                                            )
1271                                        {
1272                                            suggested_bounds.insert(pred);
1273                                        }
1274                                        format!("`{p}`\nwhich is required by `{parent_p}`")
1275                                    }
1276                                },
1277                            },
1278                            *pred,
1279                        )
1280                    })
1281                })
1282                .filter(|(_, pred)| !skip_list.contains(&pred))
1283                .map(|(t, _)| t)
1284                .enumerate()
1285                .collect::<Vec<(usize, String)>>();
1286
1287            if !matches!(rcvr_ty.peel_refs().kind(), ty::Param(_)) {
1288                for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
1289                    restrict_type_params = true;
1290                    // #74886: Sort here so that the output is always the same.
1291                    let obligations = obligations.into_sorted_stable_ord();
1292                    err.span_suggestion_verbose(
1293                        span,
1294                        format!(
1295                            "consider restricting the type parameter{s} to satisfy the trait \
1296                             bound{s}",
1297                            s = pluralize!(obligations.len())
1298                        ),
1299                        format!("{} {}", add_where_or_comma, obligations.join(", ")),
1300                        Applicability::MaybeIncorrect,
1301                    );
1302                }
1303            }
1304
1305            bound_list.sort_by(|(_, a), (_, b)| a.cmp(b)); // Sort alphabetically.
1306            bound_list.dedup_by(|(_, a), (_, b)| a == b); // #35677
1307            bound_list.sort_by_key(|(pos, _)| *pos); // Keep the original predicate order.
1308
1309            if !bound_list.is_empty() || !skip_list.is_empty() {
1310                let bound_list =
1311                    bound_list.into_iter().map(|(_, path)| path).collect::<Vec<_>>().join("\n");
1312                let actual_prefix = rcvr_ty.prefix_string(self.tcx);
1313                info!("unimplemented_traits.len() == {}", unimplemented_traits.len());
1314                let (primary_message, label, notes) = if unimplemented_traits.len() == 1
1315                    && unimplemented_traits_only
1316                {
1317                    unimplemented_traits
1318                        .into_iter()
1319                        .next()
1320                        .map(|(_, (trait_ref, obligation))| {
1321                            if trait_ref.self_ty().references_error() || rcvr_ty.references_error()
1322                            {
1323                                // Avoid crashing.
1324                                return (None, None, Vec::new());
1325                            }
1326                            let OnUnimplementedNote { message, label, notes, .. } = self
1327                                .err_ctxt()
1328                                .on_unimplemented_note(trait_ref, &obligation, err.long_ty_path());
1329                            (message, label, notes)
1330                        })
1331                        .unwrap()
1332                } else {
1333                    (None, None, Vec::new())
1334                };
1335                let primary_message = primary_message.unwrap_or_else(|| {
1336                    let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1337                    format!(
1338                        "the {item_kind} `{item_ident}` exists for {actual_prefix} `{ty_str}`, \
1339                         but its trait bounds were not satisfied"
1340                    )
1341                });
1342                err.primary_message(primary_message);
1343                if let Some(label) = label {
1344                    custom_span_label = true;
1345                    err.span_label(span, label);
1346                }
1347                if !bound_list.is_empty() {
1348                    err.note(format!(
1349                        "the following trait bounds were not satisfied:\n{bound_list}"
1350                    ));
1351                }
1352                for note in notes {
1353                    err.note(note);
1354                }
1355
1356                suggested_derive = self.suggest_derive(&mut err, unsatisfied_predicates);
1357
1358                unsatisfied_bounds = true;
1359            }
1360        } else if let ty::Adt(def, targs) = rcvr_ty.kind()
1361            && let SelfSource::MethodCall(rcvr_expr) = source
1362        {
1363            // This is useful for methods on arbitrary self types that might have a simple
1364            // mutability difference, like calling a method on `Pin<&mut Self>` that is on
1365            // `Pin<&Self>`.
1366            if targs.len() == 1 {
1367                let mut item_segment = hir::PathSegment::invalid();
1368                item_segment.ident = item_ident;
1369                for t in [Ty::new_mut_ref, Ty::new_imm_ref, |_, _, t| t] {
1370                    let new_args =
1371                        tcx.mk_args_from_iter(targs.iter().map(|arg| match arg.as_type() {
1372                            Some(ty) => ty::GenericArg::from(t(
1373                                tcx,
1374                                tcx.lifetimes.re_erased,
1375                                ty.peel_refs(),
1376                            )),
1377                            _ => arg,
1378                        }));
1379                    let rcvr_ty = Ty::new_adt(tcx, *def, new_args);
1380                    if let Ok(method) = self.lookup_method_for_diagnostic(
1381                        rcvr_ty,
1382                        &item_segment,
1383                        span,
1384                        tcx.parent_hir_node(rcvr_expr.hir_id).expect_expr(),
1385                        rcvr_expr,
1386                    ) {
1387                        err.span_note(
1388                            tcx.def_span(method.def_id),
1389                            format!("{item_kind} is available for `{rcvr_ty}`"),
1390                        );
1391                    }
1392                }
1393            }
1394        }
1395
1396        let mut find_candidate_for_method = false;
1397
1398        let mut label_span_not_found = |err: &mut Diag<'_>| {
1399            let ty_str = self.tcx.short_string(rcvr_ty, err.long_ty_path());
1400            if unsatisfied_predicates.is_empty() {
1401                err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
1402                let is_string_or_ref_str = match rcvr_ty.kind() {
1403                    ty::Ref(_, ty, _) => {
1404                        ty.is_str()
1405                            || matches!(
1406                                ty.kind(),
1407                                ty::Adt(adt, _) if self.tcx.is_lang_item(adt.did(), LangItem::String)
1408                            )
1409                    }
1410                    ty::Adt(adt, _) => self.tcx.is_lang_item(adt.did(), LangItem::String),
1411                    _ => false,
1412                };
1413                if is_string_or_ref_str && item_ident.name == sym::iter {
1414                    err.span_suggestion_verbose(
1415                        item_ident.span,
1416                        "because of the in-memory representation of `&str`, to obtain \
1417                         an `Iterator` over each of its codepoint use method `chars`",
1418                        "chars",
1419                        Applicability::MachineApplicable,
1420                    );
1421                }
1422                if let ty::Adt(adt, _) = rcvr_ty.kind() {
1423                    let mut inherent_impls_candidate = self
1424                        .tcx
1425                        .inherent_impls(adt.did())
1426                        .into_iter()
1427                        .copied()
1428                        .filter(|def_id| {
1429                            if let Some(assoc) = self.associated_value(*def_id, item_ident) {
1430                                // Check for both mode is the same so we avoid suggesting
1431                                // incorrect associated item.
1432                                match (mode, assoc.is_method(), source) {
1433                                    (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
1434                                        // We check that the suggest type is actually
1435                                        // different from the received one
1436                                        // So we avoid suggestion method with Box<Self>
1437                                        // for instance
1438                                        self.tcx.at(span).type_of(*def_id).instantiate_identity()
1439                                            != rcvr_ty
1440                                    }
1441                                    (Mode::Path, false, _) => true,
1442                                    _ => false,
1443                                }
1444                            } else {
1445                                false
1446                            }
1447                        })
1448                        .collect::<Vec<_>>();
1449                    if !inherent_impls_candidate.is_empty() {
1450                        inherent_impls_candidate.sort_by_key(|id| self.tcx.def_path_str(id));
1451                        inherent_impls_candidate.dedup();
1452
1453                        // number of types to show at most
1454                        let limit = if inherent_impls_candidate.len() == 5 { 5 } else { 4 };
1455                        let type_candidates = inherent_impls_candidate
1456                            .iter()
1457                            .take(limit)
1458                            .map(|impl_item| {
1459                                format!(
1460                                    "- `{}`",
1461                                    self.tcx.at(span).type_of(*impl_item).instantiate_identity()
1462                                )
1463                            })
1464                            .collect::<Vec<_>>()
1465                            .join("\n");
1466                        let additional_types = if inherent_impls_candidate.len() > limit {
1467                            format!("\nand {} more types", inherent_impls_candidate.len() - limit)
1468                        } else {
1469                            "".to_string()
1470                        };
1471                        err.note(format!(
1472                            "the {item_kind} was found for\n{type_candidates}{additional_types}"
1473                        ));
1474                        find_candidate_for_method = mode == Mode::MethodCall;
1475                    }
1476                }
1477            } else {
1478                let ty_str =
1479                    if ty_str.len() > 50 { String::new() } else { format!("on `{ty_str}` ") };
1480                err.span_label(
1481                    span,
1482                    format!("{item_kind} cannot be called {ty_str}due to unsatisfied trait bounds"),
1483                );
1484            }
1485        };
1486
1487        // If the method name is the name of a field with a function or closure type,
1488        // give a helping note that it has to be called as `(x.f)(...)`.
1489        if let SelfSource::MethodCall(expr) = source {
1490            if !self.suggest_calling_field_as_fn(span, rcvr_ty, expr, item_ident, &mut err)
1491                && similar_candidate.is_none()
1492                && !custom_span_label
1493            {
1494                label_span_not_found(&mut err);
1495            }
1496        } else if !custom_span_label {
1497            label_span_not_found(&mut err);
1498        }
1499
1500        let confusable_suggested = self.confusable_method_name(
1501            &mut err,
1502            rcvr_ty,
1503            item_ident,
1504            args.map(|args| {
1505                args.iter()
1506                    .map(|expr| {
1507                        self.node_ty_opt(expr.hir_id).unwrap_or_else(|| self.next_ty_var(expr.span))
1508                    })
1509                    .collect()
1510            }),
1511        );
1512
1513        // Don't suggest (for example) `expr.field.clone()` if `expr.clone()`
1514        // can't be called due to `typeof(expr): Clone` not holding.
1515        if unsatisfied_predicates.is_empty() {
1516            self.suggest_calling_method_on_field(
1517                &mut err,
1518                source,
1519                span,
1520                rcvr_ty,
1521                item_ident,
1522                expected.only_has_type(self),
1523            );
1524        }
1525
1526        self.suggest_unwrapping_inner_self(&mut err, source, rcvr_ty, item_ident);
1527
1528        for (span, mut bounds) in bound_spans {
1529            if !tcx.sess.source_map().is_span_accessible(span) {
1530                continue;
1531            }
1532            bounds.sort();
1533            bounds.dedup();
1534            let pre = if Some(span) == ty_span {
1535                ty_span.take();
1536                format!(
1537                    "{item_kind} `{item_ident}` not found for this {} because it ",
1538                    rcvr_ty.prefix_string(self.tcx)
1539                )
1540            } else {
1541                String::new()
1542            };
1543            let msg = match &bounds[..] {
1544                [bound] => format!("{pre}doesn't satisfy {bound}"),
1545                bounds if bounds.len() > 4 => format!("doesn't satisfy {} bounds", bounds.len()),
1546                [bounds @ .., last] => {
1547                    format!("{pre}doesn't satisfy {} or {last}", bounds.join(", "))
1548                }
1549                [] => unreachable!(),
1550            };
1551            err.span_label(span, msg);
1552        }
1553        if let Some(span) = ty_span {
1554            err.span_label(
1555                span,
1556                format!(
1557                    "{item_kind} `{item_ident}` not found for this {}",
1558                    rcvr_ty.prefix_string(self.tcx)
1559                ),
1560            );
1561        }
1562
1563        if rcvr_ty.is_numeric() && rcvr_ty.is_fresh()
1564            || restrict_type_params
1565            || suggested_derive
1566            || self.lookup_alternative_tuple_impls(&mut err, &unsatisfied_predicates)
1567        {
1568        } else {
1569            self.suggest_traits_to_import(
1570                &mut err,
1571                span,
1572                rcvr_ty,
1573                item_ident,
1574                args.map(|args| args.len() + 1),
1575                source,
1576                no_match_data.out_of_scope_traits.clone(),
1577                static_candidates,
1578                unsatisfied_bounds,
1579                expected.only_has_type(self),
1580                trait_missing_method,
1581            );
1582        }
1583
1584        // Don't emit a suggestion if we found an actual method
1585        // that had unsatisfied trait bounds
1586        if unsatisfied_predicates.is_empty() && rcvr_ty.is_enum() {
1587            let adt_def = rcvr_ty.ty_adt_def().expect("enum is not an ADT");
1588            if let Some(var_name) = edit_distance::find_best_match_for_name(
1589                &adt_def.variants().iter().map(|s| s.name).collect::<Vec<_>>(),
1590                item_ident.name,
1591                None,
1592            ) && let Some(variant) = adt_def.variants().iter().find(|s| s.name == var_name)
1593            {
1594                let mut suggestion = vec![(span, var_name.to_string())];
1595                if let SelfSource::QPath(ty) = source
1596                    && let hir::Node::Expr(ref path_expr) = self.tcx.parent_hir_node(ty.hir_id)
1597                    && let hir::ExprKind::Path(_) = path_expr.kind
1598                    && let hir::Node::Stmt(&hir::Stmt { kind: hir::StmtKind::Semi(parent), .. })
1599                    | hir::Node::Expr(parent) = self.tcx.parent_hir_node(path_expr.hir_id)
1600                {
1601                    let replacement_span =
1602                        if let hir::ExprKind::Call(..) | hir::ExprKind::Struct(..) = parent.kind {
1603                            // We want to replace the parts that need to go, like `()` and `{}`.
1604                            span.with_hi(parent.span.hi())
1605                        } else {
1606                            span
1607                        };
1608                    match (variant.ctor, parent.kind) {
1609                        (None, hir::ExprKind::Struct(..)) => {
1610                            // We want a struct and we have a struct. We won't suggest changing
1611                            // the fields (at least for now).
1612                            suggestion = vec![(span, var_name.to_string())];
1613                        }
1614                        (None, _) => {
1615                            // struct
1616                            suggestion = vec![(
1617                                replacement_span,
1618                                if variant.fields.is_empty() {
1619                                    format!("{var_name} {{}}")
1620                                } else {
1621                                    format!(
1622                                        "{var_name} {{ {} }}",
1623                                        variant
1624                                            .fields
1625                                            .iter()
1626                                            .map(|f| format!("{}: /* value */", f.name))
1627                                            .collect::<Vec<_>>()
1628                                            .join(", ")
1629                                    )
1630                                },
1631                            )];
1632                        }
1633                        (Some((hir::def::CtorKind::Const, _)), _) => {
1634                            // unit, remove the `()`.
1635                            suggestion = vec![(replacement_span, var_name.to_string())];
1636                        }
1637                        (
1638                            Some((hir::def::CtorKind::Fn, def_id)),
1639                            hir::ExprKind::Call(rcvr, args),
1640                        ) => {
1641                            let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity();
1642                            let inputs = fn_sig.inputs().skip_binder();
1643                            // FIXME: reuse the logic for "change args" suggestion to account for types
1644                            // involved and detect things like substitution.
1645                            match (inputs, args) {
1646                                (inputs, []) => {
1647                                    // Add arguments.
1648                                    suggestion.push((
1649                                        rcvr.span.shrink_to_hi().with_hi(parent.span.hi()),
1650                                        format!(
1651                                            "({})",
1652                                            inputs
1653                                                .iter()
1654                                                .map(|i| format!("/* {i} */"))
1655                                                .collect::<Vec<String>>()
1656                                                .join(", ")
1657                                        ),
1658                                    ));
1659                                }
1660                                (_, [arg]) if inputs.len() != args.len() => {
1661                                    // Replace arguments.
1662                                    suggestion.push((
1663                                        arg.span,
1664                                        inputs
1665                                            .iter()
1666                                            .map(|i| format!("/* {i} */"))
1667                                            .collect::<Vec<String>>()
1668                                            .join(", "),
1669                                    ));
1670                                }
1671                                (_, [arg_start, .., arg_end]) if inputs.len() != args.len() => {
1672                                    // Replace arguments.
1673                                    suggestion.push((
1674                                        arg_start.span.to(arg_end.span),
1675                                        inputs
1676                                            .iter()
1677                                            .map(|i| format!("/* {i} */"))
1678                                            .collect::<Vec<String>>()
1679                                            .join(", "),
1680                                    ));
1681                                }
1682                                // Argument count is the same, keep as is.
1683                                _ => {}
1684                            }
1685                        }
1686                        (Some((hir::def::CtorKind::Fn, def_id)), _) => {
1687                            let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity();
1688                            let inputs = fn_sig.inputs().skip_binder();
1689                            suggestion = vec![(
1690                                replacement_span,
1691                                format!(
1692                                    "{var_name}({})",
1693                                    inputs
1694                                        .iter()
1695                                        .map(|i| format!("/* {i} */"))
1696                                        .collect::<Vec<String>>()
1697                                        .join(", ")
1698                                ),
1699                            )];
1700                        }
1701                    }
1702                }
1703                err.multipart_suggestion_verbose(
1704                    "there is a variant with a similar name",
1705                    suggestion,
1706                    Applicability::HasPlaceholders,
1707                );
1708            }
1709        }
1710
1711        if let Some(similar_candidate) = similar_candidate {
1712            // Don't emit a suggestion if we found an actual method
1713            // that had unsatisfied trait bounds
1714            if unsatisfied_predicates.is_empty()
1715                // ...or if we already suggested that name because of `rustc_confusable` annotation
1716                && Some(similar_candidate.name()) != confusable_suggested
1717                // and if we aren't in an expansion.
1718                && !span.from_expansion()
1719            {
1720                self.find_likely_intended_associated_item(
1721                    &mut err,
1722                    similar_candidate,
1723                    span,
1724                    args,
1725                    mode,
1726                );
1727            }
1728        }
1729
1730        if !find_candidate_for_method {
1731            self.lookup_segments_chain_for_no_match_method(
1732                &mut err,
1733                item_ident,
1734                item_kind,
1735                source,
1736                no_match_data,
1737            );
1738        }
1739
1740        self.note_derefed_ty_has_method(&mut err, source, rcvr_ty, item_ident, expected);
1741        err.emit()
1742    }
1743
1744    /// If the predicate failure is caused by an unmet bound on a tuple, recheck if the bound would
1745    /// succeed if all the types on the tuple had no borrows. This is a common problem for libraries
1746    /// like Bevy and ORMs, which rely heavily on traits being implemented on tuples.
1747    fn lookup_alternative_tuple_impls(
1748        &self,
1749        err: &mut Diag<'_>,
1750        unsatisfied_predicates: &[(
1751            ty::Predicate<'tcx>,
1752            Option<ty::Predicate<'tcx>>,
1753            Option<ObligationCause<'tcx>>,
1754        )],
1755    ) -> bool {
1756        let mut found_tuple = false;
1757        for (pred, root, _ob) in unsatisfied_predicates {
1758            let mut preds = vec![pred];
1759            if let Some(root) = root {
1760                // We will look at both the current predicate and the root predicate that caused it
1761                // to be needed. If calling something like `<(A, &B)>::default()`, then `pred` is
1762                // `&B: Default` and `root` is `(A, &B): Default`, which is the one we are checking
1763                // for further down, so we check both.
1764                preds.push(root);
1765            }
1766            for pred in preds {
1767                if let Some(clause) = pred.as_clause()
1768                    && let Some(clause) = clause.as_trait_clause()
1769                    && let ty = clause.self_ty().skip_binder()
1770                    && let ty::Tuple(types) = ty.kind()
1771                {
1772                    let path = clause.skip_binder().trait_ref.print_only_trait_path();
1773                    let def_id = clause.def_id();
1774                    let ty = Ty::new_tup(
1775                        self.tcx,
1776                        self.tcx.mk_type_list_from_iter(types.iter().map(|ty| ty.peel_refs())),
1777                    );
1778                    let args = ty::GenericArgs::for_item(self.tcx, def_id, |param, _| {
1779                        if param.index == 0 {
1780                            ty.into()
1781                        } else {
1782                            self.infcx.var_for_def(DUMMY_SP, param)
1783                        }
1784                    });
1785                    if self
1786                        .infcx
1787                        .type_implements_trait(def_id, args, self.param_env)
1788                        .must_apply_modulo_regions()
1789                    {
1790                        // "`Trait` is implemented for `(A, B)` but not for `(A, &B)`"
1791                        let mut msg = DiagStyledString::normal(format!("`{path}` "));
1792                        msg.push_highlighted("is");
1793                        msg.push_normal(" implemented for `(");
1794                        let len = types.len();
1795                        for (i, t) in types.iter().enumerate() {
1796                            msg.push(
1797                                format!("{}", with_forced_trimmed_paths!(t.peel_refs())),
1798                                t.peel_refs() != t,
1799                            );
1800                            if i < len - 1 {
1801                                msg.push_normal(", ");
1802                            }
1803                        }
1804                        msg.push_normal(")` but ");
1805                        msg.push_highlighted("not");
1806                        msg.push_normal(" for `(");
1807                        for (i, t) in types.iter().enumerate() {
1808                            msg.push(
1809                                format!("{}", with_forced_trimmed_paths!(t)),
1810                                t.peel_refs() != t,
1811                            );
1812                            if i < len - 1 {
1813                                msg.push_normal(", ");
1814                            }
1815                        }
1816                        msg.push_normal(")`");
1817
1818                        // Find the span corresponding to the impl that was found to point at it.
1819                        if let Some(impl_span) = self
1820                            .tcx
1821                            .all_impls(def_id)
1822                            .filter(|&impl_def_id| {
1823                                let header = self.tcx.impl_trait_header(impl_def_id).unwrap();
1824                                let trait_ref = header.trait_ref.instantiate(
1825                                    self.tcx,
1826                                    self.infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1827                                );
1828
1829                                let value = ty::fold_regions(self.tcx, ty, |_, _| {
1830                                    self.tcx.lifetimes.re_erased
1831                                });
1832                                // FIXME: Don't bother dealing with non-lifetime binders here...
1833                                if value.has_escaping_bound_vars() {
1834                                    return false;
1835                                }
1836                                self.infcx.can_eq(ty::ParamEnv::empty(), trait_ref.self_ty(), value)
1837                                    && header.polarity == ty::ImplPolarity::Positive
1838                            })
1839                            .map(|impl_def_id| self.tcx.def_span(impl_def_id))
1840                            .next()
1841                        {
1842                            err.highlighted_span_note(impl_span, msg.0);
1843                        } else {
1844                            err.highlighted_note(msg.0);
1845                        }
1846                        found_tuple = true;
1847                    }
1848                    // If `pred` was already on the tuple, we don't need to look at the root
1849                    // obligation too.
1850                    break;
1851                }
1852            }
1853        }
1854        found_tuple
1855    }
1856
1857    /// If an appropriate error source is not found, check method chain for possible candidates
1858    fn lookup_segments_chain_for_no_match_method(
1859        &self,
1860        err: &mut Diag<'_>,
1861        item_name: Ident,
1862        item_kind: &str,
1863        source: SelfSource<'tcx>,
1864        no_match_data: &NoMatchData<'tcx>,
1865    ) {
1866        if no_match_data.unsatisfied_predicates.is_empty()
1867            && let Mode::MethodCall = no_match_data.mode
1868            && let SelfSource::MethodCall(mut source_expr) = source
1869        {
1870            let mut stack_methods = vec![];
1871            while let hir::ExprKind::MethodCall(_path_segment, rcvr_expr, _args, method_span) =
1872                source_expr.kind
1873            {
1874                // Pop the matching receiver, to align on it's notional span
1875                if let Some(prev_match) = stack_methods.pop() {
1876                    err.span_label(
1877                        method_span,
1878                        format!("{item_kind} `{item_name}` is available on `{prev_match}`"),
1879                    );
1880                }
1881                let rcvr_ty = self.resolve_vars_if_possible(
1882                    self.typeck_results
1883                        .borrow()
1884                        .expr_ty_adjusted_opt(rcvr_expr)
1885                        .unwrap_or(Ty::new_misc_error(self.tcx)),
1886                );
1887
1888                let Ok(candidates) = self.probe_for_name_many(
1889                    Mode::MethodCall,
1890                    item_name,
1891                    None,
1892                    IsSuggestion(true),
1893                    rcvr_ty,
1894                    source_expr.hir_id,
1895                    ProbeScope::TraitsInScope,
1896                ) else {
1897                    return;
1898                };
1899
1900                // FIXME: `probe_for_name_many` searches for methods in inherent implementations,
1901                // so it may return a candidate that doesn't belong to this `revr_ty`. We need to
1902                // check whether the instantiated type matches the received one.
1903                for _matched_method in candidates {
1904                    // found a match, push to stack
1905                    stack_methods.push(rcvr_ty);
1906                }
1907                source_expr = rcvr_expr;
1908            }
1909            // If there is a match at the start of the chain, add a label for it too!
1910            if let Some(prev_match) = stack_methods.pop() {
1911                err.span_label(
1912                    source_expr.span,
1913                    format!("{item_kind} `{item_name}` is available on `{prev_match}`"),
1914                );
1915            }
1916        }
1917    }
1918
1919    fn find_likely_intended_associated_item(
1920        &self,
1921        err: &mut Diag<'_>,
1922        similar_candidate: ty::AssocItem,
1923        span: Span,
1924        args: Option<&'tcx [hir::Expr<'tcx>]>,
1925        mode: Mode,
1926    ) {
1927        let tcx = self.tcx;
1928        let def_kind = similar_candidate.as_def_kind();
1929        let an = self.tcx.def_kind_descr_article(def_kind, similar_candidate.def_id);
1930        let similar_candidate_name = similar_candidate.name();
1931        let msg = format!(
1932            "there is {an} {} `{}` with a similar name",
1933            self.tcx.def_kind_descr(def_kind, similar_candidate.def_id),
1934            similar_candidate_name,
1935        );
1936        // Methods are defined within the context of a struct and their first parameter
1937        // is always `self`, which represents the instance of the struct the method is
1938        // being called on Associated functions don’t take self as a parameter and they are
1939        // not methods because they don’t have an instance of the struct to work with.
1940        if def_kind == DefKind::AssocFn {
1941            let ty_args = self.infcx.fresh_args_for_item(span, similar_candidate.def_id);
1942            let fn_sig = tcx.fn_sig(similar_candidate.def_id).instantiate(tcx, ty_args);
1943            let fn_sig = self.instantiate_binder_with_fresh_vars(
1944                span,
1945                BoundRegionConversionTime::FnCall,
1946                fn_sig,
1947            );
1948            if similar_candidate.is_method() {
1949                if let Some(args) = args
1950                    && fn_sig.inputs()[1..].len() == args.len()
1951                {
1952                    // We found a method with the same number of arguments as the method
1953                    // call expression the user wrote.
1954                    err.span_suggestion_verbose(
1955                        span,
1956                        msg,
1957                        similar_candidate_name,
1958                        Applicability::MaybeIncorrect,
1959                    );
1960                } else {
1961                    // We found a method but either the expression is not a method call or
1962                    // the argument count didn't match.
1963                    err.span_help(
1964                        tcx.def_span(similar_candidate.def_id),
1965                        format!(
1966                            "{msg}{}",
1967                            if let None = args { "" } else { ", but with different arguments" },
1968                        ),
1969                    );
1970                }
1971            } else if let Some(args) = args
1972                && fn_sig.inputs().len() == args.len()
1973            {
1974                // We have fn call expression and the argument count match the associated
1975                // function we found.
1976                err.span_suggestion_verbose(
1977                    span,
1978                    msg,
1979                    similar_candidate_name,
1980                    Applicability::MaybeIncorrect,
1981                );
1982            } else {
1983                err.span_help(tcx.def_span(similar_candidate.def_id), msg);
1984            }
1985        } else if let Mode::Path = mode
1986            && args.unwrap_or(&[]).is_empty()
1987        {
1988            // We have an associated item syntax and we found something that isn't an fn.
1989            err.span_suggestion_verbose(
1990                span,
1991                msg,
1992                similar_candidate_name,
1993                Applicability::MaybeIncorrect,
1994            );
1995        } else {
1996            // The expression is a function or method call, but the item we found is an
1997            // associated const or type.
1998            err.span_help(tcx.def_span(similar_candidate.def_id), msg);
1999        }
2000    }
2001
2002    pub(crate) fn confusable_method_name(
2003        &self,
2004        err: &mut Diag<'_>,
2005        rcvr_ty: Ty<'tcx>,
2006        item_name: Ident,
2007        call_args: Option<Vec<Ty<'tcx>>>,
2008    ) -> Option<Symbol> {
2009        if let ty::Adt(adt, adt_args) = rcvr_ty.kind() {
2010            for inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter() {
2011                for inherent_method in
2012                    self.tcx.associated_items(inherent_impl_did).in_definition_order()
2013                {
2014                    if let Some(candidates) = find_attr!(self.tcx.get_all_attrs(inherent_method.def_id), AttributeKind::Confusables{symbols, ..} => symbols)
2015                        && candidates.contains(&item_name.name)
2016                        && inherent_method.is_fn()
2017                    {
2018                        let args =
2019                            ty::GenericArgs::identity_for_item(self.tcx, inherent_method.def_id)
2020                                .rebase_onto(
2021                                    self.tcx,
2022                                    inherent_method.container_id(self.tcx),
2023                                    adt_args,
2024                                );
2025                        let fn_sig =
2026                            self.tcx.fn_sig(inherent_method.def_id).instantiate(self.tcx, args);
2027                        let fn_sig = self.instantiate_binder_with_fresh_vars(
2028                            item_name.span,
2029                            BoundRegionConversionTime::FnCall,
2030                            fn_sig,
2031                        );
2032                        let name = inherent_method.name();
2033                        if let Some(ref args) = call_args
2034                            && fn_sig.inputs()[1..]
2035                                .iter()
2036                                .zip(args.into_iter())
2037                                .all(|(expected, found)| self.may_coerce(*expected, *found))
2038                            && fn_sig.inputs()[1..].len() == args.len()
2039                        {
2040                            err.span_suggestion_verbose(
2041                                item_name.span,
2042                                format!("you might have meant to use `{}`", name),
2043                                name,
2044                                Applicability::MaybeIncorrect,
2045                            );
2046                            return Some(name);
2047                        } else if let None = call_args {
2048                            err.span_note(
2049                                self.tcx.def_span(inherent_method.def_id),
2050                                format!("you might have meant to use method `{}`", name),
2051                            );
2052                            return Some(name);
2053                        }
2054                    }
2055                }
2056            }
2057        }
2058        None
2059    }
2060    fn note_candidates_on_method_error(
2061        &self,
2062        rcvr_ty: Ty<'tcx>,
2063        item_name: Ident,
2064        self_source: SelfSource<'tcx>,
2065        args: Option<&'tcx [hir::Expr<'tcx>]>,
2066        span: Span,
2067        err: &mut Diag<'_>,
2068        sources: &mut Vec<CandidateSource>,
2069        sugg_span: Option<Span>,
2070    ) {
2071        sources.sort_by_key(|source| match source {
2072            CandidateSource::Trait(id) => (0, self.tcx.def_path_str(id)),
2073            CandidateSource::Impl(id) => (1, self.tcx.def_path_str(id)),
2074        });
2075        sources.dedup();
2076        // Dynamic limit to avoid hiding just one candidate, which is silly.
2077        let limit = if sources.len() == 5 { 5 } else { 4 };
2078
2079        let mut suggs = vec![];
2080        for (idx, source) in sources.iter().take(limit).enumerate() {
2081            match *source {
2082                CandidateSource::Impl(impl_did) => {
2083                    // Provide the best span we can. Use the item, if local to crate, else
2084                    // the impl, if local to crate (item may be defaulted), else nothing.
2085                    let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
2086                        let impl_trait_ref = self.tcx.impl_trait_ref(impl_did)?;
2087                        self.associated_value(impl_trait_ref.skip_binder().def_id, item_name)
2088                    }) else {
2089                        continue;
2090                    };
2091
2092                    let note_span = if item.def_id.is_local() {
2093                        Some(self.tcx.def_span(item.def_id))
2094                    } else if impl_did.is_local() {
2095                        Some(self.tcx.def_span(impl_did))
2096                    } else {
2097                        None
2098                    };
2099
2100                    let impl_ty = self.tcx.at(span).type_of(impl_did).instantiate_identity();
2101
2102                    let insertion = match self.tcx.impl_trait_ref(impl_did) {
2103                        None => String::new(),
2104                        Some(trait_ref) => {
2105                            format!(
2106                                " of the trait `{}`",
2107                                self.tcx.def_path_str(trait_ref.skip_binder().def_id)
2108                            )
2109                        }
2110                    };
2111
2112                    let (note_str, idx) = if sources.len() > 1 {
2113                        (
2114                            format!(
2115                                "candidate #{} is defined in an impl{} for the type `{}`",
2116                                idx + 1,
2117                                insertion,
2118                                impl_ty,
2119                            ),
2120                            Some(idx + 1),
2121                        )
2122                    } else {
2123                        (
2124                            format!(
2125                                "the candidate is defined in an impl{insertion} for the type `{impl_ty}`",
2126                            ),
2127                            None,
2128                        )
2129                    };
2130                    if let Some(note_span) = note_span {
2131                        // We have a span pointing to the method. Show note with snippet.
2132                        err.span_note(note_span, note_str);
2133                    } else {
2134                        err.note(note_str);
2135                    }
2136                    if let Some(sugg_span) = sugg_span
2137                        && let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did)
2138                        && let Some(sugg) = print_disambiguation_help(
2139                            self.tcx,
2140                            err,
2141                            self_source,
2142                            args,
2143                            trait_ref
2144                                .instantiate(
2145                                    self.tcx,
2146                                    self.fresh_args_for_item(sugg_span, impl_did),
2147                                )
2148                                .with_replaced_self_ty(self.tcx, rcvr_ty),
2149                            idx,
2150                            sugg_span,
2151                            item,
2152                        )
2153                    {
2154                        suggs.push(sugg);
2155                    }
2156                }
2157                CandidateSource::Trait(trait_did) => {
2158                    let Some(item) = self.associated_value(trait_did, item_name) else { continue };
2159                    let item_span = self.tcx.def_span(item.def_id);
2160                    let idx = if sources.len() > 1 {
2161                        let msg = format!(
2162                            "candidate #{} is defined in the trait `{}`",
2163                            idx + 1,
2164                            self.tcx.def_path_str(trait_did)
2165                        );
2166                        err.span_note(item_span, msg);
2167                        Some(idx + 1)
2168                    } else {
2169                        let msg = format!(
2170                            "the candidate is defined in the trait `{}`",
2171                            self.tcx.def_path_str(trait_did)
2172                        );
2173                        err.span_note(item_span, msg);
2174                        None
2175                    };
2176                    if let Some(sugg_span) = sugg_span
2177                        && let Some(sugg) = print_disambiguation_help(
2178                            self.tcx,
2179                            err,
2180                            self_source,
2181                            args,
2182                            ty::TraitRef::new_from_args(
2183                                self.tcx,
2184                                trait_did,
2185                                self.fresh_args_for_item(sugg_span, trait_did),
2186                            )
2187                            .with_replaced_self_ty(self.tcx, rcvr_ty),
2188                            idx,
2189                            sugg_span,
2190                            item,
2191                        )
2192                    {
2193                        suggs.push(sugg);
2194                    }
2195                }
2196            }
2197        }
2198        if !suggs.is_empty()
2199            && let Some(span) = sugg_span
2200        {
2201            suggs.sort();
2202            err.span_suggestions(
2203                span.with_hi(item_name.span.lo()),
2204                "use fully-qualified syntax to disambiguate",
2205                suggs,
2206                Applicability::MachineApplicable,
2207            );
2208        }
2209        if sources.len() > limit {
2210            err.note(format!("and {} others", sources.len() - limit));
2211        }
2212    }
2213
2214    /// Look at all the associated functions without receivers in the type's inherent impls
2215    /// to look for builders that return `Self`, `Option<Self>` or `Result<Self, _>`.
2216    fn find_builder_fn(&self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, expr_id: hir::HirId) {
2217        let ty::Adt(adt_def, _) = rcvr_ty.kind() else {
2218            return;
2219        };
2220        let mut items = self
2221            .tcx
2222            .inherent_impls(adt_def.did())
2223            .iter()
2224            .flat_map(|i| self.tcx.associated_items(i).in_definition_order())
2225            // Only assoc fn with no receivers and only if
2226            // they are resolvable
2227            .filter(|item| {
2228                matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. })
2229                    && self
2230                        .probe_for_name(
2231                            Mode::Path,
2232                            item.ident(self.tcx),
2233                            None,
2234                            IsSuggestion(true),
2235                            rcvr_ty,
2236                            expr_id,
2237                            ProbeScope::TraitsInScope,
2238                        )
2239                        .is_ok()
2240            })
2241            .filter_map(|item| {
2242                // Only assoc fns that return `Self`, `Option<Self>` or `Result<Self, _>`.
2243                let ret_ty = self
2244                    .tcx
2245                    .fn_sig(item.def_id)
2246                    .instantiate(self.tcx, self.fresh_args_for_item(DUMMY_SP, item.def_id))
2247                    .output();
2248                let ret_ty = self.tcx.instantiate_bound_regions_with_erased(ret_ty);
2249                let ty::Adt(def, args) = ret_ty.kind() else {
2250                    return None;
2251                };
2252                // Check for `-> Self`
2253                if self.can_eq(self.param_env, ret_ty, rcvr_ty) {
2254                    return Some((item.def_id, ret_ty));
2255                }
2256                // Check for `-> Option<Self>` or `-> Result<Self, _>`
2257                if ![self.tcx.lang_items().option_type(), self.tcx.get_diagnostic_item(sym::Result)]
2258                    .contains(&Some(def.did()))
2259                {
2260                    return None;
2261                }
2262                let arg = args.get(0)?.expect_ty();
2263                if self.can_eq(self.param_env, rcvr_ty, arg) {
2264                    Some((item.def_id, ret_ty))
2265                } else {
2266                    None
2267                }
2268            })
2269            .collect::<Vec<_>>();
2270        let post = if items.len() > 5 {
2271            let items_len = items.len();
2272            items.truncate(4);
2273            format!("\nand {} others", items_len - 4)
2274        } else {
2275            String::new()
2276        };
2277        match &items[..] {
2278            [] => {}
2279            [(def_id, ret_ty)] => {
2280                err.span_note(
2281                    self.tcx.def_span(def_id),
2282                    format!(
2283                        "if you're trying to build a new `{rcvr_ty}`, consider using `{}` which \
2284                         returns `{ret_ty}`",
2285                        self.tcx.def_path_str(def_id),
2286                    ),
2287                );
2288            }
2289            _ => {
2290                let span: MultiSpan = items
2291                    .iter()
2292                    .map(|(def_id, _)| self.tcx.def_span(def_id))
2293                    .collect::<Vec<Span>>()
2294                    .into();
2295                err.span_note(
2296                    span,
2297                    format!(
2298                        "if you're trying to build a new `{rcvr_ty}` consider using one of the \
2299                         following associated functions:\n{}{post}",
2300                        items
2301                            .iter()
2302                            .map(|(def_id, _ret_ty)| self.tcx.def_path_str(def_id))
2303                            .collect::<Vec<String>>()
2304                            .join("\n")
2305                    ),
2306                );
2307            }
2308        }
2309    }
2310
2311    /// Suggest calling `Ty::method` if `.method()` isn't found because the method
2312    /// doesn't take a `self` receiver.
2313    fn suggest_associated_call_syntax(
2314        &self,
2315        err: &mut Diag<'_>,
2316        static_candidates: &Vec<CandidateSource>,
2317        rcvr_ty: Ty<'tcx>,
2318        source: SelfSource<'tcx>,
2319        item_name: Ident,
2320        args: Option<&'tcx [hir::Expr<'tcx>]>,
2321        sugg_span: Span,
2322    ) {
2323        let mut has_unsuggestable_args = false;
2324        let ty_str = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
2325            // When the "method" is resolved through dereferencing, we really want the
2326            // original type that has the associated function for accurate suggestions.
2327            // (#61411)
2328            let impl_ty = self.tcx.type_of(*impl_did).instantiate_identity();
2329            let target_ty = self
2330                .autoderef(sugg_span, rcvr_ty)
2331                .silence_errors()
2332                .find(|(rcvr_ty, _)| {
2333                    DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify(*rcvr_ty, impl_ty)
2334                })
2335                .map_or(impl_ty, |(ty, _)| ty)
2336                .peel_refs();
2337            if let ty::Adt(def, args) = target_ty.kind() {
2338                // If there are any inferred arguments, (`{integer}`), we should replace
2339                // them with underscores to allow the compiler to infer them
2340                let infer_args = self.tcx.mk_args_from_iter(args.into_iter().map(|arg| {
2341                    if !arg.is_suggestable(self.tcx, true) {
2342                        has_unsuggestable_args = true;
2343                        match arg.kind() {
2344                            GenericArgKind::Lifetime(_) => {
2345                                self.next_region_var(RegionVariableOrigin::Misc(DUMMY_SP)).into()
2346                            }
2347                            GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(),
2348                            GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(),
2349                        }
2350                    } else {
2351                        arg
2352                    }
2353                }));
2354
2355                self.tcx.value_path_str_with_args(def.did(), infer_args)
2356            } else {
2357                self.ty_to_value_string(target_ty)
2358            }
2359        } else {
2360            self.ty_to_value_string(rcvr_ty.peel_refs())
2361        };
2362        if let SelfSource::MethodCall(_) = source {
2363            let first_arg = static_candidates.get(0).and_then(|candidate_source| {
2364                let (assoc_did, self_ty) = match candidate_source {
2365                    CandidateSource::Impl(impl_did) => {
2366                        (*impl_did, self.tcx.type_of(*impl_did).instantiate_identity())
2367                    }
2368                    CandidateSource::Trait(trait_did) => (*trait_did, rcvr_ty),
2369                };
2370
2371                let assoc = self.associated_value(assoc_did, item_name)?;
2372                if !assoc.is_fn() {
2373                    return None;
2374                }
2375
2376                // for CandidateSource::Impl, `Self` will be instantiated to a concrete type
2377                // but for CandidateSource::Trait, `Self` is still `Self`
2378                let sig = self.tcx.fn_sig(assoc.def_id).instantiate_identity();
2379                sig.inputs().skip_binder().get(0).and_then(|first| {
2380                    // if the type of first arg is the same as the current impl type, we should take the first arg into assoc function
2381                    let first_ty = first.peel_refs();
2382                    if first_ty == self_ty || first_ty == self.tcx.types.self_param {
2383                        Some(first.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()))
2384                    } else {
2385                        None
2386                    }
2387                })
2388            });
2389
2390            let mut applicability = Applicability::MachineApplicable;
2391            let args = if let SelfSource::MethodCall(receiver) = source
2392                && let Some(args) = args
2393            {
2394                // The first arg is the same kind as the receiver
2395                let explicit_args = if first_arg.is_some() {
2396                    std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
2397                } else {
2398                    // There is no `Self` kind to infer the arguments from
2399                    if has_unsuggestable_args {
2400                        applicability = Applicability::HasPlaceholders;
2401                    }
2402                    args.iter().collect()
2403                };
2404                format!(
2405                    "({}{})",
2406                    first_arg.unwrap_or(""),
2407                    explicit_args
2408                        .iter()
2409                        .map(|arg| self
2410                            .tcx
2411                            .sess
2412                            .source_map()
2413                            .span_to_snippet(arg.span)
2414                            .unwrap_or_else(|_| {
2415                                applicability = Applicability::HasPlaceholders;
2416                                "_".to_owned()
2417                            }))
2418                        .collect::<Vec<_>>()
2419                        .join(", "),
2420                )
2421            } else {
2422                applicability = Applicability::HasPlaceholders;
2423                "(...)".to_owned()
2424            };
2425            err.span_suggestion(
2426                sugg_span,
2427                "use associated function syntax instead",
2428                format!("{ty_str}::{item_name}{args}"),
2429                applicability,
2430            );
2431        } else {
2432            err.help(format!("try with `{ty_str}::{item_name}`",));
2433        }
2434    }
2435
2436    /// Suggest calling a field with a type that implements the `Fn*` traits instead of a method with
2437    /// the same name as the field i.e. `(a.my_fn_ptr)(10)` instead of `a.my_fn_ptr(10)`.
2438    fn suggest_calling_field_as_fn(
2439        &self,
2440        span: Span,
2441        rcvr_ty: Ty<'tcx>,
2442        expr: &hir::Expr<'_>,
2443        item_name: Ident,
2444        err: &mut Diag<'_>,
2445    ) -> bool {
2446        let tcx = self.tcx;
2447        let field_receiver =
2448            self.autoderef(span, rcvr_ty).silence_errors().find_map(|(ty, _)| match ty.kind() {
2449                ty::Adt(def, args) if !def.is_enum() => {
2450                    let variant = &def.non_enum_variant();
2451                    tcx.find_field_index(item_name, variant).map(|index| {
2452                        let field = &variant.fields[index];
2453                        let field_ty = field.ty(tcx, args);
2454                        (field, field_ty)
2455                    })
2456                }
2457                _ => None,
2458            });
2459        if let Some((field, field_ty)) = field_receiver {
2460            let scope = tcx.parent_module_from_def_id(self.body_id);
2461            let is_accessible = field.vis.is_accessible_from(scope, tcx);
2462
2463            if is_accessible {
2464                if let Some((what, _, _)) = self.extract_callable_info(field_ty) {
2465                    let what = match what {
2466                        DefIdOrName::DefId(def_id) => self.tcx.def_descr(def_id),
2467                        DefIdOrName::Name(what) => what,
2468                    };
2469                    let expr_span = expr.span.to(item_name.span);
2470                    err.multipart_suggestion(
2471                        format!(
2472                            "to call the {what} stored in `{item_name}`, \
2473                            surround the field access with parentheses",
2474                        ),
2475                        vec![
2476                            (expr_span.shrink_to_lo(), '('.to_string()),
2477                            (expr_span.shrink_to_hi(), ')'.to_string()),
2478                        ],
2479                        Applicability::MachineApplicable,
2480                    );
2481                } else {
2482                    let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
2483
2484                    if let Some(span) = call_expr.span.trim_start(item_name.span) {
2485                        err.span_suggestion(
2486                            span,
2487                            "remove the arguments",
2488                            "",
2489                            Applicability::MaybeIncorrect,
2490                        );
2491                    }
2492                }
2493            }
2494
2495            let field_kind = if is_accessible { "field" } else { "private field" };
2496            err.span_label(item_name.span, format!("{field_kind}, not a method"));
2497            return true;
2498        }
2499        false
2500    }
2501
2502    /// Suggest possible range with adding parentheses, for example:
2503    /// when encountering `0..1.map(|i| i + 1)` suggest `(0..1).map(|i| i + 1)`.
2504    fn report_failed_method_call_on_range_end(
2505        &self,
2506        tcx: TyCtxt<'tcx>,
2507        actual: Ty<'tcx>,
2508        source: SelfSource<'tcx>,
2509        span: Span,
2510        item_name: Ident,
2511    ) -> Result<(), ErrorGuaranteed> {
2512        if let SelfSource::MethodCall(expr) = source {
2513            for (_, parent) in tcx.hir_parent_iter(expr.hir_id).take(5) {
2514                if let Node::Expr(parent_expr) = parent {
2515                    let lang_item = match parent_expr.kind {
2516                        ExprKind::Struct(qpath, _, _) => match *qpath {
2517                            QPath::LangItem(LangItem::Range, ..) => Some(LangItem::Range),
2518                            QPath::LangItem(LangItem::RangeCopy, ..) => Some(LangItem::RangeCopy),
2519                            QPath::LangItem(LangItem::RangeInclusiveCopy, ..) => {
2520                                Some(LangItem::RangeInclusiveCopy)
2521                            }
2522                            QPath::LangItem(LangItem::RangeTo, ..) => Some(LangItem::RangeTo),
2523                            QPath::LangItem(LangItem::RangeToInclusive, ..) => {
2524                                Some(LangItem::RangeToInclusive)
2525                            }
2526                            _ => None,
2527                        },
2528                        ExprKind::Call(func, _) => match func.kind {
2529                            // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
2530                            ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)) => {
2531                                Some(LangItem::RangeInclusiveStruct)
2532                            }
2533                            _ => None,
2534                        },
2535                        _ => None,
2536                    };
2537
2538                    if lang_item.is_none() {
2539                        continue;
2540                    }
2541
2542                    let span_included = match parent_expr.kind {
2543                        hir::ExprKind::Struct(_, eps, _) => {
2544                            eps.len() > 0 && eps.last().is_some_and(|ep| ep.span.contains(span))
2545                        }
2546                        // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
2547                        hir::ExprKind::Call(func, ..) => func.span.contains(span),
2548                        _ => false,
2549                    };
2550
2551                    if !span_included {
2552                        continue;
2553                    }
2554
2555                    let Some(range_def_id) =
2556                        lang_item.and_then(|lang_item| self.tcx.lang_items().get(lang_item))
2557                    else {
2558                        continue;
2559                    };
2560                    let range_ty =
2561                        self.tcx.type_of(range_def_id).instantiate(self.tcx, &[actual.into()]);
2562
2563                    let pick = self.lookup_probe_for_diagnostic(
2564                        item_name,
2565                        range_ty,
2566                        expr,
2567                        ProbeScope::AllTraits,
2568                        None,
2569                    );
2570                    if pick.is_ok() {
2571                        let range_span = parent_expr.span.with_hi(expr.span.hi());
2572                        return Err(self.dcx().emit_err(errors::MissingParenthesesInRange {
2573                            span,
2574                            ty: actual,
2575                            method_name: item_name.as_str().to_string(),
2576                            add_missing_parentheses: Some(errors::AddMissingParenthesesInRange {
2577                                func_name: item_name.name.as_str().to_string(),
2578                                left: range_span.shrink_to_lo(),
2579                                right: range_span.shrink_to_hi(),
2580                            }),
2581                        }));
2582                    }
2583                }
2584            }
2585        }
2586        Ok(())
2587    }
2588
2589    fn report_failed_method_call_on_numerical_infer_var(
2590        &self,
2591        tcx: TyCtxt<'tcx>,
2592        actual: Ty<'tcx>,
2593        source: SelfSource<'_>,
2594        span: Span,
2595        item_kind: &str,
2596        item_name: Ident,
2597        long_ty_path: &mut Option<PathBuf>,
2598    ) -> Result<(), ErrorGuaranteed> {
2599        let found_candidate = all_traits(self.tcx)
2600            .into_iter()
2601            .any(|info| self.associated_value(info.def_id, item_name).is_some());
2602        let found_assoc = |ty: Ty<'tcx>| {
2603            simplify_type(tcx, ty, TreatParams::InstantiateWithInfer)
2604                .and_then(|simp| {
2605                    tcx.incoherent_impls(simp)
2606                        .into_iter()
2607                        .find_map(|&id| self.associated_value(id, item_name))
2608                })
2609                .is_some()
2610        };
2611        let found_candidate = found_candidate
2612            || found_assoc(tcx.types.i8)
2613            || found_assoc(tcx.types.i16)
2614            || found_assoc(tcx.types.i32)
2615            || found_assoc(tcx.types.i64)
2616            || found_assoc(tcx.types.i128)
2617            || found_assoc(tcx.types.u8)
2618            || found_assoc(tcx.types.u16)
2619            || found_assoc(tcx.types.u32)
2620            || found_assoc(tcx.types.u64)
2621            || found_assoc(tcx.types.u128)
2622            || found_assoc(tcx.types.f32)
2623            || found_assoc(tcx.types.f64);
2624        if found_candidate
2625            && actual.is_numeric()
2626            && !actual.has_concrete_skeleton()
2627            && let SelfSource::MethodCall(expr) = source
2628        {
2629            let ty_str = self.tcx.short_string(actual, long_ty_path);
2630            let mut err = struct_span_code_err!(
2631                self.dcx(),
2632                span,
2633                E0689,
2634                "can't call {item_kind} `{item_name}` on ambiguous numeric type `{ty_str}`"
2635            );
2636            *err.long_ty_path() = long_ty_path.take();
2637            let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
2638            match expr.kind {
2639                ExprKind::Lit(lit) => {
2640                    // numeric literal
2641                    let snippet = tcx
2642                        .sess
2643                        .source_map()
2644                        .span_to_snippet(lit.span)
2645                        .unwrap_or_else(|_| "<numeric literal>".to_owned());
2646
2647                    // If this is a floating point literal that ends with '.',
2648                    // get rid of it to stop this from becoming a member access.
2649                    let snippet = snippet.strip_suffix('.').unwrap_or(&snippet);
2650                    err.span_suggestion(
2651                        lit.span,
2652                        format!(
2653                            "you must specify a concrete type for this numeric value, \
2654                                         like `{concrete_type}`"
2655                        ),
2656                        format!("{snippet}_{concrete_type}"),
2657                        Applicability::MaybeIncorrect,
2658                    );
2659                }
2660                ExprKind::Path(QPath::Resolved(_, path)) => {
2661                    // local binding
2662                    if let hir::def::Res::Local(hir_id) = path.res {
2663                        let span = tcx.hir_span(hir_id);
2664                        let filename = tcx.sess.source_map().span_to_filename(span);
2665
2666                        let parent_node = self.tcx.parent_hir_node(hir_id);
2667                        let msg = format!(
2668                            "you must specify a type for this binding, like `{concrete_type}`",
2669                        );
2670
2671                        match (filename, parent_node) {
2672                            (
2673                                FileName::Real(_),
2674                                Node::LetStmt(hir::LetStmt {
2675                                    source: hir::LocalSource::Normal,
2676                                    ty,
2677                                    ..
2678                                }),
2679                            ) => {
2680                                let type_span = ty
2681                                    .map(|ty| ty.span.with_lo(span.hi()))
2682                                    .unwrap_or(span.shrink_to_hi());
2683                                err.span_suggestion(
2684                                    // account for `let x: _ = 42;`
2685                                    //                   ^^^
2686                                    type_span,
2687                                    msg,
2688                                    format!(": {concrete_type}"),
2689                                    Applicability::MaybeIncorrect,
2690                                );
2691                            }
2692                            _ => {
2693                                err.span_label(span, msg);
2694                            }
2695                        }
2696                    }
2697                }
2698                _ => {}
2699            }
2700            return Err(err.emit());
2701        }
2702        Ok(())
2703    }
2704
2705    /// For code `rect::area(...)`,
2706    /// if `rect` is a local variable and `area` is a valid assoc method for it,
2707    /// we try to suggest `rect.area()`
2708    pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) {
2709        debug!("suggest_assoc_method_call segs: {:?}", segs);
2710        let [seg1, seg2] = segs else {
2711            return;
2712        };
2713        self.dcx().try_steal_modify_and_emit_err(
2714            seg1.ident.span,
2715            StashKey::CallAssocMethod,
2716            |err| {
2717                let body = self.tcx.hir_body_owned_by(self.body_id);
2718                struct LetVisitor {
2719                    ident_name: Symbol,
2720                }
2721
2722                // FIXME: This really should be taking scoping, etc into account.
2723                impl<'v> Visitor<'v> for LetVisitor {
2724                    type Result = ControlFlow<Option<&'v hir::Expr<'v>>>;
2725                    fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) -> Self::Result {
2726                        if let hir::StmtKind::Let(&hir::LetStmt { pat, init, .. }) = ex.kind
2727                            && let hir::PatKind::Binding(_, _, ident, ..) = pat.kind
2728                            && ident.name == self.ident_name
2729                        {
2730                            ControlFlow::Break(init)
2731                        } else {
2732                            hir::intravisit::walk_stmt(self, ex)
2733                        }
2734                    }
2735                }
2736
2737                if let Node::Expr(call_expr) = self.tcx.parent_hir_node(seg1.hir_id)
2738                    && let ControlFlow::Break(Some(expr)) =
2739                        (LetVisitor { ident_name: seg1.ident.name }).visit_body(&body)
2740                    && let Some(self_ty) = self.node_ty_opt(expr.hir_id)
2741                {
2742                    let probe = self.lookup_probe_for_diagnostic(
2743                        seg2.ident,
2744                        self_ty,
2745                        call_expr,
2746                        ProbeScope::TraitsInScope,
2747                        None,
2748                    );
2749                    if probe.is_ok() {
2750                        let sm = self.infcx.tcx.sess.source_map();
2751                        err.span_suggestion_verbose(
2752                            sm.span_extend_while(seg1.ident.span.shrink_to_hi(), |c| c == ':')
2753                                .unwrap(),
2754                            "you may have meant to call an instance method",
2755                            ".",
2756                            Applicability::MaybeIncorrect,
2757                        );
2758                    }
2759                }
2760            },
2761        );
2762    }
2763
2764    /// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`
2765    fn suggest_calling_method_on_field(
2766        &self,
2767        err: &mut Diag<'_>,
2768        source: SelfSource<'tcx>,
2769        span: Span,
2770        actual: Ty<'tcx>,
2771        item_name: Ident,
2772        return_type: Option<Ty<'tcx>>,
2773    ) {
2774        if let SelfSource::MethodCall(expr) = source {
2775            let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
2776            for fields in self.get_field_candidates_considering_privacy_for_diag(
2777                span,
2778                actual,
2779                mod_id,
2780                expr.hir_id,
2781            ) {
2782                let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(expr.hir_id));
2783
2784                let lang_items = self.tcx.lang_items();
2785                let never_mention_traits = [
2786                    lang_items.clone_trait(),
2787                    lang_items.deref_trait(),
2788                    lang_items.deref_mut_trait(),
2789                    self.tcx.get_diagnostic_item(sym::AsRef),
2790                    self.tcx.get_diagnostic_item(sym::AsMut),
2791                    self.tcx.get_diagnostic_item(sym::Borrow),
2792                    self.tcx.get_diagnostic_item(sym::BorrowMut),
2793                ];
2794                let mut candidate_fields: Vec<_> = fields
2795                    .into_iter()
2796                    .filter_map(|candidate_field| {
2797                        self.check_for_nested_field_satisfying_condition_for_diag(
2798                            span,
2799                            &|_, field_ty| {
2800                                self.lookup_probe_for_diagnostic(
2801                                    item_name,
2802                                    field_ty,
2803                                    call_expr,
2804                                    ProbeScope::TraitsInScope,
2805                                    return_type,
2806                                )
2807                                .is_ok_and(|pick| {
2808                                    !never_mention_traits
2809                                        .iter()
2810                                        .flatten()
2811                                        .any(|def_id| self.tcx.parent(pick.item.def_id) == *def_id)
2812                                })
2813                            },
2814                            candidate_field,
2815                            vec![],
2816                            mod_id,
2817                            expr.hir_id,
2818                        )
2819                    })
2820                    .map(|field_path| {
2821                        field_path
2822                            .iter()
2823                            .map(|id| id.to_string())
2824                            .collect::<Vec<String>>()
2825                            .join(".")
2826                    })
2827                    .collect();
2828                candidate_fields.sort();
2829
2830                let len = candidate_fields.len();
2831                if len > 0 {
2832                    err.span_suggestions(
2833                        item_name.span.shrink_to_lo(),
2834                        format!(
2835                            "{} of the expressions' fields {} a method of the same name",
2836                            if len > 1 { "some" } else { "one" },
2837                            if len > 1 { "have" } else { "has" },
2838                        ),
2839                        candidate_fields.iter().map(|path| format!("{path}.")),
2840                        Applicability::MaybeIncorrect,
2841                    );
2842                }
2843            }
2844        }
2845    }
2846
2847    fn suggest_unwrapping_inner_self(
2848        &self,
2849        err: &mut Diag<'_>,
2850        source: SelfSource<'tcx>,
2851        actual: Ty<'tcx>,
2852        item_name: Ident,
2853    ) {
2854        let tcx = self.tcx;
2855        let SelfSource::MethodCall(expr) = source else {
2856            return;
2857        };
2858        let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
2859
2860        let ty::Adt(kind, args) = actual.kind() else {
2861            return;
2862        };
2863        match kind.adt_kind() {
2864            ty::AdtKind::Enum => {
2865                let matching_variants: Vec<_> = kind
2866                    .variants()
2867                    .iter()
2868                    .flat_map(|variant| {
2869                        let [field] = &variant.fields.raw[..] else {
2870                            return None;
2871                        };
2872                        let field_ty = field.ty(tcx, args);
2873
2874                        // Skip `_`, since that'll just lead to ambiguity.
2875                        if self.resolve_vars_if_possible(field_ty).is_ty_var() {
2876                            return None;
2877                        }
2878
2879                        self.lookup_probe_for_diagnostic(
2880                            item_name,
2881                            field_ty,
2882                            call_expr,
2883                            ProbeScope::TraitsInScope,
2884                            None,
2885                        )
2886                        .ok()
2887                        .map(|pick| (variant, field, pick))
2888                    })
2889                    .collect();
2890
2891                let ret_ty_matches = |diagnostic_item| {
2892                    if let Some(ret_ty) = self
2893                        .ret_coercion
2894                        .as_ref()
2895                        .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
2896                        && let ty::Adt(kind, _) = ret_ty.kind()
2897                        && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
2898                    {
2899                        true
2900                    } else {
2901                        false
2902                    }
2903                };
2904
2905                match &matching_variants[..] {
2906                    [(_, field, pick)] => {
2907                        let self_ty = field.ty(tcx, args);
2908                        err.span_note(
2909                            tcx.def_span(pick.item.def_id),
2910                            format!("the method `{item_name}` exists on the type `{self_ty}`"),
2911                        );
2912                        let (article, kind, variant, question) =
2913                            if tcx.is_diagnostic_item(sym::Result, kind.did()) {
2914                                ("a", "Result", "Err", ret_ty_matches(sym::Result))
2915                            } else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
2916                                ("an", "Option", "None", ret_ty_matches(sym::Option))
2917                            } else {
2918                                return;
2919                            };
2920                        if question {
2921                            err.span_suggestion_verbose(
2922                                expr.span.shrink_to_hi(),
2923                                format!(
2924                                    "use the `?` operator to extract the `{self_ty}` value, propagating \
2925                                    {article} `{kind}::{variant}` value to the caller"
2926                                ),
2927                                "?",
2928                                Applicability::MachineApplicable,
2929                            );
2930                        } else {
2931                            err.span_suggestion_verbose(
2932                                expr.span.shrink_to_hi(),
2933                                format!(
2934                                    "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
2935                                    panicking if the value is {article} `{kind}::{variant}`"
2936                                ),
2937                                ".expect(\"REASON\")",
2938                                Applicability::HasPlaceholders,
2939                            );
2940                        }
2941                    }
2942                    // FIXME(compiler-errors): Support suggestions for other matching enum variants
2943                    _ => {}
2944                }
2945            }
2946            // Target wrapper types - types that wrap or pretend to wrap another type,
2947            // perhaps this inner type is meant to be called?
2948            ty::AdtKind::Struct | ty::AdtKind::Union => {
2949                let [first] = ***args else {
2950                    return;
2951                };
2952                let ty::GenericArgKind::Type(ty) = first.kind() else {
2953                    return;
2954                };
2955                let Ok(pick) = self.lookup_probe_for_diagnostic(
2956                    item_name,
2957                    ty,
2958                    call_expr,
2959                    ProbeScope::TraitsInScope,
2960                    None,
2961                ) else {
2962                    return;
2963                };
2964
2965                let name = self.ty_to_value_string(actual);
2966                let inner_id = kind.did();
2967                let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
2968                    pick.autoref_or_ptr_adjustment
2969                {
2970                    Some(mutbl)
2971                } else {
2972                    None
2973                };
2974
2975                if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
2976                    err.help("use `with` or `try_with` to access thread local storage");
2977                } else if tcx.is_lang_item(kind.did(), LangItem::MaybeUninit) {
2978                    err.help(format!(
2979                        "if this `{name}` has been initialized, \
2980                        use one of the `assume_init` methods to access the inner value"
2981                    ));
2982                } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
2983                    let (suggestion, borrow_kind, panic_if) = match mutable {
2984                        Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"),
2985                        Some(Mutability::Mut) => {
2986                            (".borrow_mut()", "mutably borrow", "any borrows exist")
2987                        }
2988                        None => return,
2989                    };
2990                    err.span_suggestion_verbose(
2991                        expr.span.shrink_to_hi(),
2992                        format!(
2993                            "use `{suggestion}` to {borrow_kind} the `{ty}`, \
2994                            panicking if {panic_if}"
2995                        ),
2996                        suggestion,
2997                        Applicability::MaybeIncorrect,
2998                    );
2999                } else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
3000                    err.span_suggestion_verbose(
3001                        expr.span.shrink_to_hi(),
3002                        format!(
3003                            "use `.lock().unwrap()` to borrow the `{ty}`, \
3004                            blocking the current thread until it can be acquired"
3005                        ),
3006                        ".lock().unwrap()",
3007                        Applicability::MaybeIncorrect,
3008                    );
3009                } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
3010                    let (suggestion, borrow_kind) = match mutable {
3011                        Some(Mutability::Not) => (".read().unwrap()", "borrow"),
3012                        Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"),
3013                        None => return,
3014                    };
3015                    err.span_suggestion_verbose(
3016                        expr.span.shrink_to_hi(),
3017                        format!(
3018                            "use `{suggestion}` to {borrow_kind} the `{ty}`, \
3019                            blocking the current thread until it can be acquired"
3020                        ),
3021                        suggestion,
3022                        Applicability::MaybeIncorrect,
3023                    );
3024                } else {
3025                    return;
3026                };
3027
3028                err.span_note(
3029                    tcx.def_span(pick.item.def_id),
3030                    format!("the method `{item_name}` exists on the type `{ty}`"),
3031                );
3032            }
3033        }
3034    }
3035
3036    pub(crate) fn note_unmet_impls_on_type(
3037        &self,
3038        err: &mut Diag<'_>,
3039        errors: &[FulfillmentError<'tcx>],
3040        suggest_derive: bool,
3041    ) {
3042        let preds: Vec<_> = errors
3043            .iter()
3044            .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
3045                ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
3046                    match pred.self_ty().kind() {
3047                        ty::Adt(_, _) => Some(pred),
3048                        _ => None,
3049                    }
3050                }
3051                _ => None,
3052            })
3053            .collect();
3054
3055        // Note for local items and foreign items respectively.
3056        let (mut local_preds, mut foreign_preds): (Vec<_>, Vec<_>) =
3057            preds.iter().partition(|&pred| {
3058                if let ty::Adt(def, _) = pred.self_ty().kind() {
3059                    def.did().is_local()
3060                } else {
3061                    false
3062                }
3063            });
3064
3065        local_preds.sort_by_key(|pred: &&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3066        let local_def_ids = local_preds
3067            .iter()
3068            .filter_map(|pred| match pred.self_ty().kind() {
3069                ty::Adt(def, _) => Some(def.did()),
3070                _ => None,
3071            })
3072            .collect::<FxIndexSet<_>>();
3073        let mut local_spans: MultiSpan = local_def_ids
3074            .iter()
3075            .filter_map(|def_id| {
3076                let span = self.tcx.def_span(*def_id);
3077                if span.is_dummy() { None } else { Some(span) }
3078            })
3079            .collect::<Vec<_>>()
3080            .into();
3081        for pred in &local_preds {
3082            match pred.self_ty().kind() {
3083                ty::Adt(def, _) => {
3084                    local_spans.push_span_label(
3085                        self.tcx.def_span(def.did()),
3086                        format!("must implement `{}`", pred.trait_ref.print_trait_sugared()),
3087                    );
3088                }
3089                _ => {}
3090            }
3091        }
3092        if local_spans.primary_span().is_some() {
3093            let msg = if let [local_pred] = local_preds.as_slice() {
3094                format!(
3095                    "an implementation of `{}` might be missing for `{}`",
3096                    local_pred.trait_ref.print_trait_sugared(),
3097                    local_pred.self_ty()
3098                )
3099            } else {
3100                format!(
3101                    "the following type{} would have to `impl` {} required trait{} for this \
3102                     operation to be valid",
3103                    pluralize!(local_def_ids.len()),
3104                    if local_def_ids.len() == 1 { "its" } else { "their" },
3105                    pluralize!(local_preds.len()),
3106                )
3107            };
3108            err.span_note(local_spans, msg);
3109        }
3110
3111        foreign_preds.sort_by_key(|pred: &&ty::TraitPredicate<'_>| pred.trait_ref.to_string());
3112        let foreign_def_ids = foreign_preds
3113            .iter()
3114            .filter_map(|pred| match pred.self_ty().kind() {
3115                ty::Adt(def, _) => Some(def.did()),
3116                _ => None,
3117            })
3118            .collect::<FxIndexSet<_>>();
3119        let mut foreign_spans: MultiSpan = foreign_def_ids
3120            .iter()
3121            .filter_map(|def_id| {
3122                let span = self.tcx.def_span(*def_id);
3123                if span.is_dummy() { None } else { Some(span) }
3124            })
3125            .collect::<Vec<_>>()
3126            .into();
3127        for pred in &foreign_preds {
3128            match pred.self_ty().kind() {
3129                ty::Adt(def, _) => {
3130                    foreign_spans.push_span_label(
3131                        self.tcx.def_span(def.did()),
3132                        format!("not implement `{}`", pred.trait_ref.print_trait_sugared()),
3133                    );
3134                }
3135                _ => {}
3136            }
3137        }
3138        if foreign_spans.primary_span().is_some() {
3139            let msg = if let [foreign_pred] = foreign_preds.as_slice() {
3140                format!(
3141                    "the foreign item type `{}` doesn't implement `{}`",
3142                    foreign_pred.self_ty(),
3143                    foreign_pred.trait_ref.print_trait_sugared()
3144                )
3145            } else {
3146                format!(
3147                    "the foreign item type{} {} implement required trait{} for this \
3148                     operation to be valid",
3149                    pluralize!(foreign_def_ids.len()),
3150                    if foreign_def_ids.len() > 1 { "don't" } else { "doesn't" },
3151                    pluralize!(foreign_preds.len()),
3152                )
3153            };
3154            err.span_note(foreign_spans, msg);
3155        }
3156
3157        let preds: Vec<_> = errors
3158            .iter()
3159            .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
3160            .collect();
3161        if suggest_derive {
3162            self.suggest_derive(err, &preds);
3163        } else {
3164            // The predicate comes from a binop where the lhs and rhs have different types.
3165            let _ = self.note_predicate_source_and_get_derives(err, &preds);
3166        }
3167    }
3168
3169    fn note_predicate_source_and_get_derives(
3170        &self,
3171        err: &mut Diag<'_>,
3172        unsatisfied_predicates: &[(
3173            ty::Predicate<'tcx>,
3174            Option<ty::Predicate<'tcx>>,
3175            Option<ObligationCause<'tcx>>,
3176        )],
3177    ) -> Vec<(String, Span, Symbol)> {
3178        let mut derives = Vec::<(String, Span, Symbol)>::new();
3179        let mut traits = Vec::new();
3180        for (pred, _, _) in unsatisfied_predicates {
3181            let Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) =
3182                pred.kind().no_bound_vars()
3183            else {
3184                continue;
3185            };
3186            let adt = match trait_pred.self_ty().ty_adt_def() {
3187                Some(adt) if adt.did().is_local() => adt,
3188                _ => continue,
3189            };
3190            if let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) {
3191                let can_derive = match diagnostic_name {
3192                    sym::Default => !adt.is_enum(),
3193                    sym::Eq
3194                    | sym::PartialEq
3195                    | sym::Ord
3196                    | sym::PartialOrd
3197                    | sym::Clone
3198                    | sym::Copy
3199                    | sym::Hash
3200                    | sym::Debug => true,
3201                    _ => false,
3202                };
3203                if can_derive {
3204                    let self_name = trait_pred.self_ty().to_string();
3205                    let self_span = self.tcx.def_span(adt.did());
3206                    for super_trait in
3207                        supertraits(self.tcx, ty::Binder::dummy(trait_pred.trait_ref))
3208                    {
3209                        if let Some(parent_diagnostic_name) =
3210                            self.tcx.get_diagnostic_name(super_trait.def_id())
3211                        {
3212                            derives.push((self_name.clone(), self_span, parent_diagnostic_name));
3213                        }
3214                    }
3215                    derives.push((self_name, self_span, diagnostic_name));
3216                } else {
3217                    traits.push(trait_pred.def_id());
3218                }
3219            } else {
3220                traits.push(trait_pred.def_id());
3221            }
3222        }
3223        traits.sort_by_key(|id| self.tcx.def_path_str(id));
3224        traits.dedup();
3225
3226        let len = traits.len();
3227        if len > 0 {
3228            let span =
3229                MultiSpan::from_spans(traits.iter().map(|&did| self.tcx.def_span(did)).collect());
3230            let mut names = format!("`{}`", self.tcx.def_path_str(traits[0]));
3231            for (i, &did) in traits.iter().enumerate().skip(1) {
3232                if len > 2 {
3233                    names.push_str(", ");
3234                }
3235                if i == len - 1 {
3236                    names.push_str(" and ");
3237                }
3238                names.push('`');
3239                names.push_str(&self.tcx.def_path_str(did));
3240                names.push('`');
3241            }
3242            err.span_note(
3243                span,
3244                format!("the trait{} {} must be implemented", pluralize!(len), names),
3245            );
3246        }
3247
3248        derives
3249    }
3250
3251    pub(crate) fn suggest_derive(
3252        &self,
3253        err: &mut Diag<'_>,
3254        unsatisfied_predicates: &[(
3255            ty::Predicate<'tcx>,
3256            Option<ty::Predicate<'tcx>>,
3257            Option<ObligationCause<'tcx>>,
3258        )],
3259    ) -> bool {
3260        let mut derives = self.note_predicate_source_and_get_derives(err, unsatisfied_predicates);
3261        derives.sort();
3262        derives.dedup();
3263
3264        let mut derives_grouped = Vec::<(String, Span, String)>::new();
3265        for (self_name, self_span, trait_name) in derives.into_iter() {
3266            if let Some((last_self_name, _, last_trait_names)) = derives_grouped.last_mut() {
3267                if last_self_name == &self_name {
3268                    last_trait_names.push_str(format!(", {trait_name}").as_str());
3269                    continue;
3270                }
3271            }
3272            derives_grouped.push((self_name, self_span, trait_name.to_string()));
3273        }
3274
3275        for (self_name, self_span, traits) in &derives_grouped {
3276            err.span_suggestion_verbose(
3277                self_span.shrink_to_lo(),
3278                format!("consider annotating `{self_name}` with `#[derive({traits})]`"),
3279                format!("#[derive({traits})]\n"),
3280                Applicability::MaybeIncorrect,
3281            );
3282        }
3283        !derives_grouped.is_empty()
3284    }
3285
3286    fn note_derefed_ty_has_method(
3287        &self,
3288        err: &mut Diag<'_>,
3289        self_source: SelfSource<'tcx>,
3290        rcvr_ty: Ty<'tcx>,
3291        item_name: Ident,
3292        expected: Expectation<'tcx>,
3293    ) {
3294        let SelfSource::QPath(ty) = self_source else {
3295            return;
3296        };
3297        for (deref_ty, _) in self.autoderef(DUMMY_SP, rcvr_ty).silence_errors().skip(1) {
3298            if let Ok(pick) = self.probe_for_name(
3299                Mode::Path,
3300                item_name,
3301                expected.only_has_type(self),
3302                IsSuggestion(true),
3303                deref_ty,
3304                ty.hir_id,
3305                ProbeScope::TraitsInScope,
3306            ) {
3307                if deref_ty.is_suggestable(self.tcx, true)
3308                    // If this method receives `&self`, then the provided
3309                    // argument _should_ coerce, so it's valid to suggest
3310                    // just changing the path.
3311                    && pick.item.is_method()
3312                    && let Some(self_ty) =
3313                        self.tcx.fn_sig(pick.item.def_id).instantiate_identity().inputs().skip_binder().get(0)
3314                    && self_ty.is_ref()
3315                {
3316                    let suggested_path = match deref_ty.kind() {
3317                        ty::Bool
3318                        | ty::Char
3319                        | ty::Int(_)
3320                        | ty::Uint(_)
3321                        | ty::Float(_)
3322                        | ty::Adt(_, _)
3323                        | ty::Str
3324                        | ty::Alias(ty::Projection | ty::Inherent, _)
3325                        | ty::Param(_) => format!("{deref_ty}"),
3326                        // we need to test something like  <&[_]>::len or <(&[u32])>::len
3327                        // and Vec::function();
3328                        // <&[_]>::len or <&[u32]>::len doesn't need an extra "<>" between
3329                        // but for Adt type like Vec::function()
3330                        // we would suggest <[_]>::function();
3331                        _ if self
3332                            .tcx
3333                            .sess
3334                            .source_map()
3335                            .span_wrapped_by_angle_or_parentheses(ty.span) =>
3336                        {
3337                            format!("{deref_ty}")
3338                        }
3339                        _ => format!("<{deref_ty}>"),
3340                    };
3341                    err.span_suggestion_verbose(
3342                        ty.span,
3343                        format!("the function `{item_name}` is implemented on `{deref_ty}`"),
3344                        suggested_path,
3345                        Applicability::MaybeIncorrect,
3346                    );
3347                } else {
3348                    err.span_note(
3349                        ty.span,
3350                        format!("the function `{item_name}` is implemented on `{deref_ty}`"),
3351                    );
3352                }
3353                return;
3354            }
3355        }
3356    }
3357
3358    /// Print out the type for use in value namespace.
3359    fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
3360        match ty.kind() {
3361            ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3362            _ => self.ty_to_string(ty),
3363        }
3364    }
3365
3366    fn suggest_await_before_method(
3367        &self,
3368        err: &mut Diag<'_>,
3369        item_name: Ident,
3370        ty: Ty<'tcx>,
3371        call: &hir::Expr<'_>,
3372        span: Span,
3373        return_type: Option<Ty<'tcx>>,
3374    ) {
3375        let output_ty = match self.err_ctxt().get_impl_future_output_ty(ty) {
3376            Some(output_ty) => self.resolve_vars_if_possible(output_ty),
3377            _ => return,
3378        };
3379        let method_exists =
3380            self.method_exists_for_diagnostic(item_name, output_ty, call.hir_id, return_type);
3381        debug!("suggest_await_before_method: is_method_exist={}", method_exists);
3382        if method_exists {
3383            err.span_suggestion_verbose(
3384                span.shrink_to_lo(),
3385                "consider `await`ing on the `Future` and calling the method on its `Output`",
3386                "await.",
3387                Applicability::MaybeIncorrect,
3388            );
3389        }
3390    }
3391
3392    fn suggest_use_candidates<F>(&self, candidates: Vec<DefId>, handle_candidates: F)
3393    where
3394        F: FnOnce(Vec<String>, Vec<String>, Span),
3395    {
3396        let parent_map = self.tcx.visible_parent_map(());
3397
3398        let scope = self.tcx.parent_module_from_def_id(self.body_id);
3399        let (accessible_candidates, inaccessible_candidates): (Vec<_>, Vec<_>) =
3400            candidates.into_iter().partition(|id| {
3401                let vis = self.tcx.visibility(*id);
3402                vis.is_accessible_from(scope, self.tcx)
3403            });
3404
3405        let sugg = |candidates: Vec<_>, visible| {
3406            // Separate out candidates that must be imported with a glob, because they are named `_`
3407            // and cannot be referred with their identifier.
3408            let (candidates, globs): (Vec<_>, Vec<_>) =
3409                candidates.into_iter().partition(|trait_did| {
3410                    if let Some(parent_did) = parent_map.get(trait_did) {
3411                        // If the item is re-exported as `_`, we should suggest a glob-import instead.
3412                        if *parent_did != self.tcx.parent(*trait_did)
3413                            && self
3414                                .tcx
3415                                .module_children(*parent_did)
3416                                .iter()
3417                                .filter(|child| child.res.opt_def_id() == Some(*trait_did))
3418                                .all(|child| child.ident.name == kw::Underscore)
3419                        {
3420                            return false;
3421                        }
3422                    }
3423
3424                    true
3425                });
3426
3427            let prefix = if visible { "use " } else { "" };
3428            let postfix = if visible { ";" } else { "" };
3429            let path_strings = candidates.iter().map(|trait_did| {
3430                format!(
3431                    "{prefix}{}{postfix}\n",
3432                    with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
3433                        self.tcx.def_path_str(*trait_did)
3434                    )),
3435                )
3436            });
3437
3438            let glob_path_strings = globs.iter().map(|trait_did| {
3439                let parent_did = parent_map.get(trait_did).unwrap();
3440                format!(
3441                    "{prefix}{}::*{postfix} // trait {}\n",
3442                    with_no_visible_paths_if_doc_hidden!(with_crate_prefix!(
3443                        self.tcx.def_path_str(*parent_did)
3444                    )),
3445                    self.tcx.item_name(*trait_did),
3446                )
3447            });
3448            let mut sugg: Vec<_> = path_strings.chain(glob_path_strings).collect();
3449            sugg.sort();
3450            sugg
3451        };
3452
3453        let accessible_sugg = sugg(accessible_candidates, true);
3454        let inaccessible_sugg = sugg(inaccessible_candidates, false);
3455
3456        let (module, _, _) = self.tcx.hir_get_module(scope);
3457        let span = module.spans.inject_use_span;
3458        handle_candidates(accessible_sugg, inaccessible_sugg, span);
3459    }
3460
3461    fn suggest_valid_traits(
3462        &self,
3463        err: &mut Diag<'_>,
3464        item_name: Ident,
3465        mut valid_out_of_scope_traits: Vec<DefId>,
3466        explain: bool,
3467    ) -> bool {
3468        valid_out_of_scope_traits.retain(|id| self.tcx.is_user_visible_dep(id.krate));
3469        if !valid_out_of_scope_traits.is_empty() {
3470            let mut candidates = valid_out_of_scope_traits;
3471            candidates.sort_by_key(|id| self.tcx.def_path_str(id));
3472            candidates.dedup();
3473
3474            // `TryFrom` and `FromIterator` have no methods
3475            let edition_fix = candidates
3476                .iter()
3477                .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
3478                .copied();
3479
3480            if explain {
3481                err.help("items from traits can only be used if the trait is in scope");
3482            }
3483
3484            let msg = format!(
3485                "{this_trait_is} implemented but not in scope",
3486                this_trait_is = if candidates.len() == 1 {
3487                    format!(
3488                        "trait `{}` which provides `{item_name}` is",
3489                        self.tcx.item_name(candidates[0]),
3490                    )
3491                } else {
3492                    format!("the following traits which provide `{item_name}` are")
3493                }
3494            );
3495
3496            self.suggest_use_candidates(candidates, |accessible_sugg, inaccessible_sugg, span| {
3497                let suggest_for_access = |err: &mut Diag<'_>, mut msg: String, suggs: Vec<_>| {
3498                    msg += &format!(
3499                        "; perhaps you want to import {one_of}",
3500                        one_of = if suggs.len() == 1 { "it" } else { "one of them" },
3501                    );
3502                    err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
3503                };
3504                let suggest_for_privacy = |err: &mut Diag<'_>, suggs: Vec<String>| {
3505                    let msg = format!(
3506                        "{this_trait_is} implemented but not reachable",
3507                        this_trait_is = if let [sugg] = suggs.as_slice() {
3508                            format!("trait `{}` which provides `{item_name}` is", sugg.trim())
3509                        } else {
3510                            format!("the following traits which provide `{item_name}` are")
3511                        }
3512                    );
3513                    if suggs.len() == 1 {
3514                        err.help(msg);
3515                    } else {
3516                        err.span_suggestions(span, msg, suggs, Applicability::MaybeIncorrect);
3517                    }
3518                };
3519                if accessible_sugg.is_empty() {
3520                    // `inaccessible_sugg` must not be empty
3521                    suggest_for_privacy(err, inaccessible_sugg);
3522                } else if inaccessible_sugg.is_empty() {
3523                    suggest_for_access(err, msg, accessible_sugg);
3524                } else {
3525                    suggest_for_access(err, msg, accessible_sugg);
3526                    suggest_for_privacy(err, inaccessible_sugg);
3527                }
3528            });
3529
3530            if let Some(did) = edition_fix {
3531                err.note(format!(
3532                    "'{}' is included in the prelude starting in Edition 2021",
3533                    with_crate_prefix!(self.tcx.def_path_str(did))
3534                ));
3535            }
3536
3537            true
3538        } else {
3539            false
3540        }
3541    }
3542
3543    fn suggest_traits_to_import(
3544        &self,
3545        err: &mut Diag<'_>,
3546        span: Span,
3547        rcvr_ty: Ty<'tcx>,
3548        item_name: Ident,
3549        inputs_len: Option<usize>,
3550        source: SelfSource<'tcx>,
3551        valid_out_of_scope_traits: Vec<DefId>,
3552        static_candidates: &[CandidateSource],
3553        unsatisfied_bounds: bool,
3554        return_type: Option<Ty<'tcx>>,
3555        trait_missing_method: bool,
3556    ) {
3557        let mut alt_rcvr_sugg = false;
3558        let mut trait_in_other_version_found = false;
3559        if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
3560            debug!(
3561                "suggest_traits_to_import: span={:?}, item_name={:?}, rcvr_ty={:?}, rcvr={:?}",
3562                span, item_name, rcvr_ty, rcvr
3563            );
3564            let skippable = [
3565                self.tcx.lang_items().clone_trait(),
3566                self.tcx.lang_items().deref_trait(),
3567                self.tcx.lang_items().deref_mut_trait(),
3568                self.tcx.lang_items().drop_trait(),
3569                self.tcx.get_diagnostic_item(sym::AsRef),
3570            ];
3571            // Try alternative arbitrary self types that could fulfill this call.
3572            // FIXME: probe for all types that *could* be arbitrary self-types, not
3573            // just this list.
3574            for (rcvr_ty, post, pin_call) in &[
3575                (rcvr_ty, "", None),
3576                (
3577                    Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
3578                    "&mut ",
3579                    Some("as_mut"),
3580                ),
3581                (
3582                    Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
3583                    "&",
3584                    Some("as_ref"),
3585                ),
3586            ] {
3587                match self.lookup_probe_for_diagnostic(
3588                    item_name,
3589                    *rcvr_ty,
3590                    rcvr,
3591                    ProbeScope::AllTraits,
3592                    return_type,
3593                ) {
3594                    Ok(pick) => {
3595                        // If the method is defined for the receiver we have, it likely wasn't `use`d.
3596                        // We point at the method, but we just skip the rest of the check for arbitrary
3597                        // self types and rely on the suggestion to `use` the trait from
3598                        // `suggest_valid_traits`.
3599                        let did = Some(pick.item.container_id(self.tcx));
3600                        if skippable.contains(&did) {
3601                            continue;
3602                        }
3603                        trait_in_other_version_found = self
3604                            .detect_and_explain_multiple_crate_versions_of_trait_item(
3605                                err,
3606                                pick.item.def_id,
3607                                rcvr.hir_id,
3608                                Some(*rcvr_ty),
3609                            );
3610                        if pick.autoderefs == 0 && !trait_in_other_version_found {
3611                            err.span_label(
3612                                pick.item.ident(self.tcx).span,
3613                                format!("the method is available for `{rcvr_ty}` here"),
3614                            );
3615                        }
3616                        break;
3617                    }
3618                    Err(MethodError::Ambiguity(_)) => {
3619                        // If the method is defined (but ambiguous) for the receiver we have, it is also
3620                        // likely we haven't `use`d it. It may be possible that if we `Box`/`Pin`/etc.
3621                        // the receiver, then it might disambiguate this method, but I think these
3622                        // suggestions are generally misleading (see #94218).
3623                        break;
3624                    }
3625                    Err(_) => (),
3626                }
3627
3628                let Some(unpin_trait) = self.tcx.lang_items().unpin_trait() else {
3629                    return;
3630                };
3631                let pred = ty::TraitRef::new(self.tcx, unpin_trait, [*rcvr_ty]);
3632                let unpin = self.predicate_must_hold_considering_regions(&Obligation::new(
3633                    self.tcx,
3634                    self.misc(rcvr.span),
3635                    self.param_env,
3636                    pred,
3637                ));
3638                for (rcvr_ty, pre) in &[
3639                    (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::OwnedBox), "Box::new"),
3640                    (Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin), "Pin::new"),
3641                    (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Arc), "Arc::new"),
3642                    (Ty::new_diagnostic_item(self.tcx, *rcvr_ty, sym::Rc), "Rc::new"),
3643                ] {
3644                    if let Some(new_rcvr_t) = *rcvr_ty
3645                        && let Ok(pick) = self.lookup_probe_for_diagnostic(
3646                            item_name,
3647                            new_rcvr_t,
3648                            rcvr,
3649                            ProbeScope::AllTraits,
3650                            return_type,
3651                        )
3652                    {
3653                        debug!("try_alt_rcvr: pick candidate {:?}", pick);
3654                        let did = pick.item.trait_container(self.tcx);
3655                        // We don't want to suggest a container type when the missing
3656                        // method is `.clone()` or `.deref()` otherwise we'd suggest
3657                        // `Arc::new(foo).clone()`, which is far from what the user wants.
3658                        // Explicitly ignore the `Pin::as_ref()` method as `Pin` does not
3659                        // implement the `AsRef` trait.
3660                        let skip = skippable.contains(&did)
3661                            || (("Pin::new" == *pre)
3662                                && ((sym::as_ref == item_name.name) || !unpin))
3663                            || inputs_len.is_some_and(|inputs_len| {
3664                                pick.item.is_fn()
3665                                    && self
3666                                        .tcx
3667                                        .fn_sig(pick.item.def_id)
3668                                        .skip_binder()
3669                                        .skip_binder()
3670                                        .inputs()
3671                                        .len()
3672                                        != inputs_len
3673                            });
3674                        // Make sure the method is defined for the *actual* receiver: we don't
3675                        // want to treat `Box<Self>` as a receiver if it only works because of
3676                        // an autoderef to `&self`
3677                        if pick.autoderefs == 0 && !skip {
3678                            err.span_label(
3679                                pick.item.ident(self.tcx).span,
3680                                format!("the method is available for `{new_rcvr_t}` here"),
3681                            );
3682                            err.multipart_suggestion(
3683                                "consider wrapping the receiver expression with the \
3684                                 appropriate type",
3685                                vec![
3686                                    (rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
3687                                    (rcvr.span.shrink_to_hi(), ")".to_string()),
3688                                ],
3689                                Applicability::MaybeIncorrect,
3690                            );
3691                            // We don't care about the other suggestions.
3692                            alt_rcvr_sugg = true;
3693                        }
3694                    }
3695                }
3696                // We special case the situation where `Pin::new` wouldn't work, and instead
3697                // suggest using the `pin!()` macro instead.
3698                if let Some(new_rcvr_t) = Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin)
3699                    // We didn't find an alternative receiver for the method.
3700                    && !alt_rcvr_sugg
3701                    // `T: !Unpin`
3702                    && !unpin
3703                    // Either `Pin::as_ref` or `Pin::as_mut`.
3704                    && let Some(pin_call) = pin_call
3705                    // Search for `item_name` as a method accessible on `Pin<T>`.
3706                    && let Ok(pick) = self.lookup_probe_for_diagnostic(
3707                        item_name,
3708                        new_rcvr_t,
3709                        rcvr,
3710                        ProbeScope::AllTraits,
3711                        return_type,
3712                    )
3713                    // We skip some common traits that we don't want to consider because autoderefs
3714                    // would take care of them.
3715                    && !skippable.contains(&Some(pick.item.container_id(self.tcx)))
3716                    // Do not suggest pinning when the method is directly on `Pin`.
3717                    && pick.item.impl_container(self.tcx).map_or(true, |did| {
3718                        match self.tcx.type_of(did).skip_binder().kind() {
3719                            ty::Adt(def, _) => Some(def.did()) != self.tcx.lang_items().pin_type(),
3720                            _ => true,
3721                        }
3722                    })
3723                    // We don't want to go through derefs.
3724                    && pick.autoderefs == 0
3725                    // Check that the method of the same name that was found on the new `Pin<T>`
3726                    // receiver has the same number of arguments that appear in the user's code.
3727                    && inputs_len.is_some_and(|inputs_len| pick.item.is_fn() && self.tcx.fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() == inputs_len)
3728                {
3729                    let indent = self
3730                        .tcx
3731                        .sess
3732                        .source_map()
3733                        .indentation_before(rcvr.span)
3734                        .unwrap_or_else(|| " ".to_string());
3735                    let mut expr = rcvr;
3736                    while let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
3737                        && let hir::ExprKind::MethodCall(hir::PathSegment { .. }, ..) =
3738                            call_expr.kind
3739                    {
3740                        expr = call_expr;
3741                    }
3742                    match self.tcx.parent_hir_node(expr.hir_id) {
3743                        Node::LetStmt(stmt)
3744                            if let Some(init) = stmt.init
3745                                && let Ok(code) =
3746                                    self.tcx.sess.source_map().span_to_snippet(rcvr.span) =>
3747                        {
3748                            // We need to take care to account for the existing binding when we
3749                            // suggest the code.
3750                            err.multipart_suggestion(
3751                                "consider pinning the expression",
3752                                vec![
3753                                    (
3754                                        stmt.span.shrink_to_lo(),
3755                                        format!(
3756                                            "let mut pinned = std::pin::pin!({code});\n{indent}"
3757                                        ),
3758                                    ),
3759                                    (
3760                                        init.span.until(rcvr.span.shrink_to_hi()),
3761                                        format!("pinned.{pin_call}()"),
3762                                    ),
3763                                ],
3764                                Applicability::MaybeIncorrect,
3765                            );
3766                        }
3767                        Node::Block(_) | Node::Stmt(_) => {
3768                            // There's no binding, so we can provide a slightly nicer looking
3769                            // suggestion.
3770                            err.multipart_suggestion(
3771                                "consider pinning the expression",
3772                                vec![
3773                                    (
3774                                        rcvr.span.shrink_to_lo(),
3775                                        format!("let mut pinned = std::pin::pin!("),
3776                                    ),
3777                                    (
3778                                        rcvr.span.shrink_to_hi(),
3779                                        format!(");\n{indent}pinned.{pin_call}()"),
3780                                    ),
3781                                ],
3782                                Applicability::MaybeIncorrect,
3783                            );
3784                        }
3785                        _ => {
3786                            // We don't quite know what the users' code looks like, so we don't
3787                            // provide a pinning suggestion.
3788                            err.span_help(
3789                                rcvr.span,
3790                                "consider pinning the expression with `std::pin::pin!()` and \
3791                                 assigning that to a new binding",
3792                            );
3793                        }
3794                    }
3795                    // We don't care about the other suggestions.
3796                    alt_rcvr_sugg = true;
3797                }
3798            }
3799        }
3800
3801        if let SelfSource::QPath(ty) = source
3802            && !valid_out_of_scope_traits.is_empty()
3803            && let hir::TyKind::Path(path) = ty.kind
3804            && let hir::QPath::Resolved(..) = path
3805            && let Some(assoc) = self
3806                .tcx
3807                .associated_items(valid_out_of_scope_traits[0])
3808                .filter_by_name_unhygienic(item_name.name)
3809                .next()
3810        {
3811            // See if the `Type::function(val)` where `function` wasn't found corresponds to a
3812            // `Trait` that is imported directly, but `Type` came from a different version of the
3813            // same crate.
3814
3815            let rcvr_ty = self.node_ty_opt(ty.hir_id);
3816            trait_in_other_version_found = self
3817                .detect_and_explain_multiple_crate_versions_of_trait_item(
3818                    err,
3819                    assoc.def_id,
3820                    ty.hir_id,
3821                    rcvr_ty,
3822                );
3823        }
3824        if !trait_in_other_version_found
3825            && self.suggest_valid_traits(err, item_name, valid_out_of_scope_traits, true)
3826        {
3827            return;
3828        }
3829
3830        let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
3831
3832        let mut arbitrary_rcvr = vec![];
3833        // There are no traits implemented, so lets suggest some traits to
3834        // implement, by finding ones that have the item name, and are
3835        // legal to implement.
3836        let mut candidates = all_traits(self.tcx)
3837            .into_iter()
3838            // Don't issue suggestions for unstable traits since they're
3839            // unlikely to be implementable anyway
3840            .filter(|info| match self.tcx.lookup_stability(info.def_id) {
3841                Some(attr) => attr.level.is_stable(),
3842                None => true,
3843            })
3844            .filter(|info| {
3845                // Static candidates are already implemented, and known not to work
3846                // Do not suggest them again
3847                static_candidates.iter().all(|sc| match *sc {
3848                    CandidateSource::Trait(def_id) => def_id != info.def_id,
3849                    CandidateSource::Impl(def_id) => {
3850                        self.tcx.trait_id_of_impl(def_id) != Some(info.def_id)
3851                    }
3852                })
3853            })
3854            .filter(|info| {
3855                // We approximate the coherence rules to only suggest
3856                // traits that are legal to implement by requiring that
3857                // either the type or trait is local. Multi-dispatch means
3858                // this isn't perfect (that is, there are cases when
3859                // implementing a trait would be legal but is rejected
3860                // here).
3861                (type_is_local || info.def_id.is_local())
3862                    && !self.tcx.trait_is_auto(info.def_id)
3863                    && self
3864                        .associated_value(info.def_id, item_name)
3865                        .filter(|item| {
3866                            if item.is_fn() {
3867                                let id = item
3868                                    .def_id
3869                                    .as_local()
3870                                    .map(|def_id| self.tcx.hir_node_by_def_id(def_id));
3871                                if let Some(hir::Node::TraitItem(hir::TraitItem {
3872                                    kind: hir::TraitItemKind::Fn(fn_sig, method),
3873                                    ..
3874                                })) = id
3875                                {
3876                                    let self_first_arg = match method {
3877                                        hir::TraitFn::Required([ident, ..]) => {
3878                                            matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
3879                                        }
3880                                        hir::TraitFn::Provided(body_id) => {
3881                                            self.tcx.hir_body(*body_id).params.first().is_some_and(
3882                                                |param| {
3883                                                    matches!(
3884                                                        param.pat.kind,
3885                                                        hir::PatKind::Binding(_, _, ident, _)
3886                                                            if ident.name == kw::SelfLower
3887                                                    )
3888                                                },
3889                                            )
3890                                        }
3891                                        _ => false,
3892                                    };
3893
3894                                    if !fn_sig.decl.implicit_self.has_implicit_self()
3895                                        && self_first_arg
3896                                    {
3897                                        if let Some(ty) = fn_sig.decl.inputs.get(0) {
3898                                            arbitrary_rcvr.push(ty.span);
3899                                        }
3900                                        return false;
3901                                    }
3902                                }
3903                            }
3904                            // We only want to suggest public or local traits (#45781).
3905                            item.visibility(self.tcx).is_public() || info.def_id.is_local()
3906                        })
3907                        .is_some()
3908            })
3909            .collect::<Vec<_>>();
3910        for span in &arbitrary_rcvr {
3911            err.span_label(
3912                *span,
3913                "the method might not be found because of this arbitrary self type",
3914            );
3915        }
3916        if alt_rcvr_sugg {
3917            return;
3918        }
3919
3920        if !candidates.is_empty() {
3921            // Sort local crate results before others
3922            candidates
3923                .sort_by_key(|&info| (!info.def_id.is_local(), self.tcx.def_path_str(info.def_id)));
3924            candidates.dedup();
3925
3926            let param_type = match *rcvr_ty.kind() {
3927                ty::Param(param) => Some(param),
3928                ty::Ref(_, ty, _) => match *ty.kind() {
3929                    ty::Param(param) => Some(param),
3930                    _ => None,
3931                },
3932                _ => None,
3933            };
3934            if !trait_missing_method {
3935                err.help(if param_type.is_some() {
3936                    "items from traits can only be used if the type parameter is bounded by the trait"
3937                } else {
3938                    "items from traits can only be used if the trait is implemented and in scope"
3939                });
3940            }
3941
3942            let candidates_len = candidates.len();
3943            let message = |action| {
3944                format!(
3945                    "the following {traits_define} an item `{name}`, perhaps you need to {action} \
3946                     {one_of_them}:",
3947                    traits_define =
3948                        if candidates_len == 1 { "trait defines" } else { "traits define" },
3949                    action = action,
3950                    one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
3951                    name = item_name,
3952                )
3953            };
3954            // Obtain the span for `param` and use it for a structured suggestion.
3955            if let Some(param) = param_type {
3956                let generics = self.tcx.generics_of(self.body_id.to_def_id());
3957                let type_param = generics.type_param(param, self.tcx);
3958                let tcx = self.tcx;
3959                if let Some(def_id) = type_param.def_id.as_local() {
3960                    let id = tcx.local_def_id_to_hir_id(def_id);
3961                    // Get the `hir::Param` to verify whether it already has any bounds.
3962                    // We do this to avoid suggesting code that ends up as `T: FooBar`,
3963                    // instead we suggest `T: Foo + Bar` in that case.
3964                    match tcx.hir_node(id) {
3965                        Node::GenericParam(param) => {
3966                            enum Introducer {
3967                                Plus,
3968                                Colon,
3969                                Nothing,
3970                            }
3971                            let hir_generics = tcx.hir_get_generics(id.owner.def_id).unwrap();
3972                            let trait_def_ids: DefIdSet = hir_generics
3973                                .bounds_for_param(def_id)
3974                                .flat_map(|bp| bp.bounds.iter())
3975                                .filter_map(|bound| bound.trait_ref()?.trait_def_id())
3976                                .collect();
3977                            if candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
3978                                return;
3979                            }
3980                            let msg = message(format!(
3981                                "restrict type parameter `{}` with",
3982                                param.name.ident(),
3983                            ));
3984                            let bounds_span = hir_generics.bounds_span_for_suggestions(def_id);
3985                            let mut applicability = Applicability::MaybeIncorrect;
3986                            // Format the path of each suggested candidate, providing placeholders
3987                            // for any generic arguments without defaults.
3988                            let candidate_strs: Vec<_> = candidates
3989                                .iter()
3990                                .map(|cand| {
3991                                    let cand_path = tcx.def_path_str(cand.def_id);
3992                                    let cand_params = &tcx.generics_of(cand.def_id).own_params;
3993                                    let cand_args: String = cand_params
3994                                        .iter()
3995                                        .skip(1)
3996                                        .filter_map(|param| match param.kind {
3997                                            ty::GenericParamDefKind::Type {
3998                                                has_default: true,
3999                                                ..
4000                                            }
4001                                            | ty::GenericParamDefKind::Const {
4002                                                has_default: true,
4003                                                ..
4004                                            } => None,
4005                                            _ => Some(param.name.as_str()),
4006                                        })
4007                                        .intersperse(", ")
4008                                        .collect();
4009                                    if cand_args.is_empty() {
4010                                        cand_path
4011                                    } else {
4012                                        applicability = Applicability::HasPlaceholders;
4013                                        format!("{cand_path}</* {cand_args} */>")
4014                                    }
4015                                })
4016                                .collect();
4017
4018                            if rcvr_ty.is_ref()
4019                                && param.is_impl_trait()
4020                                && let Some((bounds_span, _)) = bounds_span
4021                            {
4022                                err.multipart_suggestions(
4023                                    msg,
4024                                    candidate_strs.iter().map(|cand| {
4025                                        vec![
4026                                            (param.span.shrink_to_lo(), "(".to_string()),
4027                                            (bounds_span, format!(" + {cand})")),
4028                                        ]
4029                                    }),
4030                                    applicability,
4031                                );
4032                                return;
4033                            }
4034
4035                            let (sp, introducer, open_paren_sp) =
4036                                if let Some((span, open_paren_sp)) = bounds_span {
4037                                    (span, Introducer::Plus, open_paren_sp)
4038                                } else if let Some(colon_span) = param.colon_span {
4039                                    (colon_span.shrink_to_hi(), Introducer::Nothing, None)
4040                                } else if param.is_impl_trait() {
4041                                    (param.span.shrink_to_hi(), Introducer::Plus, None)
4042                                } else {
4043                                    (param.span.shrink_to_hi(), Introducer::Colon, None)
4044                                };
4045
4046                            let all_suggs = candidate_strs.iter().map(|cand| {
4047                                let suggestion = format!(
4048                                    "{} {cand}",
4049                                    match introducer {
4050                                        Introducer::Plus => " +",
4051                                        Introducer::Colon => ":",
4052                                        Introducer::Nothing => "",
4053                                    },
4054                                );
4055
4056                                let mut suggs = vec![];
4057
4058                                if let Some(open_paren_sp) = open_paren_sp {
4059                                    suggs.push((open_paren_sp, "(".to_string()));
4060                                    suggs.push((sp, format!("){suggestion}")));
4061                                } else {
4062                                    suggs.push((sp, suggestion));
4063                                }
4064
4065                                suggs
4066                            });
4067
4068                            err.multipart_suggestions(msg, all_suggs, applicability);
4069
4070                            return;
4071                        }
4072                        Node::Item(hir::Item {
4073                            kind: hir::ItemKind::Trait(_, _, _, ident, _, bounds, _),
4074                            ..
4075                        }) => {
4076                            let (sp, sep, article) = if bounds.is_empty() {
4077                                (ident.span.shrink_to_hi(), ":", "a")
4078                            } else {
4079                                (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
4080                            };
4081                            err.span_suggestions(
4082                                sp,
4083                                message(format!("add {article} supertrait for")),
4084                                candidates
4085                                    .iter()
4086                                    .map(|t| format!("{} {}", sep, tcx.def_path_str(t.def_id),)),
4087                                Applicability::MaybeIncorrect,
4088                            );
4089                            return;
4090                        }
4091                        _ => {}
4092                    }
4093                }
4094            }
4095
4096            let (potential_candidates, explicitly_negative) = if param_type.is_some() {
4097                // FIXME: Even though negative bounds are not implemented, we could maybe handle
4098                // cases where a positive bound implies a negative impl.
4099                (candidates, Vec::new())
4100            } else if let Some(simp_rcvr_ty) =
4101                simplify_type(self.tcx, rcvr_ty, TreatParams::AsRigid)
4102            {
4103                let mut potential_candidates = Vec::new();
4104                let mut explicitly_negative = Vec::new();
4105                for candidate in candidates {
4106                    // Check if there's a negative impl of `candidate` for `rcvr_ty`
4107                    if self
4108                        .tcx
4109                        .all_impls(candidate.def_id)
4110                        .map(|imp_did| {
4111                            self.tcx.impl_trait_header(imp_did).expect(
4112                                "inherent impls can't be candidates, only trait impls can be",
4113                            )
4114                        })
4115                        .filter(|header| header.polarity != ty::ImplPolarity::Positive)
4116                        .any(|header| {
4117                            let imp = header.trait_ref.instantiate_identity();
4118                            let imp_simp =
4119                                simplify_type(self.tcx, imp.self_ty(), TreatParams::AsRigid);
4120                            imp_simp.is_some_and(|s| s == simp_rcvr_ty)
4121                        })
4122                    {
4123                        explicitly_negative.push(candidate);
4124                    } else {
4125                        potential_candidates.push(candidate);
4126                    }
4127                }
4128                (potential_candidates, explicitly_negative)
4129            } else {
4130                // We don't know enough about `recv_ty` to make proper suggestions.
4131                (candidates, Vec::new())
4132            };
4133
4134            let impls_trait = |def_id: DefId| {
4135                let args = ty::GenericArgs::for_item(self.tcx, def_id, |param, _| {
4136                    if param.index == 0 {
4137                        rcvr_ty.into()
4138                    } else {
4139                        self.infcx.var_for_def(span, param)
4140                    }
4141                });
4142                self.infcx
4143                    .type_implements_trait(def_id, args, self.param_env)
4144                    .must_apply_modulo_regions()
4145                    && param_type.is_none()
4146            };
4147            match &potential_candidates[..] {
4148                [] => {}
4149                [trait_info] if trait_info.def_id.is_local() => {
4150                    if impls_trait(trait_info.def_id) {
4151                        self.suggest_valid_traits(err, item_name, vec![trait_info.def_id], false);
4152                    } else {
4153                        err.subdiagnostic(CandidateTraitNote {
4154                            span: self.tcx.def_span(trait_info.def_id),
4155                            trait_name: self.tcx.def_path_str(trait_info.def_id),
4156                            item_name,
4157                            action_or_ty: if trait_missing_method {
4158                                "NONE".to_string()
4159                            } else {
4160                                param_type.map_or_else(
4161                                    || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented.
4162                                    |p| p.to_string(),
4163                                )
4164                            },
4165                        });
4166                    }
4167                }
4168                trait_infos => {
4169                    let mut msg = message(param_type.map_or_else(
4170                        || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented.
4171                        |param| format!("restrict type parameter `{param}` with"),
4172                    ));
4173                    for (i, trait_info) in trait_infos.iter().enumerate() {
4174                        if impls_trait(trait_info.def_id) {
4175                            self.suggest_valid_traits(
4176                                err,
4177                                item_name,
4178                                vec![trait_info.def_id],
4179                                false,
4180                            );
4181                        }
4182                        msg.push_str(&format!(
4183                            "\ncandidate #{}: `{}`",
4184                            i + 1,
4185                            self.tcx.def_path_str(trait_info.def_id),
4186                        ));
4187                    }
4188                    err.note(msg);
4189                }
4190            }
4191            match &explicitly_negative[..] {
4192                [] => {}
4193                [trait_info] => {
4194                    let msg = format!(
4195                        "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
4196                        self.tcx.def_path_str(trait_info.def_id),
4197                        item_name
4198                    );
4199                    err.note(msg);
4200                }
4201                trait_infos => {
4202                    let mut msg = format!(
4203                        "the following traits define an item `{item_name}`, but are explicitly unimplemented:"
4204                    );
4205                    for trait_info in trait_infos {
4206                        msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
4207                    }
4208                    err.note(msg);
4209                }
4210            }
4211        }
4212    }
4213
4214    fn detect_and_explain_multiple_crate_versions_of_trait_item(
4215        &self,
4216        err: &mut Diag<'_>,
4217        item_def_id: DefId,
4218        hir_id: hir::HirId,
4219        rcvr_ty: Option<Ty<'_>>,
4220    ) -> bool {
4221        let hir_id = self.tcx.parent_hir_id(hir_id);
4222        let Some(traits) = self.tcx.in_scope_traits(hir_id) else { return false };
4223        if traits.is_empty() {
4224            return false;
4225        }
4226        let trait_def_id = self.tcx.parent(item_def_id);
4227        if !self.tcx.is_trait(trait_def_id) {
4228            return false;
4229        }
4230        let krate = self.tcx.crate_name(trait_def_id.krate);
4231        let name = self.tcx.item_name(trait_def_id);
4232        let candidates: Vec<_> = traits
4233            .iter()
4234            .filter(|c| {
4235                c.def_id.krate != trait_def_id.krate
4236                    && self.tcx.crate_name(c.def_id.krate) == krate
4237                    && self.tcx.item_name(c.def_id) == name
4238            })
4239            .map(|c| (c.def_id, c.import_ids.get(0).cloned()))
4240            .collect();
4241        if candidates.is_empty() {
4242            return false;
4243        }
4244        let item_span = self.tcx.def_span(item_def_id);
4245        let msg = format!(
4246            "there are multiple different versions of crate `{krate}` in the dependency graph",
4247        );
4248        let trait_span = self.tcx.def_span(trait_def_id);
4249        let mut multi_span: MultiSpan = trait_span.into();
4250        multi_span.push_span_label(trait_span, format!("this is the trait that is needed"));
4251        let descr = self.tcx.associated_item(item_def_id).descr();
4252        let rcvr_ty =
4253            rcvr_ty.map(|t| format!("`{t}`")).unwrap_or_else(|| "the receiver".to_string());
4254        multi_span
4255            .push_span_label(item_span, format!("the {descr} is available for {rcvr_ty} here"));
4256        for (def_id, import_def_id) in candidates {
4257            if let Some(import_def_id) = import_def_id {
4258                multi_span.push_span_label(
4259                    self.tcx.def_span(import_def_id),
4260                    format!(
4261                        "`{name}` imported here doesn't correspond to the right version of crate \
4262                         `{krate}`",
4263                    ),
4264                );
4265            }
4266            multi_span.push_span_label(
4267                self.tcx.def_span(def_id),
4268                format!("this is the trait that was imported"),
4269            );
4270        }
4271        err.span_note(multi_span, msg);
4272        true
4273    }
4274
4275    /// issue #102320, for `unwrap_or` with closure as argument, suggest `unwrap_or_else`
4276    /// FIXME: currently not working for suggesting `map_or_else`, see #102408
4277    pub(crate) fn suggest_else_fn_with_closure(
4278        &self,
4279        err: &mut Diag<'_>,
4280        expr: &hir::Expr<'_>,
4281        found: Ty<'tcx>,
4282        expected: Ty<'tcx>,
4283    ) -> bool {
4284        let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(found) else {
4285            return false;
4286        };
4287
4288        if !self.may_coerce(output, expected) {
4289            return false;
4290        }
4291
4292        if let Node::Expr(call_expr) = self.tcx.parent_hir_node(expr.hir_id)
4293            && let hir::ExprKind::MethodCall(
4294                hir::PathSegment { ident: method_name, .. },
4295                self_expr,
4296                args,
4297                ..,
4298            ) = call_expr.kind
4299            && let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr)
4300        {
4301            let new_name = Ident {
4302                name: Symbol::intern(&format!("{}_else", method_name.as_str())),
4303                span: method_name.span,
4304            };
4305            let probe = self.lookup_probe_for_diagnostic(
4306                new_name,
4307                self_ty,
4308                self_expr,
4309                ProbeScope::TraitsInScope,
4310                Some(expected),
4311            );
4312
4313            // check the method arguments number
4314            if let Ok(pick) = probe
4315                && let fn_sig = self.tcx.fn_sig(pick.item.def_id)
4316                && let fn_args = fn_sig.skip_binder().skip_binder().inputs()
4317                && fn_args.len() == args.len() + 1
4318            {
4319                err.span_suggestion_verbose(
4320                    method_name.span.shrink_to_hi(),
4321                    format!("try calling `{}` instead", new_name.name.as_str()),
4322                    "_else",
4323                    Applicability::MaybeIncorrect,
4324                );
4325                return true;
4326            }
4327        }
4328        false
4329    }
4330
4331    /// Checks whether there is a local type somewhere in the chain of
4332    /// autoderefs of `rcvr_ty`.
4333    fn type_derefs_to_local(
4334        &self,
4335        span: Span,
4336        rcvr_ty: Ty<'tcx>,
4337        source: SelfSource<'tcx>,
4338    ) -> bool {
4339        fn is_local(ty: Ty<'_>) -> bool {
4340            match ty.kind() {
4341                ty::Adt(def, _) => def.did().is_local(),
4342                ty::Foreign(did) => did.is_local(),
4343                ty::Dynamic(tr, ..) => tr.principal().is_some_and(|d| d.def_id().is_local()),
4344                ty::Param(_) => true,
4345
4346                // Everything else (primitive types, etc.) is effectively
4347                // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
4348                // the noise from these sort of types is usually just really
4349                // annoying, rather than any sort of help).
4350                _ => false,
4351            }
4352        }
4353
4354        // This occurs for UFCS desugaring of `T::method`, where there is no
4355        // receiver expression for the method call, and thus no autoderef.
4356        if let SelfSource::QPath(_) = source {
4357            return is_local(rcvr_ty);
4358        }
4359
4360        self.autoderef(span, rcvr_ty).silence_errors().any(|(ty, _)| is_local(ty))
4361    }
4362}
4363
4364#[derive(Copy, Clone, Debug)]
4365enum SelfSource<'a> {
4366    QPath(&'a hir::Ty<'a>),
4367    MethodCall(&'a hir::Expr<'a> /* rcvr */),
4368}
4369
4370#[derive(Copy, Clone, PartialEq, Eq)]
4371pub(crate) struct TraitInfo {
4372    pub def_id: DefId,
4373}
4374
4375/// Retrieves all traits in this crate and any dependent crates,
4376/// and wraps them into `TraitInfo` for custom sorting.
4377pub(crate) fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
4378    tcx.all_traits_including_private().map(|def_id| TraitInfo { def_id }).collect()
4379}
4380
4381fn print_disambiguation_help<'tcx>(
4382    tcx: TyCtxt<'tcx>,
4383    err: &mut Diag<'_>,
4384    source: SelfSource<'tcx>,
4385    args: Option<&'tcx [hir::Expr<'tcx>]>,
4386    trait_ref: ty::TraitRef<'tcx>,
4387    candidate_idx: Option<usize>,
4388    span: Span,
4389    item: ty::AssocItem,
4390) -> Option<String> {
4391    let trait_impl_type = trait_ref.self_ty().peel_refs();
4392    let trait_ref = if item.is_method() {
4393        trait_ref.print_only_trait_name().to_string()
4394    } else {
4395        format!("<{} as {}>", trait_ref.args[0], trait_ref.print_only_trait_name())
4396    };
4397    Some(
4398        if item.is_fn()
4399            && let SelfSource::MethodCall(receiver) = source
4400            && let Some(args) = args
4401        {
4402            let def_kind_descr = tcx.def_kind_descr(item.as_def_kind(), item.def_id);
4403            let item_name = item.ident(tcx);
4404            let first_input =
4405                tcx.fn_sig(item.def_id).instantiate_identity().skip_binder().inputs().get(0);
4406            let (first_arg_type, rcvr_ref) = (
4407                first_input.map(|first| first.peel_refs()),
4408                first_input
4409                    .and_then(|ty| ty.ref_mutability())
4410                    .map_or("", |mutbl| mutbl.ref_prefix_str()),
4411            );
4412
4413            // If the type of first arg of this assoc function is `Self` or current trait impl type or `arbitrary_self_types`, we need to take the receiver as args. Otherwise, we don't.
4414            let args = if let Some(first_arg_type) = first_arg_type
4415                && (first_arg_type == tcx.types.self_param
4416                    || first_arg_type == trait_impl_type
4417                    || item.is_method())
4418            {
4419                Some(receiver)
4420            } else {
4421                None
4422            }
4423            .into_iter()
4424            .chain(args)
4425            .map(|arg| {
4426                tcx.sess.source_map().span_to_snippet(arg.span).unwrap_or_else(|_| "_".to_owned())
4427            })
4428            .collect::<Vec<_>>()
4429            .join(", ");
4430
4431            let args = format!("({}{})", rcvr_ref, args);
4432            err.span_suggestion_verbose(
4433                span,
4434                format!(
4435                    "disambiguate the {def_kind_descr} for {}",
4436                    if let Some(candidate) = candidate_idx {
4437                        format!("candidate #{candidate}")
4438                    } else {
4439                        "the candidate".to_string()
4440                    },
4441                ),
4442                format!("{trait_ref}::{item_name}{args}"),
4443                Applicability::HasPlaceholders,
4444            );
4445            return None;
4446        } else {
4447            format!("{trait_ref}::")
4448        },
4449    )
4450}