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