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