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