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