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