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