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