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