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