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