]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/method/suggest.rs
detect () to avoid redundant <> suggestion for type
[rust.git] / compiler / rustc_hir_typeck / src / 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 use crate::errors;
5 use crate::FnCtxt;
6 use rustc_ast::ast::Mutability;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_errors::{
9     pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
10     MultiSpan,
11 };
12 use rustc_hir as hir;
13 use rustc_hir::def::DefKind;
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_hir::{ExprKind, Node, QPath};
17 use rustc_infer::infer::{
18     type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
19     RegionVariableOrigin,
20 };
21 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
22 use rustc_middle::traits::util::supertraits;
23 use rustc_middle::ty::fast_reject::DeepRejectCtxt;
24 use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
25 use rustc_middle::ty::print::with_crate_prefix;
26 use rustc_middle::ty::{self, DefIdTree, GenericArgKind, ToPredicate, Ty, TyCtxt, TypeVisitable};
27 use rustc_middle::ty::{IsSuggestable, ToPolyTraitRef};
28 use rustc_span::symbol::{kw, sym, Ident};
29 use rustc_span::Symbol;
30 use rustc_span::{lev_distance, source_map, ExpnKind, FileName, MacroKind, Span};
31 use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedNote;
32 use rustc_trait_selection::traits::error_reporting::on_unimplemented::TypeErrCtxtExt as _;
33 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34 use rustc_trait_selection::traits::{
35     FulfillmentError, Obligation, ObligationCause, ObligationCauseCode,
36 };
37
38 use std::cmp::Ordering;
39 use std::iter;
40
41 use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
42 use super::{CandidateSource, MethodError, NoMatchData};
43
44 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
45     fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
46         let tcx = self.tcx;
47         match ty.kind() {
48             // Not all of these (e.g., unsafe fns) implement `FnOnce`,
49             // so we look for these beforehand.
50             ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true,
51             // If it's not a simple function, look for things which implement `FnOnce`.
52             _ => {
53                 let Some(fn_once) = tcx.lang_items().fn_once_trait() else {
54                     return false;
55                 };
56
57                 // This conditional prevents us from asking to call errors and unresolved types.
58                 // It might seem that we can use `predicate_must_hold_modulo_regions`,
59                 // but since a Dummy binder is used to fill in the FnOnce trait's arguments,
60                 // type resolution always gives a "maybe" here.
61                 if self.autoderef(span, ty).any(|(ty, _)| {
62                     info!("check deref {:?} error", ty);
63                     matches!(ty.kind(), ty::Error(_) | ty::Infer(_))
64                 }) {
65                     return false;
66                 }
67
68                 self.autoderef(span, ty).any(|(ty, _)| {
69                     info!("check deref {:?} impl FnOnce", ty);
70                     self.probe(|_| {
71                         let fn_once_substs = tcx.mk_substs_trait(
72                             ty,
73                             &[self
74                                 .next_ty_var(TypeVariableOrigin {
75                                     kind: TypeVariableOriginKind::MiscVariable,
76                                     span,
77                                 })
78                                 .into()],
79                         );
80                         let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
81                         let poly_trait_ref = ty::Binder::dummy(trait_ref);
82                         let obligation = Obligation::misc(
83                             span,
84                             self.body_id,
85                             self.param_env,
86                             poly_trait_ref.without_const().to_predicate(tcx),
87                         );
88                         self.predicate_may_hold(&obligation)
89                     })
90                 })
91             }
92         }
93     }
94
95     fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
96         self.autoderef(span, ty).any(|(ty, _)| matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
97     }
98
99     pub fn report_method_error(
100         &self,
101         mut span: Span,
102         rcvr_ty: Ty<'tcx>,
103         item_name: Ident,
104         source: SelfSource<'tcx>,
105         error: MethodError<'tcx>,
106         args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
107     ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
108         // Avoid suggestions when we don't know what's going on.
109         if rcvr_ty.references_error() {
110             return None;
111         }
112
113         let report_candidates = |span: Span,
114                                  err: &mut Diagnostic,
115                                  sources: &mut Vec<CandidateSource>,
116                                  sugg_span: Span| {
117             sources.sort();
118             sources.dedup();
119             // Dynamic limit to avoid hiding just one candidate, which is silly.
120             let limit = if sources.len() == 5 { 5 } else { 4 };
121
122             for (idx, source) in sources.iter().take(limit).enumerate() {
123                 match *source {
124                     CandidateSource::Impl(impl_did) => {
125                         // Provide the best span we can. Use the item, if local to crate, else
126                         // the impl, if local to crate (item may be defaulted), else nothing.
127                         let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
128                             let impl_trait_ref = self.tcx.impl_trait_ref(impl_did)?;
129                             self.associated_value(impl_trait_ref.def_id, item_name)
130                         }) else {
131                             continue;
132                         };
133
134                         let note_span = if item.def_id.is_local() {
135                             Some(self.tcx.def_span(item.def_id))
136                         } else if impl_did.is_local() {
137                             Some(self.tcx.def_span(impl_did))
138                         } else {
139                             None
140                         };
141
142                         let impl_ty = self.tcx.at(span).type_of(impl_did);
143
144                         let insertion = match self.tcx.impl_trait_ref(impl_did) {
145                             None => String::new(),
146                             Some(trait_ref) => format!(
147                                 " of the trait `{}`",
148                                 self.tcx.def_path_str(trait_ref.def_id)
149                             ),
150                         };
151
152                         let (note_str, idx) = if sources.len() > 1 {
153                             (
154                                 format!(
155                                     "candidate #{} is defined in an impl{} for the type `{}`",
156                                     idx + 1,
157                                     insertion,
158                                     impl_ty,
159                                 ),
160                                 Some(idx + 1),
161                             )
162                         } else {
163                             (
164                                 format!(
165                                     "the candidate is defined in an impl{} for the type `{}`",
166                                     insertion, impl_ty,
167                                 ),
168                                 None,
169                             )
170                         };
171                         if let Some(note_span) = note_span {
172                             // We have a span pointing to the method. Show note with snippet.
173                             err.span_note(note_span, &note_str);
174                         } else {
175                             err.note(&note_str);
176                         }
177                         if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did) {
178                             let path = self.tcx.def_path_str(trait_ref.def_id);
179
180                             let ty = match item.kind {
181                                 ty::AssocKind::Const | ty::AssocKind::Type => rcvr_ty,
182                                 ty::AssocKind::Fn => self
183                                     .tcx
184                                     .fn_sig(item.def_id)
185                                     .inputs()
186                                     .skip_binder()
187                                     .get(0)
188                                     .filter(|ty| ty.is_region_ptr() && !rcvr_ty.is_region_ptr())
189                                     .copied()
190                                     .unwrap_or(rcvr_ty),
191                             };
192                             print_disambiguation_help(
193                                 item_name,
194                                 args,
195                                 err,
196                                 path,
197                                 ty,
198                                 item.kind,
199                                 item.def_id,
200                                 sugg_span,
201                                 idx,
202                                 self.tcx.sess.source_map(),
203                                 item.fn_has_self_parameter,
204                             );
205                         }
206                     }
207                     CandidateSource::Trait(trait_did) => {
208                         let Some(item) = self.associated_value(trait_did, item_name) else { continue };
209                         let item_span = self.tcx.def_span(item.def_id);
210                         let idx = if sources.len() > 1 {
211                             let msg = &format!(
212                                 "candidate #{} is defined in the trait `{}`",
213                                 idx + 1,
214                                 self.tcx.def_path_str(trait_did)
215                             );
216                             err.span_note(item_span, msg);
217                             Some(idx + 1)
218                         } else {
219                             let msg = &format!(
220                                 "the candidate is defined in the trait `{}`",
221                                 self.tcx.def_path_str(trait_did)
222                             );
223                             err.span_note(item_span, msg);
224                             None
225                         };
226                         let path = self.tcx.def_path_str(trait_did);
227                         print_disambiguation_help(
228                             item_name,
229                             args,
230                             err,
231                             path,
232                             rcvr_ty,
233                             item.kind,
234                             item.def_id,
235                             sugg_span,
236                             idx,
237                             self.tcx.sess.source_map(),
238                             item.fn_has_self_parameter,
239                         );
240                     }
241                 }
242             }
243             if sources.len() > limit {
244                 err.note(&format!("and {} others", sources.len() - limit));
245             }
246         };
247
248         let sugg_span = if let SelfSource::MethodCall(expr) = source {
249             // Given `foo.bar(baz)`, `expr` is `bar`, but we want to point to the whole thing.
250             self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)).span
251         } else {
252             span
253         };
254
255         match error {
256             MethodError::NoMatch(NoMatchData {
257                 mut static_candidates,
258                 unsatisfied_predicates,
259                 out_of_scope_traits,
260                 lev_candidate,
261                 mode,
262             }) => {
263                 let tcx = self.tcx;
264
265                 let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
266                 let ty_str = self.ty_to_string(rcvr_ty);
267                 let is_method = mode == Mode::MethodCall;
268                 let item_kind = if is_method {
269                     "method"
270                 } else if rcvr_ty.is_enum() {
271                     "variant or associated item"
272                 } else {
273                     match (item_name.as_str().chars().next(), rcvr_ty.is_fresh_ty()) {
274                         (Some(name), false) if name.is_lowercase() => "function or associated item",
275                         (Some(_), false) => "associated item",
276                         (Some(_), true) | (None, false) => "variant or associated item",
277                         (None, true) => "variant",
278                     }
279                 };
280
281                 if self.suggest_wrapping_range_with_parens(
282                     tcx, rcvr_ty, source, span, item_name, &ty_str,
283                 ) || self.suggest_constraining_numerical_ty(
284                     tcx, rcvr_ty, source, span, item_kind, item_name, &ty_str,
285                 ) {
286                     return None;
287                 }
288                 span = item_name.span;
289
290                 // Don't show generic arguments when the method can't be found in any implementation (#81576).
291                 let mut ty_str_reported = ty_str.clone();
292                 if let ty::Adt(_, generics) = rcvr_ty.kind() {
293                     if generics.len() > 0 {
294                         let mut autoderef = self.autoderef(span, rcvr_ty);
295                         let candidate_found = autoderef.any(|(ty, _)| {
296                             if let ty::Adt(adt_def, _) = ty.kind() {
297                                 self.tcx
298                                     .inherent_impls(adt_def.did())
299                                     .iter()
300                                     .filter_map(|def_id| self.associated_value(*def_id, item_name))
301                                     .count()
302                                     >= 1
303                             } else {
304                                 false
305                             }
306                         });
307                         let has_deref = autoderef.step_count() > 0;
308                         if !candidate_found && !has_deref && unsatisfied_predicates.is_empty() {
309                             if let Some((path_string, _)) = ty_str.split_once('<') {
310                                 ty_str_reported = path_string.to_string();
311                             }
312                         }
313                     }
314                 }
315
316                 let mut err = struct_span_err!(
317                     tcx.sess,
318                     span,
319                     E0599,
320                     "no {} named `{}` found for {} `{}` in the current scope",
321                     item_kind,
322                     item_name,
323                     rcvr_ty.prefix_string(self.tcx),
324                     ty_str_reported,
325                 );
326                 if rcvr_ty.references_error() {
327                     err.downgrade_to_delayed_bug();
328                 }
329
330                 if let Mode::MethodCall = mode && let SelfSource::MethodCall(cal) = source {
331                     self.suggest_await_before_method(
332                         &mut err, item_name, rcvr_ty, cal, span,
333                     );
334                 }
335                 if let Some(span) = tcx.resolutions(()).confused_type_with_std_module.get(&span) {
336                     err.span_suggestion(
337                         span.shrink_to_lo(),
338                         "you are looking for the module in `std`, not the primitive type",
339                         "std::",
340                         Applicability::MachineApplicable,
341                     );
342                 }
343                 if let ty::RawPtr(_) = &rcvr_ty.kind() {
344                     err.note(
345                         "try using `<*const T>::as_ref()` to get a reference to the \
346                          type behind the pointer: https://doc.rust-lang.org/std/\
347                          primitive.pointer.html#method.as_ref",
348                     );
349                     err.note(
350                         "using `<*const T>::as_ref()` on a pointer which is unaligned or points \
351                          to invalid or uninitialized memory is undefined behavior",
352                     );
353                 }
354
355                 let ty_span = match rcvr_ty.kind() {
356                     ty::Param(param_type) => Some(
357                         param_type.span_from_generics(self.tcx, self.body_id.owner.to_def_id()),
358                     ),
359                     ty::Adt(def, _) if def.did().is_local() => Some(tcx.def_span(def.did())),
360                     _ => None,
361                 };
362                 if let Some(span) = ty_span {
363                     err.span_label(
364                         span,
365                         format!(
366                             "{item_kind} `{item_name}` not found for this {}",
367                             rcvr_ty.prefix_string(self.tcx)
368                         ),
369                     );
370                 }
371
372                 if let SelfSource::MethodCall(rcvr_expr) = source {
373                     self.suggest_fn_call(&mut err, rcvr_expr, rcvr_ty, |output_ty| {
374                         let call_expr = self
375                             .tcx
376                             .hir()
377                             .expect_expr(self.tcx.hir().get_parent_node(rcvr_expr.hir_id));
378                         let probe = self.lookup_probe(
379                             span,
380                             item_name,
381                             output_ty,
382                             call_expr,
383                             ProbeScope::AllTraits,
384                         );
385                         probe.is_ok()
386                     });
387                 }
388
389                 let mut custom_span_label = false;
390
391                 if !static_candidates.is_empty() {
392                     err.note(
393                         "found the following associated functions; to be used as methods, \
394                          functions must have a `self` parameter",
395                     );
396                     err.span_label(span, "this is an associated function, not a method");
397                     custom_span_label = true;
398                 }
399                 if static_candidates.len() == 1 {
400                     self.suggest_associated_call_syntax(
401                         &mut err,
402                         &static_candidates,
403                         rcvr_ty,
404                         source,
405                         item_name,
406                         args,
407                         sugg_span,
408                     );
409
410                     report_candidates(span, &mut err, &mut static_candidates, sugg_span);
411                 } else if static_candidates.len() > 1 {
412                     report_candidates(span, &mut err, &mut static_candidates, sugg_span);
413                 }
414
415                 let mut bound_spans = vec![];
416                 let mut restrict_type_params = false;
417                 let mut unsatisfied_bounds = false;
418                 if item_name.name == sym::count && self.is_slice_ty(rcvr_ty, span) {
419                     let msg = "consider using `len` instead";
420                     if let SelfSource::MethodCall(_expr) = source {
421                         err.span_suggestion_short(
422                             span,
423                             msg,
424                             "len",
425                             Applicability::MachineApplicable,
426                         );
427                     } else {
428                         err.span_label(span, msg);
429                     }
430                     if let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) {
431                         let iterator_trait = self.tcx.def_path_str(iterator_trait);
432                         err.note(&format!("`count` is defined on `{iterator_trait}`, which `{rcvr_ty}` does not implement"));
433                     }
434                 } else if !unsatisfied_predicates.is_empty() {
435                     let mut type_params = FxHashMap::default();
436
437                     // Pick out the list of unimplemented traits on the receiver.
438                     // This is used for custom error messages with the `#[rustc_on_unimplemented]` attribute.
439                     let mut unimplemented_traits = FxHashMap::default();
440                     let mut unimplemented_traits_only = true;
441                     for (predicate, _parent_pred, cause) in &unsatisfied_predicates {
442                         if let (ty::PredicateKind::Trait(p), Some(cause)) =
443                             (predicate.kind().skip_binder(), cause.as_ref())
444                         {
445                             if p.trait_ref.self_ty() != rcvr_ty {
446                                 // This is necessary, not just to keep the errors clean, but also
447                                 // because our derived obligations can wind up with a trait ref that
448                                 // requires a different param_env to be correctly compared.
449                                 continue;
450                             }
451                             unimplemented_traits.entry(p.trait_ref.def_id).or_insert((
452                                 predicate.kind().rebind(p.trait_ref),
453                                 Obligation {
454                                     cause: cause.clone(),
455                                     param_env: self.param_env,
456                                     predicate: *predicate,
457                                     recursion_depth: 0,
458                                 },
459                             ));
460                         }
461                     }
462
463                     // Make sure that, if any traits other than the found ones were involved,
464                     // we don't don't report an unimplemented trait.
465                     // We don't want to say that `iter::Cloned` is not an iterator, just
466                     // because of some non-Clone item being iterated over.
467                     for (predicate, _parent_pred, _cause) in &unsatisfied_predicates {
468                         match predicate.kind().skip_binder() {
469                             ty::PredicateKind::Trait(p)
470                                 if unimplemented_traits.contains_key(&p.trait_ref.def_id) => {}
471                             _ => {
472                                 unimplemented_traits_only = false;
473                                 break;
474                             }
475                         }
476                     }
477
478                     let mut collect_type_param_suggestions =
479                         |self_ty: Ty<'tcx>, parent_pred: ty::Predicate<'tcx>, obligation: &str| {
480                             // We don't care about regions here, so it's fine to skip the binder here.
481                             if let (ty::Param(_), ty::PredicateKind::Trait(p)) =
482                                 (self_ty.kind(), parent_pred.kind().skip_binder())
483                             {
484                                 let hir = self.tcx.hir();
485                                 let node = match p.trait_ref.self_ty().kind() {
486                                     ty::Param(_) => {
487                                         // Account for `fn` items like in `issue-35677.rs` to
488                                         // suggest restricting its type params.
489                                         let parent_body =
490                                             hir.body_owner(hir::BodyId { hir_id: self.body_id });
491                                         Some(hir.get(parent_body))
492                                     }
493                                     ty::Adt(def, _) => {
494                                         def.did().as_local().map(|def_id| hir.get_by_def_id(def_id))
495                                     }
496                                     _ => None,
497                                 };
498                                 if let Some(hir::Node::Item(hir::Item { kind, .. })) = node {
499                                     if let Some(g) = kind.generics() {
500                                         let key = (
501                                             g.tail_span_for_predicate_suggestion(),
502                                             g.add_where_or_trailing_comma(),
503                                         );
504                                         type_params
505                                             .entry(key)
506                                             .or_insert_with(FxHashSet::default)
507                                             .insert(obligation.to_owned());
508                                     }
509                                 }
510                             }
511                         };
512                     let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
513                         let msg = format!(
514                             "doesn't satisfy `{}`",
515                             if obligation.len() > 50 { quiet } else { obligation }
516                         );
517                         match &self_ty.kind() {
518                             // Point at the type that couldn't satisfy the bound.
519                             ty::Adt(def, _) => {
520                                 bound_spans.push((self.tcx.def_span(def.did()), msg))
521                             }
522                             // Point at the trait object that couldn't satisfy the bound.
523                             ty::Dynamic(preds, _, _) => {
524                                 for pred in preds.iter() {
525                                     match pred.skip_binder() {
526                                         ty::ExistentialPredicate::Trait(tr) => bound_spans
527                                             .push((self.tcx.def_span(tr.def_id), msg.clone())),
528                                         ty::ExistentialPredicate::Projection(_)
529                                         | ty::ExistentialPredicate::AutoTrait(_) => {}
530                                     }
531                                 }
532                             }
533                             // Point at the closure that couldn't satisfy the bound.
534                             ty::Closure(def_id, _) => bound_spans.push((
535                                 tcx.def_span(*def_id),
536                                 format!("doesn't satisfy `{}`", quiet),
537                             )),
538                             _ => {}
539                         }
540                     };
541                     let mut format_pred = |pred: ty::Predicate<'tcx>| {
542                         let bound_predicate = pred.kind();
543                         match bound_predicate.skip_binder() {
544                             ty::PredicateKind::Projection(pred) => {
545                                 let pred = bound_predicate.rebind(pred);
546                                 // `<Foo as Iterator>::Item = String`.
547                                 let projection_ty = pred.skip_binder().projection_ty;
548
549                                 let substs_with_infer_self = tcx.mk_substs(
550                                     iter::once(tcx.mk_ty_var(ty::TyVid::from_u32(0)).into())
551                                         .chain(projection_ty.substs.iter().skip(1)),
552                                 );
553
554                                 let quiet_projection_ty = ty::ProjectionTy {
555                                     substs: substs_with_infer_self,
556                                     item_def_id: projection_ty.item_def_id,
557                                 };
558
559                                 let term = pred.skip_binder().term;
560
561                                 let obligation = format!("{} = {}", projection_ty, term);
562                                 let quiet = format!("{} = {}", quiet_projection_ty, term);
563
564                                 bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
565                                 Some((obligation, projection_ty.self_ty()))
566                             }
567                             ty::PredicateKind::Trait(poly_trait_ref) => {
568                                 let p = poly_trait_ref.trait_ref;
569                                 let self_ty = p.self_ty();
570                                 let path = p.print_only_trait_path();
571                                 let obligation = format!("{}: {}", self_ty, path);
572                                 let quiet = format!("_: {}", path);
573                                 bound_span_label(self_ty, &obligation, &quiet);
574                                 Some((obligation, self_ty))
575                             }
576                             _ => None,
577                         }
578                     };
579
580                     // Find all the requirements that come from a local `impl` block.
581                     let mut skip_list: FxHashSet<_> = Default::default();
582                     let mut spanned_predicates: FxHashMap<MultiSpan, _> = Default::default();
583                     for (data, p, parent_p, impl_def_id, cause) in unsatisfied_predicates
584                         .iter()
585                         .filter_map(|(p, parent, c)| c.as_ref().map(|c| (p, parent, c)))
586                         .filter_map(|(p, parent, c)| match c.code() {
587                             ObligationCauseCode::ImplDerivedObligation(data) => {
588                                 Some((&data.derived, p, parent, data.impl_def_id, data))
589                             }
590                             _ => None,
591                         })
592                     {
593                         let parent_trait_ref = data.parent_trait_pred;
594                         let path = parent_trait_ref.print_modifiers_and_trait_path();
595                         let tr_self_ty = parent_trait_ref.skip_binder().self_ty();
596                         let unsatisfied_msg = "unsatisfied trait bound introduced here";
597                         let derive_msg =
598                             "unsatisfied trait bound introduced in this `derive` macro";
599                         match self.tcx.hir().get_if_local(impl_def_id) {
600                             // Unmet obligation comes from a `derive` macro, point at it once to
601                             // avoid multiple span labels pointing at the same place.
602                             Some(Node::Item(hir::Item {
603                                 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
604                                 ..
605                             })) if matches!(
606                                 self_ty.span.ctxt().outer_expn_data().kind,
607                                 ExpnKind::Macro(MacroKind::Derive, _)
608                             ) || matches!(
609                                 of_trait.as_ref().map(|t| t
610                                     .path
611                                     .span
612                                     .ctxt()
613                                     .outer_expn_data()
614                                     .kind),
615                                 Some(ExpnKind::Macro(MacroKind::Derive, _))
616                             ) =>
617                             {
618                                 let span = self_ty.span.ctxt().outer_expn_data().call_site;
619                                 let mut spans: MultiSpan = span.into();
620                                 spans.push_span_label(span, derive_msg);
621                                 let entry = spanned_predicates.entry(spans);
622                                 entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p);
623                             }
624
625                             // Unmet obligation coming from an `impl`.
626                             Some(Node::Item(hir::Item {
627                                 kind:
628                                     hir::ItemKind::Impl(hir::Impl {
629                                         of_trait, self_ty, generics, ..
630                                     }),
631                                 span: item_span,
632                                 ..
633                             })) => {
634                                 let sized_pred =
635                                     unsatisfied_predicates.iter().any(|(pred, _, _)| {
636                                         match pred.kind().skip_binder() {
637                                             ty::PredicateKind::Trait(pred) => {
638                                                 Some(pred.def_id())
639                                                     == self.tcx.lang_items().sized_trait()
640                                                     && pred.polarity == ty::ImplPolarity::Positive
641                                             }
642                                             _ => false,
643                                         }
644                                     });
645                                 for param in generics.params {
646                                     if param.span == cause.span && sized_pred {
647                                         let (sp, sugg) = match param.colon_span {
648                                             Some(sp) => (sp.shrink_to_hi(), " ?Sized +"),
649                                             None => (param.span.shrink_to_hi(), ": ?Sized"),
650                                         };
651                                         err.span_suggestion_verbose(
652                                             sp,
653                                             "consider relaxing the type parameter's implicit \
654                                              `Sized` bound",
655                                             sugg,
656                                             Applicability::MachineApplicable,
657                                         );
658                                     }
659                                 }
660                                 if let Some(pred) = parent_p {
661                                     // Done to add the "doesn't satisfy" `span_label`.
662                                     let _ = format_pred(*pred);
663                                 }
664                                 skip_list.insert(p);
665                                 let mut spans = if cause.span != *item_span {
666                                     let mut spans: MultiSpan = cause.span.into();
667                                     spans.push_span_label(cause.span, unsatisfied_msg);
668                                     spans
669                                 } else {
670                                     let mut spans = Vec::with_capacity(2);
671                                     if let Some(trait_ref) = of_trait {
672                                         spans.push(trait_ref.path.span);
673                                     }
674                                     spans.push(self_ty.span);
675                                     spans.into()
676                                 };
677                                 if let Some(trait_ref) = of_trait {
678                                     spans.push_span_label(trait_ref.path.span, "");
679                                 }
680                                 spans.push_span_label(self_ty.span, "");
681
682                                 let entry = spanned_predicates.entry(spans);
683                                 entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p);
684                             }
685                             Some(_) => unreachable!(),
686                             None => (),
687                         }
688                     }
689                     let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
690                     spanned_predicates.sort_by_key(|(span, (_, _, _))| span.primary_span());
691                     for (span, (_path, _self_ty, preds)) in spanned_predicates {
692                         let mut preds: Vec<_> = preds
693                             .into_iter()
694                             .filter_map(|pred| format_pred(*pred))
695                             .map(|(p, _)| format!("`{}`", p))
696                             .collect();
697                         preds.sort();
698                         preds.dedup();
699                         let msg = if let [pred] = &preds[..] {
700                             format!("trait bound {} was not satisfied", pred)
701                         } else {
702                             format!(
703                                 "the following trait bounds were not satisfied:\n{}",
704                                 preds.join("\n"),
705                             )
706                         };
707                         err.span_note(span, &msg);
708                         unsatisfied_bounds = true;
709                     }
710
711                     // The requirements that didn't have an `impl` span to show.
712                     let mut bound_list = unsatisfied_predicates
713                         .iter()
714                         .filter_map(|(pred, parent_pred, _cause)| {
715                             format_pred(*pred).map(|(p, self_ty)| {
716                                 collect_type_param_suggestions(self_ty, *pred, &p);
717                                 (
718                                     match parent_pred {
719                                         None => format!("`{}`", &p),
720                                         Some(parent_pred) => match format_pred(*parent_pred) {
721                                             None => format!("`{}`", &p),
722                                             Some((parent_p, _)) => {
723                                                 collect_type_param_suggestions(
724                                                     self_ty,
725                                                     *parent_pred,
726                                                     &p,
727                                                 );
728                                                 format!(
729                                                     "`{}`\nwhich is required by `{}`",
730                                                     p, parent_p
731                                                 )
732                                             }
733                                         },
734                                     },
735                                     *pred,
736                                 )
737                             })
738                         })
739                         .filter(|(_, pred)| !skip_list.contains(&pred))
740                         .map(|(t, _)| t)
741                         .enumerate()
742                         .collect::<Vec<(usize, String)>>();
743
744                     for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
745                         restrict_type_params = true;
746                         // #74886: Sort here so that the output is always the same.
747                         let mut obligations = obligations.into_iter().collect::<Vec<_>>();
748                         obligations.sort();
749                         err.span_suggestion_verbose(
750                             span,
751                             &format!(
752                                 "consider restricting the type parameter{s} to satisfy the \
753                                  trait bound{s}",
754                                 s = pluralize!(obligations.len())
755                             ),
756                             format!("{} {}", add_where_or_comma, obligations.join(", ")),
757                             Applicability::MaybeIncorrect,
758                         );
759                     }
760
761                     bound_list.sort_by(|(_, a), (_, b)| a.cmp(b)); // Sort alphabetically.
762                     bound_list.dedup_by(|(_, a), (_, b)| a == b); // #35677
763                     bound_list.sort_by_key(|(pos, _)| *pos); // Keep the original predicate order.
764
765                     if !bound_list.is_empty() || !skip_list.is_empty() {
766                         let bound_list = bound_list
767                             .into_iter()
768                             .map(|(_, path)| path)
769                             .collect::<Vec<_>>()
770                             .join("\n");
771                         let actual_prefix = rcvr_ty.prefix_string(self.tcx);
772                         info!("unimplemented_traits.len() == {}", unimplemented_traits.len());
773                         let (primary_message, label) =
774                             if unimplemented_traits.len() == 1 && unimplemented_traits_only {
775                                 unimplemented_traits
776                                     .into_iter()
777                                     .next()
778                                     .map(|(_, (trait_ref, obligation))| {
779                                         if trait_ref.self_ty().references_error()
780                                             || rcvr_ty.references_error()
781                                         {
782                                             // Avoid crashing.
783                                             return (None, None);
784                                         }
785                                         let OnUnimplementedNote { message, label, .. } = self
786                                             .err_ctxt()
787                                             .on_unimplemented_note(trait_ref, &obligation);
788                                         (message, label)
789                                     })
790                                     .unwrap()
791                             } else {
792                                 (None, None)
793                             };
794                         let primary_message = primary_message.unwrap_or_else(|| format!(
795                             "the {item_kind} `{item_name}` exists for {actual_prefix} `{ty_str}`, but its trait bounds were not satisfied"
796                         ));
797                         err.set_primary_message(&primary_message);
798                         if let Some(label) = label {
799                             custom_span_label = true;
800                             err.span_label(span, label);
801                         }
802                         if !bound_list.is_empty() {
803                             err.note(&format!(
804                                 "the following trait bounds were not satisfied:\n{bound_list}"
805                             ));
806                         }
807                         self.suggest_derive(&mut err, &unsatisfied_predicates);
808
809                         unsatisfied_bounds = true;
810                     }
811                 }
812
813                 let label_span_not_found = |err: &mut Diagnostic| {
814                     if unsatisfied_predicates.is_empty() {
815                         err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
816                         let is_string_or_ref_str = match rcvr_ty.kind() {
817                             ty::Ref(_, ty, _) => {
818                                 ty.is_str()
819                                     || matches!(
820                                         ty.kind(),
821                                         ty::Adt(adt, _) if self.tcx.is_diagnostic_item(sym::String, adt.did())
822                                     )
823                             }
824                             ty::Adt(adt, _) => self.tcx.is_diagnostic_item(sym::String, adt.did()),
825                             _ => false,
826                         };
827                         if is_string_or_ref_str && item_name.name == sym::iter {
828                             err.span_suggestion_verbose(
829                                 item_name.span,
830                                 "because of the in-memory representation of `&str`, to obtain \
831                                  an `Iterator` over each of its codepoint use method `chars`",
832                                 "chars",
833                                 Applicability::MachineApplicable,
834                             );
835                         }
836                         if let ty::Adt(adt, _) = rcvr_ty.kind() {
837                             let mut inherent_impls_candidate = self
838                                 .tcx
839                                 .inherent_impls(adt.did())
840                                 .iter()
841                                 .copied()
842                                 .filter(|def_id| {
843                                     if let Some(assoc) = self.associated_value(*def_id, item_name) {
844                                         // Check for both mode is the same so we avoid suggesting
845                                         // incorrect associated item.
846                                         match (mode, assoc.fn_has_self_parameter, source) {
847                                             (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
848                                                 // We check that the suggest type is actually
849                                                 // different from the received one
850                                                 // So we avoid suggestion method with Box<Self>
851                                                 // for instance
852                                                 self.tcx.at(span).type_of(*def_id) != rcvr_ty
853                                                     && self.tcx.at(span).type_of(*def_id) != rcvr_ty
854                                             }
855                                             (Mode::Path, false, _) => true,
856                                             _ => false,
857                                         }
858                                     } else {
859                                         false
860                                     }
861                                 })
862                                 .collect::<Vec<_>>();
863                             if !inherent_impls_candidate.is_empty() {
864                                 inherent_impls_candidate.sort();
865                                 inherent_impls_candidate.dedup();
866
867                                 // number of type to shows at most.
868                                 let limit = if inherent_impls_candidate.len() == 5 { 5 } else { 4 };
869                                 let type_candidates = inherent_impls_candidate
870                                     .iter()
871                                     .take(limit)
872                                     .map(|impl_item| {
873                                         format!("- `{}`", self.tcx.at(span).type_of(*impl_item))
874                                     })
875                                     .collect::<Vec<_>>()
876                                     .join("\n");
877                                 let additional_types = if inherent_impls_candidate.len() > limit {
878                                     format!(
879                                         "\nand {} more types",
880                                         inherent_impls_candidate.len() - limit
881                                     )
882                                 } else {
883                                     "".to_string()
884                                 };
885                                 err.note(&format!(
886                                     "the {item_kind} was found for\n{}{}",
887                                     type_candidates, additional_types
888                                 ));
889                             }
890                         }
891                     } else {
892                         err.span_label(span, format!("{item_kind} cannot be called on `{ty_str}` due to unsatisfied trait bounds"));
893                     }
894                 };
895
896                 // If the method name is the name of a field with a function or closure type,
897                 // give a helping note that it has to be called as `(x.f)(...)`.
898                 if let SelfSource::MethodCall(expr) = source {
899                     if !self.suggest_calling_field_as_fn(span, rcvr_ty, expr, item_name, &mut err)
900                         && lev_candidate.is_none()
901                         && !custom_span_label
902                     {
903                         label_span_not_found(&mut err);
904                     }
905                 } else if !custom_span_label {
906                     label_span_not_found(&mut err);
907                 }
908
909                 // Don't suggest (for example) `expr.field.clone()` if `expr.clone()`
910                 // can't be called due to `typeof(expr): Clone` not holding.
911                 if unsatisfied_predicates.is_empty() {
912                     self.suggest_calling_method_on_field(
913                         &mut err, source, span, rcvr_ty, item_name,
914                     );
915                 }
916
917                 self.check_for_inner_self(&mut err, source, span, rcvr_ty, item_name);
918
919                 bound_spans.sort();
920                 bound_spans.dedup();
921                 for (span, msg) in bound_spans.into_iter() {
922                     err.span_label(span, &msg);
923                 }
924
925                 if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params {
926                 } else {
927                     self.suggest_traits_to_import(
928                         &mut err,
929                         span,
930                         rcvr_ty,
931                         item_name,
932                         args.map(|(_, args)| args.len() + 1),
933                         source,
934                         out_of_scope_traits,
935                         &unsatisfied_predicates,
936                         &static_candidates,
937                         unsatisfied_bounds,
938                     );
939                 }
940
941                 // Don't emit a suggestion if we found an actual method
942                 // that had unsatisfied trait bounds
943                 if unsatisfied_predicates.is_empty() && rcvr_ty.is_enum() {
944                     let adt_def = rcvr_ty.ty_adt_def().expect("enum is not an ADT");
945                     if let Some(suggestion) = lev_distance::find_best_match_for_name(
946                         &adt_def.variants().iter().map(|s| s.name).collect::<Vec<_>>(),
947                         item_name.name,
948                         None,
949                     ) {
950                         err.span_suggestion(
951                             span,
952                             "there is a variant with a similar name",
953                             suggestion,
954                             Applicability::MaybeIncorrect,
955                         );
956                     }
957                 }
958
959                 if item_name.name == sym::as_str && rcvr_ty.peel_refs().is_str() {
960                     let msg = "remove this method call";
961                     let mut fallback_span = true;
962                     if let SelfSource::MethodCall(expr) = source {
963                         let call_expr =
964                             self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
965                         if let Some(span) = call_expr.span.trim_start(expr.span) {
966                             err.span_suggestion(span, msg, "", Applicability::MachineApplicable);
967                             fallback_span = false;
968                         }
969                     }
970                     if fallback_span {
971                         err.span_label(span, msg);
972                     }
973                 } else if let Some(lev_candidate) = lev_candidate {
974                     // Don't emit a suggestion if we found an actual method
975                     // that had unsatisfied trait bounds
976                     if unsatisfied_predicates.is_empty() {
977                         let def_kind = lev_candidate.kind.as_def_kind();
978                         // Methods are defined within the context of a struct and their first parameter is always self,
979                         // which represents the instance of the struct the method is being called on
980                         // Associated functions don’t take self as a parameter and
981                         // they are not methods because they don’t have an instance of the struct to work with.
982                         if def_kind == DefKind::AssocFn && lev_candidate.fn_has_self_parameter {
983                             err.span_suggestion(
984                                 span,
985                                 &format!("there is a method with a similar name",),
986                                 lev_candidate.name,
987                                 Applicability::MaybeIncorrect,
988                             );
989                         } else {
990                             err.span_suggestion(
991                                 span,
992                                 &format!(
993                                     "there is {} {} with a similar name",
994                                     def_kind.article(),
995                                     def_kind.descr(lev_candidate.def_id),
996                                 ),
997                                 lev_candidate.name,
998                                 Applicability::MaybeIncorrect,
999                             );
1000                         }
1001                     }
1002                 }
1003
1004                 self.check_for_deref_method(&mut err, source, rcvr_ty, item_name);
1005
1006                 return Some(err);
1007             }
1008
1009             MethodError::Ambiguity(mut sources) => {
1010                 let mut err = struct_span_err!(
1011                     self.sess(),
1012                     item_name.span,
1013                     E0034,
1014                     "multiple applicable items in scope"
1015                 );
1016                 err.span_label(item_name.span, format!("multiple `{}` found", item_name));
1017
1018                 report_candidates(span, &mut err, &mut sources, sugg_span);
1019                 err.emit();
1020             }
1021
1022             MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
1023                 let kind = kind.descr(def_id);
1024                 let mut err = struct_span_err!(
1025                     self.tcx.sess,
1026                     item_name.span,
1027                     E0624,
1028                     "{} `{}` is private",
1029                     kind,
1030                     item_name
1031                 );
1032                 err.span_label(item_name.span, &format!("private {}", kind));
1033                 let sp = self
1034                     .tcx
1035                     .hir()
1036                     .span_if_local(def_id)
1037                     .unwrap_or_else(|| self.tcx.def_span(def_id));
1038                 err.span_label(sp, &format!("private {} defined here", kind));
1039                 self.suggest_valid_traits(&mut err, out_of_scope_traits);
1040                 err.emit();
1041             }
1042
1043             MethodError::IllegalSizedBound(candidates, needs_mut, bound_span) => {
1044                 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
1045                 let mut err = self.sess().struct_span_err(span, &msg);
1046                 err.span_label(bound_span, "this has a `Sized` requirement");
1047                 if !candidates.is_empty() {
1048                     let help = format!(
1049                         "{an}other candidate{s} {were} found in the following trait{s}, perhaps \
1050                          add a `use` for {one_of_them}:",
1051                         an = if candidates.len() == 1 { "an" } else { "" },
1052                         s = pluralize!(candidates.len()),
1053                         were = pluralize!("was", candidates.len()),
1054                         one_of_them = if candidates.len() == 1 { "it" } else { "one_of_them" },
1055                     );
1056                     self.suggest_use_candidates(&mut err, help, candidates);
1057                 }
1058                 if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind() {
1059                     if needs_mut {
1060                         let trait_type = self.tcx.mk_ref(
1061                             *region,
1062                             ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() },
1063                         );
1064                         err.note(&format!("you need `{}` instead of `{}`", trait_type, rcvr_ty));
1065                     }
1066                 }
1067                 err.emit();
1068             }
1069
1070             MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
1071         }
1072         None
1073     }
1074
1075     /// Suggest calling `Ty::method` if `.method()` isn't found because the method
1076     /// doesn't take a `self` receiver.
1077     fn suggest_associated_call_syntax(
1078         &self,
1079         err: &mut Diagnostic,
1080         static_candidates: &Vec<CandidateSource>,
1081         rcvr_ty: Ty<'tcx>,
1082         source: SelfSource<'tcx>,
1083         item_name: Ident,
1084         args: Option<(&hir::Expr<'tcx>, &[hir::Expr<'tcx>])>,
1085         sugg_span: Span,
1086     ) {
1087         let mut has_unsuggestable_args = false;
1088         let ty_str = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
1089             // When the "method" is resolved through dereferencing, we really want the
1090             // original type that has the associated function for accurate suggestions.
1091             // (#61411)
1092             let impl_ty = self.tcx.type_of(*impl_did);
1093             let target_ty = self
1094                 .autoderef(sugg_span, rcvr_ty)
1095                 .find(|(rcvr_ty, _)| {
1096                     DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer }
1097                         .types_may_unify(*rcvr_ty, impl_ty)
1098                 })
1099                 .map_or(impl_ty, |(ty, _)| ty)
1100                 .peel_refs();
1101             if let ty::Adt(def, substs) = target_ty.kind() {
1102                 // If there are any inferred arguments, (`{integer}`), we should replace
1103                 // them with underscores to allow the compiler to infer them
1104                 let infer_substs = self.tcx.mk_substs(substs.into_iter().map(|arg| {
1105                     if !arg.is_suggestable(self.tcx, true) {
1106                         has_unsuggestable_args = true;
1107                         match arg.unpack() {
1108                             GenericArgKind::Lifetime(_) => self
1109                                 .next_region_var(RegionVariableOrigin::MiscVariable(
1110                                     rustc_span::DUMMY_SP,
1111                                 ))
1112                                 .into(),
1113                             GenericArgKind::Type(_) => self
1114                                 .next_ty_var(TypeVariableOrigin {
1115                                     span: rustc_span::DUMMY_SP,
1116                                     kind: TypeVariableOriginKind::MiscVariable,
1117                                 })
1118                                 .into(),
1119                             GenericArgKind::Const(arg) => self
1120                                 .next_const_var(
1121                                     arg.ty(),
1122                                     ConstVariableOrigin {
1123                                         span: rustc_span::DUMMY_SP,
1124                                         kind: ConstVariableOriginKind::MiscVariable,
1125                                     },
1126                                 )
1127                                 .into(),
1128                         }
1129                     } else {
1130                         arg
1131                     }
1132                 }));
1133
1134                 self.tcx.value_path_str_with_substs(def.did(), infer_substs)
1135             } else {
1136                 self.ty_to_value_string(target_ty)
1137             }
1138         } else {
1139             self.ty_to_value_string(rcvr_ty.peel_refs())
1140         };
1141         if let SelfSource::MethodCall(_) = source {
1142             let first_arg = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0)
1143                 && let Some(assoc) = self.associated_value(*impl_did, item_name)
1144                 && assoc.kind == ty::AssocKind::Fn
1145             {
1146                 let sig = self.tcx.fn_sig(assoc.def_id);
1147                 if let Some(first) = sig.inputs().skip_binder().get(0) {
1148                     if first.peel_refs() == rcvr_ty.peel_refs() {
1149                         None
1150                     } else {
1151                         Some(if first.is_region_ptr() {
1152                             if first.is_mutable_ptr() { "&mut " } else { "&" }
1153                         } else {
1154                             ""
1155                         })
1156                     }
1157                 } else {
1158                     None
1159                 }
1160             } else {
1161                 None
1162             };
1163             let mut applicability = Applicability::MachineApplicable;
1164             let args = if let Some((receiver, args)) = args {
1165                 // The first arg is the same kind as the receiver
1166                 let explicit_args = if first_arg.is_some() {
1167                     std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
1168                 } else {
1169                     // There is no `Self` kind to infer the arguments from
1170                     if has_unsuggestable_args {
1171                         applicability = Applicability::HasPlaceholders;
1172                     }
1173                     args.iter().collect()
1174                 };
1175                 format!(
1176                     "({}{})",
1177                     first_arg.unwrap_or(""),
1178                     explicit_args
1179                         .iter()
1180                         .map(|arg| self
1181                             .tcx
1182                             .sess
1183                             .source_map()
1184                             .span_to_snippet(arg.span)
1185                             .unwrap_or_else(|_| {
1186                                 applicability = Applicability::HasPlaceholders;
1187                                 "_".to_owned()
1188                             }))
1189                         .collect::<Vec<_>>()
1190                         .join(", "),
1191                 )
1192             } else {
1193                 applicability = Applicability::HasPlaceholders;
1194                 "(...)".to_owned()
1195             };
1196             err.span_suggestion(
1197                 sugg_span,
1198                 "use associated function syntax instead",
1199                 format!("{}::{}{}", ty_str, item_name, args),
1200                 applicability,
1201             );
1202         } else {
1203             err.help(&format!("try with `{}::{}`", ty_str, item_name,));
1204         }
1205     }
1206
1207     /// Suggest calling a field with a type that implements the `Fn*` traits instead of a method with
1208     /// the same name as the field i.e. `(a.my_fn_ptr)(10)` instead of `a.my_fn_ptr(10)`.
1209     fn suggest_calling_field_as_fn(
1210         &self,
1211         span: Span,
1212         rcvr_ty: Ty<'tcx>,
1213         expr: &hir::Expr<'_>,
1214         item_name: Ident,
1215         err: &mut Diagnostic,
1216     ) -> bool {
1217         let tcx = self.tcx;
1218         let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() {
1219             ty::Adt(def, substs) if !def.is_enum() => {
1220                 let variant = &def.non_enum_variant();
1221                 tcx.find_field_index(item_name, variant).map(|index| {
1222                     let field = &variant.fields[index];
1223                     let field_ty = field.ty(tcx, substs);
1224                     (field, field_ty)
1225                 })
1226             }
1227             _ => None,
1228         });
1229         if let Some((field, field_ty)) = field_receiver {
1230             let scope = tcx.parent_module(self.body_id);
1231             let is_accessible = field.vis.is_accessible_from(scope, tcx);
1232
1233             if is_accessible {
1234                 if self.is_fn_ty(field_ty, span) {
1235                     let expr_span = expr.span.to(item_name.span);
1236                     err.multipart_suggestion(
1237                         &format!(
1238                             "to call the function stored in `{}`, \
1239                                          surround the field access with parentheses",
1240                             item_name,
1241                         ),
1242                         vec![
1243                             (expr_span.shrink_to_lo(), '('.to_string()),
1244                             (expr_span.shrink_to_hi(), ')'.to_string()),
1245                         ],
1246                         Applicability::MachineApplicable,
1247                     );
1248                 } else {
1249                     let call_expr = tcx.hir().expect_expr(tcx.hir().get_parent_node(expr.hir_id));
1250
1251                     if let Some(span) = call_expr.span.trim_start(item_name.span) {
1252                         err.span_suggestion(
1253                             span,
1254                             "remove the arguments",
1255                             "",
1256                             Applicability::MaybeIncorrect,
1257                         );
1258                     }
1259                 }
1260             }
1261
1262             let field_kind = if is_accessible { "field" } else { "private field" };
1263             err.span_label(item_name.span, format!("{}, not a method", field_kind));
1264             return true;
1265         }
1266         false
1267     }
1268
1269     /// Suggest possible range with adding parentheses, for example:
1270     /// when encountering `0..1.map(|i| i + 1)` suggest `(0..1).map(|i| i + 1)`.
1271     fn suggest_wrapping_range_with_parens(
1272         &self,
1273         tcx: TyCtxt<'tcx>,
1274         actual: Ty<'tcx>,
1275         source: SelfSource<'tcx>,
1276         span: Span,
1277         item_name: Ident,
1278         ty_str: &str,
1279     ) -> bool {
1280         if let SelfSource::MethodCall(expr) = source {
1281             for (_, parent) in tcx.hir().parent_iter(expr.hir_id).take(5) {
1282                 if let Node::Expr(parent_expr) = parent {
1283                     let lang_item = match parent_expr.kind {
1284                         ExprKind::Struct(ref qpath, _, _) => match **qpath {
1285                             QPath::LangItem(LangItem::Range, ..) => Some(LangItem::Range),
1286                             QPath::LangItem(LangItem::RangeTo, ..) => Some(LangItem::RangeTo),
1287                             QPath::LangItem(LangItem::RangeToInclusive, ..) => {
1288                                 Some(LangItem::RangeToInclusive)
1289                             }
1290                             _ => None,
1291                         },
1292                         ExprKind::Call(ref func, _) => match func.kind {
1293                             // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1294                             ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)) => {
1295                                 Some(LangItem::RangeInclusiveStruct)
1296                             }
1297                             _ => None,
1298                         },
1299                         _ => None,
1300                     };
1301
1302                     if lang_item.is_none() {
1303                         continue;
1304                     }
1305
1306                     let span_included = match parent_expr.kind {
1307                         hir::ExprKind::Struct(_, eps, _) => {
1308                             eps.len() > 0 && eps.last().map_or(false, |ep| ep.span.contains(span))
1309                         }
1310                         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1311                         hir::ExprKind::Call(ref func, ..) => func.span.contains(span),
1312                         _ => false,
1313                     };
1314
1315                     if !span_included {
1316                         continue;
1317                     }
1318
1319                     let range_def_id = self.tcx.require_lang_item(lang_item.unwrap(), None);
1320                     let range_ty =
1321                         self.tcx.bound_type_of(range_def_id).subst(self.tcx, &[actual.into()]);
1322
1323                     let pick = self.probe_for_name(
1324                         span,
1325                         Mode::MethodCall,
1326                         item_name,
1327                         IsSuggestion(true),
1328                         range_ty,
1329                         expr.hir_id,
1330                         ProbeScope::AllTraits,
1331                     );
1332                     if pick.is_ok() {
1333                         let range_span = parent_expr.span.with_hi(expr.span.hi());
1334                         tcx.sess.emit_err(errors::MissingParentheseInRange {
1335                             span,
1336                             ty_str: ty_str.to_string(),
1337                             method_name: item_name.as_str().to_string(),
1338                             add_missing_parentheses: Some(errors::AddMissingParenthesesInRange {
1339                                 func_name: item_name.name.as_str().to_string(),
1340                                 left: range_span.shrink_to_lo(),
1341                                 right: range_span.shrink_to_hi(),
1342                             }),
1343                         });
1344                         return true;
1345                     }
1346                 }
1347             }
1348         }
1349         false
1350     }
1351
1352     fn suggest_constraining_numerical_ty(
1353         &self,
1354         tcx: TyCtxt<'tcx>,
1355         actual: Ty<'tcx>,
1356         source: SelfSource<'_>,
1357         span: Span,
1358         item_kind: &str,
1359         item_name: Ident,
1360         ty_str: &str,
1361     ) -> bool {
1362         let found_candidate = all_traits(self.tcx)
1363             .into_iter()
1364             .any(|info| self.associated_value(info.def_id, item_name).is_some());
1365         let found_assoc = |ty: Ty<'tcx>| {
1366             simplify_type(tcx, ty, TreatParams::AsInfer)
1367                 .and_then(|simp| {
1368                     tcx.incoherent_impls(simp)
1369                         .iter()
1370                         .find_map(|&id| self.associated_value(id, item_name))
1371                 })
1372                 .is_some()
1373         };
1374         let found_candidate = found_candidate
1375             || found_assoc(tcx.types.i8)
1376             || found_assoc(tcx.types.i16)
1377             || found_assoc(tcx.types.i32)
1378             || found_assoc(tcx.types.i64)
1379             || found_assoc(tcx.types.i128)
1380             || found_assoc(tcx.types.u8)
1381             || found_assoc(tcx.types.u16)
1382             || found_assoc(tcx.types.u32)
1383             || found_assoc(tcx.types.u64)
1384             || found_assoc(tcx.types.u128)
1385             || found_assoc(tcx.types.f32)
1386             || found_assoc(tcx.types.f32);
1387         if found_candidate
1388             && actual.is_numeric()
1389             && !actual.has_concrete_skeleton()
1390             && let SelfSource::MethodCall(expr) = source
1391         {
1392             let mut err = struct_span_err!(
1393                 tcx.sess,
1394                 span,
1395                 E0689,
1396                 "can't call {} `{}` on ambiguous numeric type `{}`",
1397                 item_kind,
1398                 item_name,
1399                 ty_str
1400             );
1401             let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
1402             match expr.kind {
1403                 ExprKind::Lit(ref lit) => {
1404                     // numeric literal
1405                     let snippet = tcx
1406                         .sess
1407                         .source_map()
1408                         .span_to_snippet(lit.span)
1409                         .unwrap_or_else(|_| "<numeric literal>".to_owned());
1410
1411                     // If this is a floating point literal that ends with '.',
1412                     // get rid of it to stop this from becoming a member access.
1413                     let snippet = snippet.strip_suffix('.').unwrap_or(&snippet);
1414                     err.span_suggestion(
1415                         lit.span,
1416                         &format!(
1417                             "you must specify a concrete type for this numeric value, \
1418                                          like `{}`",
1419                             concrete_type
1420                         ),
1421                         format!("{snippet}_{concrete_type}"),
1422                         Applicability::MaybeIncorrect,
1423                     );
1424                 }
1425                 ExprKind::Path(QPath::Resolved(_, path)) => {
1426                     // local binding
1427                     if let hir::def::Res::Local(hir_id) = path.res {
1428                         let span = tcx.hir().span(hir_id);
1429                         let filename = tcx.sess.source_map().span_to_filename(span);
1430
1431                         let parent_node =
1432                             self.tcx.hir().get(self.tcx.hir().get_parent_node(hir_id));
1433                         let msg = format!(
1434                             "you must specify a type for this binding, like `{}`",
1435                             concrete_type,
1436                         );
1437
1438                         match (filename, parent_node) {
1439                             (
1440                                 FileName::Real(_),
1441                                 Node::Local(hir::Local {
1442                                     source: hir::LocalSource::Normal,
1443                                     ty,
1444                                     ..
1445                                 }),
1446                             ) => {
1447                                 let type_span = ty.map(|ty| ty.span.with_lo(span.hi())).unwrap_or(span.shrink_to_hi());
1448                                 err.span_suggestion(
1449                                     // account for `let x: _ = 42;`
1450                                     //                   ^^^
1451                                     type_span,
1452                                     &msg,
1453                                     format!(": {concrete_type}"),
1454                                     Applicability::MaybeIncorrect,
1455                                 );
1456                             }
1457                             _ => {
1458                                 err.span_label(span, msg);
1459                             }
1460                         }
1461                     }
1462                 }
1463                 _ => {}
1464             }
1465             err.emit();
1466             return true;
1467         }
1468         false
1469     }
1470
1471     /// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`
1472     fn suggest_calling_method_on_field(
1473         &self,
1474         err: &mut Diagnostic,
1475         source: SelfSource<'tcx>,
1476         span: Span,
1477         actual: Ty<'tcx>,
1478         item_name: Ident,
1479     ) {
1480         if let SelfSource::MethodCall(expr) = source
1481         && let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id()
1482         && let Some((fields, substs)) =
1483             self.get_field_candidates_considering_privacy(span, actual, mod_id)
1484         {
1485             let call_expr = self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
1486
1487             let lang_items = self.tcx.lang_items();
1488             let never_mention_traits = [
1489                 lang_items.clone_trait(),
1490                 lang_items.deref_trait(),
1491                 lang_items.deref_mut_trait(),
1492                 self.tcx.get_diagnostic_item(sym::AsRef),
1493                 self.tcx.get_diagnostic_item(sym::AsMut),
1494                 self.tcx.get_diagnostic_item(sym::Borrow),
1495                 self.tcx.get_diagnostic_item(sym::BorrowMut),
1496             ];
1497             let candidate_fields: Vec<_> = fields
1498                 .filter_map(|candidate_field| {
1499                     self.check_for_nested_field_satisfying(
1500                         span,
1501                         &|_, field_ty| {
1502                             self.lookup_probe(
1503                                 span,
1504                                 item_name,
1505                                 field_ty,
1506                                 call_expr,
1507                                 ProbeScope::TraitsInScope,
1508                             )
1509                             .map_or(false, |pick| {
1510                                 !never_mention_traits
1511                                     .iter()
1512                                     .flatten()
1513                                     .any(|def_id| self.tcx.parent(pick.item.def_id) == *def_id)
1514                             })
1515                         },
1516                         candidate_field,
1517                         substs,
1518                         vec![],
1519                         mod_id,
1520                     )
1521                 })
1522                 .map(|field_path| {
1523                     field_path
1524                         .iter()
1525                         .map(|id| id.name.to_ident_string())
1526                         .collect::<Vec<String>>()
1527                         .join(".")
1528                 })
1529                 .collect();
1530
1531             let len = candidate_fields.len();
1532             if len > 0 {
1533                 err.span_suggestions(
1534                     item_name.span.shrink_to_lo(),
1535                     format!(
1536                         "{} of the expressions' fields {} a method of the same name",
1537                         if len > 1 { "some" } else { "one" },
1538                         if len > 1 { "have" } else { "has" },
1539                     ),
1540                     candidate_fields.iter().map(|path| format!("{path}.")),
1541                     Applicability::MaybeIncorrect,
1542                 );
1543             }
1544         }
1545     }
1546
1547     fn check_for_inner_self(
1548         &self,
1549         err: &mut Diagnostic,
1550         source: SelfSource<'tcx>,
1551         span: Span,
1552         actual: Ty<'tcx>,
1553         item_name: Ident,
1554     ) {
1555         let tcx = self.tcx;
1556         let SelfSource::MethodCall(expr) = source else { return; };
1557         let call_expr = tcx.hir().expect_expr(tcx.hir().get_parent_node(expr.hir_id));
1558
1559         let ty::Adt(kind, substs) = actual.kind() else { return; };
1560         match kind.adt_kind() {
1561             ty::AdtKind::Enum => {
1562                 let matching_variants: Vec<_> = kind
1563                     .variants()
1564                     .iter()
1565                     .flat_map(|variant| {
1566                         let [field] = &variant.fields[..] else { return None; };
1567                         let field_ty = field.ty(tcx, substs);
1568
1569                         // Skip `_`, since that'll just lead to ambiguity.
1570                         if self.resolve_vars_if_possible(field_ty).is_ty_var() {
1571                             return None;
1572                         }
1573
1574                         self.lookup_probe(
1575                             span,
1576                             item_name,
1577                             field_ty,
1578                             call_expr,
1579                             ProbeScope::TraitsInScope,
1580                         )
1581                         .ok()
1582                         .map(|pick| (variant, field, pick))
1583                     })
1584                     .collect();
1585
1586                 let ret_ty_matches = |diagnostic_item| {
1587                     if let Some(ret_ty) = self
1588                         .ret_coercion
1589                         .as_ref()
1590                         .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
1591                         && let ty::Adt(kind, _) = ret_ty.kind()
1592                         && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
1593                     {
1594                         true
1595                     } else {
1596                         false
1597                     }
1598                 };
1599
1600                 match &matching_variants[..] {
1601                     [(_, field, pick)] => {
1602                         let self_ty = field.ty(tcx, substs);
1603                         err.span_note(
1604                             tcx.def_span(pick.item.def_id),
1605                             &format!("the method `{item_name}` exists on the type `{self_ty}`"),
1606                         );
1607                         let (article, kind, variant, question) =
1608                             if tcx.is_diagnostic_item(sym::Result, kind.did()) {
1609                                 ("a", "Result", "Err", ret_ty_matches(sym::Result))
1610                             } else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
1611                                 ("an", "Option", "None", ret_ty_matches(sym::Option))
1612                             } else {
1613                                 return;
1614                             };
1615                         if question {
1616                             err.span_suggestion_verbose(
1617                                 expr.span.shrink_to_hi(),
1618                                 format!(
1619                                     "use the `?` operator to extract the `{self_ty}` value, propagating \
1620                                     {article} `{kind}::{variant}` value to the caller"
1621                                 ),
1622                                 "?",
1623                                 Applicability::MachineApplicable,
1624                             );
1625                         } else {
1626                             err.span_suggestion_verbose(
1627                                 expr.span.shrink_to_hi(),
1628                                 format!(
1629                                     "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
1630                                     panicking if the value is {article} `{kind}::{variant}`"
1631                                 ),
1632                                 ".expect(\"REASON\")",
1633                                 Applicability::HasPlaceholders,
1634                             );
1635                         }
1636                     }
1637                     // FIXME(compiler-errors): Support suggestions for other matching enum variants
1638                     _ => {}
1639                 }
1640             }
1641             // Target wrapper types - types that wrap or pretend to wrap another type,
1642             // perhaps this inner type is meant to be called?
1643             ty::AdtKind::Struct | ty::AdtKind::Union => {
1644                 let [first] = ***substs else { return; };
1645                 let ty::GenericArgKind::Type(ty) = first.unpack() else { return; };
1646                 let Ok(pick) = self.lookup_probe(
1647                             span,
1648                             item_name,
1649                             ty,
1650                             call_expr,
1651                             ProbeScope::TraitsInScope,
1652                         )  else { return; };
1653
1654                 let name = self.ty_to_value_string(actual);
1655                 let inner_id = kind.did();
1656                 let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
1657                     pick.autoref_or_ptr_adjustment
1658                 {
1659                     Some(mutbl)
1660                 } else {
1661                     None
1662                 };
1663
1664                 if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
1665                     err.help("use `with` or `try_with` to access thread local storage");
1666                 } else if Some(kind.did()) == tcx.lang_items().maybe_uninit() {
1667                     err.help(format!(
1668                         "if this `{name}` has been initialized, \
1669                         use one of the `assume_init` methods to access the inner value"
1670                     ));
1671                 } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
1672                     let (suggestion, borrow_kind, panic_if) = match mutable {
1673                         Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"),
1674                         Some(Mutability::Mut) => {
1675                             (".borrow_mut()", "mutably borrow", "any borrows exist")
1676                         }
1677                         None => return,
1678                     };
1679                     err.span_suggestion_verbose(
1680                         expr.span.shrink_to_hi(),
1681                         format!(
1682                             "use `{suggestion}` to {borrow_kind} the `{ty}`, \
1683                             panicking if {panic_if}"
1684                         ),
1685                         suggestion,
1686                         Applicability::MaybeIncorrect,
1687                     );
1688                 } else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
1689                     err.span_suggestion_verbose(
1690                         expr.span.shrink_to_hi(),
1691                         format!(
1692                             "use `.lock().unwrap()` to borrow the `{ty}`, \
1693                             blocking the current thread until it can be acquired"
1694                         ),
1695                         ".lock().unwrap()",
1696                         Applicability::MaybeIncorrect,
1697                     );
1698                 } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
1699                     let (suggestion, borrow_kind) = match mutable {
1700                         Some(Mutability::Not) => (".read().unwrap()", "borrow"),
1701                         Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"),
1702                         None => return,
1703                     };
1704                     err.span_suggestion_verbose(
1705                         expr.span.shrink_to_hi(),
1706                         format!(
1707                             "use `{suggestion}` to {borrow_kind} the `{ty}`, \
1708                             blocking the current thread until it can be acquired"
1709                         ),
1710                         suggestion,
1711                         Applicability::MaybeIncorrect,
1712                     );
1713                 } else {
1714                     return;
1715                 };
1716
1717                 err.span_note(
1718                     tcx.def_span(pick.item.def_id),
1719                     &format!("the method `{item_name}` exists on the type `{ty}`"),
1720                 );
1721             }
1722         }
1723     }
1724
1725     pub(crate) fn note_unmet_impls_on_type(
1726         &self,
1727         err: &mut Diagnostic,
1728         errors: Vec<FulfillmentError<'tcx>>,
1729     ) {
1730         let all_local_types_needing_impls =
1731             errors.iter().all(|e| match e.obligation.predicate.kind().skip_binder() {
1732                 ty::PredicateKind::Trait(pred) => match pred.self_ty().kind() {
1733                     ty::Adt(def, _) => def.did().is_local(),
1734                     _ => false,
1735                 },
1736                 _ => false,
1737             });
1738         let mut preds: Vec<_> = errors
1739             .iter()
1740             .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
1741                 ty::PredicateKind::Trait(pred) => Some(pred),
1742                 _ => None,
1743             })
1744             .collect();
1745         preds.sort_by_key(|pred| (pred.def_id(), pred.self_ty()));
1746         let def_ids = preds
1747             .iter()
1748             .filter_map(|pred| match pred.self_ty().kind() {
1749                 ty::Adt(def, _) => Some(def.did()),
1750                 _ => None,
1751             })
1752             .collect::<FxHashSet<_>>();
1753         let mut spans: MultiSpan = def_ids
1754             .iter()
1755             .filter_map(|def_id| {
1756                 let span = self.tcx.def_span(*def_id);
1757                 if span.is_dummy() { None } else { Some(span) }
1758             })
1759             .collect::<Vec<_>>()
1760             .into();
1761
1762         for pred in &preds {
1763             match pred.self_ty().kind() {
1764                 ty::Adt(def, _) if def.did().is_local() => {
1765                     spans.push_span_label(
1766                         self.tcx.def_span(def.did()),
1767                         format!("must implement `{}`", pred.trait_ref.print_only_trait_path()),
1768                     );
1769                 }
1770                 _ => {}
1771             }
1772         }
1773
1774         if all_local_types_needing_impls && spans.primary_span().is_some() {
1775             let msg = if preds.len() == 1 {
1776                 format!(
1777                     "an implementation of `{}` might be missing for `{}`",
1778                     preds[0].trait_ref.print_only_trait_path(),
1779                     preds[0].self_ty()
1780                 )
1781             } else {
1782                 format!(
1783                     "the following type{} would have to `impl` {} required trait{} for this \
1784                      operation to be valid",
1785                     pluralize!(def_ids.len()),
1786                     if def_ids.len() == 1 { "its" } else { "their" },
1787                     pluralize!(preds.len()),
1788                 )
1789             };
1790             err.span_note(spans, &msg);
1791         }
1792
1793         let preds: Vec<_> = errors
1794             .iter()
1795             .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
1796             .collect();
1797         self.suggest_derive(err, &preds);
1798     }
1799
1800     fn suggest_derive(
1801         &self,
1802         err: &mut Diagnostic,
1803         unsatisfied_predicates: &[(
1804             ty::Predicate<'tcx>,
1805             Option<ty::Predicate<'tcx>>,
1806             Option<ObligationCause<'tcx>>,
1807         )],
1808     ) {
1809         let mut derives = Vec::<(String, Span, Symbol)>::new();
1810         let mut traits = Vec::<Span>::new();
1811         for (pred, _, _) in unsatisfied_predicates {
1812             let ty::PredicateKind::Trait(trait_pred) = pred.kind().skip_binder() else { continue };
1813             let adt = match trait_pred.self_ty().ty_adt_def() {
1814                 Some(adt) if adt.did().is_local() => adt,
1815                 _ => continue,
1816             };
1817             if let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) {
1818                 let can_derive = match diagnostic_name {
1819                     sym::Default => !adt.is_enum(),
1820                     sym::Eq
1821                     | sym::PartialEq
1822                     | sym::Ord
1823                     | sym::PartialOrd
1824                     | sym::Clone
1825                     | sym::Copy
1826                     | sym::Hash
1827                     | sym::Debug => true,
1828                     _ => false,
1829                 };
1830                 if can_derive {
1831                     let self_name = trait_pred.self_ty().to_string();
1832                     let self_span = self.tcx.def_span(adt.did());
1833                     if let Some(poly_trait_ref) = pred.to_opt_poly_trait_pred() {
1834                         for super_trait in supertraits(self.tcx, poly_trait_ref.to_poly_trait_ref())
1835                         {
1836                             if let Some(parent_diagnostic_name) =
1837                                 self.tcx.get_diagnostic_name(super_trait.def_id())
1838                             {
1839                                 derives.push((
1840                                     self_name.clone(),
1841                                     self_span,
1842                                     parent_diagnostic_name,
1843                                 ));
1844                             }
1845                         }
1846                     }
1847                     derives.push((self_name, self_span, diagnostic_name));
1848                 } else {
1849                     traits.push(self.tcx.def_span(trait_pred.def_id()));
1850                 }
1851             } else {
1852                 traits.push(self.tcx.def_span(trait_pred.def_id()));
1853             }
1854         }
1855         traits.sort();
1856         traits.dedup();
1857
1858         derives.sort();
1859         derives.dedup();
1860
1861         let mut derives_grouped = Vec::<(String, Span, String)>::new();
1862         for (self_name, self_span, trait_name) in derives.into_iter() {
1863             if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut()
1864             {
1865                 if last_self_name == &self_name {
1866                     last_trait_names.push_str(format!(", {}", trait_name).as_str());
1867                     continue;
1868                 }
1869             }
1870             derives_grouped.push((self_name, self_span, trait_name.to_string()));
1871         }
1872
1873         let len = traits.len();
1874         if len > 0 {
1875             let span: MultiSpan = traits.into();
1876             err.span_note(
1877                 span,
1878                 &format!("the following trait{} must be implemented", pluralize!(len),),
1879             );
1880         }
1881
1882         for (self_name, self_span, traits) in &derives_grouped {
1883             err.span_suggestion_verbose(
1884                 self_span.shrink_to_lo(),
1885                 &format!("consider annotating `{}` with `#[derive({})]`", self_name, traits),
1886                 format!("#[derive({})]\n", traits),
1887                 Applicability::MaybeIncorrect,
1888             );
1889         }
1890     }
1891
1892     fn check_for_deref_method(
1893         &self,
1894         err: &mut Diagnostic,
1895         self_source: SelfSource<'tcx>,
1896         rcvr_ty: Ty<'tcx>,
1897         item_name: Ident,
1898     ) {
1899         let SelfSource::QPath(ty) = self_source else { return; };
1900         for (deref_ty, _) in self.autoderef(rustc_span::DUMMY_SP, rcvr_ty).skip(1) {
1901             if let Ok(pick) = self.probe_for_name(
1902                 ty.span,
1903                 Mode::Path,
1904                 item_name,
1905                 IsSuggestion(true),
1906                 deref_ty,
1907                 ty.hir_id,
1908                 ProbeScope::TraitsInScope,
1909             ) {
1910                 if deref_ty.is_suggestable(self.tcx, true)
1911                     // If this method receives `&self`, then the provided
1912                     // argument _should_ coerce, so it's valid to suggest
1913                     // just changing the path.
1914                     && pick.item.fn_has_self_parameter
1915                     && let Some(self_ty) =
1916                         self.tcx.fn_sig(pick.item.def_id).inputs().skip_binder().get(0)
1917                     && self_ty.is_ref()
1918                 {
1919                     let suggested_path = match deref_ty.kind() {
1920                         ty::Bool
1921                         | ty::Char
1922                         | ty::Int(_)
1923                         | ty::Uint(_)
1924                         | ty::Float(_)
1925                         | ty::Adt(_, _)
1926                         | ty::Str
1927                         | ty::Projection(_)
1928                         | ty::Param(_) => format!("{deref_ty}"),
1929                         // we need to test something like  <&[_]>::len or <(&[u32])>::len
1930                         // and Vec::function();
1931                         // <&[_]>::len or <&[u32]>::len doesn't need an extra "<>" between
1932                         // but for Adt type like Vec::function()
1933                         // we would suggest <[_]>::function();
1934                         _ if self.tcx.sess.source_map().span_wrapped_by_angle_or_parentheses(ty.span)  => format!("{deref_ty}"),
1935                         _ => format!("<{deref_ty}>"),
1936                     };
1937                     err.span_suggestion_verbose(
1938                         ty.span,
1939                         format!("the function `{item_name}` is implemented on `{deref_ty}`"),
1940                         suggested_path,
1941                         Applicability::MaybeIncorrect,
1942                     );
1943                 } else {
1944                     err.span_note(
1945                         ty.span,
1946                         format!("the function `{item_name}` is implemented on `{deref_ty}`"),
1947                     );
1948                 }
1949                 return;
1950             }
1951         }
1952     }
1953
1954     /// Print out the type for use in value namespace.
1955     fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
1956         match ty.kind() {
1957             ty::Adt(def, substs) => self.tcx.def_path_str_with_substs(def.did(), substs),
1958             _ => self.ty_to_string(ty),
1959         }
1960     }
1961
1962     fn suggest_await_before_method(
1963         &self,
1964         err: &mut Diagnostic,
1965         item_name: Ident,
1966         ty: Ty<'tcx>,
1967         call: &hir::Expr<'_>,
1968         span: Span,
1969     ) {
1970         let output_ty = match self.get_impl_future_output_ty(ty) {
1971             Some(output_ty) => self.resolve_vars_if_possible(output_ty).skip_binder(),
1972             _ => return,
1973         };
1974         let method_exists = self.method_exists(item_name, output_ty, call.hir_id, true);
1975         debug!("suggest_await_before_method: is_method_exist={}", method_exists);
1976         if method_exists {
1977             err.span_suggestion_verbose(
1978                 span.shrink_to_lo(),
1979                 "consider `await`ing on the `Future` and calling the method on its `Output`",
1980                 "await.",
1981                 Applicability::MaybeIncorrect,
1982             );
1983         }
1984     }
1985
1986     fn suggest_use_candidates(&self, err: &mut Diagnostic, msg: String, candidates: Vec<DefId>) {
1987         let parent_map = self.tcx.visible_parent_map(());
1988
1989         // Separate out candidates that must be imported with a glob, because they are named `_`
1990         // and cannot be referred with their identifier.
1991         let (candidates, globs): (Vec<_>, Vec<_>) = candidates.into_iter().partition(|trait_did| {
1992             if let Some(parent_did) = parent_map.get(trait_did) {
1993                 // If the item is re-exported as `_`, we should suggest a glob-import instead.
1994                 if *parent_did != self.tcx.parent(*trait_did)
1995                     && self
1996                         .tcx
1997                         .module_children(*parent_did)
1998                         .iter()
1999                         .filter(|child| child.res.opt_def_id() == Some(*trait_did))
2000                         .all(|child| child.ident.name == kw::Underscore)
2001                 {
2002                     return false;
2003                 }
2004             }
2005
2006             true
2007         });
2008
2009         let module_did = self.tcx.parent_module(self.body_id);
2010         let (module, _, _) = self.tcx.hir().get_module(module_did);
2011         let span = module.spans.inject_use_span;
2012
2013         let path_strings = candidates.iter().map(|trait_did| {
2014             format!("use {};\n", with_crate_prefix!(self.tcx.def_path_str(*trait_did)),)
2015         });
2016
2017         let glob_path_strings = globs.iter().map(|trait_did| {
2018             let parent_did = parent_map.get(trait_did).unwrap();
2019             format!(
2020                 "use {}::*; // trait {}\n",
2021                 with_crate_prefix!(self.tcx.def_path_str(*parent_did)),
2022                 self.tcx.item_name(*trait_did),
2023             )
2024         });
2025
2026         err.span_suggestions(
2027             span,
2028             &msg,
2029             path_strings.chain(glob_path_strings),
2030             Applicability::MaybeIncorrect,
2031         );
2032     }
2033
2034     fn suggest_valid_traits(
2035         &self,
2036         err: &mut Diagnostic,
2037         valid_out_of_scope_traits: Vec<DefId>,
2038     ) -> bool {
2039         if !valid_out_of_scope_traits.is_empty() {
2040             let mut candidates = valid_out_of_scope_traits;
2041             candidates.sort();
2042             candidates.dedup();
2043
2044             // `TryFrom` and `FromIterator` have no methods
2045             let edition_fix = candidates
2046                 .iter()
2047                 .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
2048                 .copied();
2049
2050             err.help("items from traits can only be used if the trait is in scope");
2051             let msg = format!(
2052                 "the following {traits_are} implemented but not in scope; \
2053                  perhaps add a `use` for {one_of_them}:",
2054                 traits_are = if candidates.len() == 1 { "trait is" } else { "traits are" },
2055                 one_of_them = if candidates.len() == 1 { "it" } else { "one of them" },
2056             );
2057
2058             self.suggest_use_candidates(err, msg, candidates);
2059             if let Some(did) = edition_fix {
2060                 err.note(&format!(
2061                     "'{}' is included in the prelude starting in Edition 2021",
2062                     with_crate_prefix!(self.tcx.def_path_str(did))
2063                 ));
2064             }
2065
2066             true
2067         } else {
2068             false
2069         }
2070     }
2071
2072     fn suggest_traits_to_import(
2073         &self,
2074         err: &mut Diagnostic,
2075         span: Span,
2076         rcvr_ty: Ty<'tcx>,
2077         item_name: Ident,
2078         inputs_len: Option<usize>,
2079         source: SelfSource<'tcx>,
2080         valid_out_of_scope_traits: Vec<DefId>,
2081         unsatisfied_predicates: &[(
2082             ty::Predicate<'tcx>,
2083             Option<ty::Predicate<'tcx>>,
2084             Option<ObligationCause<'tcx>>,
2085         )],
2086         static_candidates: &[CandidateSource],
2087         unsatisfied_bounds: bool,
2088     ) {
2089         let mut alt_rcvr_sugg = false;
2090         if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
2091             debug!(
2092                 "suggest_traits_to_import: span={:?}, item_name={:?}, rcvr_ty={:?}, rcvr={:?}",
2093                 span, item_name, rcvr_ty, rcvr
2094             );
2095             let skippable = [
2096                 self.tcx.lang_items().clone_trait(),
2097                 self.tcx.lang_items().deref_trait(),
2098                 self.tcx.lang_items().deref_mut_trait(),
2099                 self.tcx.lang_items().drop_trait(),
2100                 self.tcx.get_diagnostic_item(sym::AsRef),
2101             ];
2102             // Try alternative arbitrary self types that could fulfill this call.
2103             // FIXME: probe for all types that *could* be arbitrary self-types, not
2104             // just this list.
2105             for (rcvr_ty, post) in &[
2106                 (rcvr_ty, ""),
2107                 (self.tcx.mk_mut_ref(self.tcx.lifetimes.re_erased, rcvr_ty), "&mut "),
2108                 (self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, rcvr_ty), "&"),
2109             ] {
2110                 match self.lookup_probe(span, item_name, *rcvr_ty, rcvr, ProbeScope::AllTraits) {
2111                     Ok(pick) => {
2112                         // If the method is defined for the receiver we have, it likely wasn't `use`d.
2113                         // We point at the method, but we just skip the rest of the check for arbitrary
2114                         // self types and rely on the suggestion to `use` the trait from
2115                         // `suggest_valid_traits`.
2116                         let did = Some(pick.item.container_id(self.tcx));
2117                         let skip = skippable.contains(&did);
2118                         if pick.autoderefs == 0 && !skip {
2119                             err.span_label(
2120                                 pick.item.ident(self.tcx).span,
2121                                 &format!("the method is available for `{}` here", rcvr_ty),
2122                             );
2123                         }
2124                         break;
2125                     }
2126                     Err(MethodError::Ambiguity(_)) => {
2127                         // If the method is defined (but ambiguous) for the receiver we have, it is also
2128                         // likely we haven't `use`d it. It may be possible that if we `Box`/`Pin`/etc.
2129                         // the receiver, then it might disambiguate this method, but I think these
2130                         // suggestions are generally misleading (see #94218).
2131                         break;
2132                     }
2133                     Err(_) => (),
2134                 }
2135
2136                 for (rcvr_ty, pre) in &[
2137                     (self.tcx.mk_lang_item(*rcvr_ty, LangItem::OwnedBox), "Box::new"),
2138                     (self.tcx.mk_lang_item(*rcvr_ty, LangItem::Pin), "Pin::new"),
2139                     (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Arc), "Arc::new"),
2140                     (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Rc), "Rc::new"),
2141                 ] {
2142                     if let Some(new_rcvr_t) = *rcvr_ty
2143                         && let Ok(pick) = self.lookup_probe(
2144                             span,
2145                             item_name,
2146                             new_rcvr_t,
2147                             rcvr,
2148                             ProbeScope::AllTraits,
2149                         )
2150                     {
2151                         debug!("try_alt_rcvr: pick candidate {:?}", pick);
2152                         let did = Some(pick.item.container_id(self.tcx));
2153                         // We don't want to suggest a container type when the missing
2154                         // method is `.clone()` or `.deref()` otherwise we'd suggest
2155                         // `Arc::new(foo).clone()`, which is far from what the user wants.
2156                         // Explicitly ignore the `Pin::as_ref()` method as `Pin` does not
2157                         // implement the `AsRef` trait.
2158                         let skip = skippable.contains(&did)
2159                             || (("Pin::new" == *pre) && (sym::as_ref == item_name.name))
2160                             || inputs_len.map_or(false, |inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.fn_sig(pick.item.def_id).skip_binder().inputs().len() != inputs_len);
2161                         // Make sure the method is defined for the *actual* receiver: we don't
2162                         // want to treat `Box<Self>` as a receiver if it only works because of
2163                         // an autoderef to `&self`
2164                         if pick.autoderefs == 0 && !skip {
2165                             err.span_label(
2166                                 pick.item.ident(self.tcx).span,
2167                                 &format!("the method is available for `{}` here", new_rcvr_t),
2168                             );
2169                             err.multipart_suggestion(
2170                                 "consider wrapping the receiver expression with the \
2171                                     appropriate type",
2172                                 vec![
2173                                     (rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)),
2174                                     (rcvr.span.shrink_to_hi(), ")".to_string()),
2175                                 ],
2176                                 Applicability::MaybeIncorrect,
2177                             );
2178                             // We don't care about the other suggestions.
2179                             alt_rcvr_sugg = true;
2180                         }
2181                     }
2182                 }
2183             }
2184         }
2185         if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
2186             return;
2187         }
2188
2189         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
2190
2191         let mut arbitrary_rcvr = vec![];
2192         // There are no traits implemented, so lets suggest some traits to
2193         // implement, by finding ones that have the item name, and are
2194         // legal to implement.
2195         let mut candidates = all_traits(self.tcx)
2196             .into_iter()
2197             // Don't issue suggestions for unstable traits since they're
2198             // unlikely to be implementable anyway
2199             .filter(|info| match self.tcx.lookup_stability(info.def_id) {
2200                 Some(attr) => attr.level.is_stable(),
2201                 None => true,
2202             })
2203             .filter(|info| {
2204                 // Static candidates are already implemented, and known not to work
2205                 // Do not suggest them again
2206                 static_candidates.iter().all(|sc| match *sc {
2207                     CandidateSource::Trait(def_id) => def_id != info.def_id,
2208                     CandidateSource::Impl(def_id) => {
2209                         self.tcx.trait_id_of_impl(def_id) != Some(info.def_id)
2210                     }
2211                 })
2212             })
2213             .filter(|info| {
2214                 // We approximate the coherence rules to only suggest
2215                 // traits that are legal to implement by requiring that
2216                 // either the type or trait is local. Multi-dispatch means
2217                 // this isn't perfect (that is, there are cases when
2218                 // implementing a trait would be legal but is rejected
2219                 // here).
2220                 unsatisfied_predicates.iter().all(|(p, _, _)| {
2221                     match p.kind().skip_binder() {
2222                         // Hide traits if they are present in predicates as they can be fixed without
2223                         // having to implement them.
2224                         ty::PredicateKind::Trait(t) => t.def_id() == info.def_id,
2225                         ty::PredicateKind::Projection(p) => {
2226                             p.projection_ty.item_def_id == info.def_id
2227                         }
2228                         _ => false,
2229                     }
2230                 }) && (type_is_local || info.def_id.is_local())
2231                     && self
2232                         .associated_value(info.def_id, item_name)
2233                         .filter(|item| {
2234                             if let ty::AssocKind::Fn = item.kind {
2235                                 let id = item
2236                                     .def_id
2237                                     .as_local()
2238                                     .map(|def_id| self.tcx.hir().local_def_id_to_hir_id(def_id));
2239                                 if let Some(hir::Node::TraitItem(hir::TraitItem {
2240                                     kind: hir::TraitItemKind::Fn(fn_sig, method),
2241                                     ..
2242                                 })) = id.map(|id| self.tcx.hir().get(id))
2243                                 {
2244                                     let self_first_arg = match method {
2245                                         hir::TraitFn::Required([ident, ..]) => {
2246                                             ident.name == kw::SelfLower
2247                                         }
2248                                         hir::TraitFn::Provided(body_id) => {
2249                                             self.tcx.hir().body(*body_id).params.first().map_or(
2250                                                 false,
2251                                                 |param| {
2252                                                     matches!(
2253                                                         param.pat.kind,
2254                                                         hir::PatKind::Binding(_, _, ident, _)
2255                                                             if ident.name == kw::SelfLower
2256                                                     )
2257                                                 },
2258                                             )
2259                                         }
2260                                         _ => false,
2261                                     };
2262
2263                                     if !fn_sig.decl.implicit_self.has_implicit_self()
2264                                         && self_first_arg
2265                                     {
2266                                         if let Some(ty) = fn_sig.decl.inputs.get(0) {
2267                                             arbitrary_rcvr.push(ty.span);
2268                                         }
2269                                         return false;
2270                                     }
2271                                 }
2272                             }
2273                             // We only want to suggest public or local traits (#45781).
2274                             item.visibility(self.tcx).is_public() || info.def_id.is_local()
2275                         })
2276                         .is_some()
2277             })
2278             .collect::<Vec<_>>();
2279         for span in &arbitrary_rcvr {
2280             err.span_label(
2281                 *span,
2282                 "the method might not be found because of this arbitrary self type",
2283             );
2284         }
2285         if alt_rcvr_sugg {
2286             return;
2287         }
2288
2289         if !candidates.is_empty() {
2290             // Sort from most relevant to least relevant.
2291             candidates.sort_by(|a, b| a.cmp(b).reverse());
2292             candidates.dedup();
2293
2294             let param_type = match rcvr_ty.kind() {
2295                 ty::Param(param) => Some(param),
2296                 ty::Ref(_, ty, _) => match ty.kind() {
2297                     ty::Param(param) => Some(param),
2298                     _ => None,
2299                 },
2300                 _ => None,
2301             };
2302             err.help(if param_type.is_some() {
2303                 "items from traits can only be used if the type parameter is bounded by the trait"
2304             } else {
2305                 "items from traits can only be used if the trait is implemented and in scope"
2306             });
2307             let candidates_len = candidates.len();
2308             let message = |action| {
2309                 format!(
2310                     "the following {traits_define} an item `{name}`, perhaps you need to {action} \
2311                      {one_of_them}:",
2312                     traits_define =
2313                         if candidates_len == 1 { "trait defines" } else { "traits define" },
2314                     action = action,
2315                     one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
2316                     name = item_name,
2317                 )
2318             };
2319             // Obtain the span for `param` and use it for a structured suggestion.
2320             if let Some(param) = param_type {
2321                 let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
2322                 let type_param = generics.type_param(param, self.tcx);
2323                 let hir = self.tcx.hir();
2324                 if let Some(def_id) = type_param.def_id.as_local() {
2325                     let id = hir.local_def_id_to_hir_id(def_id);
2326                     // Get the `hir::Param` to verify whether it already has any bounds.
2327                     // We do this to avoid suggesting code that ends up as `T: FooBar`,
2328                     // instead we suggest `T: Foo + Bar` in that case.
2329                     match hir.get(id) {
2330                         Node::GenericParam(param) => {
2331                             enum Introducer {
2332                                 Plus,
2333                                 Colon,
2334                                 Nothing,
2335                             }
2336                             let ast_generics = hir.get_generics(id.owner.def_id).unwrap();
2337                             let (sp, mut introducer) = if let Some(span) =
2338                                 ast_generics.bounds_span_for_suggestions(def_id)
2339                             {
2340                                 (span, Introducer::Plus)
2341                             } else if let Some(colon_span) = param.colon_span {
2342                                 (colon_span.shrink_to_hi(), Introducer::Nothing)
2343                             } else {
2344                                 (param.span.shrink_to_hi(), Introducer::Colon)
2345                             };
2346                             if matches!(
2347                                 param.kind,
2348                                 hir::GenericParamKind::Type { synthetic: true, .. },
2349                             ) {
2350                                 introducer = Introducer::Plus
2351                             }
2352                             let trait_def_ids: FxHashSet<DefId> = ast_generics
2353                                 .bounds_for_param(def_id)
2354                                 .flat_map(|bp| bp.bounds.iter())
2355                                 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
2356                                 .collect();
2357                             if !candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
2358                                 err.span_suggestions(
2359                                     sp,
2360                                     &message(format!(
2361                                         "restrict type parameter `{}` with",
2362                                         param.name.ident(),
2363                                     )),
2364                                     candidates.iter().map(|t| {
2365                                         format!(
2366                                             "{} {}",
2367                                             match introducer {
2368                                                 Introducer::Plus => " +",
2369                                                 Introducer::Colon => ":",
2370                                                 Introducer::Nothing => "",
2371                                             },
2372                                             self.tcx.def_path_str(t.def_id),
2373                                         )
2374                                     }),
2375                                     Applicability::MaybeIncorrect,
2376                                 );
2377                             }
2378                             return;
2379                         }
2380                         Node::Item(hir::Item {
2381                             kind: hir::ItemKind::Trait(.., bounds, _),
2382                             ident,
2383                             ..
2384                         }) => {
2385                             let (sp, sep, article) = if bounds.is_empty() {
2386                                 (ident.span.shrink_to_hi(), ":", "a")
2387                             } else {
2388                                 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
2389                             };
2390                             err.span_suggestions(
2391                                 sp,
2392                                 &message(format!("add {} supertrait for", article)),
2393                                 candidates.iter().map(|t| {
2394                                     format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
2395                                 }),
2396                                 Applicability::MaybeIncorrect,
2397                             );
2398                             return;
2399                         }
2400                         _ => {}
2401                     }
2402                 }
2403             }
2404
2405             let (potential_candidates, explicitly_negative) = if param_type.is_some() {
2406                 // FIXME: Even though negative bounds are not implemented, we could maybe handle
2407                 // cases where a positive bound implies a negative impl.
2408                 (candidates, Vec::new())
2409             } else if let Some(simp_rcvr_ty) =
2410                 simplify_type(self.tcx, rcvr_ty, TreatParams::AsPlaceholder)
2411             {
2412                 let mut potential_candidates = Vec::new();
2413                 let mut explicitly_negative = Vec::new();
2414                 for candidate in candidates {
2415                     // Check if there's a negative impl of `candidate` for `rcvr_ty`
2416                     if self
2417                         .tcx
2418                         .all_impls(candidate.def_id)
2419                         .filter(|imp_did| {
2420                             self.tcx.impl_polarity(*imp_did) == ty::ImplPolarity::Negative
2421                         })
2422                         .any(|imp_did| {
2423                             let imp = self.tcx.impl_trait_ref(imp_did).unwrap();
2424                             let imp_simp =
2425                                 simplify_type(self.tcx, imp.self_ty(), TreatParams::AsPlaceholder);
2426                             imp_simp.map_or(false, |s| s == simp_rcvr_ty)
2427                         })
2428                     {
2429                         explicitly_negative.push(candidate);
2430                     } else {
2431                         potential_candidates.push(candidate);
2432                     }
2433                 }
2434                 (potential_candidates, explicitly_negative)
2435             } else {
2436                 // We don't know enough about `recv_ty` to make proper suggestions.
2437                 (candidates, Vec::new())
2438             };
2439
2440             let action = if let Some(param) = param_type {
2441                 format!("restrict type parameter `{}` with", param)
2442             } else {
2443                 // FIXME: it might only need to be imported into scope, not implemented.
2444                 "implement".to_string()
2445             };
2446             match &potential_candidates[..] {
2447                 [] => {}
2448                 [trait_info] if trait_info.def_id.is_local() => {
2449                     err.span_note(
2450                         self.tcx.def_span(trait_info.def_id),
2451                         &format!(
2452                             "`{}` defines an item `{}`, perhaps you need to {} it",
2453                             self.tcx.def_path_str(trait_info.def_id),
2454                             item_name,
2455                             action
2456                         ),
2457                     );
2458                 }
2459                 trait_infos => {
2460                     let mut msg = message(action);
2461                     for (i, trait_info) in trait_infos.iter().enumerate() {
2462                         msg.push_str(&format!(
2463                             "\ncandidate #{}: `{}`",
2464                             i + 1,
2465                             self.tcx.def_path_str(trait_info.def_id),
2466                         ));
2467                     }
2468                     err.note(&msg);
2469                 }
2470             }
2471             match &explicitly_negative[..] {
2472                 [] => {}
2473                 [trait_info] => {
2474                     let msg = format!(
2475                         "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
2476                         self.tcx.def_path_str(trait_info.def_id),
2477                         item_name
2478                     );
2479                     err.note(&msg);
2480                 }
2481                 trait_infos => {
2482                     let mut msg = format!(
2483                         "the following traits define an item `{}`, but are explicitly unimplemented:",
2484                         item_name
2485                     );
2486                     for trait_info in trait_infos {
2487                         msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
2488                     }
2489                     err.note(&msg);
2490                 }
2491             }
2492         }
2493     }
2494
2495     /// issue #102320, for `unwrap_or` with closure as argument, suggest `unwrap_or_else`
2496     /// FIXME: currently not working for suggesting `map_or_else`, see #102408
2497     pub(crate) fn suggest_else_fn_with_closure(
2498         &self,
2499         err: &mut Diagnostic,
2500         expr: &hir::Expr<'_>,
2501         found: Ty<'tcx>,
2502         expected: Ty<'tcx>,
2503     ) -> bool {
2504         let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(expr, found)
2505         else { return false; };
2506
2507         if !self.can_coerce(output, expected) {
2508             return false;
2509         }
2510
2511         let parent = self.tcx.hir().get_parent_node(expr.hir_id);
2512         if  let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) &&
2513             let hir::ExprKind::MethodCall(
2514                 hir::PathSegment { ident: method_name, .. },
2515                 self_expr,
2516                 args,
2517                 ..,
2518              ) = call_expr.kind &&
2519             let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr) {
2520             let new_name = Ident {
2521                 name: Symbol::intern(&format!("{}_else", method_name.as_str())),
2522                 span: method_name.span,
2523             };
2524             let probe = self.lookup_probe(
2525                 expr.span,
2526                 new_name,
2527                 self_ty,
2528                 self_expr,
2529                 ProbeScope::TraitsInScope,
2530             );
2531
2532             // check the method arguments number
2533             if let Ok(pick) = probe &&
2534                 let fn_sig = self.tcx.fn_sig(pick.item.def_id) &&
2535                 let fn_args = fn_sig.skip_binder().inputs() &&
2536                 fn_args.len() == args.len() + 1 {
2537                 err.span_suggestion_verbose(
2538                     method_name.span.shrink_to_hi(),
2539                     &format!("try calling `{}` instead", new_name.name.as_str()),
2540                     "_else",
2541                     Applicability::MaybeIncorrect,
2542                 );
2543                 return true;
2544             }
2545         }
2546         false
2547     }
2548
2549     /// Checks whether there is a local type somewhere in the chain of
2550     /// autoderefs of `rcvr_ty`.
2551     fn type_derefs_to_local(
2552         &self,
2553         span: Span,
2554         rcvr_ty: Ty<'tcx>,
2555         source: SelfSource<'tcx>,
2556     ) -> bool {
2557         fn is_local(ty: Ty<'_>) -> bool {
2558             match ty.kind() {
2559                 ty::Adt(def, _) => def.did().is_local(),
2560                 ty::Foreign(did) => did.is_local(),
2561                 ty::Dynamic(tr, ..) => tr.principal().map_or(false, |d| d.def_id().is_local()),
2562                 ty::Param(_) => true,
2563
2564                 // Everything else (primitive types, etc.) is effectively
2565                 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
2566                 // the noise from these sort of types is usually just really
2567                 // annoying, rather than any sort of help).
2568                 _ => false,
2569             }
2570         }
2571
2572         // This occurs for UFCS desugaring of `T::method`, where there is no
2573         // receiver expression for the method call, and thus no autoderef.
2574         if let SelfSource::QPath(_) = source {
2575             return is_local(self.resolve_vars_with_obligations(rcvr_ty));
2576         }
2577
2578         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
2579     }
2580 }
2581
2582 #[derive(Copy, Clone, Debug)]
2583 pub enum SelfSource<'a> {
2584     QPath(&'a hir::Ty<'a>),
2585     MethodCall(&'a hir::Expr<'a> /* rcvr */),
2586 }
2587
2588 #[derive(Copy, Clone)]
2589 pub struct TraitInfo {
2590     pub def_id: DefId,
2591 }
2592
2593 impl PartialEq for TraitInfo {
2594     fn eq(&self, other: &TraitInfo) -> bool {
2595         self.cmp(other) == Ordering::Equal
2596     }
2597 }
2598 impl Eq for TraitInfo {}
2599 impl PartialOrd for TraitInfo {
2600     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
2601         Some(self.cmp(other))
2602     }
2603 }
2604 impl Ord for TraitInfo {
2605     fn cmp(&self, other: &TraitInfo) -> Ordering {
2606         // Local crates are more important than remote ones (local:
2607         // `cnum == 0`), and otherwise we throw in the defid for totality.
2608
2609         let lhs = (other.def_id.krate, other.def_id);
2610         let rhs = (self.def_id.krate, self.def_id);
2611         lhs.cmp(&rhs)
2612     }
2613 }
2614
2615 /// Retrieves all traits in this crate and any dependent crates,
2616 /// and wraps them into `TraitInfo` for custom sorting.
2617 pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
2618     tcx.all_traits().map(|def_id| TraitInfo { def_id }).collect()
2619 }
2620
2621 fn print_disambiguation_help<'tcx>(
2622     item_name: Ident,
2623     args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
2624     err: &mut Diagnostic,
2625     trait_name: String,
2626     rcvr_ty: Ty<'_>,
2627     kind: ty::AssocKind,
2628     def_id: DefId,
2629     span: Span,
2630     candidate: Option<usize>,
2631     source_map: &source_map::SourceMap,
2632     fn_has_self_parameter: bool,
2633 ) {
2634     let mut applicability = Applicability::MachineApplicable;
2635     let (span, sugg) = if let (ty::AssocKind::Fn, Some((receiver, args))) = (kind, args) {
2636         let args = format!(
2637             "({}{})",
2638             if rcvr_ty.is_region_ptr() {
2639                 if rcvr_ty.is_mutable_ptr() { "&mut " } else { "&" }
2640             } else {
2641                 ""
2642             },
2643             std::iter::once(receiver)
2644                 .chain(args.iter())
2645                 .map(|arg| source_map.span_to_snippet(arg.span).unwrap_or_else(|_| {
2646                     applicability = Applicability::HasPlaceholders;
2647                     "_".to_owned()
2648                 }))
2649                 .collect::<Vec<_>>()
2650                 .join(", "),
2651         );
2652         let trait_name = if !fn_has_self_parameter {
2653             format!("<{} as {}>", rcvr_ty, trait_name)
2654         } else {
2655             trait_name
2656         };
2657         (span, format!("{}::{}{}", trait_name, item_name, args))
2658     } else {
2659         (span.with_hi(item_name.span.lo()), format!("<{} as {}>::", rcvr_ty, trait_name))
2660     };
2661     err.span_suggestion_verbose(
2662         span,
2663         &format!(
2664             "disambiguate the {} for {}",
2665             kind.as_def_kind().descr(def_id),
2666             if let Some(candidate) = candidate {
2667                 format!("candidate #{}", candidate)
2668             } else {
2669                 "the candidate".to_string()
2670             },
2671         ),
2672         sugg,
2673         applicability,
2674     );
2675 }