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