rustc_hir_typeck/method/
suggest.rs

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