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