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