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