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