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