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