]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late/diagnostics.rs
review comment: suggestion message wording
[rust.git] / src / librustc_resolve / late / diagnostics.rs
1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{LateResolutionVisitor, RibKind};
4 use crate::path_names_to_string;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
6 use crate::{PathResult, PathSource, Segment};
7
8 use rustc_ast::ast::{self, Expr, ExprKind, Item, ItemKind, NodeId, Path, Ty, TyKind};
9 use rustc_ast::util::lev_distance::find_best_match_for_name;
10 use rustc_ast::visit::FnKind;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
13 use rustc_hir as hir;
14 use rustc_hir::def::Namespace::{self, *};
15 use rustc_hir::def::{self, CtorKind, DefKind};
16 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
17 use rustc_hir::PrimTy;
18 use rustc_session::config::nightly_options;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::symbol::{kw, sym, Ident};
21 use rustc_span::{BytePos, Span};
22
23 use log::debug;
24
25 type Res = def::Res<ast::NodeId>;
26
27 /// A field or associated item from self type suggested in case of resolution failure.
28 enum AssocSuggestion {
29     Field,
30     MethodWithSelf,
31     AssocItem,
32 }
33
34 crate enum MissingLifetimeSpot<'tcx> {
35     Generics(&'tcx hir::Generics<'tcx>),
36     HigherRanked { span: Span, span_type: ForLifetimeSpanType },
37 }
38
39 crate enum ForLifetimeSpanType {
40     BoundEmpty,
41     BoundTail,
42     TypeEmpty,
43     TypeTail,
44 }
45
46 impl ForLifetimeSpanType {
47     crate fn descr(&self) -> &'static str {
48         match self {
49             Self::BoundEmpty | Self::BoundTail => "bound",
50             Self::TypeEmpty | Self::TypeTail => "type",
51         }
52     }
53
54     crate fn suggestion(&self, sugg: &str) -> String {
55         match self {
56             Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
57             Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
58         }
59     }
60 }
61
62 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
63     fn into(self) -> MissingLifetimeSpot<'tcx> {
64         MissingLifetimeSpot::Generics(self)
65     }
66 }
67
68 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
69     namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
70 }
71
72 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
73     namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
74 }
75
76 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
77 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
78     let variant_path = &suggestion.path;
79     let variant_path_string = path_names_to_string(variant_path);
80
81     let path_len = suggestion.path.segments.len();
82     let enum_path = ast::Path {
83         span: suggestion.path.span,
84         segments: suggestion.path.segments[0..path_len - 1].to_vec(),
85     };
86     let enum_path_string = path_names_to_string(&enum_path);
87
88     (variant_path_string, enum_path_string)
89 }
90
91 impl<'a> LateResolutionVisitor<'a, '_, '_> {
92     fn def_span(&self, def_id: DefId) -> Option<Span> {
93         match def_id.krate {
94             LOCAL_CRATE => self.r.opt_span(def_id),
95             _ => Some(
96                 self.r
97                     .session
98                     .source_map()
99                     .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
100             ),
101         }
102     }
103
104     /// Handles error reporting for `smart_resolve_path_fragment` function.
105     /// Creates base error and amends it with one short label and possibly some longer helps/notes.
106     pub(crate) fn smart_resolve_report_errors(
107         &mut self,
108         path: &[Segment],
109         span: Span,
110         source: PathSource<'_>,
111         res: Option<Res>,
112     ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
113         let ident_span = path.last().map_or(span, |ident| ident.ident.span);
114         let ns = source.namespace();
115         let is_expected = &|res| source.is_expected(res);
116         let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
117
118         // Make the base error.
119         let expected = source.descr_expected();
120         let path_str = Segment::names_to_string(path);
121         let item_str = path.last().unwrap().ident;
122         let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
123             (
124                 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
125                 format!("not a {}", expected),
126                 span,
127                 match res {
128                     Res::Def(DefKind::Fn, _) => {
129                         // Verify whether this is a fn call or an Fn used as a type.
130                         self.r
131                             .session
132                             .source_map()
133                             .span_to_snippet(span)
134                             .map(|snippet| snippet.ends_with(')'))
135                             .unwrap_or(false)
136                     }
137                     Res::Def(
138                         DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
139                         _,
140                     )
141                     | Res::SelfCtor(_)
142                     | Res::PrimTy(_)
143                     | Res::Local(_) => true,
144                     _ => false,
145                 },
146             )
147         } else {
148             let item_span = path.last().unwrap().ident.span;
149             let (mod_prefix, mod_str) = if path.len() == 1 {
150                 (String::new(), "this scope".to_string())
151             } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
152                 (String::new(), "the crate root".to_string())
153             } else {
154                 let mod_path = &path[..path.len() - 1];
155                 let mod_prefix =
156                     match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
157                         PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
158                         _ => None,
159                     }
160                     .map_or(String::new(), |res| format!("{} ", res.descr()));
161                 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
162             };
163             (
164                 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
165                 if path_str == "async" && expected.starts_with("struct") {
166                     "`async` blocks are only allowed in the 2018 edition".to_string()
167                 } else {
168                     format!("not found in {}", mod_str)
169                 },
170                 item_span,
171                 false,
172             )
173         };
174
175         let code = source.error_code(res.is_some());
176         let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
177
178         let is_assoc_fn = self.self_type_is_available(span);
179         // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
180         if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
181             err.span_suggestion_short(
182                 span,
183                 "you might have meant to use `self` here instead",
184                 "self".to_string(),
185                 Applicability::MaybeIncorrect,
186             );
187             if !self.self_value_is_available(path[0].ident.span, span) {
188                 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
189                     &self.diagnostic_metadata.current_function
190                 {
191                     let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
192                         (param.span.shrink_to_lo(), "&self, ")
193                     } else {
194                         (
195                             self.r
196                                 .session
197                                 .source_map()
198                                 .span_through_char(*fn_span, '(')
199                                 .shrink_to_hi(),
200                             "&self",
201                         )
202                     };
203                     err.span_suggestion_verbose(
204                         span,
205                         "if you meant to use `self`, you are also missing a `self` receiver \
206                          argument",
207                         sugg.to_string(),
208                         Applicability::MaybeIncorrect,
209                     );
210                 }
211             }
212         }
213
214         // Emit special messages for unresolved `Self` and `self`.
215         if is_self_type(path, ns) {
216             err.code(rustc_errors::error_code!(E0411));
217             err.span_label(
218                 span,
219                 "`Self` is only available in impls, traits, and type definitions".to_string(),
220             );
221             return (err, Vec::new());
222         }
223         if is_self_value(path, ns) {
224             debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
225
226             err.code(rustc_errors::error_code!(E0424));
227             err.span_label(span, match source {
228                 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
229                                    .to_string(),
230                 _ => "`self` value is a keyword only available in methods with a `self` parameter"
231                      .to_string(),
232             });
233             if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
234                 // The current function has a `self' parameter, but we were unable to resolve
235                 // a reference to `self`. This can only happen if the `self` identifier we
236                 // are resolving came from a different hygiene context.
237                 if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
238                     err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
239                 } else {
240                     let doesnt = if is_assoc_fn {
241                         let (span, sugg) = fn_kind
242                             .decl()
243                             .inputs
244                             .get(0)
245                             .map(|p| (p.span.shrink_to_lo(), "&self, "))
246                             .unwrap_or_else(|| {
247                                 (
248                                     self.r
249                                         .session
250                                         .source_map()
251                                         .span_through_char(*span, '(')
252                                         .shrink_to_hi(),
253                                     "&self",
254                                 )
255                             });
256                         err.span_suggestion_verbose(
257                             span,
258                             "add a `self` receiver parameter to make the associated `fn` a method",
259                             sugg.to_string(),
260                             Applicability::MaybeIncorrect,
261                         );
262                         "doesn't"
263                     } else {
264                         "can't"
265                     };
266                     if let Some(ident) = fn_kind.ident() {
267                         err.span_label(
268                             ident.span,
269                             &format!("this function {} have a `self` parameter", doesnt),
270                         );
271                     }
272                 }
273             }
274             return (err, Vec::new());
275         }
276
277         // Try to lookup name in more relaxed fashion for better error reporting.
278         let ident = path.last().unwrap().ident;
279         let candidates = self
280             .r
281             .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
282             .drain(..)
283             .filter(|ImportSuggestion { did, .. }| {
284                 match (did, res.and_then(|res| res.opt_def_id())) {
285                     (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
286                     _ => true,
287                 }
288             })
289             .collect::<Vec<_>>();
290         let crate_def_id = DefId::local(CRATE_DEF_INDEX);
291         if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
292             let enum_candidates =
293                 self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
294
295             if !enum_candidates.is_empty() {
296                 if let (PathSource::Type, Some(span)) =
297                     (source, self.diagnostic_metadata.current_type_ascription.last())
298                 {
299                     if self
300                         .r
301                         .session
302                         .parse_sess
303                         .type_ascription_path_suggestions
304                         .borrow()
305                         .contains(span)
306                     {
307                         // Already reported this issue on the lhs of the type ascription.
308                         err.delay_as_bug();
309                         return (err, candidates);
310                     }
311                 }
312
313                 let mut enum_candidates = enum_candidates
314                     .iter()
315                     .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
316                     .collect::<Vec<_>>();
317                 enum_candidates.sort();
318
319                 // Contextualize for E0412 "cannot find type", but don't belabor the point
320                 // (that it's a variant) for E0573 "expected type, found variant".
321                 let preamble = if res.is_none() {
322                     let others = match enum_candidates.len() {
323                         1 => String::new(),
324                         2 => " and 1 other".to_owned(),
325                         n => format!(" and {} others", n),
326                     };
327                     format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
328                 } else {
329                     String::new()
330                 };
331                 let msg = format!("{}try using the variant's enum", preamble);
332
333                 err.span_suggestions(
334                     span,
335                     &msg,
336                     enum_candidates
337                         .into_iter()
338                         .map(|(_variant_path, enum_ty_path)| enum_ty_path)
339                         // Variants re-exported in prelude doesn't mean `prelude::v1` is the
340                         // type name!
341                         // FIXME: is there a more principled way to do this that
342                         // would work for other re-exports?
343                         .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
344                         // Also write `Option` rather than `std::prelude::v1::Option`.
345                         .map(|enum_ty_path| {
346                             // FIXME #56861: DRY-er prelude filtering.
347                             enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
348                         }),
349                     Applicability::MachineApplicable,
350                 );
351             }
352         }
353         if path.len() == 1 && self.self_type_is_available(span) {
354             if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
355                 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
356                 match candidate {
357                     AssocSuggestion::Field => {
358                         if self_is_available {
359                             err.span_suggestion(
360                                 span,
361                                 "you might have meant to use the available field",
362                                 format!("self.{}", path_str),
363                                 Applicability::MachineApplicable,
364                             );
365                         } else {
366                             err.span_label(span, "a field by this name exists in `Self`");
367                         }
368                     }
369                     AssocSuggestion::MethodWithSelf if self_is_available => {
370                         err.span_suggestion(
371                             span,
372                             "try",
373                             format!("self.{}", path_str),
374                             Applicability::MachineApplicable,
375                         );
376                     }
377                     AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
378                         err.span_suggestion(
379                             span,
380                             "try",
381                             format!("Self::{}", path_str),
382                             Applicability::MachineApplicable,
383                         );
384                     }
385                 }
386                 return (err, candidates);
387             }
388
389             // If the first argument in call is `self` suggest calling a method.
390             if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
391                 let mut args_snippet = String::new();
392                 if let Some(args_span) = args_span {
393                     if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
394                         args_snippet = snippet;
395                     }
396                 }
397
398                 err.span_suggestion(
399                     call_span,
400                     &format!("try calling `{}` as a method", ident),
401                     format!("self.{}({})", path_str, args_snippet),
402                     Applicability::MachineApplicable,
403                 );
404                 return (err, candidates);
405             }
406         }
407
408         // Try Levenshtein algorithm.
409         let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
410         // Try context-dependent help if relaxed lookup didn't work.
411         if let Some(res) = res {
412             if self.smart_resolve_context_dependent_help(
413                 &mut err,
414                 span,
415                 source,
416                 res,
417                 &path_str,
418                 &fallback_label,
419             ) {
420                 // We do this to avoid losing a secondary span when we override the main error span.
421                 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
422                 return (err, candidates);
423             }
424         }
425
426         if !self.type_ascription_suggestion(&mut err, base_span)
427             && !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span)
428         {
429             // Fallback label.
430             err.span_label(base_span, fallback_label);
431
432             match self.diagnostic_metadata.current_let_binding {
433                 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
434                     err.span_suggestion_short(
435                         pat_sp.between(ty_sp),
436                         "use `=` if you meant to assign",
437                         " = ".to_string(),
438                         Applicability::MaybeIncorrect,
439                     );
440                 }
441                 _ => {}
442             }
443         }
444         (err, candidates)
445     }
446
447     /// Check if the source is call expression and the first argument is `self`. If true,
448     /// return the span of whole call and the span for all arguments expect the first one (`self`).
449     fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
450         let mut has_self_arg = None;
451         if let PathSource::Expr(Some(parent)) = source {
452             match &parent.kind {
453                 ExprKind::Call(_, args) if !args.is_empty() => {
454                     let mut expr_kind = &args[0].kind;
455                     loop {
456                         match expr_kind {
457                             ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
458                                 if arg_name.segments[0].ident.name == kw::SelfLower {
459                                     let call_span = parent.span;
460                                     let tail_args_span = if args.len() > 1 {
461                                         Some(Span::new(
462                                             args[1].span.lo(),
463                                             args.last().unwrap().span.hi(),
464                                             call_span.ctxt(),
465                                         ))
466                                     } else {
467                                         None
468                                     };
469                                     has_self_arg = Some((call_span, tail_args_span));
470                                 }
471                                 break;
472                             }
473                             ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
474                             _ => break,
475                         }
476                     }
477                 }
478                 _ => (),
479             }
480         };
481         has_self_arg
482     }
483
484     fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
485         // HACK(estebank): find a better way to figure out that this was a
486         // parser issue where a struct literal is being used on an expression
487         // where a brace being opened means a block is being started. Look
488         // ahead for the next text to see if `span` is followed by a `{`.
489         let sm = self.r.session.source_map();
490         let mut sp = span;
491         loop {
492             sp = sm.next_point(sp);
493             match sm.span_to_snippet(sp) {
494                 Ok(ref snippet) => {
495                     if snippet.chars().any(|c| !c.is_whitespace()) {
496                         break;
497                     }
498                 }
499                 _ => break,
500             }
501         }
502         let followed_by_brace = match sm.span_to_snippet(sp) {
503             Ok(ref snippet) if snippet == "{" => true,
504             _ => false,
505         };
506         // In case this could be a struct literal that needs to be surrounded
507         // by parentheses, find the appropriate span.
508         let mut i = 0;
509         let mut closing_brace = None;
510         loop {
511             sp = sm.next_point(sp);
512             match sm.span_to_snippet(sp) {
513                 Ok(ref snippet) => {
514                     if snippet == "}" {
515                         closing_brace = Some(span.to(sp));
516                         break;
517                     }
518                 }
519                 _ => break,
520             }
521             i += 1;
522             // The bigger the span, the more likely we're incorrect --
523             // bound it to 100 chars long.
524             if i > 100 {
525                 break;
526             }
527         }
528         (followed_by_brace, closing_brace)
529     }
530
531     /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
532     /// function.
533     /// Returns `true` if able to provide context-dependent help.
534     fn smart_resolve_context_dependent_help(
535         &mut self,
536         err: &mut DiagnosticBuilder<'a>,
537         span: Span,
538         source: PathSource<'_>,
539         res: Res,
540         path_str: &str,
541         fallback_label: &str,
542     ) -> bool {
543         let ns = source.namespace();
544         let is_expected = &|res| source.is_expected(res);
545
546         let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
547             ExprKind::Field(_, ident) => {
548                 err.span_suggestion(
549                     expr.span,
550                     "use the path separator to refer to an item",
551                     format!("{}::{}", path_str, ident),
552                     Applicability::MaybeIncorrect,
553                 );
554                 true
555             }
556             ExprKind::MethodCall(ref segment, ..) => {
557                 let span = expr.span.with_hi(segment.ident.span.hi());
558                 err.span_suggestion(
559                     span,
560                     "use the path separator to refer to an item",
561                     format!("{}::{}", path_str, segment.ident),
562                     Applicability::MaybeIncorrect,
563                 );
564                 true
565             }
566             _ => false,
567         };
568
569         let mut bad_struct_syntax_suggestion = |def_id: DefId| {
570             let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
571
572             match source {
573                 PathSource::Expr(Some(
574                     parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
575                 )) if path_sep(err, &parent) => {}
576                 PathSource::Expr(
577                     None
578                     | Some(Expr {
579                         kind:
580                             ExprKind::Path(..)
581                             | ExprKind::Binary(..)
582                             | ExprKind::Unary(..)
583                             | ExprKind::If(..)
584                             | ExprKind::While(..)
585                             | ExprKind::ForLoop(..)
586                             | ExprKind::Match(..),
587                         ..
588                     }),
589                 ) if followed_by_brace => {
590                     if let Some(sp) = closing_brace {
591                         err.span_label(span, fallback_label);
592                         err.multipart_suggestion(
593                             "surround the struct literal with parentheses",
594                             vec![
595                                 (sp.shrink_to_lo(), "(".to_string()),
596                                 (sp.shrink_to_hi(), ")".to_string()),
597                             ],
598                             Applicability::MaybeIncorrect,
599                         );
600                     } else {
601                         err.span_label(
602                             span, // Note the parentheses surrounding the suggestion below
603                             format!(
604                                 "you might want to surround a struct literal with parentheses: \
605                                  `({} {{ /* fields */ }})`?",
606                                 path_str
607                             ),
608                         );
609                     }
610                 }
611                 PathSource::Expr(_) | PathSource::TupleStruct(_) | PathSource::Pat => {
612                     let span = match &source {
613                         PathSource::Expr(Some(Expr {
614                             span, kind: ExprKind::Call(_, _), ..
615                         }))
616                         | PathSource::TupleStruct(span) => {
617                             // We want the main underline to cover the suggested code as well for
618                             // cleaner output.
619                             err.set_span(*span);
620                             *span
621                         }
622                         _ => span,
623                     };
624                     if let Some(span) = self.def_span(def_id) {
625                         err.span_label(span, &format!("`{}` defined here", path_str));
626                     }
627                     let (tail, descr, applicability) = match source {
628                         PathSource::Pat | PathSource::TupleStruct(_) => {
629                             ("", "pattern", Applicability::MachineApplicable)
630                         }
631                         _ => (": val", "literal", Applicability::HasPlaceholders),
632                     };
633                     let (fields, applicability) = match self.r.field_names.get(&def_id) {
634                         Some(fields) => (
635                             fields
636                                 .iter()
637                                 .map(|f| format!("{}{}", f.node, tail))
638                                 .collect::<Vec<String>>()
639                                 .join(", "),
640                             applicability,
641                         ),
642                         None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
643                     };
644                     let pad = match self.r.field_names.get(&def_id) {
645                         Some(fields) if fields.is_empty() => "",
646                         _ => " ",
647                     };
648                     err.span_suggestion(
649                         span,
650                         &format!("use struct {} syntax instead", descr),
651                         format!("{} {{{pad}{}{pad}}}", path_str, fields, pad = pad),
652                         applicability,
653                     );
654                 }
655                 _ => {
656                     err.span_label(span, fallback_label);
657                 }
658             }
659         };
660
661         match (res, source) {
662             (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
663                 err.span_label(span, fallback_label);
664                 err.span_suggestion_verbose(
665                     span.shrink_to_hi(),
666                     "use `!` to invoke the macro",
667                     "!".to_string(),
668                     Applicability::MaybeIncorrect,
669                 );
670                 if path_str == "try" && span.rust_2015() {
671                     err.note("if you want the `try` keyword, you need to be in the 2018 edition");
672                 }
673             }
674             (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
675                 err.span_label(span, "type aliases cannot be used as traits");
676                 if nightly_options::is_nightly_build() {
677                     let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
678                                `type` alias";
679                     if let Some(span) = self.def_span(def_id) {
680                         err.span_help(span, msg);
681                     } else {
682                         err.help(msg);
683                     }
684                 }
685             }
686             (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
687                 if !path_sep(err, &parent) {
688                     return false;
689                 }
690             }
691             (
692                 Res::Def(DefKind::Enum, def_id),
693                 PathSource::TupleStruct(_) | PathSource::Expr(..),
694             ) => {
695                 if self
696                     .diagnostic_metadata
697                     .current_type_ascription
698                     .last()
699                     .map(|sp| {
700                         self.r
701                             .session
702                             .parse_sess
703                             .type_ascription_path_suggestions
704                             .borrow()
705                             .contains(&sp)
706                     })
707                     .unwrap_or(false)
708                 {
709                     err.delay_as_bug();
710                     // We already suggested changing `:` into `::` during parsing.
711                     return false;
712                 }
713                 if let Some(variants) = self.collect_enum_variants(def_id) {
714                     if !variants.is_empty() {
715                         let msg = if variants.len() == 1 {
716                             "try using the enum's variant"
717                         } else {
718                             "try using one of the enum's variants"
719                         };
720
721                         err.span_suggestions(
722                             span,
723                             msg,
724                             variants.iter().map(path_names_to_string),
725                             Applicability::MaybeIncorrect,
726                         );
727                     }
728                 } else {
729                     err.note("you might have meant to use one of the enum's variants");
730                 }
731             }
732             (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
733                 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
734                 {
735                     let accessible_ctor =
736                         self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
737                     if is_expected(ctor_def) && !accessible_ctor {
738                         err.span_label(
739                             span,
740                             "constructor is not visible here due to private fields".to_string(),
741                         );
742                     }
743                 } else {
744                     bad_struct_syntax_suggestion(def_id);
745                 }
746             }
747             (
748                 Res::Def(
749                     DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
750                     def_id,
751                 ),
752                 _,
753             ) if ns == ValueNS => {
754                 bad_struct_syntax_suggestion(def_id);
755             }
756             (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
757                 if let Some(span) = self.def_span(def_id) {
758                     err.span_label(span, &format!("`{}` defined here", path_str));
759                 }
760                 err.span_label(span, format!("did you mean `{}( /* fields */ )`?", path_str));
761             }
762             (Res::SelfTy(..), _) if ns == ValueNS => {
763                 err.span_label(span, fallback_label);
764                 err.note("can't use `Self` as a constructor, you must use the implemented struct");
765             }
766             (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
767                 err.note("can't use a type alias as a constructor");
768             }
769             _ => return false,
770         }
771         true
772     }
773
774     fn lookup_assoc_candidate<FilterFn>(
775         &mut self,
776         ident: Ident,
777         ns: Namespace,
778         filter_fn: FilterFn,
779     ) -> Option<AssocSuggestion>
780     where
781         FilterFn: Fn(Res) -> bool,
782     {
783         fn extract_node_id(t: &Ty) -> Option<NodeId> {
784             match t.kind {
785                 TyKind::Path(None, _) => Some(t.id),
786                 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
787                 // This doesn't handle the remaining `Ty` variants as they are not
788                 // that commonly the self_type, it might be interesting to provide
789                 // support for those in future.
790                 _ => None,
791             }
792         }
793
794         // Fields are generally expected in the same contexts as locals.
795         if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
796             if let Some(node_id) =
797                 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
798             {
799                 // Look for a field with the same name in the current self_type.
800                 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
801                     match resolution.base_res() {
802                         Res::Def(DefKind::Struct | DefKind::Union, did)
803                             if resolution.unresolved_segments() == 0 =>
804                         {
805                             if let Some(field_names) = self.r.field_names.get(&did) {
806                                 if field_names
807                                     .iter()
808                                     .any(|&field_name| ident.name == field_name.node)
809                                 {
810                                     return Some(AssocSuggestion::Field);
811                                 }
812                             }
813                         }
814                         _ => {}
815                     }
816                 }
817             }
818         }
819
820         for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
821             if *assoc_type_ident == ident {
822                 return Some(AssocSuggestion::AssocItem);
823             }
824         }
825
826         // Look for associated items in the current trait.
827         if let Some((module, _)) = self.current_trait_ref {
828             if let Ok(binding) = self.r.resolve_ident_in_module(
829                 ModuleOrUniformRoot::Module(module),
830                 ident,
831                 ns,
832                 &self.parent_scope,
833                 false,
834                 module.span,
835             ) {
836                 let res = binding.res();
837                 if filter_fn(res) {
838                     return Some(if self.r.has_self.contains(&res.def_id()) {
839                         AssocSuggestion::MethodWithSelf
840                     } else {
841                         AssocSuggestion::AssocItem
842                     });
843                 }
844             }
845         }
846
847         None
848     }
849
850     fn lookup_typo_candidate(
851         &mut self,
852         path: &[Segment],
853         ns: Namespace,
854         filter_fn: &impl Fn(Res) -> bool,
855         span: Span,
856     ) -> Option<TypoSuggestion> {
857         let mut names = Vec::new();
858         if path.len() == 1 {
859             // Search in lexical scope.
860             // Walk backwards up the ribs in scope and collect candidates.
861             for rib in self.ribs[ns].iter().rev() {
862                 // Locals and type parameters
863                 for (ident, &res) in &rib.bindings {
864                     if filter_fn(res) {
865                         names.push(TypoSuggestion::from_res(ident.name, res));
866                     }
867                 }
868                 // Items in scope
869                 if let RibKind::ModuleRibKind(module) = rib.kind {
870                     // Items from this module
871                     self.r.add_module_candidates(module, &mut names, &filter_fn);
872
873                     if let ModuleKind::Block(..) = module.kind {
874                         // We can see through blocks
875                     } else {
876                         // Items from the prelude
877                         if !module.no_implicit_prelude {
878                             let extern_prelude = self.r.extern_prelude.clone();
879                             names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
880                                 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
881                                     |crate_id| {
882                                         let crate_mod = Res::Def(
883                                             DefKind::Mod,
884                                             DefId { krate: crate_id, index: CRATE_DEF_INDEX },
885                                         );
886
887                                         if filter_fn(crate_mod) {
888                                             Some(TypoSuggestion::from_res(ident.name, crate_mod))
889                                         } else {
890                                             None
891                                         }
892                                     },
893                                 )
894                             }));
895
896                             if let Some(prelude) = self.r.prelude {
897                                 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
898                             }
899                         }
900                         break;
901                     }
902                 }
903             }
904             // Add primitive types to the mix
905             if filter_fn(Res::PrimTy(PrimTy::Bool)) {
906                 names.extend(
907                     self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
908                         TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
909                     }),
910                 )
911             }
912         } else {
913             // Search in module.
914             let mod_path = &path[..path.len() - 1];
915             if let PathResult::Module(module) =
916                 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
917             {
918                 if let ModuleOrUniformRoot::Module(module) = module {
919                     self.r.add_module_candidates(module, &mut names, &filter_fn);
920                 }
921             }
922         }
923
924         let name = path[path.len() - 1].ident.name;
925         // Make sure error reporting is deterministic.
926         names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
927
928         match find_best_match_for_name(
929             names.iter().map(|suggestion| &suggestion.candidate),
930             name,
931             None,
932         ) {
933             Some(found) if found != name => {
934                 names.into_iter().find(|suggestion| suggestion.candidate == found)
935             }
936             _ => None,
937         }
938     }
939
940     /// Only used in a specific case of type ascription suggestions
941     fn get_colon_suggestion_span(&self, start: Span) -> Span {
942         let sm = self.r.session.source_map();
943         start.to(sm.next_point(start))
944     }
945
946     fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
947         let sm = self.r.session.source_map();
948         let base_snippet = sm.span_to_snippet(base_span);
949         if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
950             if let Ok(snippet) = sm.span_to_snippet(sp) {
951                 let len = snippet.trim_end().len() as u32;
952                 if snippet.trim() == ":" {
953                     let colon_sp =
954                         sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
955                     let mut show_label = true;
956                     if sm.is_multiline(sp) {
957                         err.span_suggestion_short(
958                             colon_sp,
959                             "maybe you meant to write `;` here",
960                             ";".to_string(),
961                             Applicability::MaybeIncorrect,
962                         );
963                     } else {
964                         let after_colon_sp =
965                             self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
966                         if snippet.len() == 1 {
967                             // `foo:bar`
968                             err.span_suggestion(
969                                 colon_sp,
970                                 "maybe you meant to write a path separator here",
971                                 "::".to_string(),
972                                 Applicability::MaybeIncorrect,
973                             );
974                             show_label = false;
975                             if !self
976                                 .r
977                                 .session
978                                 .parse_sess
979                                 .type_ascription_path_suggestions
980                                 .borrow_mut()
981                                 .insert(colon_sp)
982                             {
983                                 err.delay_as_bug();
984                             }
985                         }
986                         if let Ok(base_snippet) = base_snippet {
987                             let mut sp = after_colon_sp;
988                             for _ in 0..100 {
989                                 // Try to find an assignment
990                                 sp = sm.next_point(sp);
991                                 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
992                                 match snippet {
993                                     Ok(ref x) if x.as_str() == "=" => {
994                                         err.span_suggestion(
995                                             base_span,
996                                             "maybe you meant to write an assignment here",
997                                             format!("let {}", base_snippet),
998                                             Applicability::MaybeIncorrect,
999                                         );
1000                                         show_label = false;
1001                                         break;
1002                                     }
1003                                     Ok(ref x) if x.as_str() == "\n" => break,
1004                                     Err(_) => break,
1005                                     Ok(_) => {}
1006                                 }
1007                             }
1008                         }
1009                     }
1010                     if show_label {
1011                         err.span_label(
1012                             base_span,
1013                             "expecting a type here because of type ascription",
1014                         );
1015                     }
1016                     return show_label;
1017                 }
1018             }
1019         }
1020         false
1021     }
1022
1023     fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1024         let mut result = None;
1025         let mut seen_modules = FxHashSet::default();
1026         let mut worklist = vec![(self.r.graph_root, Vec::new())];
1027
1028         while let Some((in_module, path_segments)) = worklist.pop() {
1029             // abort if the module is already found
1030             if result.is_some() {
1031                 break;
1032             }
1033
1034             in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1035                 // abort if the module is already found or if name_binding is private external
1036                 if result.is_some() || !name_binding.vis.is_visible_locally() {
1037                     return;
1038                 }
1039                 if let Some(module) = name_binding.module() {
1040                     // form the path
1041                     let mut path_segments = path_segments.clone();
1042                     path_segments.push(ast::PathSegment::from_ident(ident));
1043                     let module_def_id = module.def_id().unwrap();
1044                     if module_def_id == def_id {
1045                         let path = Path { span: name_binding.span, segments: path_segments };
1046                         result = Some((
1047                             module,
1048                             ImportSuggestion {
1049                                 did: Some(def_id),
1050                                 descr: "module",
1051                                 path,
1052                                 accessible: true,
1053                             },
1054                         ));
1055                     } else {
1056                         // add the module to the lookup
1057                         if seen_modules.insert(module_def_id) {
1058                             worklist.push((module, path_segments));
1059                         }
1060                     }
1061                 }
1062             });
1063         }
1064
1065         result
1066     }
1067
1068     fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
1069         self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1070             let mut variants = Vec::new();
1071             enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1072                 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
1073                     let mut segms = enum_import_suggestion.path.segments.clone();
1074                     segms.push(ast::PathSegment::from_ident(ident));
1075                     variants.push(Path { span: name_binding.span, segments: segms });
1076                 }
1077             });
1078             variants
1079         })
1080     }
1081
1082     crate fn report_missing_type_error(
1083         &self,
1084         path: &[Segment],
1085     ) -> Option<(Span, &'static str, String, Applicability)> {
1086         let (ident, span) = match path {
1087             [segment] if !segment.has_generic_args => {
1088                 (segment.ident.to_string(), segment.ident.span)
1089             }
1090             _ => return None,
1091         };
1092         let mut iter = ident.chars().map(|c| c.is_uppercase());
1093         let single_uppercase_char =
1094             matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1095         if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1096             return None;
1097         }
1098         match (self.diagnostic_metadata.current_item, single_uppercase_char) {
1099             (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
1100                 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1101             }
1102             (
1103                 Some(Item {
1104                     kind:
1105                         kind @ ItemKind::Fn(..)
1106                         | kind @ ItemKind::Enum(..)
1107                         | kind @ ItemKind::Struct(..)
1108                         | kind @ ItemKind::Union(..),
1109                     ..
1110                 }),
1111                 true,
1112             )
1113             | (Some(Item { kind, .. }), false) => {
1114                 // Likely missing type parameter.
1115                 if let Some(generics) = kind.generics() {
1116                     if span.overlaps(generics.span) {
1117                         // Avoid the following:
1118                         // error[E0405]: cannot find trait `A` in this scope
1119                         //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1120                         //   |
1121                         // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1122                         //   |           ^- help: you might be missing a type parameter: `, A`
1123                         //   |           |
1124                         //   |           not found in this scope
1125                         return None;
1126                     }
1127                     let msg = "you might be missing a type parameter";
1128                     let (span, sugg) = if let [.., param] = &generics.params[..] {
1129                         let span = if let [.., bound] = &param.bounds[..] {
1130                             bound.span()
1131                         } else {
1132                             param.ident.span
1133                         };
1134                         (span, format!(", {}", ident))
1135                     } else {
1136                         (generics.span, format!("<{}>", ident))
1137                     };
1138                     // Do not suggest if this is coming from macro expansion.
1139                     if !span.from_expansion() {
1140                         return Some((
1141                             span.shrink_to_hi(),
1142                             msg,
1143                             sugg,
1144                             Applicability::MaybeIncorrect,
1145                         ));
1146                     }
1147                 }
1148             }
1149             _ => {}
1150         }
1151         None
1152     }
1153
1154     /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1155     /// optionally returning the closest match and whether it is reachable.
1156     crate fn suggestion_for_label_in_rib(
1157         &self,
1158         rib_index: usize,
1159         label: Ident,
1160     ) -> Option<LabelSuggestion> {
1161         // Are ribs from this `rib_index` within scope?
1162         let within_scope = self.is_label_valid_from_rib(rib_index);
1163
1164         let rib = &self.label_ribs[rib_index];
1165         let names = rib
1166             .bindings
1167             .iter()
1168             .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1169             .map(|(id, _)| &id.name);
1170
1171         find_best_match_for_name(names, label.name, None).map(|symbol| {
1172             // Upon finding a similar name, get the ident that it was from - the span
1173             // contained within helps make a useful diagnostic. In addition, determine
1174             // whether this candidate is within scope.
1175             let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1176             (*ident, within_scope)
1177         })
1178     }
1179 }
1180
1181 impl<'tcx> LifetimeContext<'_, 'tcx> {
1182     crate fn report_missing_lifetime_specifiers(
1183         &self,
1184         span: Span,
1185         count: usize,
1186     ) -> DiagnosticBuilder<'tcx> {
1187         struct_span_err!(
1188             self.tcx.sess,
1189             span,
1190             E0106,
1191             "missing lifetime specifier{}",
1192             pluralize!(count)
1193         )
1194     }
1195
1196     crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1197         let mut err = struct_span_err!(
1198             self.tcx.sess,
1199             lifetime_ref.span,
1200             E0261,
1201             "use of undeclared lifetime name `{}`",
1202             lifetime_ref
1203         );
1204         err.span_label(lifetime_ref.span, "undeclared lifetime");
1205         let mut suggests_in_band = false;
1206         for missing in &self.missing_named_lifetime_spots {
1207             match missing {
1208                 MissingLifetimeSpot::Generics(generics) => {
1209                     let (span, sugg) = if let Some(param) =
1210                         generics.params.iter().find(|p| match p.kind {
1211                             hir::GenericParamKind::Type {
1212                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1213                                 ..
1214                             } => false,
1215                             _ => true,
1216                         }) {
1217                         (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1218                     } else {
1219                         suggests_in_band = true;
1220                         (generics.span, format!("<{}>", lifetime_ref))
1221                     };
1222                     err.span_suggestion(
1223                         span,
1224                         &format!("consider introducing lifetime `{}` here", lifetime_ref),
1225                         sugg,
1226                         Applicability::MaybeIncorrect,
1227                     );
1228                 }
1229                 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1230                     err.span_suggestion(
1231                         *span,
1232                         &format!(
1233                             "consider making the {} lifetime-generic with a new `{}` lifetime",
1234                             span_type.descr(),
1235                             lifetime_ref
1236                         ),
1237                         span_type.suggestion(&lifetime_ref.to_string()),
1238                         Applicability::MaybeIncorrect,
1239                     );
1240                     err.note(
1241                         "for more information on higher-ranked polymorphism, visit \
1242                             https://doc.rust-lang.org/nomicon/hrtb.html",
1243                     );
1244                 }
1245             }
1246         }
1247         if nightly_options::is_nightly_build()
1248             && !self.tcx.features().in_band_lifetimes
1249             && suggests_in_band
1250         {
1251             err.help(
1252                 "if you want to experiment with in-band lifetime bindings, \
1253                     add `#![feature(in_band_lifetimes)]` to the crate attributes",
1254             );
1255         }
1256         err.emit();
1257     }
1258
1259     // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
1260     // generics. We are disallowing this until we can decide on how we want to handle non-'static
1261     // lifetimes in const generics. See issue #74052 for discussion.
1262     crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1263         let mut err = struct_span_err!(
1264             self.tcx.sess,
1265             lifetime_ref.span,
1266             E0771,
1267             "use of non-static lifetime `{}` in const generic",
1268             lifetime_ref
1269         );
1270         err.note(
1271             "for more information, see issue #74052 \
1272             <https://github.com/rust-lang/rust/issues/74052>",
1273         );
1274         err.emit();
1275     }
1276
1277     crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1278         if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1279             if [
1280                 self.tcx.lang_items().fn_once_trait(),
1281                 self.tcx.lang_items().fn_trait(),
1282                 self.tcx.lang_items().fn_mut_trait(),
1283             ]
1284             .contains(&Some(did))
1285             {
1286                 let (span, span_type) = match &trait_ref.bound_generic_params {
1287                     [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1288                     [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1289                 };
1290                 self.missing_named_lifetime_spots
1291                     .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1292                 return true;
1293             }
1294         };
1295         false
1296     }
1297
1298     crate fn add_missing_lifetime_specifiers_label(
1299         &self,
1300         err: &mut DiagnosticBuilder<'_>,
1301         span: Span,
1302         count: usize,
1303         lifetime_names: &FxHashSet<Ident>,
1304         params: &[ElisionFailureInfo],
1305     ) {
1306         let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1307
1308         err.span_label(
1309             span,
1310             &format!(
1311                 "expected {} lifetime parameter{}",
1312                 if count == 1 { "named".to_string() } else { count.to_string() },
1313                 pluralize!(count)
1314             ),
1315         );
1316
1317         let suggest_existing = |err: &mut DiagnosticBuilder<'_>, sugg| {
1318             err.span_suggestion_verbose(
1319                 span,
1320                 &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
1321                 sugg,
1322                 Applicability::MaybeIncorrect,
1323             );
1324         };
1325         let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1326             for missing in self.missing_named_lifetime_spots.iter().rev() {
1327                 let mut introduce_suggestion = vec![];
1328                 let msg;
1329                 let should_break;
1330                 introduce_suggestion.push(match missing {
1331                     MissingLifetimeSpot::Generics(generics) => {
1332                         msg = "consider introducing a named lifetime parameter".to_string();
1333                         should_break = true;
1334                         if let Some(param) = generics.params.iter().find(|p| match p.kind {
1335                             hir::GenericParamKind::Type {
1336                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1337                                 ..
1338                             } => false,
1339                             _ => true,
1340                         }) {
1341                             (param.span.shrink_to_lo(), "'a, ".to_string())
1342                         } else {
1343                             (generics.span, "<'a>".to_string())
1344                         }
1345                     }
1346                     MissingLifetimeSpot::HigherRanked { span, span_type } => {
1347                         msg = format!(
1348                             "consider making the {} lifetime-generic with a new `'a` lifetime",
1349                             span_type.descr(),
1350                         );
1351                         should_break = false;
1352                         err.note(
1353                             "for more information on higher-ranked polymorphism, visit \
1354                             https://doc.rust-lang.org/nomicon/hrtb.html",
1355                         );
1356                         (*span, span_type.suggestion("'a"))
1357                     }
1358                 });
1359                 for param in params {
1360                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1361                         if snippet.starts_with('&') && !snippet.starts_with("&'") {
1362                             introduce_suggestion
1363                                 .push((param.span, format!("&'a {}", &snippet[1..])));
1364                         } else if snippet.starts_with("&'_ ") {
1365                             introduce_suggestion
1366                                 .push((param.span, format!("&'a {}", &snippet[4..])));
1367                         }
1368                     }
1369                 }
1370                 introduce_suggestion.push((span, sugg.to_string()));
1371                 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1372                 if should_break {
1373                     break;
1374                 }
1375             }
1376         };
1377
1378         match (lifetime_names.len(), lifetime_names.iter().next(), snippet.as_deref()) {
1379             (1, Some(name), Some("&")) => {
1380                 suggest_existing(err, format!("&{} ", name));
1381             }
1382             (1, Some(name), Some("'_")) => {
1383                 suggest_existing(err, name.to_string());
1384             }
1385             (1, Some(name), Some("")) => {
1386                 suggest_existing(err, format!("{}, ", name).repeat(count));
1387             }
1388             (1, Some(name), Some(snippet)) if !snippet.ends_with('>') => {
1389                 suggest_existing(
1390                     err,
1391                     format!(
1392                         "{}<{}>",
1393                         snippet,
1394                         std::iter::repeat(name.to_string())
1395                             .take(count)
1396                             .collect::<Vec<_>>()
1397                             .join(", ")
1398                     ),
1399                 );
1400             }
1401             (0, _, Some("&")) if count == 1 => {
1402                 suggest_new(err, "&'a ");
1403             }
1404             (0, _, Some("'_")) if count == 1 => {
1405                 suggest_new(err, "'a");
1406             }
1407             (0, _, Some(snippet)) if !snippet.ends_with('>') && count == 1 => {
1408                 suggest_new(err, &format!("{}<'a>", snippet));
1409             }
1410             (n, ..) if n > 1 => {
1411                 let spans: Vec<Span> = lifetime_names.iter().map(|lt| lt.span).collect();
1412                 err.span_note(spans, "these named lifetimes are available to use");
1413                 if Some("") == snippet.as_deref() {
1414                     // This happens when we have `Foo<T>` where we point at the space before `T`,
1415                     // but this can be confusing so we give a suggestion with placeholders.
1416                     err.span_suggestion_verbose(
1417                         span,
1418                         "consider using one of the available lifetimes here",
1419                         "'lifetime, ".repeat(count),
1420                         Applicability::HasPlaceholders,
1421                     );
1422                 }
1423             }
1424             _ => {}
1425         }
1426     }
1427 }