]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/method/suggest.rs
Auto merge of #79608 - alessandrod:bpf, r=nagisa
[rust.git] / compiler / rustc_typeck / src / check / method / suggest.rs
1 //! Give useful errors and suggestions to users when an item can't be
2 //! found or is otherwise invalid.
3
4 use crate::check::FnCtxt;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
7 use rustc_hir as hir;
8 use rustc_hir::def::{DefKind, Namespace, Res};
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_hir::intravisit;
11 use rustc_hir::lang_items::LangItem;
12 use rustc_hir::{ExprKind, Node, QPath};
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_middle::ty::fast_reject::simplify_type;
15 use rustc_middle::ty::print::with_crate_prefix;
16 use rustc_middle::ty::{
17     self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
18 };
19 use rustc_span::lev_distance;
20 use rustc_span::symbol::{kw, sym, Ident};
21 use rustc_span::{source_map, FileName, Span};
22 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
23 use rustc_trait_selection::traits::Obligation;
24
25 use std::cmp::Ordering;
26 use std::iter;
27
28 use super::probe::Mode;
29 use super::{CandidateSource, MethodError, NoMatchData};
30
31 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
32     fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
33         let tcx = self.tcx;
34         match ty.kind() {
35             // Not all of these (e.g., unsafe fns) implement `FnOnce`,
36             // so we look for these beforehand.
37             ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true,
38             // If it's not a simple function, look for things which implement `FnOnce`.
39             _ => {
40                 let fn_once = match tcx.lang_items().require(LangItem::FnOnce) {
41                     Ok(fn_once) => fn_once,
42                     Err(..) => return false,
43                 };
44
45                 self.autoderef(span, ty).any(|(ty, _)| {
46                     self.probe(|_| {
47                         let fn_once_substs = tcx.mk_substs_trait(
48                             ty,
49                             &[self
50                                 .next_ty_var(TypeVariableOrigin {
51                                     kind: TypeVariableOriginKind::MiscVariable,
52                                     span,
53                                 })
54                                 .into()],
55                         );
56                         let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
57                         let poly_trait_ref = trait_ref.to_poly_trait_ref();
58                         let obligation = Obligation::misc(
59                             span,
60                             self.body_id,
61                             self.param_env,
62                             poly_trait_ref.without_const().to_predicate(tcx),
63                         );
64                         self.predicate_may_hold(&obligation)
65                     })
66                 })
67             }
68         }
69     }
70
71     pub fn report_method_error(
72         &self,
73         span: Span,
74         rcvr_ty: Ty<'tcx>,
75         item_name: Ident,
76         source: SelfSource<'tcx>,
77         error: MethodError<'tcx>,
78         args: Option<&'tcx [hir::Expr<'tcx>]>,
79     ) -> Option<DiagnosticBuilder<'_>> {
80         let orig_span = span;
81         let mut span = span;
82         // Avoid suggestions when we don't know what's going on.
83         if rcvr_ty.references_error() {
84             return None;
85         }
86
87         let report_candidates = |span: Span,
88                                  err: &mut DiagnosticBuilder<'_>,
89                                  mut sources: Vec<CandidateSource>,
90                                  sugg_span: Span| {
91             sources.sort();
92             sources.dedup();
93             // Dynamic limit to avoid hiding just one candidate, which is silly.
94             let limit = if sources.len() == 5 { 5 } else { 4 };
95
96             for (idx, source) in sources.iter().take(limit).enumerate() {
97                 match *source {
98                     CandidateSource::ImplSource(impl_did) => {
99                         // Provide the best span we can. Use the item, if local to crate, else
100                         // the impl, if local to crate (item may be defaulted), else nothing.
101                         let item = match self
102                             .associated_item(impl_did, item_name, Namespace::ValueNS)
103                             .or_else(|| {
104                                 let impl_trait_ref = self.tcx.impl_trait_ref(impl_did)?;
105                                 self.associated_item(
106                                     impl_trait_ref.def_id,
107                                     item_name,
108                                     Namespace::ValueNS,
109                                 )
110                             }) {
111                             Some(item) => item,
112                             None => continue,
113                         };
114                         let note_span = self
115                             .tcx
116                             .hir()
117                             .span_if_local(item.def_id)
118                             .or_else(|| self.tcx.hir().span_if_local(impl_did));
119
120                         let impl_ty = self.tcx.at(span).type_of(impl_did);
121
122                         let insertion = match self.tcx.impl_trait_ref(impl_did) {
123                             None => String::new(),
124                             Some(trait_ref) => format!(
125                                 " of the trait `{}`",
126                                 self.tcx.def_path_str(trait_ref.def_id)
127                             ),
128                         };
129
130                         let (note_str, idx) = if sources.len() > 1 {
131                             (
132                                 format!(
133                                     "candidate #{} is defined in an impl{} for the type `{}`",
134                                     idx + 1,
135                                     insertion,
136                                     impl_ty,
137                                 ),
138                                 Some(idx + 1),
139                             )
140                         } else {
141                             (
142                                 format!(
143                                     "the candidate is defined in an impl{} for the type `{}`",
144                                     insertion, impl_ty,
145                                 ),
146                                 None,
147                             )
148                         };
149                         if let Some(note_span) = note_span {
150                             // We have a span pointing to the method. Show note with snippet.
151                             err.span_note(
152                                 self.tcx.sess.source_map().guess_head_span(note_span),
153                                 &note_str,
154                             );
155                         } else {
156                             err.note(&note_str);
157                         }
158                         if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did) {
159                             let path = self.tcx.def_path_str(trait_ref.def_id);
160
161                             let ty = match item.kind {
162                                 ty::AssocKind::Const | ty::AssocKind::Type => rcvr_ty,
163                                 ty::AssocKind::Fn => self
164                                     .tcx
165                                     .fn_sig(item.def_id)
166                                     .inputs()
167                                     .skip_binder()
168                                     .get(0)
169                                     .filter(|ty| ty.is_region_ptr() && !rcvr_ty.is_region_ptr())
170                                     .copied()
171                                     .unwrap_or(rcvr_ty),
172                             };
173                             print_disambiguation_help(
174                                 item_name,
175                                 args,
176                                 err,
177                                 path,
178                                 ty,
179                                 item.kind,
180                                 item.def_id,
181                                 sugg_span,
182                                 idx,
183                                 self.tcx.sess.source_map(),
184                             );
185                         }
186                     }
187                     CandidateSource::TraitSource(trait_did) => {
188                         let item =
189                             match self.associated_item(trait_did, item_name, Namespace::ValueNS) {
190                                 Some(item) => item,
191                                 None => continue,
192                             };
193                         let item_span = self
194                             .tcx
195                             .sess
196                             .source_map()
197                             .guess_head_span(self.tcx.def_span(item.def_id));
198                         let idx = if sources.len() > 1 {
199                             let msg = &format!(
200                                 "candidate #{} is defined in the trait `{}`",
201                                 idx + 1,
202                                 self.tcx.def_path_str(trait_did)
203                             );
204                             err.span_note(item_span, msg);
205                             Some(idx + 1)
206                         } else {
207                             let msg = &format!(
208                                 "the candidate is defined in the trait `{}`",
209                                 self.tcx.def_path_str(trait_did)
210                             );
211                             err.span_note(item_span, msg);
212                             None
213                         };
214                         let path = self.tcx.def_path_str(trait_did);
215                         print_disambiguation_help(
216                             item_name,
217                             args,
218                             err,
219                             path,
220                             rcvr_ty,
221                             item.kind,
222                             item.def_id,
223                             sugg_span,
224                             idx,
225                             self.tcx.sess.source_map(),
226                         );
227                     }
228                 }
229             }
230             if sources.len() > limit {
231                 err.note(&format!("and {} others", sources.len() - limit));
232             }
233         };
234
235         let sugg_span = if let SelfSource::MethodCall(expr) = source {
236             // Given `foo.bar(baz)`, `expr` is `bar`, but we want to point to the whole thing.
237             self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)).span
238         } else {
239             span
240         };
241
242         match error {
243             MethodError::NoMatch(NoMatchData {
244                 static_candidates: static_sources,
245                 unsatisfied_predicates,
246                 out_of_scope_traits,
247                 lev_candidate,
248                 mode,
249             }) => {
250                 let tcx = self.tcx;
251
252                 let actual = self.resolve_vars_if_possible(rcvr_ty);
253                 let ty_str = self.ty_to_string(actual);
254                 let is_method = mode == Mode::MethodCall;
255                 let item_kind = if is_method {
256                     "method"
257                 } else if actual.is_enum() {
258                     "variant or associated item"
259                 } else {
260                     match (item_name.as_str().chars().next(), actual.is_fresh_ty()) {
261                         (Some(name), false) if name.is_lowercase() => "function or associated item",
262                         (Some(_), false) => "associated item",
263                         (Some(_), true) | (None, false) => "variant or associated item",
264                         (None, true) => "variant",
265                     }
266                 };
267                 let mut err = if !actual.references_error() {
268                     // Suggest clamping down the type if the method that is being attempted to
269                     // be used exists at all, and the type is an ambiguous numeric type
270                     // ({integer}/{float}).
271                     let mut candidates = all_traits(self.tcx).into_iter().filter_map(|info| {
272                         self.associated_item(info.def_id, item_name, Namespace::ValueNS)
273                     });
274                     // There are methods that are defined on the primitive types and won't be
275                     // found when exploring `all_traits`, but we also need them to be acurate on
276                     // our suggestions (#47759).
277                     let fund_assoc = |opt_def_id: Option<DefId>| {
278                         opt_def_id
279                             .and_then(|id| self.associated_item(id, item_name, Namespace::ValueNS))
280                             .is_some()
281                     };
282                     let lang_items = tcx.lang_items();
283                     let found_candidate = candidates.next().is_some()
284                         || fund_assoc(lang_items.i8_impl())
285                         || fund_assoc(lang_items.i16_impl())
286                         || fund_assoc(lang_items.i32_impl())
287                         || fund_assoc(lang_items.i64_impl())
288                         || fund_assoc(lang_items.i128_impl())
289                         || fund_assoc(lang_items.u8_impl())
290                         || fund_assoc(lang_items.u16_impl())
291                         || fund_assoc(lang_items.u32_impl())
292                         || fund_assoc(lang_items.u64_impl())
293                         || fund_assoc(lang_items.u128_impl())
294                         || fund_assoc(lang_items.f32_impl())
295                         || fund_assoc(lang_items.f32_runtime_impl())
296                         || fund_assoc(lang_items.f64_impl())
297                         || fund_assoc(lang_items.f64_runtime_impl());
298                     if let (true, false, SelfSource::MethodCall(expr), true) = (
299                         actual.is_numeric(),
300                         actual.has_concrete_skeleton(),
301                         source,
302                         found_candidate,
303                     ) {
304                         let mut err = struct_span_err!(
305                             tcx.sess,
306                             span,
307                             E0689,
308                             "can't call {} `{}` on ambiguous numeric type `{}`",
309                             item_kind,
310                             item_name,
311                             ty_str
312                         );
313                         let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
314                         match expr.kind {
315                             ExprKind::Lit(ref lit) => {
316                                 // numeric literal
317                                 let snippet = tcx
318                                     .sess
319                                     .source_map()
320                                     .span_to_snippet(lit.span)
321                                     .unwrap_or_else(|_| "<numeric literal>".to_owned());
322
323                                 err.span_suggestion(
324                                     lit.span,
325                                     &format!(
326                                         "you must specify a concrete type for this numeric value, \
327                                          like `{}`",
328                                         concrete_type
329                                     ),
330                                     format!("{}_{}", snippet, concrete_type),
331                                     Applicability::MaybeIncorrect,
332                                 );
333                             }
334                             ExprKind::Path(ref qpath) => {
335                                 // local binding
336                                 if let QPath::Resolved(_, path) = qpath {
337                                     if let hir::def::Res::Local(hir_id) = path.res {
338                                         let span = tcx.hir().span(hir_id);
339                                         let snippet = tcx.sess.source_map().span_to_snippet(span);
340                                         let filename = tcx.sess.source_map().span_to_filename(span);
341
342                                         let parent_node = self
343                                             .tcx
344                                             .hir()
345                                             .get(self.tcx.hir().get_parent_node(hir_id));
346                                         let msg = format!(
347                                             "you must specify a type for this binding, like `{}`",
348                                             concrete_type,
349                                         );
350
351                                         match (filename, parent_node, snippet) {
352                                             (
353                                                 FileName::Real(_),
354                                                 Node::Local(hir::Local {
355                                                     source: hir::LocalSource::Normal,
356                                                     ty,
357                                                     ..
358                                                 }),
359                                                 Ok(ref snippet),
360                                             ) => {
361                                                 err.span_suggestion(
362                                                     // account for `let x: _ = 42;`
363                                                     //                  ^^^^
364                                                     span.to(ty
365                                                         .as_ref()
366                                                         .map(|ty| ty.span)
367                                                         .unwrap_or(span)),
368                                                     &msg,
369                                                     format!("{}: {}", snippet, concrete_type),
370                                                     Applicability::MaybeIncorrect,
371                                                 );
372                                             }
373                                             _ => {
374                                                 err.span_label(span, msg);
375                                             }
376                                         }
377                                     }
378                                 }
379                             }
380                             _ => {}
381                         }
382                         err.emit();
383                         return None;
384                     } else {
385                         span = item_name.span;
386
387                         // Don't show generic arguments when the method can't be found in any implementation (#81576).
388                         let mut ty_str_reported = ty_str.clone();
389                         if let ty::Adt(_, ref generics) = actual.kind() {
390                             if generics.len() > 0 {
391                                 let mut autoderef = self.autoderef(span, actual);
392                                 let candidate_found = autoderef.any(|(ty, _)| {
393                                     if let ty::Adt(ref adt_deref, _) = ty.kind() {
394                                         self.tcx
395                                             .inherent_impls(adt_deref.did)
396                                             .iter()
397                                             .filter_map(|def_id| {
398                                                 self.associated_item(
399                                                     *def_id,
400                                                     item_name,
401                                                     Namespace::ValueNS,
402                                                 )
403                                             })
404                                             .count()
405                                             >= 1
406                                     } else {
407                                         false
408                                     }
409                                 });
410                                 let has_deref = autoderef.step_count() > 0;
411                                 if !candidate_found
412                                     && !has_deref
413                                     && unsatisfied_predicates.is_empty()
414                                 {
415                                     if let Some((path_string, _)) = ty_str.split_once('<') {
416                                         ty_str_reported = path_string.to_string();
417                                     }
418                                 }
419                             }
420                         }
421
422                         let mut err = struct_span_err!(
423                             tcx.sess,
424                             span,
425                             E0599,
426                             "no {} named `{}` found for {} `{}` in the current scope",
427                             item_kind,
428                             item_name,
429                             actual.prefix_string(self.tcx),
430                             ty_str_reported,
431                         );
432                         if let Mode::MethodCall = mode {
433                             if let SelfSource::MethodCall(call) = source {
434                                 self.suggest_await_before_method(
435                                     &mut err, item_name, actual, call, span,
436                                 );
437                             }
438                         }
439                         if let Some(span) =
440                             tcx.sess.confused_type_with_std_module.borrow().get(&span)
441                         {
442                             if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*span) {
443                                 err.span_suggestion(
444                                     *span,
445                                     "you are looking for the module in `std`, \
446                                      not the primitive type",
447                                     format!("std::{}", snippet),
448                                     Applicability::MachineApplicable,
449                                 );
450                             }
451                         }
452                         if let ty::RawPtr(_) = &actual.kind() {
453                             err.note(
454                                 "try using `<*const T>::as_ref()` to get a reference to the \
455                                       type behind the pointer: https://doc.rust-lang.org/std/\
456                                       primitive.pointer.html#method.as_ref",
457                             );
458                             err.note(
459                                 "using `<*const T>::as_ref()` on a pointer \
460                                       which is unaligned or points to invalid \
461                                       or uninitialized memory is undefined behavior",
462                             );
463                         }
464                         err
465                     }
466                 } else {
467                     tcx.sess.diagnostic().struct_dummy()
468                 };
469
470                 if let Some(def) = actual.ty_adt_def() {
471                     if let Some(full_sp) = tcx.hir().span_if_local(def.did) {
472                         let def_sp = tcx.sess.source_map().guess_head_span(full_sp);
473                         err.span_label(
474                             def_sp,
475                             format!(
476                                 "{} `{}` not found {}",
477                                 item_kind,
478                                 item_name,
479                                 if def.is_enum() && !is_method { "here" } else { "for this" }
480                             ),
481                         );
482                     }
483                 }
484
485                 let mut label_span_not_found = || {
486                     if unsatisfied_predicates.is_empty() {
487                         err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
488                         if let ty::Adt(ref adt, _) = rcvr_ty.kind() {
489                             let mut inherent_impls_candidate = self
490                                 .tcx
491                                 .inherent_impls(adt.did)
492                                 .iter()
493                                 .copied()
494                                 .filter(|def_id| {
495                                     if let Some(assoc) =
496                                         self.associated_item(*def_id, item_name, Namespace::ValueNS)
497                                     {
498                                         // Check for both mode is the same so we avoid suggesting
499                                         // incorrect associated item.
500                                         match (mode, assoc.fn_has_self_parameter, source) {
501                                             (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
502                                                 // We check that the suggest type is actually
503                                                 // different from the received one
504                                                 // So we avoid suggestion method with Box<Self>
505                                                 // for instance
506                                                 self.tcx.at(span).type_of(*def_id) != actual
507                                                     && self.tcx.at(span).type_of(*def_id) != rcvr_ty
508                                             }
509                                             (Mode::Path, false, _) => true,
510                                             _ => false,
511                                         }
512                                     } else {
513                                         false
514                                     }
515                                 })
516                                 .collect::<Vec<_>>();
517                             if inherent_impls_candidate.len() > 0 {
518                                 inherent_impls_candidate.sort();
519                                 inherent_impls_candidate.dedup();
520
521                                 // number of type to shows at most.
522                                 let limit = if inherent_impls_candidate.len() == 5 { 5 } else { 4 };
523                                 let type_candidates = inherent_impls_candidate
524                                     .iter()
525                                     .take(limit)
526                                     .map(|impl_item| {
527                                         format!("- `{}`", self.tcx.at(span).type_of(*impl_item))
528                                     })
529                                     .collect::<Vec<_>>()
530                                     .join("\n");
531                                 let additional_types = if inherent_impls_candidate.len() > limit {
532                                     format!(
533                                         "\nand {} more types",
534                                         inherent_impls_candidate.len() - limit
535                                     )
536                                 } else {
537                                     "".to_string()
538                                 };
539                                 err.note(&format!(
540                                     "the {item_kind} was found for\n{}{}",
541                                     type_candidates, additional_types
542                                 ));
543                             }
544                         }
545                     } else {
546                         err.span_label(span, format!("{item_kind} cannot be called on `{ty_str}` due to unsatisfied trait bounds"));
547                     }
548                     self.tcx.sess.trait_methods_not_found.borrow_mut().insert(orig_span);
549                 };
550
551                 // If the method name is the name of a field with a function or closure type,
552                 // give a helping note that it has to be called as `(x.f)(...)`.
553                 if let SelfSource::MethodCall(expr) = source {
554                     let field_receiver =
555                         self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() {
556                             ty::Adt(def, substs) if !def.is_enum() => {
557                                 let variant = &def.non_enum_variant();
558                                 self.tcx.find_field_index(item_name, variant).map(|index| {
559                                     let field = &variant.fields[index];
560                                     let field_ty = field.ty(tcx, substs);
561                                     (field, field_ty)
562                                 })
563                             }
564                             _ => None,
565                         });
566
567                     if let Some((field, field_ty)) = field_receiver {
568                         let scope = self.tcx.parent_module(self.body_id).to_def_id();
569                         let is_accessible = field.vis.is_accessible_from(scope, self.tcx);
570
571                         if is_accessible {
572                             if self.is_fn_ty(&field_ty, span) {
573                                 let expr_span = expr.span.to(item_name.span);
574                                 err.multipart_suggestion(
575                                     &format!(
576                                         "to call the function stored in `{}`, \
577                                          surround the field access with parentheses",
578                                         item_name,
579                                     ),
580                                     vec![
581                                         (expr_span.shrink_to_lo(), '('.to_string()),
582                                         (expr_span.shrink_to_hi(), ')'.to_string()),
583                                     ],
584                                     Applicability::MachineApplicable,
585                                 );
586                             } else {
587                                 let call_expr = self
588                                     .tcx
589                                     .hir()
590                                     .expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
591
592                                 if let Some(span) = call_expr.span.trim_start(item_name.span) {
593                                     err.span_suggestion(
594                                         span,
595                                         "remove the arguments",
596                                         String::new(),
597                                         Applicability::MaybeIncorrect,
598                                     );
599                                 }
600                             }
601                         }
602
603                         let field_kind = if is_accessible { "field" } else { "private field" };
604                         err.span_label(item_name.span, format!("{}, not a method", field_kind));
605                     } else if lev_candidate.is_none() && static_sources.is_empty() {
606                         label_span_not_found();
607                     }
608                 } else {
609                     label_span_not_found();
610                 }
611
612                 if self.is_fn_ty(&rcvr_ty, span) {
613                     fn report_function<T: std::fmt::Display>(
614                         err: &mut DiagnosticBuilder<'_>,
615                         name: T,
616                     ) {
617                         err.note(
618                             &format!("`{}` is a function, perhaps you wish to call it", name,),
619                         );
620                     }
621
622                     if let SelfSource::MethodCall(expr) = source {
623                         if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr.span) {
624                             report_function(&mut err, expr_string);
625                         } else if let ExprKind::Path(QPath::Resolved(_, ref path)) = expr.kind {
626                             if let Some(segment) = path.segments.last() {
627                                 report_function(&mut err, segment.ident);
628                             }
629                         }
630                     }
631                 }
632
633                 if !static_sources.is_empty() {
634                     err.note(
635                         "found the following associated functions; to be used as methods, \
636                          functions must have a `self` parameter",
637                     );
638                     err.span_label(span, "this is an associated function, not a method");
639                 }
640                 if static_sources.len() == 1 {
641                     let ty_str = if let Some(CandidateSource::ImplSource(impl_did)) =
642                         static_sources.get(0)
643                     {
644                         // When the "method" is resolved through dereferencing, we really want the
645                         // original type that has the associated function for accurate suggestions.
646                         // (#61411)
647                         let ty = tcx.at(span).type_of(*impl_did);
648                         match (&ty.peel_refs().kind(), &actual.peel_refs().kind()) {
649                             (ty::Adt(def, _), ty::Adt(def_actual, _)) if def == def_actual => {
650                                 // Use `actual` as it will have more `substs` filled in.
651                                 self.ty_to_value_string(actual.peel_refs())
652                             }
653                             _ => self.ty_to_value_string(ty.peel_refs()),
654                         }
655                     } else {
656                         self.ty_to_value_string(actual.peel_refs())
657                     };
658                     if let SelfSource::MethodCall(expr) = source {
659                         err.span_suggestion(
660                             expr.span.to(span),
661                             "use associated function syntax instead",
662                             format!("{}::{}", ty_str, item_name),
663                             Applicability::MachineApplicable,
664                         );
665                     } else {
666                         err.help(&format!("try with `{}::{}`", ty_str, item_name,));
667                     }
668
669                     report_candidates(span, &mut err, static_sources, sugg_span);
670                 } else if static_sources.len() > 1 {
671                     report_candidates(span, &mut err, static_sources, sugg_span);
672                 }
673
674                 let mut restrict_type_params = false;
675                 let mut unsatisfied_bounds = false;
676                 if !unsatisfied_predicates.is_empty() {
677                     let def_span = |def_id| {
678                         self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id))
679                     };
680                     let mut type_params = FxHashMap::default();
681                     let mut bound_spans = vec![];
682
683                     let mut collect_type_param_suggestions =
684                         |self_ty: Ty<'tcx>, parent_pred: &ty::Predicate<'tcx>, obligation: &str| {
685                             // We don't care about regions here, so it's fine to skip the binder here.
686                             if let (ty::Param(_), ty::PredicateKind::Trait(p, _)) =
687                                 (self_ty.kind(), parent_pred.kind().skip_binder())
688                             {
689                                 if let ty::Adt(def, _) = p.trait_ref.self_ty().kind() {
690                                     let node = def.did.as_local().map(|def_id| {
691                                         self.tcx
692                                             .hir()
693                                             .get(self.tcx.hir().local_def_id_to_hir_id(def_id))
694                                     });
695                                     if let Some(hir::Node::Item(hir::Item { kind, .. })) = node {
696                                         if let Some(g) = kind.generics() {
697                                             let key = match g.where_clause.predicates {
698                                                 [.., pred] => (pred.span().shrink_to_hi(), false),
699                                                 [] => (
700                                                     g.where_clause
701                                                         .span_for_predicates_or_empty_place(),
702                                                     true,
703                                                 ),
704                                             };
705                                             type_params
706                                                 .entry(key)
707                                                 .or_insert_with(FxHashSet::default)
708                                                 .insert(obligation.to_owned());
709                                         }
710                                     }
711                                 }
712                             }
713                         };
714                     let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
715                         let msg = format!(
716                             "doesn't satisfy `{}`",
717                             if obligation.len() > 50 { quiet } else { obligation }
718                         );
719                         match &self_ty.kind() {
720                             // Point at the type that couldn't satisfy the bound.
721                             ty::Adt(def, _) => bound_spans.push((def_span(def.did), msg)),
722                             // Point at the trait object that couldn't satisfy the bound.
723                             ty::Dynamic(preds, _) => {
724                                 for pred in preds.iter() {
725                                     match pred.skip_binder() {
726                                         ty::ExistentialPredicate::Trait(tr) => {
727                                             bound_spans.push((def_span(tr.def_id), msg.clone()))
728                                         }
729                                         ty::ExistentialPredicate::Projection(_)
730                                         | ty::ExistentialPredicate::AutoTrait(_) => {}
731                                     }
732                                 }
733                             }
734                             // Point at the closure that couldn't satisfy the bound.
735                             ty::Closure(def_id, _) => bound_spans
736                                 .push((def_span(*def_id), format!("doesn't satisfy `{}`", quiet))),
737                             _ => {}
738                         }
739                     };
740                     let mut format_pred = |pred: ty::Predicate<'tcx>| {
741                         let bound_predicate = pred.kind();
742                         match bound_predicate.skip_binder() {
743                             ty::PredicateKind::Projection(pred) => {
744                                 let pred = bound_predicate.rebind(pred);
745                                 // `<Foo as Iterator>::Item = String`.
746                                 let projection_ty = pred.skip_binder().projection_ty;
747
748                                 let substs_with_infer_self = tcx.mk_substs(
749                                     iter::once(tcx.mk_ty_var(ty::TyVid { index: 0 }).into())
750                                         .chain(projection_ty.substs.iter().skip(1)),
751                                 );
752
753                                 let quiet_projection_ty = ty::ProjectionTy {
754                                     substs: substs_with_infer_self,
755                                     item_def_id: projection_ty.item_def_id,
756                                 };
757
758                                 let ty = pred.skip_binder().ty;
759
760                                 let obligation = format!("{} = {}", projection_ty, ty);
761                                 let quiet = format!("{} = {}", quiet_projection_ty, ty);
762
763                                 bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
764                                 Some((obligation, projection_ty.self_ty()))
765                             }
766                             ty::PredicateKind::Trait(poly_trait_ref, _) => {
767                                 let p = poly_trait_ref.trait_ref;
768                                 let self_ty = p.self_ty();
769                                 let path = p.print_only_trait_path();
770                                 let obligation = format!("{}: {}", self_ty, path);
771                                 let quiet = format!("_: {}", path);
772                                 bound_span_label(self_ty, &obligation, &quiet);
773                                 Some((obligation, self_ty))
774                             }
775                             _ => None,
776                         }
777                     };
778                     let mut bound_list = unsatisfied_predicates
779                         .iter()
780                         .filter_map(|(pred, parent_pred)| {
781                             format_pred(*pred).map(|(p, self_ty)| match parent_pred {
782                                 None => format!("`{}`", &p),
783                                 Some(parent_pred) => match format_pred(*parent_pred) {
784                                     None => format!("`{}`", &p),
785                                     Some((parent_p, _)) => {
786                                         collect_type_param_suggestions(self_ty, parent_pred, &p);
787                                         format!("`{}`\nwhich is required by `{}`", p, parent_p)
788                                     }
789                                 },
790                             })
791                         })
792                         .enumerate()
793                         .collect::<Vec<(usize, String)>>();
794                     for ((span, empty_where), obligations) in type_params.into_iter() {
795                         restrict_type_params = true;
796                         // #74886: Sort here so that the output is always the same.
797                         let mut obligations = obligations.into_iter().collect::<Vec<_>>();
798                         obligations.sort();
799                         err.span_suggestion_verbose(
800                             span,
801                             &format!(
802                                 "consider restricting the type parameter{s} to satisfy the \
803                                  trait bound{s}",
804                                 s = pluralize!(obligations.len())
805                             ),
806                             format!(
807                                 "{} {}",
808                                 if empty_where { " where" } else { "," },
809                                 obligations.join(", ")
810                             ),
811                             Applicability::MaybeIncorrect,
812                         );
813                     }
814
815                     bound_list.sort_by(|(_, a), (_, b)| a.cmp(&b)); // Sort alphabetically.
816                     bound_list.dedup_by(|(_, a), (_, b)| a == b); // #35677
817                     bound_list.sort_by_key(|(pos, _)| *pos); // Keep the original predicate order.
818                     bound_spans.sort();
819                     bound_spans.dedup();
820                     for (span, msg) in bound_spans.into_iter() {
821                         err.span_label(span, &msg);
822                     }
823                     if !bound_list.is_empty() {
824                         let bound_list = bound_list
825                             .into_iter()
826                             .map(|(_, path)| path)
827                             .collect::<Vec<_>>()
828                             .join("\n");
829                         let actual_prefix = actual.prefix_string(self.tcx);
830                         err.set_primary_message(&format!(
831                             "the {item_kind} `{item_name}` exists for {actual_prefix} `{ty_str}`, but its trait bounds were not satisfied"
832                         ));
833                         err.note(&format!(
834                             "the following trait bounds were not satisfied:\n{bound_list}"
835                         ));
836                         unsatisfied_bounds = true;
837                     }
838                 }
839
840                 if actual.is_numeric() && actual.is_fresh() || restrict_type_params {
841                 } else {
842                     self.suggest_traits_to_import(
843                         &mut err,
844                         span,
845                         rcvr_ty,
846                         item_name,
847                         source,
848                         out_of_scope_traits,
849                         &unsatisfied_predicates,
850                         unsatisfied_bounds,
851                     );
852                 }
853
854                 // Don't emit a suggestion if we found an actual method
855                 // that had unsatisfied trait bounds
856                 if unsatisfied_predicates.is_empty() && actual.is_enum() {
857                     let adt_def = actual.ty_adt_def().expect("enum is not an ADT");
858                     if let Some(suggestion) = lev_distance::find_best_match_for_name(
859                         &adt_def.variants.iter().map(|s| s.ident.name).collect::<Vec<_>>(),
860                         item_name.name,
861                         None,
862                     ) {
863                         err.span_suggestion(
864                             span,
865                             "there is a variant with a similar name",
866                             suggestion.to_string(),
867                             Applicability::MaybeIncorrect,
868                         );
869                     }
870                 }
871
872                 let mut fallback_span = true;
873                 let msg = "remove this method call";
874                 if item_name.name == sym::as_str && actual.peel_refs().is_str() {
875                     if let SelfSource::MethodCall(expr) = source {
876                         let call_expr =
877                             self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
878                         if let Some(span) = call_expr.span.trim_start(expr.span) {
879                             err.span_suggestion(
880                                 span,
881                                 msg,
882                                 String::new(),
883                                 Applicability::MachineApplicable,
884                             );
885                             fallback_span = false;
886                         }
887                     }
888                     if fallback_span {
889                         err.span_label(span, msg);
890                     }
891                 } else if let Some(lev_candidate) = lev_candidate {
892                     // Don't emit a suggestion if we found an actual method
893                     // that had unsatisfied trait bounds
894                     if unsatisfied_predicates.is_empty() {
895                         let def_kind = lev_candidate.kind.as_def_kind();
896                         err.span_suggestion(
897                             span,
898                             &format!(
899                                 "there is {} {} with a similar name",
900                                 def_kind.article(),
901                                 def_kind.descr(lev_candidate.def_id),
902                             ),
903                             lev_candidate.ident.to_string(),
904                             Applicability::MaybeIncorrect,
905                         );
906                     }
907                 }
908
909                 return Some(err);
910             }
911
912             MethodError::Ambiguity(sources) => {
913                 let mut err = struct_span_err!(
914                     self.sess(),
915                     item_name.span,
916                     E0034,
917                     "multiple applicable items in scope"
918                 );
919                 err.span_label(item_name.span, format!("multiple `{}` found", item_name));
920
921                 report_candidates(span, &mut err, sources, sugg_span);
922                 err.emit();
923             }
924
925             MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
926                 let kind = kind.descr(def_id);
927                 let mut err = struct_span_err!(
928                     self.tcx.sess,
929                     item_name.span,
930                     E0624,
931                     "{} `{}` is private",
932                     kind,
933                     item_name
934                 );
935                 err.span_label(item_name.span, &format!("private {}", kind));
936                 self.suggest_valid_traits(&mut err, out_of_scope_traits);
937                 err.emit();
938             }
939
940             MethodError::IllegalSizedBound(candidates, needs_mut, bound_span) => {
941                 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
942                 let mut err = self.sess().struct_span_err(span, &msg);
943                 err.span_label(bound_span, "this has a `Sized` requirement");
944                 if !candidates.is_empty() {
945                     let help = format!(
946                         "{an}other candidate{s} {were} found in the following trait{s}, perhaps \
947                          add a `use` for {one_of_them}:",
948                         an = if candidates.len() == 1 { "an" } else { "" },
949                         s = pluralize!(candidates.len()),
950                         were = if candidates.len() == 1 { "was" } else { "were" },
951                         one_of_them = if candidates.len() == 1 { "it" } else { "one_of_them" },
952                     );
953                     self.suggest_use_candidates(&mut err, help, candidates);
954                 }
955                 if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind() {
956                     if needs_mut {
957                         let trait_type = self.tcx.mk_ref(
958                             region,
959                             ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() },
960                         );
961                         err.note(&format!("you need `{}` instead of `{}`", trait_type, rcvr_ty));
962                     }
963                 }
964                 err.emit();
965             }
966
967             MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
968         }
969         None
970     }
971
972     /// Print out the type for use in value namespace.
973     fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
974         match ty.kind() {
975             ty::Adt(def, substs) => format!("{}", ty::Instance::new(def.did, substs)),
976             _ => self.ty_to_string(ty),
977         }
978     }
979
980     fn suggest_await_before_method(
981         &self,
982         err: &mut DiagnosticBuilder<'_>,
983         item_name: Ident,
984         ty: Ty<'tcx>,
985         call: &hir::Expr<'_>,
986         span: Span,
987     ) {
988         let output_ty = match self.infcx.get_impl_future_output_ty(ty) {
989             Some(output_ty) => self.resolve_vars_if_possible(output_ty),
990             _ => return,
991         };
992         let method_exists = self.method_exists(item_name, output_ty, call.hir_id, true);
993         debug!("suggest_await_before_method: is_method_exist={}", method_exists);
994         if method_exists {
995             err.span_suggestion_verbose(
996                 span.shrink_to_lo(),
997                 "consider `await`ing on the `Future` and calling the method on its `Output`",
998                 "await.".to_string(),
999                 Applicability::MaybeIncorrect,
1000             );
1001         }
1002     }
1003
1004     fn suggest_use_candidates(
1005         &self,
1006         err: &mut DiagnosticBuilder<'_>,
1007         mut msg: String,
1008         candidates: Vec<DefId>,
1009     ) {
1010         let module_did = self.tcx.parent_module(self.body_id);
1011         let module_id = self.tcx.hir().local_def_id_to_hir_id(module_did);
1012         let krate = self.tcx.hir().krate();
1013         let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
1014         if let Some(span) = span {
1015             let path_strings = candidates.iter().map(|did| {
1016                 // Produce an additional newline to separate the new use statement
1017                 // from the directly following item.
1018                 let additional_newline = if found_use { "" } else { "\n" };
1019                 format!(
1020                     "use {};\n{}",
1021                     with_crate_prefix(|| self.tcx.def_path_str(*did)),
1022                     additional_newline
1023                 )
1024             });
1025
1026             err.span_suggestions(span, &msg, path_strings, Applicability::MaybeIncorrect);
1027         } else {
1028             let limit = if candidates.len() == 5 { 5 } else { 4 };
1029             for (i, trait_did) in candidates.iter().take(limit).enumerate() {
1030                 if candidates.len() > 1 {
1031                     msg.push_str(&format!(
1032                         "\ncandidate #{}: `use {};`",
1033                         i + 1,
1034                         with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
1035                     ));
1036                 } else {
1037                     msg.push_str(&format!(
1038                         "\n`use {};`",
1039                         with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
1040                     ));
1041                 }
1042             }
1043             if candidates.len() > limit {
1044                 msg.push_str(&format!("\nand {} others", candidates.len() - limit));
1045             }
1046             err.note(&msg[..]);
1047         }
1048     }
1049
1050     fn suggest_valid_traits(
1051         &self,
1052         err: &mut DiagnosticBuilder<'_>,
1053         valid_out_of_scope_traits: Vec<DefId>,
1054     ) -> bool {
1055         if !valid_out_of_scope_traits.is_empty() {
1056             let mut candidates = valid_out_of_scope_traits;
1057             candidates.sort();
1058             candidates.dedup();
1059             err.help("items from traits can only be used if the trait is in scope");
1060             let msg = format!(
1061                 "the following {traits_are} implemented but not in scope; \
1062                  perhaps add a `use` for {one_of_them}:",
1063                 traits_are = if candidates.len() == 1 { "trait is" } else { "traits are" },
1064                 one_of_them = if candidates.len() == 1 { "it" } else { "one of them" },
1065             );
1066
1067             self.suggest_use_candidates(err, msg, candidates);
1068             true
1069         } else {
1070             false
1071         }
1072     }
1073
1074     fn suggest_traits_to_import(
1075         &self,
1076         err: &mut DiagnosticBuilder<'_>,
1077         span: Span,
1078         rcvr_ty: Ty<'tcx>,
1079         item_name: Ident,
1080         source: SelfSource<'tcx>,
1081         valid_out_of_scope_traits: Vec<DefId>,
1082         unsatisfied_predicates: &[(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)],
1083         unsatisfied_bounds: bool,
1084     ) {
1085         let mut alt_rcvr_sugg = false;
1086         if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
1087             debug!(?span, ?item_name, ?rcvr_ty, ?rcvr);
1088             let skippable = [
1089                 self.tcx.lang_items().clone_trait(),
1090                 self.tcx.lang_items().deref_trait(),
1091                 self.tcx.lang_items().deref_mut_trait(),
1092                 self.tcx.lang_items().drop_trait(),
1093             ];
1094             // Try alternative arbitrary self types that could fulfill this call.
1095             // FIXME: probe for all types that *could* be arbitrary self-types, not
1096             // just this list.
1097             for (rcvr_ty, post) in &[
1098                 (rcvr_ty, ""),
1099                 (self.tcx.mk_mut_ref(&ty::ReErased, rcvr_ty), "&mut "),
1100                 (self.tcx.mk_imm_ref(&ty::ReErased, rcvr_ty), "&"),
1101             ] {
1102                 if let Ok(pick) = self.lookup_probe(
1103                     span,
1104                     item_name,
1105                     rcvr_ty,
1106                     rcvr,
1107                     crate::check::method::probe::ProbeScope::AllTraits,
1108                 ) {
1109                     // If the method is defined for the receiver we have, it likely wasn't `use`d.
1110                     // We point at the method, but we just skip the rest of the check for arbitrary
1111                     // self types and rely on the suggestion to `use` the trait from
1112                     // `suggest_valid_traits`.
1113                     let did = Some(pick.item.container.id());
1114                     let skip = skippable.contains(&did);
1115                     if pick.autoderefs == 0 && !skip {
1116                         err.span_label(
1117                             pick.item.ident.span,
1118                             &format!("the method is available for `{}` here", rcvr_ty),
1119                         );
1120                     }
1121                     break;
1122                 }
1123                 for (rcvr_ty, pre) in &[
1124                     (self.tcx.mk_lang_item(rcvr_ty, LangItem::OwnedBox), "Box::new"),
1125                     (self.tcx.mk_lang_item(rcvr_ty, LangItem::Pin), "Pin::new"),
1126                     (self.tcx.mk_diagnostic_item(rcvr_ty, sym::Arc), "Arc::new"),
1127                     (self.tcx.mk_diagnostic_item(rcvr_ty, sym::Rc), "Rc::new"),
1128                 ] {
1129                     if let Some(new_rcvr_t) = *rcvr_ty {
1130                         if let Ok(pick) = self.lookup_probe(
1131                             span,
1132                             item_name,
1133                             new_rcvr_t,
1134                             rcvr,
1135                             crate::check::method::probe::ProbeScope::AllTraits,
1136                         ) {
1137                             debug!("try_alt_rcvr: pick candidate {:?}", pick);
1138                             let did = Some(pick.item.container.id());
1139                             // We don't want to suggest a container type when the missing
1140                             // method is `.clone()` or `.deref()` otherwise we'd suggest
1141                             // `Arc::new(foo).clone()`, which is far from what the user wants.
1142                             let skip = skippable.contains(&did);
1143                             // Make sure the method is defined for the *actual* receiver: we don't
1144                             // want to treat `Box<Self>` as a receiver if it only works because of
1145                             // an autoderef to `&self`
1146                             if pick.autoderefs == 0 && !skip {
1147                                 err.span_label(
1148                                     pick.item.ident.span,
1149                                     &format!("the method is available for `{}` here", new_rcvr_t),
1150                                 );
1151                                 err.multipart_suggestion(
1152                                     "consider wrapping the receiver expression with the \
1153                                         appropriate type",
1154                                     vec![
1155                                         (rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)),
1156                                         (rcvr.span.shrink_to_hi(), ")".to_string()),
1157                                     ],
1158                                     Applicability::MaybeIncorrect,
1159                                 );
1160                                 // We don't care about the other suggestions.
1161                                 alt_rcvr_sugg = true;
1162                             }
1163                         }
1164                     }
1165                 }
1166             }
1167         }
1168         if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
1169             return;
1170         }
1171
1172         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
1173
1174         let mut arbitrary_rcvr = vec![];
1175         // There are no traits implemented, so lets suggest some traits to
1176         // implement, by finding ones that have the item name, and are
1177         // legal to implement.
1178         let mut candidates = all_traits(self.tcx)
1179             .into_iter()
1180             // Don't issue suggestions for unstable traits since they're
1181             // unlikely to be implementable anyway
1182             .filter(|info| match self.tcx.lookup_stability(info.def_id) {
1183                 Some(attr) => attr.level.is_stable(),
1184                 None => true,
1185             })
1186             .filter(|info| {
1187                 // We approximate the coherence rules to only suggest
1188                 // traits that are legal to implement by requiring that
1189                 // either the type or trait is local. Multi-dispatch means
1190                 // this isn't perfect (that is, there are cases when
1191                 // implementing a trait would be legal but is rejected
1192                 // here).
1193                 unsatisfied_predicates.iter().all(|(p, _)| {
1194                     match p.kind().skip_binder() {
1195                         // Hide traits if they are present in predicates as they can be fixed without
1196                         // having to implement them.
1197                         ty::PredicateKind::Trait(t, _) => t.def_id() == info.def_id,
1198                         ty::PredicateKind::Projection(p) => {
1199                             p.projection_ty.item_def_id == info.def_id
1200                         }
1201                         _ => false,
1202                     }
1203                 }) && (type_is_local || info.def_id.is_local())
1204                     && self
1205                         .associated_item(info.def_id, item_name, Namespace::ValueNS)
1206                         .filter(|item| {
1207                             if let ty::AssocKind::Fn = item.kind {
1208                                 let id = item
1209                                     .def_id
1210                                     .as_local()
1211                                     .map(|def_id| self.tcx.hir().local_def_id_to_hir_id(def_id));
1212                                 if let Some(hir::Node::TraitItem(hir::TraitItem {
1213                                     kind: hir::TraitItemKind::Fn(fn_sig, method),
1214                                     ..
1215                                 })) = id.map(|id| self.tcx.hir().get(id))
1216                                 {
1217                                     let self_first_arg = match method {
1218                                         hir::TraitFn::Required([ident, ..]) => {
1219                                             ident.name == kw::SelfLower
1220                                         }
1221                                         hir::TraitFn::Provided(body_id) => {
1222                                             self.tcx.hir().body(*body_id).params.first().map_or(
1223                                                 false,
1224                                                 |param| {
1225                                                     matches!(
1226                                                         param.pat.kind,
1227                                                         hir::PatKind::Binding(_, _, ident, _)
1228                                                             if ident.name == kw::SelfLower
1229                                                     )
1230                                                 },
1231                                             )
1232                                         }
1233                                         _ => false,
1234                                     };
1235
1236                                     if !fn_sig.decl.implicit_self.has_implicit_self()
1237                                         && self_first_arg
1238                                     {
1239                                         if let Some(ty) = fn_sig.decl.inputs.get(0) {
1240                                             arbitrary_rcvr.push(ty.span);
1241                                         }
1242                                         return false;
1243                                     }
1244                                 }
1245                             }
1246                             // We only want to suggest public or local traits (#45781).
1247                             item.vis == ty::Visibility::Public || info.def_id.is_local()
1248                         })
1249                         .is_some()
1250             })
1251             .collect::<Vec<_>>();
1252         for span in &arbitrary_rcvr {
1253             err.span_label(
1254                 *span,
1255                 "the method might not be found because of this arbitrary self type",
1256             );
1257         }
1258         if alt_rcvr_sugg {
1259             return;
1260         }
1261
1262         if !candidates.is_empty() {
1263             // Sort from most relevant to least relevant.
1264             candidates.sort_by(|a, b| a.cmp(b).reverse());
1265             candidates.dedup();
1266
1267             let param_type = match rcvr_ty.kind() {
1268                 ty::Param(param) => Some(param),
1269                 ty::Ref(_, ty, _) => match ty.kind() {
1270                     ty::Param(param) => Some(param),
1271                     _ => None,
1272                 },
1273                 _ => None,
1274             };
1275             err.help(if param_type.is_some() {
1276                 "items from traits can only be used if the type parameter is bounded by the trait"
1277             } else {
1278                 "items from traits can only be used if the trait is implemented and in scope"
1279             });
1280             let candidates_len = candidates.len();
1281             let message = |action| {
1282                 format!(
1283                     "the following {traits_define} an item `{name}`, perhaps you need to {action} \
1284                      {one_of_them}:",
1285                     traits_define =
1286                         if candidates_len == 1 { "trait defines" } else { "traits define" },
1287                     action = action,
1288                     one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
1289                     name = item_name,
1290                 )
1291             };
1292             // Obtain the span for `param` and use it for a structured suggestion.
1293             if let (Some(ref param), Some(ref table)) =
1294                 (param_type, self.in_progress_typeck_results)
1295             {
1296                 let table_owner = table.borrow().hir_owner;
1297                 let generics = self.tcx.generics_of(table_owner.to_def_id());
1298                 let type_param = generics.type_param(param, self.tcx);
1299                 let hir = &self.tcx.hir();
1300                 if let Some(def_id) = type_param.def_id.as_local() {
1301                     let id = hir.local_def_id_to_hir_id(def_id);
1302                     // Get the `hir::Param` to verify whether it already has any bounds.
1303                     // We do this to avoid suggesting code that ends up as `T: FooBar`,
1304                     // instead we suggest `T: Foo + Bar` in that case.
1305                     match hir.get(id) {
1306                         Node::GenericParam(ref param) => {
1307                             let mut impl_trait = false;
1308                             let has_bounds =
1309                                 if let hir::GenericParamKind::Type { synthetic: Some(_), .. } =
1310                                     &param.kind
1311                                 {
1312                                     // We've found `fn foo(x: impl Trait)` instead of
1313                                     // `fn foo<T>(x: T)`. We want to suggest the correct
1314                                     // `fn foo(x: impl Trait + TraitBound)` instead of
1315                                     // `fn foo<T: TraitBound>(x: T)`. (#63706)
1316                                     impl_trait = true;
1317                                     param.bounds.get(1)
1318                                 } else {
1319                                     param.bounds.get(0)
1320                                 };
1321                             let sp = hir.span(id);
1322                             let sp = if let Some(first_bound) = has_bounds {
1323                                 // `sp` only covers `T`, change it so that it covers
1324                                 // `T:` when appropriate
1325                                 sp.until(first_bound.span())
1326                             } else {
1327                                 sp
1328                             };
1329                             let trait_def_ids: FxHashSet<DefId> = param
1330                                 .bounds
1331                                 .iter()
1332                                 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
1333                                 .collect();
1334                             if !candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
1335                                 err.span_suggestions(
1336                                     sp,
1337                                     &message(format!(
1338                                         "restrict type parameter `{}` with",
1339                                         param.name.ident(),
1340                                     )),
1341                                     candidates.iter().map(|t| {
1342                                         format!(
1343                                             "{}{} {}{}",
1344                                             param.name.ident(),
1345                                             if impl_trait { " +" } else { ":" },
1346                                             self.tcx.def_path_str(t.def_id),
1347                                             if has_bounds.is_some() { " + " } else { "" },
1348                                         )
1349                                     }),
1350                                     Applicability::MaybeIncorrect,
1351                                 );
1352                             }
1353                             return;
1354                         }
1355                         Node::Item(hir::Item {
1356                             kind: hir::ItemKind::Trait(.., bounds, _),
1357                             ident,
1358                             ..
1359                         }) => {
1360                             let (sp, sep, article) = if bounds.is_empty() {
1361                                 (ident.span.shrink_to_hi(), ":", "a")
1362                             } else {
1363                                 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
1364                             };
1365                             err.span_suggestions(
1366                                 sp,
1367                                 &message(format!("add {} supertrait for", article)),
1368                                 candidates.iter().map(|t| {
1369                                     format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
1370                                 }),
1371                                 Applicability::MaybeIncorrect,
1372                             );
1373                             return;
1374                         }
1375                         _ => {}
1376                     }
1377                 }
1378             }
1379
1380             let (potential_candidates, explicitly_negative) = if param_type.is_some() {
1381                 // FIXME: Even though negative bounds are not implemented, we could maybe handle
1382                 // cases where a positive bound implies a negative impl.
1383                 (candidates, Vec::new())
1384             } else if let Some(simp_rcvr_ty) = simplify_type(self.tcx, rcvr_ty, true) {
1385                 let mut potential_candidates = Vec::new();
1386                 let mut explicitly_negative = Vec::new();
1387                 for candidate in candidates {
1388                     // Check if there's a negative impl of `candidate` for `rcvr_ty`
1389                     if self
1390                         .tcx
1391                         .all_impls(candidate.def_id)
1392                         .filter(|imp_did| {
1393                             self.tcx.impl_polarity(*imp_did) == ty::ImplPolarity::Negative
1394                         })
1395                         .any(|imp_did| {
1396                             let imp = self.tcx.impl_trait_ref(imp_did).unwrap();
1397                             let imp_simp = simplify_type(self.tcx, imp.self_ty(), true);
1398                             imp_simp.map_or(false, |s| s == simp_rcvr_ty)
1399                         })
1400                     {
1401                         explicitly_negative.push(candidate);
1402                     } else {
1403                         potential_candidates.push(candidate);
1404                     }
1405                 }
1406                 (potential_candidates, explicitly_negative)
1407             } else {
1408                 // We don't know enough about `recv_ty` to make proper suggestions.
1409                 (candidates, Vec::new())
1410             };
1411
1412             let action = if let Some(param) = param_type {
1413                 format!("restrict type parameter `{}` with", param)
1414             } else {
1415                 // FIXME: it might only need to be imported into scope, not implemented.
1416                 "implement".to_string()
1417             };
1418             match &potential_candidates[..] {
1419                 [] => {}
1420                 [trait_info] if trait_info.def_id.is_local() => {
1421                     let span = self.tcx.hir().span_if_local(trait_info.def_id).unwrap();
1422                     err.span_note(
1423                         self.tcx.sess.source_map().guess_head_span(span),
1424                         &format!(
1425                             "`{}` defines an item `{}`, perhaps you need to {} it",
1426                             self.tcx.def_path_str(trait_info.def_id),
1427                             item_name,
1428                             action
1429                         ),
1430                     );
1431                 }
1432                 trait_infos => {
1433                     let mut msg = message(action);
1434                     for (i, trait_info) in trait_infos.iter().enumerate() {
1435                         msg.push_str(&format!(
1436                             "\ncandidate #{}: `{}`",
1437                             i + 1,
1438                             self.tcx.def_path_str(trait_info.def_id),
1439                         ));
1440                     }
1441                     err.note(&msg);
1442                 }
1443             }
1444             match &explicitly_negative[..] {
1445                 [] => {}
1446                 [trait_info] => {
1447                     let msg = format!(
1448                         "the trait `{}` defines an item `{}`, but is explicitely unimplemented",
1449                         self.tcx.def_path_str(trait_info.def_id),
1450                         item_name
1451                     );
1452                     err.note(&msg);
1453                 }
1454                 trait_infos => {
1455                     let mut msg = format!(
1456                         "the following traits define an item `{}`, but are explicitely unimplemented:",
1457                         item_name
1458                     );
1459                     for trait_info in trait_infos {
1460                         msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
1461                     }
1462                     err.note(&msg);
1463                 }
1464             }
1465         }
1466     }
1467
1468     /// Checks whether there is a local type somewhere in the chain of
1469     /// autoderefs of `rcvr_ty`.
1470     fn type_derefs_to_local(
1471         &self,
1472         span: Span,
1473         rcvr_ty: Ty<'tcx>,
1474         source: SelfSource<'tcx>,
1475     ) -> bool {
1476         fn is_local(ty: Ty<'_>) -> bool {
1477             match ty.kind() {
1478                 ty::Adt(def, _) => def.did.is_local(),
1479                 ty::Foreign(did) => did.is_local(),
1480                 ty::Dynamic(ref tr, ..) => tr.principal().map_or(false, |d| d.def_id().is_local()),
1481                 ty::Param(_) => true,
1482
1483                 // Everything else (primitive types, etc.) is effectively
1484                 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
1485                 // the noise from these sort of types is usually just really
1486                 // annoying, rather than any sort of help).
1487                 _ => false,
1488             }
1489         }
1490
1491         // This occurs for UFCS desugaring of `T::method`, where there is no
1492         // receiver expression for the method call, and thus no autoderef.
1493         if let SelfSource::QPath(_) = source {
1494             return is_local(self.resolve_vars_with_obligations(rcvr_ty));
1495         }
1496
1497         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
1498     }
1499 }
1500
1501 #[derive(Copy, Clone, Debug)]
1502 pub enum SelfSource<'a> {
1503     QPath(&'a hir::Ty<'a>),
1504     MethodCall(&'a hir::Expr<'a> /* rcvr */),
1505 }
1506
1507 #[derive(Copy, Clone)]
1508 pub struct TraitInfo {
1509     pub def_id: DefId,
1510 }
1511
1512 impl PartialEq for TraitInfo {
1513     fn eq(&self, other: &TraitInfo) -> bool {
1514         self.cmp(other) == Ordering::Equal
1515     }
1516 }
1517 impl Eq for TraitInfo {}
1518 impl PartialOrd for TraitInfo {
1519     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
1520         Some(self.cmp(other))
1521     }
1522 }
1523 impl Ord for TraitInfo {
1524     fn cmp(&self, other: &TraitInfo) -> Ordering {
1525         // Local crates are more important than remote ones (local:
1526         // `cnum == 0`), and otherwise we throw in the defid for totality.
1527
1528         let lhs = (other.def_id.krate, other.def_id);
1529         let rhs = (self.def_id.krate, self.def_id);
1530         lhs.cmp(&rhs)
1531     }
1532 }
1533
1534 /// Retrieves all traits in this crate and any dependent crates.
1535 pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
1536     tcx.all_traits(()).iter().map(|&def_id| TraitInfo { def_id }).collect()
1537 }
1538
1539 /// Computes all traits in this crate and any dependent crates.
1540 fn compute_all_traits(tcx: TyCtxt<'_>, (): ()) -> &[DefId] {
1541     use hir::itemlikevisit;
1542
1543     let mut traits = vec![];
1544
1545     // Crate-local:
1546
1547     struct Visitor<'a> {
1548         traits: &'a mut Vec<DefId>,
1549     }
1550
1551     impl<'v, 'a> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a> {
1552         fn visit_item(&mut self, i: &'v hir::Item<'v>) {
1553             match i.kind {
1554                 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1555                     self.traits.push(i.def_id.to_def_id());
1556                 }
1557                 _ => (),
1558             }
1559         }
1560
1561         fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
1562
1563         fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
1564
1565         fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
1566     }
1567
1568     tcx.hir().krate().visit_all_item_likes(&mut Visitor { traits: &mut traits });
1569
1570     // Cross-crate:
1571
1572     let mut external_mods = FxHashSet::default();
1573     fn handle_external_res(
1574         tcx: TyCtxt<'_>,
1575         traits: &mut Vec<DefId>,
1576         external_mods: &mut FxHashSet<DefId>,
1577         res: Res,
1578     ) {
1579         match res {
1580             Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) => {
1581                 traits.push(def_id);
1582             }
1583             Res::Def(DefKind::Mod, def_id) => {
1584                 if !external_mods.insert(def_id) {
1585                     return;
1586                 }
1587                 for child in tcx.item_children(def_id).iter() {
1588                     handle_external_res(tcx, traits, external_mods, child.res)
1589                 }
1590             }
1591             _ => {}
1592         }
1593     }
1594     for &cnum in tcx.crates().iter() {
1595         let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1596         handle_external_res(tcx, &mut traits, &mut external_mods, Res::Def(DefKind::Mod, def_id));
1597     }
1598
1599     tcx.arena.alloc_from_iter(traits)
1600 }
1601
1602 pub fn provide(providers: &mut ty::query::Providers) {
1603     providers.all_traits = compute_all_traits;
1604 }
1605
1606 struct UsePlacementFinder<'tcx> {
1607     target_module: hir::HirId,
1608     span: Option<Span>,
1609     found_use: bool,
1610     tcx: TyCtxt<'tcx>,
1611 }
1612
1613 impl UsePlacementFinder<'tcx> {
1614     fn check(
1615         tcx: TyCtxt<'tcx>,
1616         krate: &'tcx hir::Crate<'tcx>,
1617         target_module: hir::HirId,
1618     ) -> (Option<Span>, bool) {
1619         let mut finder = UsePlacementFinder { target_module, span: None, found_use: false, tcx };
1620         intravisit::walk_crate(&mut finder, krate);
1621         (finder.span, finder.found_use)
1622     }
1623 }
1624
1625 impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> {
1626     fn visit_mod(&mut self, module: &'tcx hir::Mod<'tcx>, _: Span, hir_id: hir::HirId) {
1627         if self.span.is_some() {
1628             return;
1629         }
1630         if hir_id != self.target_module {
1631             intravisit::walk_mod(self, module, hir_id);
1632             return;
1633         }
1634         // Find a `use` statement.
1635         for &item_id in module.item_ids {
1636             let item = self.tcx.hir().item(item_id);
1637             match item.kind {
1638                 hir::ItemKind::Use(..) => {
1639                     // Don't suggest placing a `use` before the prelude
1640                     // import or other generated ones.
1641                     if !item.span.from_expansion() {
1642                         self.span = Some(item.span.shrink_to_lo());
1643                         self.found_use = true;
1644                         return;
1645                     }
1646                 }
1647                 // Don't place `use` before `extern crate`...
1648                 hir::ItemKind::ExternCrate(_) => {}
1649                 // ...but do place them before the first other item.
1650                 _ => {
1651                     if self.span.map_or(true, |span| item.span < span) {
1652                         if !item.span.from_expansion() {
1653                             // Don't insert between attributes and an item.
1654                             let attrs = self.tcx.hir().attrs(item.hir_id());
1655                             if attrs.is_empty() {
1656                                 self.span = Some(item.span.shrink_to_lo());
1657                             } else {
1658                                 // Find the first attribute on the item.
1659                                 for attr in attrs {
1660                                     if self.span.map_or(true, |span| attr.span < span) {
1661                                         self.span = Some(attr.span.shrink_to_lo());
1662                                     }
1663                                 }
1664                             }
1665                         }
1666                     }
1667                 }
1668             }
1669         }
1670     }
1671
1672     type Map = intravisit::ErasedMap<'tcx>;
1673
1674     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1675         intravisit::NestedVisitorMap::None
1676     }
1677 }
1678
1679 fn print_disambiguation_help(
1680     item_name: Ident,
1681     args: Option<&'tcx [hir::Expr<'tcx>]>,
1682     err: &mut DiagnosticBuilder<'_>,
1683     trait_name: String,
1684     rcvr_ty: Ty<'_>,
1685     kind: ty::AssocKind,
1686     def_id: DefId,
1687     span: Span,
1688     candidate: Option<usize>,
1689     source_map: &source_map::SourceMap,
1690 ) {
1691     let mut applicability = Applicability::MachineApplicable;
1692     let sugg_args = if let (ty::AssocKind::Fn, Some(args)) = (kind, args) {
1693         format!(
1694             "({}{})",
1695             if rcvr_ty.is_region_ptr() {
1696                 if rcvr_ty.is_mutable_ptr() { "&mut " } else { "&" }
1697             } else {
1698                 ""
1699             },
1700             args.iter()
1701                 .map(|arg| source_map.span_to_snippet(arg.span).unwrap_or_else(|_| {
1702                     applicability = Applicability::HasPlaceholders;
1703                     "_".to_owned()
1704                 }))
1705                 .collect::<Vec<_>>()
1706                 .join(", "),
1707         )
1708     } else {
1709         String::new()
1710     };
1711     let sugg = format!("{}::{}{}", trait_name, item_name, sugg_args);
1712     err.span_suggestion(
1713         span,
1714         &format!(
1715             "disambiguate the {} for {}",
1716             kind.as_def_kind().descr(def_id),
1717             if let Some(candidate) = candidate {
1718                 format!("candidate #{}", candidate)
1719             } else {
1720                 "the candidate".to_string()
1721             },
1722         ),
1723         sugg,
1724         applicability,
1725     );
1726 }