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