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