]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/late/diagnostics.rs
Detect bare blocks with type ascription that were meant to be a `struct` literal
[rust.git] / compiler / rustc_resolve / src / late / diagnostics.rs
1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, 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::visit::FnKind;
9 use rustc_ast::{
10     self as ast, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind, NodeId, Path, Ty,
11     TyKind,
12 };
13 use rustc_ast_pretty::pprust::path_segment_to_string;
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, SuggestionStyle};
16 use rustc_hir as hir;
17 use rustc_hir::def::Namespace::{self, *};
18 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
19 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
20 use rustc_hir::PrimTy;
21 use rustc_session::parse::feature_err;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::MacroKind;
24 use rustc_span::lev_distance::find_best_match_for_name;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
27
28 use std::iter;
29
30 use tracing::debug;
31
32 type Res = def::Res<ast::NodeId>;
33
34 /// A field or associated item from self type suggested in case of resolution failure.
35 enum AssocSuggestion {
36     Field,
37     MethodWithSelf,
38     AssocFn,
39     AssocType,
40     AssocConst,
41 }
42
43 impl AssocSuggestion {
44     fn action(&self) -> &'static str {
45         match self {
46             AssocSuggestion::Field => "use the available field",
47             AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
48             AssocSuggestion::AssocFn => "call the associated function",
49             AssocSuggestion::AssocConst => "use the associated `const`",
50             AssocSuggestion::AssocType => "use the associated type",
51         }
52     }
53 }
54
55 crate enum MissingLifetimeSpot<'tcx> {
56     Generics(&'tcx hir::Generics<'tcx>),
57     HigherRanked { span: Span, span_type: ForLifetimeSpanType },
58     Static,
59 }
60
61 crate enum ForLifetimeSpanType {
62     BoundEmpty,
63     BoundTail,
64     TypeEmpty,
65     TypeTail,
66 }
67
68 impl ForLifetimeSpanType {
69     crate fn descr(&self) -> &'static str {
70         match self {
71             Self::BoundEmpty | Self::BoundTail => "bound",
72             Self::TypeEmpty | Self::TypeTail => "type",
73         }
74     }
75
76     crate fn suggestion(&self, sugg: &str) -> String {
77         match self {
78             Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
79             Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
80         }
81     }
82 }
83
84 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
85     fn into(self) -> MissingLifetimeSpot<'tcx> {
86         MissingLifetimeSpot::Generics(self)
87     }
88 }
89
90 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
91     namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
92 }
93
94 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
95     namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
96 }
97
98 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
99 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
100     let variant_path = &suggestion.path;
101     let variant_path_string = path_names_to_string(variant_path);
102
103     let path_len = suggestion.path.segments.len();
104     let enum_path = ast::Path {
105         span: suggestion.path.span,
106         segments: suggestion.path.segments[0..path_len - 1].to_vec(),
107         tokens: None,
108     };
109     let enum_path_string = path_names_to_string(&enum_path);
110
111     (variant_path_string, enum_path_string)
112 }
113
114 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
115     fn def_span(&self, def_id: DefId) -> Option<Span> {
116         match def_id.krate {
117             LOCAL_CRATE => self.r.opt_span(def_id),
118             _ => Some(
119                 self.r
120                     .session
121                     .source_map()
122                     .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
123             ),
124         }
125     }
126
127     /// Handles error reporting for `smart_resolve_path_fragment` function.
128     /// Creates base error and amends it with one short label and possibly some longer helps/notes.
129     pub(crate) fn smart_resolve_report_errors(
130         &mut self,
131         path: &[Segment],
132         span: Span,
133         source: PathSource<'_>,
134         res: Option<Res>,
135     ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
136         let ident_span = path.last().map_or(span, |ident| ident.ident.span);
137         let ns = source.namespace();
138         let is_expected = &|res| source.is_expected(res);
139         let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
140
141         // Make the base error.
142         let mut expected = source.descr_expected();
143         let path_str = Segment::names_to_string(path);
144         let item_str = path.last().unwrap().ident;
145         let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
146             (
147                 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
148                 format!("not a {}", expected),
149                 span,
150                 match res {
151                     Res::Def(DefKind::Fn, _) => {
152                         // Verify whether this is a fn call or an Fn used as a type.
153                         self.r
154                             .session
155                             .source_map()
156                             .span_to_snippet(span)
157                             .map(|snippet| snippet.ends_with(')'))
158                             .unwrap_or(false)
159                     }
160                     Res::Def(
161                         DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
162                         _,
163                     )
164                     | Res::SelfCtor(_)
165                     | Res::PrimTy(_)
166                     | Res::Local(_) => true,
167                     _ => false,
168                 },
169             )
170         } else {
171             let item_span = path.last().unwrap().ident.span;
172             let (mod_prefix, mod_str) = if path.len() == 1 {
173                 (String::new(), "this scope".to_string())
174             } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
175                 if self.r.session.edition() > Edition::Edition2015 {
176                     // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
177                     // which overrides all other expectations of item type
178                     expected = "crate";
179                     (String::new(), "the list of imported crates".to_string())
180                 } else {
181                     (String::new(), "the crate root".to_string())
182                 }
183             } else if path.len() == 2 && path[0].ident.name == kw::Crate {
184                 (String::new(), "the crate root".to_string())
185             } else {
186                 let mod_path = &path[..path.len() - 1];
187                 let mod_prefix =
188                     match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
189                         PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
190                         _ => None,
191                     }
192                     .map_or_else(String::new, |res| format!("{} ", res.descr()));
193                 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
194             };
195             (
196                 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
197                 if path_str == "async" && expected.starts_with("struct") {
198                     "`async` blocks are only allowed in Rust 2018 or later".to_string()
199                 } else {
200                     format!("not found in {}", mod_str)
201                 },
202                 item_span,
203                 false,
204             )
205         };
206
207         let code = source.error_code(res.is_some());
208         let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
209
210         if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
211             err.multipart_suggestion(
212                 "you might have meant to write a `struct` literal",
213                 vec![
214                     (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
215                     (span.shrink_to_hi(), "}".to_string()),
216                 ],
217                 Applicability::HasPlaceholders,
218             );
219         }
220         match (source, self.diagnostic_metadata.in_if_condition) {
221             (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
222                 err.span_suggestion_verbose(
223                     span.shrink_to_lo(),
224                     "you might have meant to use pattern matching",
225                     "let ".to_string(),
226                     Applicability::MaybeIncorrect,
227                 );
228             }
229             _ => {}
230         }
231
232         let is_assoc_fn = self.self_type_is_available(span);
233         // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
234         if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
235             err.span_suggestion_short(
236                 span,
237                 "you might have meant to use `self` here instead",
238                 "self".to_string(),
239                 Applicability::MaybeIncorrect,
240             );
241             if !self.self_value_is_available(path[0].ident.span, span) {
242                 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
243                     &self.diagnostic_metadata.current_function
244                 {
245                     let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
246                         (param.span.shrink_to_lo(), "&self, ")
247                     } else {
248                         (
249                             self.r
250                                 .session
251                                 .source_map()
252                                 .span_through_char(*fn_span, '(')
253                                 .shrink_to_hi(),
254                             "&self",
255                         )
256                     };
257                     err.span_suggestion_verbose(
258                         span,
259                         "if you meant to use `self`, you are also missing a `self` receiver \
260                          argument",
261                         sugg.to_string(),
262                         Applicability::MaybeIncorrect,
263                     );
264                 }
265             }
266         }
267
268         // Emit special messages for unresolved `Self` and `self`.
269         if is_self_type(path, ns) {
270             err.code(rustc_errors::error_code!(E0411));
271             err.span_label(
272                 span,
273                 "`Self` is only available in impls, traits, and type definitions".to_string(),
274             );
275             return (err, Vec::new());
276         }
277         if is_self_value(path, ns) {
278             debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
279
280             err.code(rustc_errors::error_code!(E0424));
281             err.span_label(span, match source {
282                 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
283                                    .to_string(),
284                 _ => "`self` value is a keyword only available in methods with a `self` parameter"
285                      .to_string(),
286             });
287             if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
288                 // The current function has a `self' parameter, but we were unable to resolve
289                 // a reference to `self`. This can only happen if the `self` identifier we
290                 // are resolving came from a different hygiene context.
291                 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
292                     err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
293                 } else {
294                     let doesnt = if is_assoc_fn {
295                         let (span, sugg) = fn_kind
296                             .decl()
297                             .inputs
298                             .get(0)
299                             .map(|p| (p.span.shrink_to_lo(), "&self, "))
300                             .unwrap_or_else(|| {
301                                 (
302                                     self.r
303                                         .session
304                                         .source_map()
305                                         .span_through_char(*span, '(')
306                                         .shrink_to_hi(),
307                                     "&self",
308                                 )
309                             });
310                         err.span_suggestion_verbose(
311                             span,
312                             "add a `self` receiver parameter to make the associated `fn` a method",
313                             sugg.to_string(),
314                             Applicability::MaybeIncorrect,
315                         );
316                         "doesn't"
317                     } else {
318                         "can't"
319                     };
320                     if let Some(ident) = fn_kind.ident() {
321                         err.span_label(
322                             ident.span,
323                             &format!("this function {} have a `self` parameter", doesnt),
324                         );
325                     }
326                 }
327             }
328             return (err, Vec::new());
329         }
330
331         // Try to lookup name in more relaxed fashion for better error reporting.
332         let ident = path.last().unwrap().ident;
333         let candidates = self
334             .r
335             .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
336             .drain(..)
337             .filter(|ImportSuggestion { did, .. }| {
338                 match (did, res.and_then(|res| res.opt_def_id())) {
339                     (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
340                     _ => true,
341                 }
342             })
343             .collect::<Vec<_>>();
344         let crate_def_id = DefId::local(CRATE_DEF_INDEX);
345         if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
346             let mut enum_candidates: Vec<_> = self
347                 .r
348                 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
349                 .into_iter()
350                 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
351                 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
352                 .collect();
353             if !enum_candidates.is_empty() {
354                 if let (PathSource::Type, Some(span)) =
355                     (source, self.diagnostic_metadata.current_type_ascription.last())
356                 {
357                     if self
358                         .r
359                         .session
360                         .parse_sess
361                         .type_ascription_path_suggestions
362                         .borrow()
363                         .contains(span)
364                     {
365                         // Already reported this issue on the lhs of the type ascription.
366                         err.delay_as_bug();
367                         return (err, candidates);
368                     }
369                 }
370
371                 enum_candidates.sort();
372
373                 // Contextualize for E0412 "cannot find type", but don't belabor the point
374                 // (that it's a variant) for E0573 "expected type, found variant".
375                 let preamble = if res.is_none() {
376                     let others = match enum_candidates.len() {
377                         1 => String::new(),
378                         2 => " and 1 other".to_owned(),
379                         n => format!(" and {} others", n),
380                     };
381                     format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
382                 } else {
383                     String::new()
384                 };
385                 let msg = format!("{}try using the variant's enum", preamble);
386
387                 err.span_suggestions(
388                     span,
389                     &msg,
390                     enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
391                     Applicability::MachineApplicable,
392                 );
393             }
394         }
395         if path.len() == 1 && self.self_type_is_available(span) {
396             if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
397                 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
398                 match candidate {
399                     AssocSuggestion::Field => {
400                         if self_is_available {
401                             err.span_suggestion(
402                                 span,
403                                 "you might have meant to use the available field",
404                                 format!("self.{}", path_str),
405                                 Applicability::MachineApplicable,
406                             );
407                         } else {
408                             err.span_label(span, "a field by this name exists in `Self`");
409                         }
410                     }
411                     AssocSuggestion::MethodWithSelf if self_is_available => {
412                         err.span_suggestion(
413                             span,
414                             "you might have meant to call the method",
415                             format!("self.{}", path_str),
416                             Applicability::MachineApplicable,
417                         );
418                     }
419                     AssocSuggestion::MethodWithSelf
420                     | AssocSuggestion::AssocFn
421                     | AssocSuggestion::AssocConst
422                     | AssocSuggestion::AssocType => {
423                         err.span_suggestion(
424                             span,
425                             &format!("you might have meant to {}", candidate.action()),
426                             format!("Self::{}", path_str),
427                             Applicability::MachineApplicable,
428                         );
429                     }
430                 }
431                 return (err, candidates);
432             }
433
434             // If the first argument in call is `self` suggest calling a method.
435             if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
436                 let mut args_snippet = String::new();
437                 if let Some(args_span) = args_span {
438                     if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
439                         args_snippet = snippet;
440                     }
441                 }
442
443                 err.span_suggestion(
444                     call_span,
445                     &format!("try calling `{}` as a method", ident),
446                     format!("self.{}({})", path_str, args_snippet),
447                     Applicability::MachineApplicable,
448                 );
449                 return (err, candidates);
450             }
451         }
452
453         // Try Levenshtein algorithm.
454         let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
455         // Try context-dependent help if relaxed lookup didn't work.
456         if let Some(res) = res {
457             if self.smart_resolve_context_dependent_help(
458                 &mut err,
459                 span,
460                 source,
461                 res,
462                 &path_str,
463                 &fallback_label,
464             ) {
465                 // We do this to avoid losing a secondary span when we override the main error span.
466                 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
467                 return (err, candidates);
468             }
469         }
470
471         let is_macro = base_span.from_expansion() && base_span.desugaring_kind().is_none();
472         if !self.type_ascription_suggestion(&mut err, base_span) {
473             let mut fallback = false;
474             if let (
475                 PathSource::Trait(AliasPossibility::Maybe),
476                 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
477                 false,
478             ) = (source, res, is_macro)
479             {
480                 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
481                     fallback = true;
482                     let spans: Vec<Span> = bounds
483                         .iter()
484                         .map(|bound| bound.span())
485                         .filter(|&sp| sp != base_span)
486                         .collect();
487
488                     let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
489                     // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
490                     let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
491                     // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
492                     let last_bound_span = spans.last().cloned().unwrap();
493                     let mut multi_span: MultiSpan = spans.clone().into();
494                     for sp in spans {
495                         let msg = if sp == last_bound_span {
496                             format!(
497                                 "...because of {} bound{}",
498                                 if bounds.len() <= 2 { "this" } else { "these" },
499                                 if bounds.len() <= 2 { "" } else { "s" },
500                             )
501                         } else {
502                             String::new()
503                         };
504                         multi_span.push_span_label(sp, msg);
505                     }
506                     multi_span.push_span_label(
507                         base_span,
508                         "expected this type to be a trait...".to_string(),
509                     );
510                     err.span_help(
511                         multi_span,
512                         "`+` is used to constrain a \"trait object\" type with lifetimes or \
513                          auto-traits; structs and enums can't be bound in that way",
514                     );
515                     if bounds.iter().all(|bound| match bound {
516                         ast::GenericBound::Outlives(_) => true,
517                         ast::GenericBound::Trait(tr, _) => tr.span == base_span,
518                     }) {
519                         let mut sugg = vec![];
520                         if base_span != start_span {
521                             sugg.push((start_span.until(base_span), String::new()));
522                         }
523                         if base_span != end_span {
524                             sugg.push((base_span.shrink_to_hi().to(end_span), String::new()));
525                         }
526
527                         err.multipart_suggestion(
528                             "if you meant to use a type and not a trait here, remove the bounds",
529                             sugg,
530                             Applicability::MaybeIncorrect,
531                         );
532                     }
533                 }
534             }
535
536             fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
537
538             if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
539                 fallback = true;
540                 match self.diagnostic_metadata.current_let_binding {
541                     Some((pat_sp, Some(ty_sp), None))
542                         if ty_sp.contains(base_span) && could_be_expr =>
543                     {
544                         err.span_suggestion_short(
545                             pat_sp.between(ty_sp),
546                             "use `=` if you meant to assign",
547                             " = ".to_string(),
548                             Applicability::MaybeIncorrect,
549                         );
550                     }
551                     _ => {}
552                 }
553
554                 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
555                 let suggestion = self.get_single_associated_item(&path, span, &source, is_expected);
556                 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
557             }
558             if fallback {
559                 // Fallback label.
560                 err.span_label(base_span, fallback_label);
561             }
562         }
563         if let Some(err_code) = &err.code {
564             if err_code == &rustc_errors::error_code!(E0425) {
565                 for label_rib in &self.label_ribs {
566                     for (label_ident, node_id) in &label_rib.bindings {
567                         if format!("'{}", ident) == label_ident.to_string() {
568                             err.span_label(label_ident.span, "a label with a similar name exists");
569                             if let PathSource::Expr(Some(Expr {
570                                 kind: ExprKind::Break(None, Some(_)),
571                                 ..
572                             })) = source
573                             {
574                                 err.span_suggestion(
575                                     span,
576                                     "use the similarly named label",
577                                     label_ident.name.to_string(),
578                                     Applicability::MaybeIncorrect,
579                                 );
580                                 // Do not lint against unused label when we suggest them.
581                                 self.diagnostic_metadata.unused_labels.remove(node_id);
582                             }
583                         }
584                     }
585                 }
586             } else if err_code == &rustc_errors::error_code!(E0412) {
587                 if let Some(correct) = Self::likely_rust_type(path) {
588                     err.span_suggestion(
589                         span,
590                         "perhaps you intended to use this type",
591                         correct.to_string(),
592                         Applicability::MaybeIncorrect,
593                     );
594                 }
595             }
596         }
597
598         (err, candidates)
599     }
600
601     fn get_single_associated_item(
602         &mut self,
603         path: &[Segment],
604         span: Span,
605         source: &PathSource<'_>,
606         filter_fn: &impl Fn(Res) -> bool,
607     ) -> Option<TypoSuggestion> {
608         if let crate::PathSource::TraitItem(_) = source {
609             let mod_path = &path[..path.len() - 1];
610             if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
611                 self.resolve_path(mod_path, None, false, span, CrateLint::No)
612             {
613                 let resolutions = self.r.resolutions(module).borrow();
614                 let targets: Vec<_> =
615                     resolutions
616                         .iter()
617                         .filter_map(|(key, resolution)| {
618                             resolution.borrow().binding.map(|binding| binding.res()).and_then(
619                                 |res| if filter_fn(res) { Some((key, res)) } else { None },
620                             )
621                         })
622                         .collect();
623                 if targets.len() == 1 {
624                     let target = targets[0];
625                     return Some(TypoSuggestion::single_item_from_res(
626                         target.0.ident.name,
627                         target.1,
628                     ));
629                 }
630             }
631         }
632         None
633     }
634
635     /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
636     fn restrict_assoc_type_in_where_clause(
637         &mut self,
638         span: Span,
639         err: &mut DiagnosticBuilder<'_>,
640     ) -> bool {
641         // Detect that we are actually in a `where` predicate.
642         let (bounded_ty, bounds, where_span) =
643             if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
644                 bounded_ty,
645                 bound_generic_params,
646                 bounds,
647                 span,
648             })) = self.diagnostic_metadata.current_where_predicate
649             {
650                 if !bound_generic_params.is_empty() {
651                     return false;
652                 }
653                 (bounded_ty, bounds, span)
654             } else {
655                 return false;
656             };
657
658         // Confirm that the target is an associated type.
659         let (ty, position, path) = if let ast::TyKind::Path(
660             Some(ast::QSelf { ty, position, .. }),
661             path,
662         ) = &bounded_ty.kind
663         {
664             // use this to verify that ident is a type param.
665             let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
666                 bounded_ty.id,
667                 None,
668                 &Segment::from_path(path),
669                 Namespace::TypeNS,
670                 span,
671                 true,
672                 CrateLint::No,
673             ) {
674                 partial_res
675             } else {
676                 return false;
677             };
678             if !(matches!(
679                 partial_res.base_res(),
680                 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
681             ) && partial_res.unresolved_segments() == 0)
682             {
683                 return false;
684             }
685             (ty, position, path)
686         } else {
687             return false;
688         };
689
690         if let ast::TyKind::Path(None, type_param_path) = &ty.peel_refs().kind {
691             // Confirm that the `SelfTy` is a type parameter.
692             let partial_res = if let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
693                 bounded_ty.id,
694                 None,
695                 &Segment::from_path(type_param_path),
696                 Namespace::TypeNS,
697                 span,
698                 true,
699                 CrateLint::No,
700             ) {
701                 partial_res
702             } else {
703                 return false;
704             };
705             if !(matches!(
706                 partial_res.base_res(),
707                 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
708             ) && partial_res.unresolved_segments() == 0)
709             {
710                 return false;
711             }
712             if let (
713                 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
714                 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
715             ) = (&type_param_path.segments[..], &bounds[..])
716             {
717                 if let [ast::PathSegment { ident, args: None, .. }] =
718                     &poly_trait_ref.trait_ref.path.segments[..]
719                 {
720                     if ident.span == span {
721                         err.span_suggestion_verbose(
722                             *where_span,
723                             &format!("constrain the associated type to `{}`", ident),
724                             format!(
725                                 "{}: {}<{} = {}>",
726                                 self.r
727                                     .session
728                                     .source_map()
729                                     .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
730                                     .unwrap_or_else(|_| constrain_ident.to_string()),
731                                 path.segments[..*position]
732                                     .iter()
733                                     .map(|segment| path_segment_to_string(segment))
734                                     .collect::<Vec<_>>()
735                                     .join("::"),
736                                 path.segments[*position..]
737                                     .iter()
738                                     .map(|segment| path_segment_to_string(segment))
739                                     .collect::<Vec<_>>()
740                                     .join("::"),
741                                 ident,
742                             ),
743                             Applicability::MaybeIncorrect,
744                         );
745                     }
746                     return true;
747                 }
748             }
749         }
750         false
751     }
752
753     /// Check if the source is call expression and the first argument is `self`. If true,
754     /// return the span of whole call and the span for all arguments expect the first one (`self`).
755     fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
756         let mut has_self_arg = None;
757         if let PathSource::Expr(Some(parent)) = source {
758             match &parent.kind {
759                 ExprKind::Call(_, args) if !args.is_empty() => {
760                     let mut expr_kind = &args[0].kind;
761                     loop {
762                         match expr_kind {
763                             ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
764                                 if arg_name.segments[0].ident.name == kw::SelfLower {
765                                     let call_span = parent.span;
766                                     let tail_args_span = if args.len() > 1 {
767                                         Some(Span::new(
768                                             args[1].span.lo(),
769                                             args.last().unwrap().span.hi(),
770                                             call_span.ctxt(),
771                                         ))
772                                     } else {
773                                         None
774                                     };
775                                     has_self_arg = Some((call_span, tail_args_span));
776                                 }
777                                 break;
778                             }
779                             ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
780                             _ => break,
781                         }
782                     }
783                 }
784                 _ => (),
785             }
786         };
787         has_self_arg
788     }
789
790     fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
791         // HACK(estebank): find a better way to figure out that this was a
792         // parser issue where a struct literal is being used on an expression
793         // where a brace being opened means a block is being started. Look
794         // ahead for the next text to see if `span` is followed by a `{`.
795         let sm = self.r.session.source_map();
796         let mut sp = span;
797         loop {
798             sp = sm.next_point(sp);
799             match sm.span_to_snippet(sp) {
800                 Ok(ref snippet) => {
801                     if snippet.chars().any(|c| !c.is_whitespace()) {
802                         break;
803                     }
804                 }
805                 _ => break,
806             }
807         }
808         let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
809         // In case this could be a struct literal that needs to be surrounded
810         // by parentheses, find the appropriate span.
811         let mut i = 0;
812         let mut closing_brace = None;
813         loop {
814             sp = sm.next_point(sp);
815             match sm.span_to_snippet(sp) {
816                 Ok(ref snippet) => {
817                     if snippet == "}" {
818                         closing_brace = Some(span.to(sp));
819                         break;
820                     }
821                 }
822                 _ => break,
823             }
824             i += 1;
825             // The bigger the span, the more likely we're incorrect --
826             // bound it to 100 chars long.
827             if i > 100 {
828                 break;
829             }
830         }
831         (followed_by_brace, closing_brace)
832     }
833
834     /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
835     /// function.
836     /// Returns `true` if able to provide context-dependent help.
837     fn smart_resolve_context_dependent_help(
838         &mut self,
839         err: &mut DiagnosticBuilder<'a>,
840         span: Span,
841         source: PathSource<'_>,
842         res: Res,
843         path_str: &str,
844         fallback_label: &str,
845     ) -> bool {
846         let ns = source.namespace();
847         let is_expected = &|res| source.is_expected(res);
848
849         let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
850             ExprKind::Field(_, ident) => {
851                 err.span_suggestion(
852                     expr.span,
853                     "use the path separator to refer to an item",
854                     format!("{}::{}", path_str, ident),
855                     Applicability::MaybeIncorrect,
856                 );
857                 true
858             }
859             ExprKind::MethodCall(ref segment, ..) => {
860                 let span = expr.span.with_hi(segment.ident.span.hi());
861                 err.span_suggestion(
862                     span,
863                     "use the path separator to refer to an item",
864                     format!("{}::{}", path_str, segment.ident),
865                     Applicability::MaybeIncorrect,
866                 );
867                 true
868             }
869             _ => false,
870         };
871
872         let find_span = |source: &PathSource<'_>, err: &mut DiagnosticBuilder<'_>| {
873             match source {
874                 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
875                 | PathSource::TupleStruct(span, _) => {
876                     // We want the main underline to cover the suggested code as well for
877                     // cleaner output.
878                     err.set_span(*span);
879                     *span
880                 }
881                 _ => span,
882             }
883         };
884
885         let mut bad_struct_syntax_suggestion = |def_id: DefId| {
886             let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
887
888             match source {
889                 PathSource::Expr(Some(
890                     parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
891                 )) if path_sep(err, &parent) => {}
892                 PathSource::Expr(
893                     None
894                     | Some(Expr {
895                         kind:
896                             ExprKind::Path(..)
897                             | ExprKind::Binary(..)
898                             | ExprKind::Unary(..)
899                             | ExprKind::If(..)
900                             | ExprKind::While(..)
901                             | ExprKind::ForLoop(..)
902                             | ExprKind::Match(..),
903                         ..
904                     }),
905                 ) if followed_by_brace => {
906                     if let Some(sp) = closing_brace {
907                         err.span_label(span, fallback_label);
908                         err.multipart_suggestion(
909                             "surround the struct literal with parentheses",
910                             vec![
911                                 (sp.shrink_to_lo(), "(".to_string()),
912                                 (sp.shrink_to_hi(), ")".to_string()),
913                             ],
914                             Applicability::MaybeIncorrect,
915                         );
916                     } else {
917                         err.span_label(
918                             span, // Note the parentheses surrounding the suggestion below
919                             format!(
920                                 "you might want to surround a struct literal with parentheses: \
921                                  `({} {{ /* fields */ }})`?",
922                                 path_str
923                             ),
924                         );
925                     }
926                 }
927                 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
928                     let span = find_span(&source, err);
929                     if let Some(span) = self.def_span(def_id) {
930                         err.span_label(span, &format!("`{}` defined here", path_str));
931                     }
932                     let (tail, descr, applicability) = match source {
933                         PathSource::Pat | PathSource::TupleStruct(..) => {
934                             ("", "pattern", Applicability::MachineApplicable)
935                         }
936                         _ => (": val", "literal", Applicability::HasPlaceholders),
937                     };
938                     let (fields, applicability) = match self.r.field_names.get(&def_id) {
939                         Some(fields) => (
940                             fields
941                                 .iter()
942                                 .map(|f| format!("{}{}", f.node, tail))
943                                 .collect::<Vec<String>>()
944                                 .join(", "),
945                             applicability,
946                         ),
947                         None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
948                     };
949                     let pad = match self.r.field_names.get(&def_id) {
950                         Some(fields) if fields.is_empty() => "",
951                         _ => " ",
952                     };
953                     err.span_suggestion(
954                         span,
955                         &format!("use struct {} syntax instead", descr),
956                         format!("{path_str} {{{pad}{fields}{pad}}}"),
957                         applicability,
958                     );
959                 }
960                 _ => {
961                     err.span_label(span, fallback_label);
962                 }
963             }
964         };
965
966         match (res, source) {
967             (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
968                 err.span_label(span, fallback_label);
969                 err.span_suggestion_verbose(
970                     span.shrink_to_hi(),
971                     "use `!` to invoke the macro",
972                     "!".to_string(),
973                     Applicability::MaybeIncorrect,
974                 );
975                 if path_str == "try" && span.rust_2015() {
976                     err.note("if you want the `try` keyword, you need Rust 2018 or later");
977                 }
978             }
979             (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
980                 err.span_label(span, "type aliases cannot be used as traits");
981                 if self.r.session.is_nightly_build() {
982                     let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
983                                `type` alias";
984                     if let Some(span) = self.def_span(def_id) {
985                         if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
986                             // The span contains a type alias so we should be able to
987                             // replace `type` with `trait`.
988                             let snip = snip.replacen("type", "trait", 1);
989                             err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
990                         } else {
991                             err.span_help(span, msg);
992                         }
993                     } else {
994                         err.help(msg);
995                     }
996                 }
997             }
998             (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
999                 if !path_sep(err, &parent) {
1000                     return false;
1001                 }
1002             }
1003             (
1004                 Res::Def(DefKind::Enum, def_id),
1005                 PathSource::TupleStruct(..) | PathSource::Expr(..),
1006             ) => {
1007                 if self
1008                     .diagnostic_metadata
1009                     .current_type_ascription
1010                     .last()
1011                     .map(|sp| {
1012                         self.r
1013                             .session
1014                             .parse_sess
1015                             .type_ascription_path_suggestions
1016                             .borrow()
1017                             .contains(&sp)
1018                     })
1019                     .unwrap_or(false)
1020                 {
1021                     err.delay_as_bug();
1022                     // We already suggested changing `:` into `::` during parsing.
1023                     return false;
1024                 }
1025
1026                 self.suggest_using_enum_variant(err, source, def_id, span);
1027             }
1028             (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
1029                 let (ctor_def, ctor_vis, fields) =
1030                     if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1031                         struct_ctor
1032                     } else {
1033                         bad_struct_syntax_suggestion(def_id);
1034                         return true;
1035                     };
1036
1037                 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1038                 if !is_expected(ctor_def) || is_accessible {
1039                     return true;
1040                 }
1041
1042                 let field_spans = match source {
1043                     // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1044                     PathSource::TupleStruct(_, pattern_spans) => {
1045                         err.set_primary_message(
1046                             "cannot match against a tuple struct which contains private fields",
1047                         );
1048
1049                         // Use spans of the tuple struct pattern.
1050                         Some(Vec::from(pattern_spans))
1051                     }
1052                     // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1053                     _ if source.is_call() => {
1054                         err.set_primary_message(
1055                             "cannot initialize a tuple struct which contains private fields",
1056                         );
1057
1058                         // Use spans of the tuple struct definition.
1059                         self.r
1060                             .field_names
1061                             .get(&def_id)
1062                             .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1063                     }
1064                     _ => None,
1065                 };
1066
1067                 if let Some(spans) =
1068                     field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1069                 {
1070                     let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1071                         .filter(|(vis, _)| {
1072                             !self.r.is_accessible_from(**vis, self.parent_scope.module)
1073                         })
1074                         .map(|(_, span)| *span)
1075                         .collect();
1076
1077                     if non_visible_spans.len() > 0 {
1078                         let mut m: rustc_span::MultiSpan = non_visible_spans.clone().into();
1079                         non_visible_spans
1080                             .into_iter()
1081                             .for_each(|s| m.push_span_label(s, "private field".to_string()));
1082                         err.span_note(m, "constructor is not visible here due to private fields");
1083                     }
1084
1085                     return true;
1086                 }
1087
1088                 err.span_label(
1089                     span,
1090                     "constructor is not visible here due to private fields".to_string(),
1091                 );
1092             }
1093             (
1094                 Res::Def(
1095                     DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1096                     def_id,
1097                 ),
1098                 _,
1099             ) if ns == ValueNS => {
1100                 bad_struct_syntax_suggestion(def_id);
1101             }
1102             (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1103                 match source {
1104                     PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1105                         let span = find_span(&source, err);
1106                         if let Some(span) = self.def_span(def_id) {
1107                             err.span_label(span, &format!("`{}` defined here", path_str));
1108                         }
1109                         err.span_suggestion(
1110                             span,
1111                             &"use this syntax instead",
1112                             format!("{path_str}"),
1113                             Applicability::MaybeIncorrect,
1114                         );
1115                     }
1116                     _ => return false,
1117                 }
1118             }
1119             (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1120                 if let Some(span) = self.def_span(def_id) {
1121                     err.span_label(span, &format!("`{}` defined here", path_str));
1122                 }
1123                 let fields = self.r.field_names.get(&def_id).map_or_else(
1124                     || "/* fields */".to_string(),
1125                     |fields| vec!["_"; fields.len()].join(", "),
1126                 );
1127                 err.span_suggestion(
1128                     span,
1129                     "use the tuple variant pattern syntax instead",
1130                     format!("{}({})", path_str, fields),
1131                     Applicability::HasPlaceholders,
1132                 );
1133             }
1134             (Res::SelfTy(..), _) if ns == ValueNS => {
1135                 err.span_label(span, fallback_label);
1136                 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1137             }
1138             (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1139                 err.note("can't use a type alias as a constructor");
1140             }
1141             _ => return false,
1142         }
1143         true
1144     }
1145
1146     fn lookup_assoc_candidate<FilterFn>(
1147         &mut self,
1148         ident: Ident,
1149         ns: Namespace,
1150         filter_fn: FilterFn,
1151     ) -> Option<AssocSuggestion>
1152     where
1153         FilterFn: Fn(Res) -> bool,
1154     {
1155         fn extract_node_id(t: &Ty) -> Option<NodeId> {
1156             match t.kind {
1157                 TyKind::Path(None, _) => Some(t.id),
1158                 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1159                 // This doesn't handle the remaining `Ty` variants as they are not
1160                 // that commonly the self_type, it might be interesting to provide
1161                 // support for those in future.
1162                 _ => None,
1163             }
1164         }
1165
1166         // Fields are generally expected in the same contexts as locals.
1167         if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1168             if let Some(node_id) =
1169                 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1170             {
1171                 // Look for a field with the same name in the current self_type.
1172                 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1173                     match resolution.base_res() {
1174                         Res::Def(DefKind::Struct | DefKind::Union, did)
1175                             if resolution.unresolved_segments() == 0 =>
1176                         {
1177                             if let Some(field_names) = self.r.field_names.get(&did) {
1178                                 if field_names
1179                                     .iter()
1180                                     .any(|&field_name| ident.name == field_name.node)
1181                                 {
1182                                     return Some(AssocSuggestion::Field);
1183                                 }
1184                             }
1185                         }
1186                         _ => {}
1187                     }
1188                 }
1189             }
1190         }
1191
1192         if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1193             for assoc_item in items {
1194                 if assoc_item.ident == ident {
1195                     return Some(match &assoc_item.kind {
1196                         ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1197                         ast::AssocItemKind::Fn(box ast::FnKind(_, sig, ..))
1198                             if sig.decl.has_self() =>
1199                         {
1200                             AssocSuggestion::MethodWithSelf
1201                         }
1202                         ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1203                         ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1204                         ast::AssocItemKind::MacCall(_) => continue,
1205                     });
1206                 }
1207             }
1208         }
1209
1210         // Look for associated items in the current trait.
1211         if let Some((module, _)) = self.current_trait_ref {
1212             if let Ok(binding) = self.r.resolve_ident_in_module(
1213                 ModuleOrUniformRoot::Module(module),
1214                 ident,
1215                 ns,
1216                 &self.parent_scope,
1217                 false,
1218                 module.span,
1219             ) {
1220                 let res = binding.res();
1221                 if filter_fn(res) {
1222                     if self.r.has_self.contains(&res.def_id()) {
1223                         return Some(AssocSuggestion::MethodWithSelf);
1224                     } else {
1225                         match res {
1226                             Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1227                             Res::Def(DefKind::AssocConst, _) => {
1228                                 return Some(AssocSuggestion::AssocConst);
1229                             }
1230                             Res::Def(DefKind::AssocTy, _) => {
1231                                 return Some(AssocSuggestion::AssocType);
1232                             }
1233                             _ => {}
1234                         }
1235                     }
1236                 }
1237             }
1238         }
1239
1240         None
1241     }
1242
1243     fn lookup_typo_candidate(
1244         &mut self,
1245         path: &[Segment],
1246         ns: Namespace,
1247         filter_fn: &impl Fn(Res) -> bool,
1248         span: Span,
1249     ) -> Option<TypoSuggestion> {
1250         let mut names = Vec::new();
1251         if path.len() == 1 {
1252             // Search in lexical scope.
1253             // Walk backwards up the ribs in scope and collect candidates.
1254             for rib in self.ribs[ns].iter().rev() {
1255                 // Locals and type parameters
1256                 for (ident, &res) in &rib.bindings {
1257                     if filter_fn(res) {
1258                         names.push(TypoSuggestion::typo_from_res(ident.name, res));
1259                     }
1260                 }
1261                 // Items in scope
1262                 if let RibKind::ModuleRibKind(module) = rib.kind {
1263                     // Items from this module
1264                     self.r.add_module_candidates(module, &mut names, &filter_fn);
1265
1266                     if let ModuleKind::Block(..) = module.kind {
1267                         // We can see through blocks
1268                     } else {
1269                         // Items from the prelude
1270                         if !module.no_implicit_prelude {
1271                             let extern_prelude = self.r.extern_prelude.clone();
1272                             names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1273                                 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1274                                     |crate_id| {
1275                                         let crate_mod = Res::Def(
1276                                             DefKind::Mod,
1277                                             DefId { krate: crate_id, index: CRATE_DEF_INDEX },
1278                                         );
1279
1280                                         if filter_fn(crate_mod) {
1281                                             Some(TypoSuggestion::typo_from_res(
1282                                                 ident.name, crate_mod,
1283                                             ))
1284                                         } else {
1285                                             None
1286                                         }
1287                                     },
1288                                 )
1289                             }));
1290
1291                             if let Some(prelude) = self.r.prelude {
1292                                 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1293                             }
1294                         }
1295                         break;
1296                     }
1297                 }
1298             }
1299             // Add primitive types to the mix
1300             if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1301                 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1302                     TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1303                 }))
1304             }
1305         } else {
1306             // Search in module.
1307             let mod_path = &path[..path.len() - 1];
1308             if let PathResult::Module(module) =
1309                 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
1310             {
1311                 if let ModuleOrUniformRoot::Module(module) = module {
1312                     self.r.add_module_candidates(module, &mut names, &filter_fn);
1313                 }
1314             }
1315         }
1316
1317         let name = path[path.len() - 1].ident.name;
1318         // Make sure error reporting is deterministic.
1319         names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
1320
1321         match find_best_match_for_name(
1322             &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1323             name,
1324             None,
1325         ) {
1326             Some(found) if found != name => {
1327                 names.into_iter().find(|suggestion| suggestion.candidate == found)
1328             }
1329             _ => None,
1330         }
1331     }
1332
1333     // Returns the name of the Rust type approximately corresponding to
1334     // a type name in another programming language.
1335     fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1336         let name = path[path.len() - 1].ident.as_str();
1337         // Common Java types
1338         Some(match &*name {
1339             "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1340             "short" => sym::i16,
1341             "boolean" => sym::bool,
1342             "int" => sym::i32,
1343             "long" => sym::i64,
1344             "float" => sym::f32,
1345             "double" => sym::f64,
1346             _ => return None,
1347         })
1348     }
1349
1350     /// Only used in a specific case of type ascription suggestions
1351     fn get_colon_suggestion_span(&self, start: Span) -> Span {
1352         let sm = self.r.session.source_map();
1353         start.to(sm.next_point(start))
1354     }
1355
1356     fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
1357         let sm = self.r.session.source_map();
1358         let base_snippet = sm.span_to_snippet(base_span);
1359         if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1360             if let Ok(snippet) = sm.span_to_snippet(sp) {
1361                 let len = snippet.trim_end().len() as u32;
1362                 if snippet.trim() == ":" {
1363                     let colon_sp =
1364                         sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1365                     let mut show_label = true;
1366                     if sm.is_multiline(sp) {
1367                         err.span_suggestion_short(
1368                             colon_sp,
1369                             "maybe you meant to write `;` here",
1370                             ";".to_string(),
1371                             Applicability::MaybeIncorrect,
1372                         );
1373                     } else {
1374                         let after_colon_sp =
1375                             self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1376                         if snippet.len() == 1 {
1377                             // `foo:bar`
1378                             err.span_suggestion(
1379                                 colon_sp,
1380                                 "maybe you meant to write a path separator here",
1381                                 "::".to_string(),
1382                                 Applicability::MaybeIncorrect,
1383                             );
1384                             show_label = false;
1385                             if !self
1386                                 .r
1387                                 .session
1388                                 .parse_sess
1389                                 .type_ascription_path_suggestions
1390                                 .borrow_mut()
1391                                 .insert(colon_sp)
1392                             {
1393                                 err.delay_as_bug();
1394                             }
1395                         }
1396                         if let Ok(base_snippet) = base_snippet {
1397                             let mut sp = after_colon_sp;
1398                             for _ in 0..100 {
1399                                 // Try to find an assignment
1400                                 sp = sm.next_point(sp);
1401                                 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1402                                 match snippet {
1403                                     Ok(ref x) if x.as_str() == "=" => {
1404                                         err.span_suggestion(
1405                                             base_span,
1406                                             "maybe you meant to write an assignment here",
1407                                             format!("let {}", base_snippet),
1408                                             Applicability::MaybeIncorrect,
1409                                         );
1410                                         show_label = false;
1411                                         break;
1412                                     }
1413                                     Ok(ref x) if x.as_str() == "\n" => break,
1414                                     Err(_) => break,
1415                                     Ok(_) => {}
1416                                 }
1417                             }
1418                         }
1419                     }
1420                     if show_label {
1421                         err.span_label(
1422                             base_span,
1423                             "expecting a type here because of type ascription",
1424                         );
1425                     }
1426                     return show_label;
1427                 }
1428             }
1429         }
1430         false
1431     }
1432
1433     fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1434         let mut result = None;
1435         let mut seen_modules = FxHashSet::default();
1436         let mut worklist = vec![(self.r.graph_root, Vec::new())];
1437
1438         while let Some((in_module, path_segments)) = worklist.pop() {
1439             // abort if the module is already found
1440             if result.is_some() {
1441                 break;
1442             }
1443
1444             in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1445                 // abort if the module is already found or if name_binding is private external
1446                 if result.is_some() || !name_binding.vis.is_visible_locally() {
1447                     return;
1448                 }
1449                 if let Some(module) = name_binding.module() {
1450                     // form the path
1451                     let mut path_segments = path_segments.clone();
1452                     path_segments.push(ast::PathSegment::from_ident(ident));
1453                     let module_def_id = module.def_id().unwrap();
1454                     if module_def_id == def_id {
1455                         let path =
1456                             Path { span: name_binding.span, segments: path_segments, tokens: None };
1457                         result = Some((
1458                             module,
1459                             ImportSuggestion {
1460                                 did: Some(def_id),
1461                                 descr: "module",
1462                                 path,
1463                                 accessible: true,
1464                             },
1465                         ));
1466                     } else {
1467                         // add the module to the lookup
1468                         if seen_modules.insert(module_def_id) {
1469                             worklist.push((module, path_segments));
1470                         }
1471                     }
1472                 }
1473             });
1474         }
1475
1476         result
1477     }
1478
1479     fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1480         self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1481             let mut variants = Vec::new();
1482             enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1483                 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1484                     let mut segms = enum_import_suggestion.path.segments.clone();
1485                     segms.push(ast::PathSegment::from_ident(ident));
1486                     let path = Path { span: name_binding.span, segments: segms, tokens: None };
1487                     variants.push((path, def_id, kind));
1488                 }
1489             });
1490             variants
1491         })
1492     }
1493
1494     /// Adds a suggestion for using an enum's variant when an enum is used instead.
1495     fn suggest_using_enum_variant(
1496         &mut self,
1497         err: &mut DiagnosticBuilder<'a>,
1498         source: PathSource<'_>,
1499         def_id: DefId,
1500         span: Span,
1501     ) {
1502         let variants = match self.collect_enum_ctors(def_id) {
1503             Some(variants) => variants,
1504             None => {
1505                 err.note("you might have meant to use one of the enum's variants");
1506                 return;
1507             }
1508         };
1509
1510         let suggest_only_tuple_variants =
1511             matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1512         if suggest_only_tuple_variants {
1513             // Suggest only tuple variants regardless of whether they have fields and do not
1514             // suggest path with added parenthesis.
1515             let mut suggestable_variants = variants
1516                 .iter()
1517                 .filter(|(.., kind)| *kind == CtorKind::Fn)
1518                 .map(|(variant, ..)| path_names_to_string(variant))
1519                 .collect::<Vec<_>>();
1520
1521             let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1522
1523             let source_msg = if source.is_call() {
1524                 "to construct"
1525             } else if matches!(source, PathSource::TupleStruct(..)) {
1526                 "to match against"
1527             } else {
1528                 unreachable!()
1529             };
1530
1531             if !suggestable_variants.is_empty() {
1532                 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1533                     format!("try {} the enum's variant", source_msg)
1534                 } else {
1535                     format!("try {} one of the enum's variants", source_msg)
1536                 };
1537
1538                 err.span_suggestions(
1539                     span,
1540                     &msg,
1541                     suggestable_variants.drain(..),
1542                     Applicability::MaybeIncorrect,
1543                 );
1544             }
1545
1546             // If the enum has no tuple variants..
1547             if non_suggestable_variant_count == variants.len() {
1548                 err.help(&format!("the enum has no tuple variants {}", source_msg));
1549             }
1550
1551             // If there are also non-tuple variants..
1552             if non_suggestable_variant_count == 1 {
1553                 err.help(&format!(
1554                     "you might have meant {} the enum's non-tuple variant",
1555                     source_msg
1556                 ));
1557             } else if non_suggestable_variant_count >= 1 {
1558                 err.help(&format!(
1559                     "you might have meant {} one of the enum's non-tuple variants",
1560                     source_msg
1561                 ));
1562             }
1563         } else {
1564             let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1565                 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1566                 match kind {
1567                     CtorKind::Const => false,
1568                     CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1569                     _ => true,
1570                 }
1571             };
1572
1573             let mut suggestable_variants = variants
1574                 .iter()
1575                 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1576                 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1577                 .map(|(variant, kind)| match kind {
1578                     CtorKind::Const => variant,
1579                     CtorKind::Fn => format!("({}())", variant),
1580                     CtorKind::Fictive => format!("({} {{}})", variant),
1581                 })
1582                 .collect::<Vec<_>>();
1583
1584             if !suggestable_variants.is_empty() {
1585                 let msg = if suggestable_variants.len() == 1 {
1586                     "you might have meant to use the following enum variant"
1587                 } else {
1588                     "you might have meant to use one of the following enum variants"
1589                 };
1590
1591                 err.span_suggestions(
1592                     span,
1593                     msg,
1594                     suggestable_variants.drain(..),
1595                     Applicability::MaybeIncorrect,
1596                 );
1597             }
1598
1599             let mut suggestable_variants_with_placeholders = variants
1600                 .iter()
1601                 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1602                 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1603                 .filter_map(|(variant, kind)| match kind {
1604                     CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1605                     CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1606                     _ => None,
1607                 })
1608                 .collect::<Vec<_>>();
1609
1610             if !suggestable_variants_with_placeholders.is_empty() {
1611                 let msg = match (
1612                     suggestable_variants.is_empty(),
1613                     suggestable_variants_with_placeholders.len(),
1614                 ) {
1615                     (true, 1) => "the following enum variant is available",
1616                     (true, _) => "the following enum variants are available",
1617                     (false, 1) => "alternatively, the following enum variant is available",
1618                     (false, _) => "alternatively, the following enum variants are also available",
1619                 };
1620
1621                 err.span_suggestions(
1622                     span,
1623                     msg,
1624                     suggestable_variants_with_placeholders.drain(..),
1625                     Applicability::HasPlaceholders,
1626                 );
1627             }
1628         };
1629
1630         if def_id.is_local() {
1631             if let Some(span) = self.def_span(def_id) {
1632                 err.span_note(span, "the enum is defined here");
1633             }
1634         }
1635     }
1636
1637     crate fn report_missing_type_error(
1638         &self,
1639         path: &[Segment],
1640     ) -> Option<(Span, &'static str, String, Applicability)> {
1641         let (ident, span) = match path {
1642             [segment] if !segment.has_generic_args => {
1643                 (segment.ident.to_string(), segment.ident.span)
1644             }
1645             _ => return None,
1646         };
1647         let mut iter = ident.chars().map(|c| c.is_uppercase());
1648         let single_uppercase_char =
1649             matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1650         if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1651             return None;
1652         }
1653         match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1654             (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1655                 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1656             }
1657             (
1658                 Some(Item {
1659                     kind:
1660                         kind @ ItemKind::Fn(..)
1661                         | kind @ ItemKind::Enum(..)
1662                         | kind @ ItemKind::Struct(..)
1663                         | kind @ ItemKind::Union(..),
1664                     ..
1665                 }),
1666                 true, _
1667             )
1668             // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1669             | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1670             | (Some(Item { kind, .. }), false, _) => {
1671                 // Likely missing type parameter.
1672                 if let Some(generics) = kind.generics() {
1673                     if span.overlaps(generics.span) {
1674                         // Avoid the following:
1675                         // error[E0405]: cannot find trait `A` in this scope
1676                         //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1677                         //   |
1678                         // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1679                         //   |           ^- help: you might be missing a type parameter: `, A`
1680                         //   |           |
1681                         //   |           not found in this scope
1682                         return None;
1683                     }
1684                     let msg = "you might be missing a type parameter";
1685                     let (span, sugg) = if let [.., param] = &generics.params[..] {
1686                         let span = if let [.., bound] = &param.bounds[..] {
1687                             bound.span()
1688                         } else if let GenericParam {
1689                             kind: GenericParamKind::Const { ty, kw_span: _, default  }, ..
1690                         } = param {
1691                             default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1692                         } else {
1693                             param.ident.span
1694                         };
1695                         (span, format!(", {}", ident))
1696                     } else {
1697                         (generics.span, format!("<{}>", ident))
1698                     };
1699                     // Do not suggest if this is coming from macro expansion.
1700                     if !span.from_expansion() {
1701                         return Some((
1702                             span.shrink_to_hi(),
1703                             msg,
1704                             sugg,
1705                             Applicability::MaybeIncorrect,
1706                         ));
1707                     }
1708                 }
1709             }
1710             _ => {}
1711         }
1712         None
1713     }
1714
1715     /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1716     /// optionally returning the closest match and whether it is reachable.
1717     crate fn suggestion_for_label_in_rib(
1718         &self,
1719         rib_index: usize,
1720         label: Ident,
1721     ) -> Option<LabelSuggestion> {
1722         // Are ribs from this `rib_index` within scope?
1723         let within_scope = self.is_label_valid_from_rib(rib_index);
1724
1725         let rib = &self.label_ribs[rib_index];
1726         let names = rib
1727             .bindings
1728             .iter()
1729             .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1730             .map(|(id, _)| id.name)
1731             .collect::<Vec<Symbol>>();
1732
1733         find_best_match_for_name(&names, label.name, None).map(|symbol| {
1734             // Upon finding a similar name, get the ident that it was from - the span
1735             // contained within helps make a useful diagnostic. In addition, determine
1736             // whether this candidate is within scope.
1737             let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1738             (*ident, within_scope)
1739         })
1740     }
1741 }
1742
1743 impl<'tcx> LifetimeContext<'_, 'tcx> {
1744     crate fn report_missing_lifetime_specifiers(
1745         &self,
1746         spans: Vec<Span>,
1747         count: usize,
1748     ) -> DiagnosticBuilder<'tcx> {
1749         struct_span_err!(
1750             self.tcx.sess,
1751             spans,
1752             E0106,
1753             "missing lifetime specifier{}",
1754             pluralize!(count)
1755         )
1756     }
1757
1758     crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1759         let mut err = struct_span_err!(
1760             self.tcx.sess,
1761             lifetime_ref.span,
1762             E0261,
1763             "use of undeclared lifetime name `{}`",
1764             lifetime_ref
1765         );
1766         err.span_label(lifetime_ref.span, "undeclared lifetime");
1767         let mut suggests_in_band = false;
1768         let mut suggest_note = true;
1769         for missing in &self.missing_named_lifetime_spots {
1770             match missing {
1771                 MissingLifetimeSpot::Generics(generics) => {
1772                     let (span, sugg) = if let Some(param) = generics.params.iter().find(|p| {
1773                         !matches!(
1774                             p.kind,
1775                             hir::GenericParamKind::Type {
1776                                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1777                                 ..
1778                             } | hir::GenericParamKind::Lifetime {
1779                                 kind: hir::LifetimeParamKind::Elided,
1780                             }
1781                         )
1782                     }) {
1783                         (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1784                     } else {
1785                         suggests_in_band = true;
1786                         (generics.span, format!("<{}>", lifetime_ref))
1787                     };
1788                     if !span.from_expansion() {
1789                         err.span_suggestion(
1790                             span,
1791                             &format!("consider introducing lifetime `{}` here", lifetime_ref),
1792                             sugg,
1793                             Applicability::MaybeIncorrect,
1794                         );
1795                     } else if suggest_note {
1796                         suggest_note = false; // Avoid displaying the same help multiple times.
1797                         err.span_label(
1798                             span,
1799                             &format!(
1800                                 "lifetime `{}` is missing in item created through this procedural \
1801                                  macro",
1802                                 lifetime_ref,
1803                             ),
1804                         );
1805                     }
1806                 }
1807                 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1808                     err.span_suggestion(
1809                         *span,
1810                         &format!(
1811                             "consider making the {} lifetime-generic with a new `{}` lifetime",
1812                             span_type.descr(),
1813                             lifetime_ref
1814                         ),
1815                         span_type.suggestion(&lifetime_ref.to_string()),
1816                         Applicability::MaybeIncorrect,
1817                     );
1818                     err.note(
1819                         "for more information on higher-ranked polymorphism, visit \
1820                          https://doc.rust-lang.org/nomicon/hrtb.html",
1821                     );
1822                 }
1823                 _ => {}
1824             }
1825         }
1826         if self.tcx.sess.is_nightly_build()
1827             && !self.tcx.features().in_band_lifetimes
1828             && suggests_in_band
1829         {
1830             err.help(
1831                 "if you want to experiment with in-band lifetime bindings, \
1832                  add `#![feature(in_band_lifetimes)]` to the crate attributes",
1833             );
1834         }
1835         err.emit();
1836     }
1837
1838     // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
1839     // generics. We are disallowing this until we can decide on how we want to handle non-'static
1840     // lifetimes in const generics. See issue #74052 for discussion.
1841     crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1842         let mut err = struct_span_err!(
1843             self.tcx.sess,
1844             lifetime_ref.span,
1845             E0771,
1846             "use of non-static lifetime `{}` in const generic",
1847             lifetime_ref
1848         );
1849         err.note(
1850             "for more information, see issue #74052 \
1851             <https://github.com/rust-lang/rust/issues/74052>",
1852         );
1853         err.emit();
1854     }
1855
1856     crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1857         if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1858             if [
1859                 self.tcx.lang_items().fn_once_trait(),
1860                 self.tcx.lang_items().fn_trait(),
1861                 self.tcx.lang_items().fn_mut_trait(),
1862             ]
1863             .contains(&Some(did))
1864             {
1865                 let (span, span_type) = match &trait_ref.bound_generic_params {
1866                     [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1867                     [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1868                 };
1869                 self.missing_named_lifetime_spots
1870                     .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1871                 return true;
1872             }
1873         };
1874         false
1875     }
1876
1877     crate fn add_missing_lifetime_specifiers_label(
1878         &self,
1879         err: &mut DiagnosticBuilder<'_>,
1880         mut spans_with_counts: Vec<(Span, usize)>,
1881         lifetime_names: &FxHashSet<Symbol>,
1882         lifetime_spans: Vec<Span>,
1883         params: &[ElisionFailureInfo],
1884     ) {
1885         let snippets: Vec<Option<String>> = spans_with_counts
1886             .iter()
1887             .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
1888             .collect();
1889
1890         // Empty generics are marked with a span of "<", but since from now on
1891         // that information is in the snippets it can be removed from the spans.
1892         for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
1893             if snippet.as_deref() == Some("<") {
1894                 *span = span.shrink_to_hi();
1895             }
1896         }
1897
1898         for &(span, count) in &spans_with_counts {
1899             err.span_label(
1900                 span,
1901                 format!(
1902                     "expected {} lifetime parameter{}",
1903                     if count == 1 { "named".to_string() } else { count.to_string() },
1904                     pluralize!(count),
1905                 ),
1906             );
1907         }
1908
1909         let suggest_existing =
1910             |err: &mut DiagnosticBuilder<'_>,
1911              name: &str,
1912              formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
1913                 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
1914                     self.missing_named_lifetime_spots.iter().rev().next()
1915                 {
1916                     // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
1917                     // using `'a`, but also introduce the concept of HRLTs by suggesting
1918                     // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
1919                     let mut introduce_suggestion = vec![];
1920
1921                     let a_to_z_repeat_n = |n| {
1922                         (b'a'..=b'z').map(move |c| {
1923                             let mut s = '\''.to_string();
1924                             s.extend(std::iter::repeat(char::from(c)).take(n));
1925                             s
1926                         })
1927                     };
1928
1929                     // If all single char lifetime names are present, we wrap around and double the chars.
1930                     let lt_name = (1..)
1931                         .flat_map(a_to_z_repeat_n)
1932                         .find(|lt| !lifetime_names.contains(&Symbol::intern(&lt)))
1933                         .unwrap();
1934                     let msg = format!(
1935                         "consider making the {} lifetime-generic with a new `{}` lifetime",
1936                         span_type.descr(),
1937                         lt_name,
1938                     );
1939                     err.note(
1940                         "for more information on higher-ranked polymorphism, visit \
1941                     https://doc.rust-lang.org/nomicon/hrtb.html",
1942                     );
1943                     let for_sugg = span_type.suggestion(&lt_name);
1944                     for param in params {
1945                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
1946                         {
1947                             if snippet.starts_with('&') && !snippet.starts_with("&'") {
1948                                 introduce_suggestion
1949                                     .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
1950                             } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
1951                                 introduce_suggestion
1952                                     .push((param.span, format!("&{} {}", lt_name, stripped)));
1953                             }
1954                         }
1955                     }
1956                     introduce_suggestion.push((*for_span, for_sugg));
1957                     for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
1958                         if let Some(formatter) = formatter {
1959                             introduce_suggestion.push((*span, formatter(&lt_name)));
1960                         }
1961                     }
1962                     err.multipart_suggestion_with_style(
1963                         &msg,
1964                         introduce_suggestion,
1965                         Applicability::MaybeIncorrect,
1966                         SuggestionStyle::ShowAlways,
1967                     );
1968                 }
1969
1970                 let spans_suggs: Vec<_> = formatters
1971                     .into_iter()
1972                     .zip(spans_with_counts.iter())
1973                     .filter_map(|(fmt, (span, _))| {
1974                         if let Some(formatter) = fmt { Some((formatter, span)) } else { None }
1975                     })
1976                     .map(|(formatter, span)| (*span, formatter(name)))
1977                     .collect();
1978                 err.multipart_suggestion_with_style(
1979                     &format!(
1980                         "consider using the `{}` lifetime",
1981                         lifetime_names.iter().next().unwrap()
1982                     ),
1983                     spans_suggs,
1984                     Applicability::MaybeIncorrect,
1985                     SuggestionStyle::ShowAlways,
1986                 );
1987             };
1988         let suggest_new = |err: &mut DiagnosticBuilder<'_>, suggs: Vec<Option<String>>| {
1989             for missing in self.missing_named_lifetime_spots.iter().rev() {
1990                 let mut introduce_suggestion = vec![];
1991                 let msg;
1992                 let should_break;
1993                 introduce_suggestion.push(match missing {
1994                     MissingLifetimeSpot::Generics(generics) => {
1995                         if generics.span == DUMMY_SP {
1996                             // Account for malformed generics in the HIR. This shouldn't happen,
1997                             // but if we make a mistake elsewhere, mainly by keeping something in
1998                             // `missing_named_lifetime_spots` that we shouldn't, like associated
1999                             // `const`s or making a mistake in the AST lowering we would provide
2000                             // non-sensical suggestions. Guard against that by skipping these.
2001                             // (#74264)
2002                             continue;
2003                         }
2004                         msg = "consider introducing a named lifetime parameter".to_string();
2005                         should_break = true;
2006                         if let Some(param) = generics.params.iter().find(|p| {
2007                             !matches!(
2008                                 p.kind,
2009                                 hir::GenericParamKind::Type {
2010                                     synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
2011                                     ..
2012                                 } | hir::GenericParamKind::Lifetime {
2013                                     kind: hir::LifetimeParamKind::Elided
2014                                 }
2015                             )
2016                         }) {
2017                             (param.span.shrink_to_lo(), "'a, ".to_string())
2018                         } else {
2019                             (generics.span, "<'a>".to_string())
2020                         }
2021                     }
2022                     MissingLifetimeSpot::HigherRanked { span, span_type } => {
2023                         msg = format!(
2024                             "consider making the {} lifetime-generic with a new `'a` lifetime",
2025                             span_type.descr(),
2026                         );
2027                         should_break = false;
2028                         err.note(
2029                             "for more information on higher-ranked polymorphism, visit \
2030                             https://doc.rust-lang.org/nomicon/hrtb.html",
2031                         );
2032                         (*span, span_type.suggestion("'a"))
2033                     }
2034                     MissingLifetimeSpot::Static => {
2035                         let mut spans_suggs = Vec::new();
2036                         for ((span, count), snippet) in
2037                             spans_with_counts.iter().copied().zip(snippets.iter())
2038                         {
2039                             let (span, sugg) = match snippet.as_deref() {
2040                                 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2041                                 Some("'_") => (span, "'static".to_owned()),
2042                                 Some(snippet) if !snippet.ends_with('>') => {
2043                                     if snippet == "" {
2044                                         (
2045                                             span,
2046                                             std::iter::repeat("'static")
2047                                                 .take(count)
2048                                                 .collect::<Vec<_>>()
2049                                                 .join(", "),
2050                                         )
2051                                     } else if snippet == "<" || snippet == "(" {
2052                                         (
2053                                             span.shrink_to_hi(),
2054                                             std::iter::repeat("'static")
2055                                                 .take(count)
2056                                                 .collect::<Vec<_>>()
2057                                                 .join(", "),
2058                                         )
2059                                     } else {
2060                                         (
2061                                             span.shrink_to_hi(),
2062                                             format!(
2063                                                 "<{}>",
2064                                                 std::iter::repeat("'static")
2065                                                     .take(count)
2066                                                     .collect::<Vec<_>>()
2067                                                     .join(", "),
2068                                             ),
2069                                         )
2070                                     }
2071                                 }
2072                                 _ => continue,
2073                             };
2074                             spans_suggs.push((span, sugg.to_string()));
2075                         }
2076                         err.multipart_suggestion_with_style(
2077                             "consider using the `'static` lifetime",
2078                             spans_suggs,
2079                             Applicability::MaybeIncorrect,
2080                             SuggestionStyle::ShowAlways,
2081                         );
2082                         continue;
2083                     }
2084                 });
2085
2086                 struct Lifetime(Span, String);
2087                 impl Lifetime {
2088                     fn is_unnamed(&self) -> bool {
2089                         self.1.starts_with('&') && !self.1.starts_with("&'")
2090                     }
2091                     fn is_underscore(&self) -> bool {
2092                         self.1.starts_with("&'_ ")
2093                     }
2094                     fn is_named(&self) -> bool {
2095                         self.1.starts_with("&'")
2096                     }
2097                     fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2098                         Some(
2099                             match (
2100                                 self.is_unnamed(),
2101                                 self.is_underscore(),
2102                                 self.is_named(),
2103                                 sugg.starts_with('&'),
2104                             ) {
2105                                 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2106                                 (true, _, _, true) => {
2107                                     (self.span_unnamed_borrow(), sugg[1..].to_string())
2108                                 }
2109                                 (_, true, _, false) => {
2110                                     (self.span_underscore_borrow(), sugg.trim().to_string())
2111                                 }
2112                                 (_, true, _, true) => {
2113                                     (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2114                                 }
2115                                 (_, _, true, false) => {
2116                                     (self.span_named_borrow(), sugg.trim().to_string())
2117                                 }
2118                                 (_, _, true, true) => {
2119                                     (self.span_named_borrow(), sugg[1..].trim().to_string())
2120                                 }
2121                                 _ => return None,
2122                             },
2123                         )
2124                     }
2125                     fn span_unnamed_borrow(&self) -> Span {
2126                         let lo = self.0.lo() + BytePos(1);
2127                         self.0.with_lo(lo).with_hi(lo)
2128                     }
2129                     fn span_named_borrow(&self) -> Span {
2130                         let lo = self.0.lo() + BytePos(1);
2131                         self.0.with_lo(lo)
2132                     }
2133                     fn span_underscore_borrow(&self) -> Span {
2134                         let lo = self.0.lo() + BytePos(1);
2135                         let hi = lo + BytePos(2);
2136                         self.0.with_lo(lo).with_hi(hi)
2137                     }
2138                 }
2139
2140                 for param in params {
2141                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2142                         if let Some((span, sugg)) =
2143                             Lifetime(param.span, snippet).suggestion("'a ".to_string())
2144                         {
2145                             introduce_suggestion.push((span, sugg));
2146                         }
2147                     }
2148                 }
2149                 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2150                     |((span, _), sugg)| match &sugg {
2151                         Some(sugg) => Some((span, sugg.to_string())),
2152                         _ => None,
2153                     },
2154                 ) {
2155                     let (span, sugg) = self
2156                         .tcx
2157                         .sess
2158                         .source_map()
2159                         .span_to_snippet(span)
2160                         .ok()
2161                         .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2162                         .unwrap_or((span, sugg));
2163                     introduce_suggestion.push((span, sugg.to_string()));
2164                 }
2165                 err.multipart_suggestion_with_style(
2166                     &msg,
2167                     introduce_suggestion,
2168                     Applicability::MaybeIncorrect,
2169                     SuggestionStyle::ShowAlways,
2170                 );
2171                 if should_break {
2172                     break;
2173                 }
2174             }
2175         };
2176
2177         let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2178         match &lifetime_names[..] {
2179             [name] => {
2180                 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2181                 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2182                 {
2183                     suggs.push(match snippet.as_deref() {
2184                         Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2185                         Some("'_") => Some(Box::new(|n| n.to_string())),
2186                         Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2187                         Some("<") => Some(Box::new(move |n| {
2188                             std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2189                         })),
2190                         Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2191                             format!(
2192                                 "{}<{}>",
2193                                 snippet,
2194                                 std::iter::repeat(name.to_string())
2195                                     .take(count)
2196                                     .collect::<Vec<_>>()
2197                                     .join(", ")
2198                             )
2199                         })),
2200                         _ => None,
2201                     });
2202                 }
2203                 suggest_existing(err, &name.as_str()[..], suggs);
2204             }
2205             [] => {
2206                 let mut suggs = Vec::new();
2207                 for (snippet, (_, count)) in
2208                     snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2209                 {
2210                     suggs.push(match snippet.as_deref() {
2211                         Some("&") => Some("&'a ".to_string()),
2212                         Some("'_") => Some("'a".to_string()),
2213                         Some("") => {
2214                             Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2215                         }
2216                         Some("<") => {
2217                             Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2218                         }
2219                         Some(snippet) => Some(format!(
2220                             "{}<{}>",
2221                             snippet,
2222                             std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2223                         )),
2224                         None => None,
2225                     });
2226                 }
2227                 suggest_new(err, suggs);
2228             }
2229             lts if lts.len() > 1 => {
2230                 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2231
2232                 let mut spans_suggs: Vec<_> = Vec::new();
2233                 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2234                     match snippet.as_deref() {
2235                         Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2236                         Some("&") => spans_suggs
2237                             .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2238                         _ => {}
2239                     }
2240                 }
2241
2242                 if spans_suggs.len() > 0 {
2243                     // This happens when we have `Foo<T>` where we point at the space before `T`,
2244                     // but this can be confusing so we give a suggestion with placeholders.
2245                     err.multipart_suggestion_with_style(
2246                         "consider using one of the available lifetimes here",
2247                         spans_suggs,
2248                         Applicability::HasPlaceholders,
2249                         SuggestionStyle::ShowAlways,
2250                     );
2251                 }
2252             }
2253             _ => unreachable!(),
2254         }
2255     }
2256
2257     /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2258     /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2259     /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2260     crate fn maybe_emit_forbidden_non_static_lifetime_error(
2261         &self,
2262         body_id: hir::BodyId,
2263         lifetime_ref: &'tcx hir::Lifetime,
2264     ) {
2265         let is_anon_const = matches!(
2266             self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
2267             hir::def::DefKind::AnonConst
2268         );
2269         let is_allowed_lifetime = matches!(
2270             lifetime_ref.name,
2271             hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore
2272         );
2273
2274         if !self.tcx.lazy_normalization() && is_anon_const && !is_allowed_lifetime {
2275             feature_err(
2276                 &self.tcx.sess.parse_sess,
2277                 sym::generic_const_exprs,
2278                 lifetime_ref.span,
2279                 "a non-static lifetime is not allowed in a `const`",
2280             )
2281             .emit();
2282         }
2283     }
2284 }