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