]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/suggest.rs
Suggest constraining type parameters
[rust.git] / src / librustc_typeck / 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 crate::middle::lang_items::FnOnceTraitLangItem;
6 use rustc::hir::map as hir_map;
7 use rustc::hir::map::Map;
8 use rustc::ty::print::with_crate_prefix;
9 use rustc::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
12 use rustc_hir as hir;
13 use rustc_hir::def::{DefKind, Namespace, Res};
14 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
15 use rustc_hir::intravisit;
16 use rustc_hir::{ExprKind, Node, QPath};
17 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
18 use rustc_infer::traits::Obligation;
19 use rustc_span::{source_map, FileName, Span};
20 use syntax::ast;
21 use syntax::util::lev_distance;
22
23 use std::cmp::Ordering;
24
25 use super::probe::Mode;
26 use super::{CandidateSource, MethodError, NoMatchData};
27
28 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
29     fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
30         let tcx = self.tcx;
31         match ty.kind {
32             // Not all of these (e.g., unsafe fns) implement `FnOnce`,
33             // so we look for these beforehand.
34             ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true,
35             // If it's not a simple function, look for things which implement `FnOnce`.
36             _ => {
37                 let fn_once = match tcx.lang_items().require(FnOnceTraitLangItem) {
38                     Ok(fn_once) => fn_once,
39                     Err(..) => return false,
40                 };
41
42                 self.autoderef(span, ty).any(|(ty, _)| {
43                     self.probe(|_| {
44                         let fn_once_substs = tcx.mk_substs_trait(
45                             ty,
46                             &[self
47                                 .next_ty_var(TypeVariableOrigin {
48                                     kind: TypeVariableOriginKind::MiscVariable,
49                                     span,
50                                 })
51                                 .into()],
52                         );
53                         let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
54                         let poly_trait_ref = trait_ref.to_poly_trait_ref();
55                         let obligation = Obligation::misc(
56                             span,
57                             self.body_id,
58                             self.param_env,
59                             poly_trait_ref.without_const().to_predicate(),
60                         );
61                         self.predicate_may_hold(&obligation)
62                     })
63                 })
64             }
65         }
66     }
67
68     pub fn report_method_error<'b>(
69         &self,
70         span: Span,
71         rcvr_ty: Ty<'tcx>,
72         item_name: ast::Ident,
73         source: SelfSource<'b>,
74         error: MethodError<'tcx>,
75         args: Option<&'tcx [hir::Expr<'tcx>]>,
76     ) -> Option<DiagnosticBuilder<'_>> {
77         let orig_span = span;
78         let mut span = span;
79         // Avoid suggestions when we don't know what's going on.
80         if rcvr_ty.references_error() {
81             return None;
82         }
83
84         let report_candidates = |span: Span,
85                                  err: &mut DiagnosticBuilder<'_>,
86                                  mut sources: Vec<CandidateSource>,
87                                  sugg_span: Span| {
88             sources.sort();
89             sources.dedup();
90             // Dynamic limit to avoid hiding just one candidate, which is silly.
91             let limit = if sources.len() == 5 { 5 } else { 4 };
92
93             for (idx, source) in sources.iter().take(limit).enumerate() {
94                 match *source {
95                     CandidateSource::ImplSource(impl_did) => {
96                         // Provide the best span we can. Use the item, if local to crate, else
97                         // the impl, if local to crate (item may be defaulted), else nothing.
98                         let item = match self
99                             .associated_item(impl_did, item_name, Namespace::ValueNS)
100                             .or_else(|| {
101                                 let impl_trait_ref = self.tcx.impl_trait_ref(impl_did)?;
102                                 self.associated_item(
103                                     impl_trait_ref.def_id,
104                                     item_name,
105                                     Namespace::ValueNS,
106                                 )
107                             }) {
108                             Some(item) => item,
109                             None => continue,
110                         };
111                         let note_span = self
112                             .tcx
113                             .hir()
114                             .span_if_local(item.def_id)
115                             .or_else(|| self.tcx.hir().span_if_local(impl_did));
116
117                         let impl_ty = self.impl_self_ty(span, impl_did).ty;
118
119                         let insertion = match self.tcx.impl_trait_ref(impl_did) {
120                             None => String::new(),
121                             Some(trait_ref) => format!(
122                                 " of the trait `{}`",
123                                 self.tcx.def_path_str(trait_ref.def_id)
124                             ),
125                         };
126
127                         let (note_str, idx) = if sources.len() > 1 {
128                             (
129                                 format!(
130                                     "candidate #{} is defined in an impl{} for the type `{}`",
131                                     idx + 1,
132                                     insertion,
133                                     impl_ty,
134                                 ),
135                                 Some(idx + 1),
136                             )
137                         } else {
138                             (
139                                 format!(
140                                     "the candidate is defined in an impl{} for the type `{}`",
141                                     insertion, impl_ty,
142                                 ),
143                                 None,
144                             )
145                         };
146                         if let Some(note_span) = note_span {
147                             // We have a span pointing to the method. Show note with snippet.
148                             err.span_note(
149                                 self.tcx.sess.source_map().def_span(note_span),
150                                 &note_str,
151                             );
152                         } else {
153                             err.note(&note_str);
154                         }
155                         if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did) {
156                             let path = self.tcx.def_path_str(trait_ref.def_id);
157
158                             let ty = match item.kind {
159                                 ty::AssocKind::Const
160                                 | ty::AssocKind::Type
161                                 | ty::AssocKind::OpaqueTy => rcvr_ty,
162                                 ty::AssocKind::Method => self
163                                     .tcx
164                                     .fn_sig(item.def_id)
165                                     .inputs()
166                                     .skip_binder()
167                                     .get(0)
168                                     .filter(|ty| ty.is_region_ptr() && !rcvr_ty.is_region_ptr())
169                                     .map(|ty| *ty)
170                                     .unwrap_or(rcvr_ty),
171                             };
172                             print_disambiguation_help(
173                                 item_name,
174                                 args,
175                                 err,
176                                 path,
177                                 ty,
178                                 item.kind,
179                                 sugg_span,
180                                 idx,
181                                 self.tcx.sess.source_map(),
182                             );
183                         }
184                     }
185                     CandidateSource::TraitSource(trait_did) => {
186                         let item =
187                             match self.associated_item(trait_did, item_name, Namespace::ValueNS) {
188                                 Some(item) => item,
189                                 None => continue,
190                             };
191                         let item_span =
192                             self.tcx.sess.source_map().def_span(self.tcx.def_span(item.def_id));
193                         let idx = if sources.len() > 1 {
194                             let msg = &format!(
195                                 "candidate #{} is defined in the trait `{}`",
196                                 idx + 1,
197                                 self.tcx.def_path_str(trait_did)
198                             );
199                             err.span_note(item_span, msg);
200                             Some(idx + 1)
201                         } else {
202                             let msg = &format!(
203                                 "the candidate is defined in the trait `{}`",
204                                 self.tcx.def_path_str(trait_did)
205                             );
206                             err.span_note(item_span, msg);
207                             None
208                         };
209                         let path = self.tcx.def_path_str(trait_did);
210                         print_disambiguation_help(
211                             item_name,
212                             args,
213                             err,
214                             path,
215                             rcvr_ty,
216                             item.kind,
217                             sugg_span,
218                             idx,
219                             self.tcx.sess.source_map(),
220                         );
221                     }
222                 }
223             }
224             if sources.len() > limit {
225                 err.note(&format!("and {} others", sources.len() - limit));
226             }
227         };
228
229         let sugg_span = if let SelfSource::MethodCall(expr) = source {
230             // Given `foo.bar(baz)`, `expr` is `bar`, but we want to point to the whole thing.
231             self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)).span
232         } else {
233             span
234         };
235
236         match error {
237             MethodError::NoMatch(NoMatchData {
238                 static_candidates: static_sources,
239                 unsatisfied_predicates,
240                 out_of_scope_traits,
241                 lev_candidate,
242                 mode,
243             }) => {
244                 let tcx = self.tcx;
245
246                 let actual = self.resolve_vars_if_possible(&rcvr_ty);
247                 let ty_str = self.ty_to_string(actual);
248                 let is_method = mode == Mode::MethodCall;
249                 let item_kind = if is_method {
250                     "method"
251                 } else if actual.is_enum() {
252                     "variant or associated item"
253                 } else {
254                     match (item_name.as_str().chars().next(), actual.is_fresh_ty()) {
255                         (Some(name), false) if name.is_lowercase() => "function or associated item",
256                         (Some(_), false) => "associated item",
257                         (Some(_), true) | (None, false) => "variant or associated item",
258                         (None, true) => "variant",
259                     }
260                 };
261                 let mut err = if !actual.references_error() {
262                     // Suggest clamping down the type if the method that is being attempted to
263                     // be used exists at all, and the type is an ambiguous numeric type
264                     // ({integer}/{float}).
265                     let mut candidates = all_traits(self.tcx).into_iter().filter_map(|info| {
266                         self.associated_item(info.def_id, item_name, Namespace::ValueNS)
267                     });
268                     if let (true, false, SelfSource::MethodCall(expr), Some(_)) = (
269                         actual.is_numeric(),
270                         actual.has_concrete_skeleton(),
271                         source,
272                         candidates.next(),
273                     ) {
274                         let mut err = struct_span_err!(
275                             tcx.sess,
276                             span,
277                             E0689,
278                             "can't call {} `{}` on ambiguous numeric type `{}`",
279                             item_kind,
280                             item_name,
281                             ty_str
282                         );
283                         let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
284                         match expr.kind {
285                             ExprKind::Lit(ref lit) => {
286                                 // numeric literal
287                                 let snippet = tcx
288                                     .sess
289                                     .source_map()
290                                     .span_to_snippet(lit.span)
291                                     .unwrap_or_else(|_| "<numeric literal>".to_owned());
292
293                                 err.span_suggestion(
294                                     lit.span,
295                                     &format!(
296                                         "you must specify a concrete type for \
297                                               this numeric value, like `{}`",
298                                         concrete_type
299                                     ),
300                                     format!("{}_{}", snippet, concrete_type),
301                                     Applicability::MaybeIncorrect,
302                                 );
303                             }
304                             ExprKind::Path(ref qpath) => {
305                                 // local binding
306                                 if let &QPath::Resolved(_, ref path) = &qpath {
307                                     if let hir::def::Res::Local(hir_id) = path.res {
308                                         let span = tcx.hir().span(hir_id);
309                                         let snippet = tcx.sess.source_map().span_to_snippet(span);
310                                         let filename = tcx.sess.source_map().span_to_filename(span);
311
312                                         let parent_node = self
313                                             .tcx
314                                             .hir()
315                                             .get(self.tcx.hir().get_parent_node(hir_id));
316                                         let msg = format!(
317                                             "you must specify a type for this binding, like `{}`",
318                                             concrete_type,
319                                         );
320
321                                         match (filename, parent_node, snippet) {
322                                             (
323                                                 FileName::Real(_),
324                                                 Node::Local(hir::Local {
325                                                     source: hir::LocalSource::Normal,
326                                                     ty,
327                                                     ..
328                                                 }),
329                                                 Ok(ref snippet),
330                                             ) => {
331                                                 err.span_suggestion(
332                                                     // account for `let x: _ = 42;`
333                                                     //                  ^^^^
334                                                     span.to(ty
335                                                         .as_ref()
336                                                         .map(|ty| ty.span)
337                                                         .unwrap_or(span)),
338                                                     &msg,
339                                                     format!("{}: {}", snippet, concrete_type),
340                                                     Applicability::MaybeIncorrect,
341                                                 );
342                                             }
343                                             _ => {
344                                                 err.span_label(span, msg);
345                                             }
346                                         }
347                                     }
348                                 }
349                             }
350                             _ => {}
351                         }
352                         err.emit();
353                         return None;
354                     } else {
355                         span = item_name.span;
356                         let mut err = struct_span_err!(
357                             tcx.sess,
358                             span,
359                             E0599,
360                             "no {} named `{}` found for {} `{}` in the current scope",
361                             item_kind,
362                             item_name,
363                             actual.prefix_string(),
364                             ty_str,
365                         );
366                         if let Some(span) =
367                             tcx.sess.confused_type_with_std_module.borrow().get(&span)
368                         {
369                             if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*span) {
370                                 err.span_suggestion(
371                                     *span,
372                                     "you are looking for the module in `std`, \
373                                      not the primitive type",
374                                     format!("std::{}", snippet),
375                                     Applicability::MachineApplicable,
376                                 );
377                             }
378                         }
379                         if let ty::RawPtr(_) = &actual.kind {
380                             err.note(
381                                 "try using `<*const T>::as_ref()` to get a reference to the \
382                                       type behind the pointer: https://doc.rust-lang.org/std/\
383                                       primitive.pointer.html#method.as_ref",
384                             );
385                             err.note(
386                                 "using `<*const T>::as_ref()` on a pointer \
387                                       which is unaligned or points to invalid \
388                                       or uninitialized memory is undefined behavior",
389                             );
390                         }
391                         err
392                     }
393                 } else {
394                     tcx.sess.diagnostic().struct_dummy()
395                 };
396
397                 if let Some(def) = actual.ty_adt_def() {
398                     if let Some(full_sp) = tcx.hir().span_if_local(def.did) {
399                         let def_sp = tcx.sess.source_map().def_span(full_sp);
400                         err.span_label(
401                             def_sp,
402                             format!(
403                                 "{} `{}` not found {}",
404                                 item_kind,
405                                 item_name,
406                                 if def.is_enum() && !is_method { "here" } else { "for this" }
407                             ),
408                         );
409                     }
410                 }
411
412                 // If the method name is the name of a field with a function or closure type,
413                 // give a helping note that it has to be called as `(x.f)(...)`.
414                 if let SelfSource::MethodCall(expr) = source {
415                     let field_receiver =
416                         self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind {
417                             ty::Adt(def, substs) if !def.is_enum() => {
418                                 let variant = &def.non_enum_variant();
419                                 self.tcx.find_field_index(item_name, variant).map(|index| {
420                                     let field = &variant.fields[index];
421                                     let field_ty = field.ty(tcx, substs);
422                                     (field, field_ty)
423                                 })
424                             }
425                             _ => None,
426                         });
427
428                     if let Some((field, field_ty)) = field_receiver {
429                         let scope = self.tcx.hir().get_module_parent(self.body_id);
430                         let is_accessible = field.vis.is_accessible_from(scope, self.tcx);
431
432                         if is_accessible {
433                             if self.is_fn_ty(&field_ty, span) {
434                                 let expr_span = expr.span.to(item_name.span);
435                                 err.multipart_suggestion(
436                                     &format!(
437                                         "to call the function stored in `{}`, \
438                                          surround the field access with parentheses",
439                                         item_name,
440                                     ),
441                                     vec![
442                                         (expr_span.shrink_to_lo(), '('.to_string()),
443                                         (expr_span.shrink_to_hi(), ')'.to_string()),
444                                     ],
445                                     Applicability::MachineApplicable,
446                                 );
447                             } else {
448                                 let call_expr = self
449                                     .tcx
450                                     .hir()
451                                     .expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
452
453                                 if let Some(span) = call_expr.span.trim_start(item_name.span) {
454                                     err.span_suggestion(
455                                         span,
456                                         "remove the arguments",
457                                         String::new(),
458                                         Applicability::MaybeIncorrect,
459                                     );
460                                 }
461                             }
462                         }
463
464                         let field_kind = if is_accessible { "field" } else { "private field" };
465                         err.span_label(item_name.span, format!("{}, not a method", field_kind));
466                     } else if lev_candidate.is_none() && static_sources.is_empty() {
467                         err.span_label(span, format!("{} not found in `{}`", item_kind, ty_str));
468                         self.tcx.sess.trait_methods_not_found.borrow_mut().insert(orig_span);
469                     }
470                 } else {
471                     err.span_label(span, format!("{} not found in `{}`", item_kind, ty_str));
472                     self.tcx.sess.trait_methods_not_found.borrow_mut().insert(orig_span);
473                 }
474
475                 if self.is_fn_ty(&rcvr_ty, span) {
476                     macro_rules! report_function {
477                         ($span:expr, $name:expr) => {
478                             err.note(&format!(
479                                 "`{}` is a function, perhaps you wish to call it",
480                                 $name
481                             ));
482                         };
483                     }
484
485                     if let SelfSource::MethodCall(expr) = source {
486                         if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr.span) {
487                             report_function!(expr.span, expr_string);
488                         } else if let ExprKind::Path(QPath::Resolved(_, ref path)) = expr.kind {
489                             if let Some(segment) = path.segments.last() {
490                                 report_function!(expr.span, segment.ident);
491                             }
492                         }
493                     }
494                 }
495
496                 if !static_sources.is_empty() {
497                     err.note(
498                         "found the following associated functions; to be used as methods, \
499                               functions must have a `self` parameter",
500                     );
501                     err.span_label(span, "this is an associated function, not a method");
502                 }
503                 if static_sources.len() == 1 {
504                     let ty_str = if let Some(CandidateSource::ImplSource(impl_did)) =
505                         static_sources.get(0)
506                     {
507                         // When the "method" is resolved through dereferencing, we really want the
508                         // original type that has the associated function for accurate suggestions.
509                         // (#61411)
510                         let ty = self.impl_self_ty(span, *impl_did).ty;
511                         match (&ty.peel_refs().kind, &actual.peel_refs().kind) {
512                             (ty::Adt(def, _), ty::Adt(def_actual, _)) if def == def_actual => {
513                                 // Use `actual` as it will have more `substs` filled in.
514                                 self.ty_to_value_string(actual.peel_refs())
515                             }
516                             _ => self.ty_to_value_string(ty.peel_refs()),
517                         }
518                     } else {
519                         self.ty_to_value_string(actual.peel_refs())
520                     };
521                     if let SelfSource::MethodCall(expr) = source {
522                         err.span_suggestion(
523                             expr.span.to(span),
524                             "use associated function syntax instead",
525                             format!("{}::{}", ty_str, item_name),
526                             Applicability::MachineApplicable,
527                         );
528                     } else {
529                         err.help(&format!("try with `{}::{}`", ty_str, item_name,));
530                     }
531
532                     report_candidates(span, &mut err, static_sources, sugg_span);
533                 } else if static_sources.len() > 1 {
534                     report_candidates(span, &mut err, static_sources, sugg_span);
535                 }
536
537                 if !unsatisfied_predicates.is_empty() {
538                     let def_span =
539                         |def_id| self.tcx.sess.source_map().def_span(self.tcx.def_span(def_id));
540                     let mut type_params = FxHashMap::default();
541                     let mut bound_spans = vec![];
542                     let mut collect_type_param_suggestions =
543                         |self_ty: Ty<'_>, parent_pred: &ty::Predicate<'_>, obligation: &str| {
544                             if let (ty::Param(_), ty::Predicate::Trait(p, _)) =
545                                 (&self_ty.kind, parent_pred)
546                             {
547                                 if let ty::Adt(def, _) = p.skip_binder().trait_ref.self_ty().kind {
548                                     let id = self.tcx.hir().as_local_hir_id(def.did).unwrap();
549                                     let node = self.tcx.hir().get(id);
550                                     match node {
551                                         hir::Node::Item(hir::Item { kind, .. }) => {
552                                             if let Some(g) = kind.generics() {
553                                                 let key = match &g.where_clause.predicates[..] {
554                                                     [.., pred] => {
555                                                         (pred.span().shrink_to_hi(), false)
556                                                     }
557                                                     [] => (
558                                                         g.where_clause
559                                                             .span_for_predicates_or_empty_place(),
560                                                         true,
561                                                     ),
562                                                 };
563                                                 type_params
564                                                     .entry(key)
565                                                     .or_insert_with(FxHashSet::default)
566                                                     .insert(obligation.to_owned());
567                                             }
568                                         }
569                                         _ => {}
570                                     }
571                                 }
572                             }
573                         };
574                     let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
575                         let msg = format!(
576                             "doesn't satisfy `{}`",
577                             if obligation.len() > 50 { quiet } else { obligation }
578                         );
579                         match &self_ty.kind {
580                             // Point at the type that couldn't satisfy the bound.
581                             ty::Adt(def, _) => bound_spans.push((def_span(def.did), msg)),
582                             // Point at the trait object that couldn't satisfy the bound.
583                             ty::Dynamic(preds, _) => {
584                                 for pred in *preds.skip_binder() {
585                                     match pred {
586                                         ty::ExistentialPredicate::Trait(tr) => {
587                                             bound_spans.push((def_span(tr.def_id), msg.clone()))
588                                         }
589                                         ty::ExistentialPredicate::Projection(_)
590                                         | ty::ExistentialPredicate::AutoTrait(_) => {}
591                                     }
592                                 }
593                             }
594                             // Point at the closure that couldn't satisfy the bound.
595                             ty::Closure(def_id, _) => bound_spans
596                                 .push((def_span(*def_id), format!("doesn't satisfy `{}`", quiet))),
597                             _ => {}
598                         }
599                     };
600                     let mut format_pred = |pred| {
601                         match pred {
602                             ty::Predicate::Projection(pred) => {
603                                 // `<Foo as Iterator>::Item = String`.
604                                 let trait_ref =
605                                     pred.skip_binder().projection_ty.trait_ref(self.tcx);
606                                 let assoc = self
607                                     .tcx
608                                     .associated_item(pred.skip_binder().projection_ty.item_def_id);
609                                 let ty = pred.skip_binder().ty;
610                                 let obligation = format!("{}::{} = {}", trait_ref, assoc.ident, ty);
611                                 let quiet = format!(
612                                     "<_ as {}>::{} = {}",
613                                     trait_ref.print_only_trait_path(),
614                                     assoc.ident,
615                                     ty
616                                 );
617                                 bound_span_label(trait_ref.self_ty(), &obligation, &quiet);
618                                 Some((obligation, trait_ref.self_ty()))
619                             }
620                             ty::Predicate::Trait(poly_trait_ref, _) => {
621                                 let p = poly_trait_ref.skip_binder().trait_ref;
622                                 let self_ty = p.self_ty();
623                                 let path = p.print_only_trait_path();
624                                 let obligation = format!("{}: {}", self_ty, path);
625                                 let quiet = format!("_: {}", path);
626                                 bound_span_label(self_ty, &obligation, &quiet);
627                                 Some((obligation, self_ty))
628                             }
629                             _ => None,
630                         }
631                     };
632                     let mut bound_list = unsatisfied_predicates
633                         .iter()
634                         .filter_map(|(pred, parent_pred)| {
635                             format_pred(*pred).map(|(p, self_ty)| match parent_pred {
636                                 None => format!("`{}`", p),
637                                 Some(parent_pred) => match format_pred(*parent_pred) {
638                                     None => format!("`{}`", p),
639                                     Some((parent_p, _)) => {
640                                         collect_type_param_suggestions(self_ty, parent_pred, &p);
641                                         format!("`{}` which is required by `{}`", p, parent_p)
642                                     }
643                                 },
644                             })
645                         })
646                         .collect::<Vec<String>>();
647                     for ((span, empty_where), obligations) in type_params.into_iter() {
648                         err.span_suggestion_verbose(
649                             span,
650                             &format!(
651                                 "consider restricting the type parameter{s} to satisfy the \
652                                  obligation{s}",
653                                 s = pluralize!(obligations.len())
654                             ),
655                             format!(
656                                 "{} {}",
657                                 if empty_where { " where" } else { "," },
658                                 obligations.into_iter().collect::<Vec<_>>().join(", ")
659                             ),
660                             Applicability::MaybeIncorrect,
661                         );
662                     }
663
664                     bound_list.sort();
665                     bound_list.dedup(); // #35677
666                     bound_spans.sort();
667                     bound_spans.dedup();
668                     for (span, msg) in bound_spans.into_iter() {
669                         err.span_label(span, &msg);
670                     }
671                     if !bound_list.is_empty() {
672                         let bound_list = bound_list.join("\n");
673                         err.note(&format!(
674                             "the method `{}` exists but the following trait bounds were not \
675                              satisfied:\n{}",
676                             item_name, bound_list
677                         ));
678                     }
679                 }
680
681                 if actual.is_numeric() && actual.is_fresh() {
682                 } else {
683                     self.suggest_traits_to_import(
684                         &mut err,
685                         span,
686                         rcvr_ty,
687                         item_name,
688                         source,
689                         out_of_scope_traits,
690                     );
691                 }
692
693                 if actual.is_enum() {
694                     let adt_def = actual.ty_adt_def().expect("enum is not an ADT");
695                     if let Some(suggestion) = lev_distance::find_best_match_for_name(
696                         adt_def.variants.iter().map(|s| &s.ident.name),
697                         &item_name.as_str(),
698                         None,
699                     ) {
700                         err.span_suggestion(
701                             span,
702                             "there is a variant with a similar name",
703                             suggestion.to_string(),
704                             Applicability::MaybeIncorrect,
705                         );
706                     }
707                 }
708
709                 let mut fallback_span = true;
710                 let msg = "remove this method call";
711                 if item_name.as_str() == "as_str" && actual.peel_refs().is_str() {
712                     if let SelfSource::MethodCall(expr) = source {
713                         let call_expr =
714                             self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
715                         if let Some(span) = call_expr.span.trim_start(expr.span) {
716                             err.span_suggestion(
717                                 span,
718                                 msg,
719                                 String::new(),
720                                 Applicability::MachineApplicable,
721                             );
722                             fallback_span = false;
723                         }
724                     }
725                     if fallback_span {
726                         err.span_label(span, msg);
727                     }
728                 } else if let Some(lev_candidate) = lev_candidate {
729                     let def_kind = lev_candidate.def_kind();
730                     err.span_suggestion(
731                         span,
732                         &format!(
733                             "there is {} {} with a similar name",
734                             def_kind.article(),
735                             def_kind.descr(lev_candidate.def_id),
736                         ),
737                         lev_candidate.ident.to_string(),
738                         Applicability::MaybeIncorrect,
739                     );
740                 }
741
742                 return Some(err);
743             }
744
745             MethodError::Ambiguity(sources) => {
746                 let mut err = struct_span_err!(
747                     self.sess(),
748                     span,
749                     E0034,
750                     "multiple applicable items in scope"
751                 );
752                 err.span_label(span, format!("multiple `{}` found", item_name));
753
754                 report_candidates(span, &mut err, sources, sugg_span);
755                 err.emit();
756             }
757
758             MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
759                 let mut err = struct_span_err!(
760                     self.tcx.sess,
761                     span,
762                     E0624,
763                     "{} `{}` is private",
764                     kind.descr(def_id),
765                     item_name
766                 );
767                 self.suggest_valid_traits(&mut err, out_of_scope_traits);
768                 err.emit();
769             }
770
771             MethodError::IllegalSizedBound(candidates, needs_mut, bound_span) => {
772                 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
773                 let mut err = self.sess().struct_span_err(span, &msg);
774                 err.span_label(bound_span, "this has a `Sized` requirement");
775                 if !candidates.is_empty() {
776                     let help = format!(
777                         "{an}other candidate{s} {were} found in the following trait{s}, perhaps \
778                          add a `use` for {one_of_them}:",
779                         an = if candidates.len() == 1 { "an" } else { "" },
780                         s = pluralize!(candidates.len()),
781                         were = if candidates.len() == 1 { "was" } else { "were" },
782                         one_of_them = if candidates.len() == 1 { "it" } else { "one_of_them" },
783                     );
784                     self.suggest_use_candidates(&mut err, help, candidates);
785                 }
786                 if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind {
787                     if needs_mut {
788                         let trait_type = self.tcx.mk_ref(
789                             region,
790                             ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() },
791                         );
792                         err.note(&format!("you need `{}` instead of `{}`", trait_type, rcvr_ty));
793                     }
794                 }
795                 err.emit();
796             }
797
798             MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
799         }
800         None
801     }
802
803     /// Print out the type for use in value namespace.
804     fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
805         match ty.kind {
806             ty::Adt(def, substs) => format!("{}", ty::Instance::new(def.did, substs)),
807             _ => self.ty_to_string(ty),
808         }
809     }
810
811     fn suggest_use_candidates(
812         &self,
813         err: &mut DiagnosticBuilder<'_>,
814         mut msg: String,
815         candidates: Vec<DefId>,
816     ) {
817         let module_did = self.tcx.hir().get_module_parent(self.body_id);
818         let module_id = self.tcx.hir().as_local_hir_id(module_did).unwrap();
819         let krate = self.tcx.hir().krate();
820         let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
821         if let Some(span) = span {
822             let path_strings = candidates.iter().map(|did| {
823                 // Produce an additional newline to separate the new use statement
824                 // from the directly following item.
825                 let additional_newline = if found_use { "" } else { "\n" };
826                 format!(
827                     "use {};\n{}",
828                     with_crate_prefix(|| self.tcx.def_path_str(*did)),
829                     additional_newline
830                 )
831             });
832
833             err.span_suggestions(span, &msg, path_strings, Applicability::MaybeIncorrect);
834         } else {
835             let limit = if candidates.len() == 5 { 5 } else { 4 };
836             for (i, trait_did) in candidates.iter().take(limit).enumerate() {
837                 if candidates.len() > 1 {
838                     msg.push_str(&format!(
839                         "\ncandidate #{}: `use {};`",
840                         i + 1,
841                         with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
842                     ));
843                 } else {
844                     msg.push_str(&format!(
845                         "\n`use {};`",
846                         with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
847                     ));
848                 }
849             }
850             if candidates.len() > limit {
851                 msg.push_str(&format!("\nand {} others", candidates.len() - limit));
852             }
853             err.note(&msg[..]);
854         }
855     }
856
857     fn suggest_valid_traits(
858         &self,
859         err: &mut DiagnosticBuilder<'_>,
860         valid_out_of_scope_traits: Vec<DefId>,
861     ) -> bool {
862         if !valid_out_of_scope_traits.is_empty() {
863             let mut candidates = valid_out_of_scope_traits;
864             candidates.sort();
865             candidates.dedup();
866             err.help("items from traits can only be used if the trait is in scope");
867             let msg = format!(
868                 "the following {traits_are} implemented but not in scope; \
869                  perhaps add a `use` for {one_of_them}:",
870                 traits_are = if candidates.len() == 1 { "trait is" } else { "traits are" },
871                 one_of_them = if candidates.len() == 1 { "it" } else { "one of them" },
872             );
873
874             self.suggest_use_candidates(err, msg, candidates);
875             true
876         } else {
877             false
878         }
879     }
880
881     fn suggest_traits_to_import<'b>(
882         &self,
883         err: &mut DiagnosticBuilder<'_>,
884         span: Span,
885         rcvr_ty: Ty<'tcx>,
886         item_name: ast::Ident,
887         source: SelfSource<'b>,
888         valid_out_of_scope_traits: Vec<DefId>,
889     ) {
890         if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
891             return;
892         }
893
894         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
895
896         // There are no traits implemented, so lets suggest some traits to
897         // implement, by finding ones that have the item name, and are
898         // legal to implement.
899         let mut candidates = all_traits(self.tcx)
900             .into_iter()
901             .filter(|info| {
902                 // We approximate the coherence rules to only suggest
903                 // traits that are legal to implement by requiring that
904                 // either the type or trait is local. Multi-dispatch means
905                 // this isn't perfect (that is, there are cases when
906                 // implementing a trait would be legal but is rejected
907                 // here).
908                 (type_is_local || info.def_id.is_local())
909                     && self
910                         .associated_item(info.def_id, item_name, Namespace::ValueNS)
911                         .filter(|item| {
912                             // We only want to suggest public or local traits (#45781).
913                             item.vis == ty::Visibility::Public || info.def_id.is_local()
914                         })
915                         .is_some()
916             })
917             .collect::<Vec<_>>();
918
919         if !candidates.is_empty() {
920             // Sort from most relevant to least relevant.
921             candidates.sort_by(|a, b| a.cmp(b).reverse());
922             candidates.dedup();
923
924             let param_type = match rcvr_ty.kind {
925                 ty::Param(param) => Some(param),
926                 ty::Ref(_, ty, _) => match ty.kind {
927                     ty::Param(param) => Some(param),
928                     _ => None,
929                 },
930                 _ => None,
931             };
932             err.help(if param_type.is_some() {
933                 "items from traits can only be used if the type parameter is bounded by the trait"
934             } else {
935                 "items from traits can only be used if the trait is implemented and in scope"
936             });
937             let message = |action| {
938                 format!(
939                     "the following {traits_define} an item `{name}`, perhaps you need to {action} \
940                      {one_of_them}:",
941                     traits_define =
942                         if candidates.len() == 1 { "trait defines" } else { "traits define" },
943                     action = action,
944                     one_of_them = if candidates.len() == 1 { "it" } else { "one of them" },
945                     name = item_name,
946                 )
947             };
948             // Obtain the span for `param` and use it for a structured suggestion.
949             let mut suggested = false;
950             if let (Some(ref param), Some(ref table)) = (param_type, self.in_progress_tables) {
951                 let table = table.borrow();
952                 if let Some(did) = table.local_id_root {
953                     let generics = self.tcx.generics_of(did);
954                     let type_param = generics.type_param(param, self.tcx);
955                     let hir = &self.tcx.hir();
956                     if let Some(id) = hir.as_local_hir_id(type_param.def_id) {
957                         // Get the `hir::Param` to verify whether it already has any bounds.
958                         // We do this to avoid suggesting code that ends up as `T: FooBar`,
959                         // instead we suggest `T: Foo + Bar` in that case.
960                         match hir.get(id) {
961                             Node::GenericParam(ref param) => {
962                                 let mut impl_trait = false;
963                                 let has_bounds = if let hir::GenericParamKind::Type {
964                                     synthetic: Some(_),
965                                     ..
966                                 } = &param.kind
967                                 {
968                                     // We've found `fn foo(x: impl Trait)` instead of
969                                     // `fn foo<T>(x: T)`. We want to suggest the correct
970                                     // `fn foo(x: impl Trait + TraitBound)` instead of
971                                     // `fn foo<T: TraitBound>(x: T)`. (#63706)
972                                     impl_trait = true;
973                                     param.bounds.get(1)
974                                 } else {
975                                     param.bounds.get(0)
976                                 };
977                                 let sp = hir.span(id);
978                                 let sp = if let Some(first_bound) = has_bounds {
979                                     // `sp` only covers `T`, change it so that it covers
980                                     // `T:` when appropriate
981                                     sp.until(first_bound.span())
982                                 } else {
983                                     sp
984                                 };
985                                 let trait_def_ids: FxHashSet<DefId> = param
986                                     .bounds
987                                     .iter()
988                                     .filter_map(|bound| bound.trait_def_id())
989                                     .collect();
990                                 if !candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
991                                     err.span_suggestions(
992                                         sp,
993                                         &message(format!(
994                                             "restrict type parameter `{}` with",
995                                             param.name.ident(),
996                                         )),
997                                         candidates.iter().map(|t| {
998                                             format!(
999                                                 "{}{} {}{}",
1000                                                 param.name.ident(),
1001                                                 if impl_trait { " +" } else { ":" },
1002                                                 self.tcx.def_path_str(t.def_id),
1003                                                 if has_bounds.is_some() { " + " } else { "" },
1004                                             )
1005                                         }),
1006                                         Applicability::MaybeIncorrect,
1007                                     );
1008                                 }
1009                                 suggested = true;
1010                             }
1011                             Node::Item(hir::Item {
1012                                 kind: hir::ItemKind::Trait(.., bounds, _),
1013                                 ident,
1014                                 ..
1015                             }) => {
1016                                 let (sp, sep, article) = if bounds.is_empty() {
1017                                     (ident.span.shrink_to_hi(), ":", "a")
1018                                 } else {
1019                                     (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
1020                                 };
1021                                 err.span_suggestions(
1022                                     sp,
1023                                     &message(format!("add {} supertrait for", article)),
1024                                     candidates.iter().map(|t| {
1025                                         format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
1026                                     }),
1027                                     Applicability::MaybeIncorrect,
1028                                 );
1029                                 suggested = true;
1030                             }
1031                             _ => {}
1032                         }
1033                     }
1034                 };
1035             }
1036
1037             if !suggested {
1038                 let action = if let Some(param) = param_type {
1039                     format!("restrict type parameter `{}` with", param)
1040                 } else {
1041                     // FIXME: it might only need to be imported into scope, not implemented.
1042                     "implement".to_string()
1043                 };
1044                 let mut use_note = true;
1045                 if let [trait_info] = &candidates[..] {
1046                     if let Some(span) = self.tcx.hir().span_if_local(trait_info.def_id) {
1047                         err.span_label(
1048                             self.tcx.sess.source_map().def_span(span),
1049                             &format!(
1050                                 "`{}` defines an item `{}`, perhaps you need to {} it",
1051                                 self.tcx.def_path_str(trait_info.def_id),
1052                                 item_name,
1053                                 action
1054                             ),
1055                         );
1056                         use_note = false
1057                     }
1058                 }
1059                 if use_note {
1060                     let mut msg = message(action);
1061                     for (i, trait_info) in candidates.iter().enumerate() {
1062                         msg.push_str(&format!(
1063                             "\ncandidate #{}: `{}`",
1064                             i + 1,
1065                             self.tcx.def_path_str(trait_info.def_id),
1066                         ));
1067                     }
1068                     err.note(&msg[..]);
1069                 }
1070             }
1071         }
1072     }
1073
1074     /// Checks whether there is a local type somewhere in the chain of
1075     /// autoderefs of `rcvr_ty`.
1076     fn type_derefs_to_local(&self, span: Span, rcvr_ty: Ty<'tcx>, source: SelfSource<'_>) -> bool {
1077         fn is_local(ty: Ty<'_>) -> bool {
1078             match ty.kind {
1079                 ty::Adt(def, _) => def.did.is_local(),
1080                 ty::Foreign(did) => did.is_local(),
1081
1082                 ty::Dynamic(ref tr, ..) => {
1083                     tr.principal().map(|d| d.def_id().is_local()).unwrap_or(false)
1084                 }
1085
1086                 ty::Param(_) => true,
1087
1088                 // Everything else (primitive types, etc.) is effectively
1089                 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
1090                 // the noise from these sort of types is usually just really
1091                 // annoying, rather than any sort of help).
1092                 _ => false,
1093             }
1094         }
1095
1096         // This occurs for UFCS desugaring of `T::method`, where there is no
1097         // receiver expression for the method call, and thus no autoderef.
1098         if let SelfSource::QPath(_) = source {
1099             return is_local(self.resolve_vars_with_obligations(rcvr_ty));
1100         }
1101
1102         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
1103     }
1104 }
1105
1106 #[derive(Copy, Clone)]
1107 pub enum SelfSource<'a> {
1108     QPath(&'a hir::Ty<'a>),
1109     MethodCall(&'a hir::Expr<'a> /* rcvr */),
1110 }
1111
1112 #[derive(Copy, Clone)]
1113 pub struct TraitInfo {
1114     pub def_id: DefId,
1115 }
1116
1117 impl PartialEq for TraitInfo {
1118     fn eq(&self, other: &TraitInfo) -> bool {
1119         self.cmp(other) == Ordering::Equal
1120     }
1121 }
1122 impl Eq for TraitInfo {}
1123 impl PartialOrd for TraitInfo {
1124     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
1125         Some(self.cmp(other))
1126     }
1127 }
1128 impl Ord for TraitInfo {
1129     fn cmp(&self, other: &TraitInfo) -> Ordering {
1130         // Local crates are more important than remote ones (local:
1131         // `cnum == 0`), and otherwise we throw in the defid for totality.
1132
1133         let lhs = (other.def_id.krate, other.def_id);
1134         let rhs = (self.def_id.krate, self.def_id);
1135         lhs.cmp(&rhs)
1136     }
1137 }
1138
1139 /// Retrieves all traits in this crate and any dependent crates.
1140 pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
1141     tcx.all_traits(LOCAL_CRATE).iter().map(|&def_id| TraitInfo { def_id }).collect()
1142 }
1143
1144 /// Computes all traits in this crate and any dependent crates.
1145 fn compute_all_traits(tcx: TyCtxt<'_>) -> Vec<DefId> {
1146     use hir::itemlikevisit;
1147
1148     let mut traits = vec![];
1149
1150     // Crate-local:
1151
1152     struct Visitor<'a, 'tcx> {
1153         map: &'a hir_map::Map<'tcx>,
1154         traits: &'a mut Vec<DefId>,
1155     }
1156
1157     impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
1158         fn visit_item(&mut self, i: &'v hir::Item<'v>) {
1159             match i.kind {
1160                 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1161                     let def_id = self.map.local_def_id(i.hir_id);
1162                     self.traits.push(def_id);
1163                 }
1164                 _ => (),
1165             }
1166         }
1167
1168         fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
1169
1170         fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
1171     }
1172
1173     tcx.hir().krate().visit_all_item_likes(&mut Visitor { map: &tcx.hir(), traits: &mut traits });
1174
1175     // Cross-crate:
1176
1177     let mut external_mods = FxHashSet::default();
1178     fn handle_external_res(
1179         tcx: TyCtxt<'_>,
1180         traits: &mut Vec<DefId>,
1181         external_mods: &mut FxHashSet<DefId>,
1182         res: Res,
1183     ) {
1184         match res {
1185             Res::Def(DefKind::Trait, def_id) | Res::Def(DefKind::TraitAlias, def_id) => {
1186                 traits.push(def_id);
1187             }
1188             Res::Def(DefKind::Mod, def_id) => {
1189                 if !external_mods.insert(def_id) {
1190                     return;
1191                 }
1192                 for child in tcx.item_children(def_id).iter() {
1193                     handle_external_res(tcx, traits, external_mods, child.res)
1194                 }
1195             }
1196             _ => {}
1197         }
1198     }
1199     for &cnum in tcx.crates().iter() {
1200         let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1201         handle_external_res(tcx, &mut traits, &mut external_mods, Res::Def(DefKind::Mod, def_id));
1202     }
1203
1204     traits
1205 }
1206
1207 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1208     providers.all_traits = |tcx, cnum| {
1209         assert_eq!(cnum, LOCAL_CRATE);
1210         &tcx.arena.alloc(compute_all_traits(tcx))[..]
1211     }
1212 }
1213
1214 struct UsePlacementFinder<'tcx> {
1215     target_module: hir::HirId,
1216     span: Option<Span>,
1217     found_use: bool,
1218     tcx: TyCtxt<'tcx>,
1219 }
1220
1221 impl UsePlacementFinder<'tcx> {
1222     fn check(
1223         tcx: TyCtxt<'tcx>,
1224         krate: &'tcx hir::Crate<'tcx>,
1225         target_module: hir::HirId,
1226     ) -> (Option<Span>, bool) {
1227         let mut finder = UsePlacementFinder { target_module, span: None, found_use: false, tcx };
1228         intravisit::walk_crate(&mut finder, krate);
1229         (finder.span, finder.found_use)
1230     }
1231 }
1232
1233 impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> {
1234     fn visit_mod(&mut self, module: &'tcx hir::Mod<'tcx>, _: Span, hir_id: hir::HirId) {
1235         if self.span.is_some() {
1236             return;
1237         }
1238         if hir_id != self.target_module {
1239             intravisit::walk_mod(self, module, hir_id);
1240             return;
1241         }
1242         // Find a `use` statement.
1243         for item_id in module.item_ids {
1244             let item = self.tcx.hir().expect_item(item_id.id);
1245             match item.kind {
1246                 hir::ItemKind::Use(..) => {
1247                     // Don't suggest placing a `use` before the prelude
1248                     // import or other generated ones.
1249                     if !item.span.from_expansion() {
1250                         self.span = Some(item.span.shrink_to_lo());
1251                         self.found_use = true;
1252                         return;
1253                     }
1254                 }
1255                 // Don't place `use` before `extern crate`...
1256                 hir::ItemKind::ExternCrate(_) => {}
1257                 // ...but do place them before the first other item.
1258                 _ => {
1259                     if self.span.map_or(true, |span| item.span < span) {
1260                         if !item.span.from_expansion() {
1261                             // Don't insert between attributes and an item.
1262                             if item.attrs.is_empty() {
1263                                 self.span = Some(item.span.shrink_to_lo());
1264                             } else {
1265                                 // Find the first attribute on the item.
1266                                 for attr in item.attrs {
1267                                     if self.span.map_or(true, |span| attr.span < span) {
1268                                         self.span = Some(attr.span.shrink_to_lo());
1269                                     }
1270                                 }
1271                             }
1272                         }
1273                     }
1274                 }
1275             }
1276         }
1277     }
1278
1279     type Map = Map<'tcx>;
1280
1281     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1282         intravisit::NestedVisitorMap::None
1283     }
1284 }
1285
1286 fn print_disambiguation_help(
1287     item_name: ast::Ident,
1288     args: Option<&'tcx [hir::Expr<'tcx>]>,
1289     err: &mut DiagnosticBuilder<'_>,
1290     trait_name: String,
1291     rcvr_ty: Ty<'_>,
1292     kind: ty::AssocKind,
1293     span: Span,
1294     candidate: Option<usize>,
1295     source_map: &source_map::SourceMap,
1296 ) {
1297     let mut applicability = Applicability::MachineApplicable;
1298     let sugg_args = if let (ty::AssocKind::Method, Some(args)) = (kind, args) {
1299         format!(
1300             "({}{})",
1301             if rcvr_ty.is_region_ptr() {
1302                 if rcvr_ty.is_mutable_ptr() { "&mut " } else { "&" }
1303             } else {
1304                 ""
1305             },
1306             args.iter()
1307                 .map(|arg| source_map.span_to_snippet(arg.span).unwrap_or_else(|_| {
1308                     applicability = Applicability::HasPlaceholders;
1309                     "_".to_owned()
1310                 }))
1311                 .collect::<Vec<_>>()
1312                 .join(", "),
1313         )
1314     } else {
1315         String::new()
1316     };
1317     let sugg = format!("{}::{}{}", trait_name, item_name, sugg_args);
1318     err.span_suggestion(
1319         span,
1320         &format!(
1321             "disambiguate the {} for {}",
1322             kind.suggestion_descr(),
1323             if let Some(candidate) = candidate {
1324                 format!("candidate #{}", candidate)
1325             } else {
1326                 "the candidate".to_string()
1327             },
1328         ),
1329         sugg,
1330         applicability,
1331     );
1332 }