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