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