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