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};
8 use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt};
10 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
11 MethodCall, NodeId, Path, Ty, TyKind, DUMMY_NODE_ID,
13 use rustc_ast_pretty::pprust::path_segment_to_string;
14 use rustc_data_structures::fx::FxHashSet;
16 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
20 use rustc_hir::def::Namespace::{self, *};
21 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
22 use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
23 use rustc_hir::PrimTy;
24 use rustc_middle::ty::DefIdTree;
25 use rustc_session::lint;
26 use rustc_session::parse::feature_err;
27 use rustc_session::Session;
28 use rustc_span::edition::Edition;
29 use rustc_span::hygiene::MacroKind;
30 use rustc_span::lev_distance::find_best_match_for_name;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{BytePos, Span};
37 use thin_vec::ThinVec;
39 type Res = def::Res<ast::NodeId>;
41 /// A field or associated item from self type suggested in case of resolution failure.
42 enum AssocSuggestion {
44 MethodWithSelf { called: bool },
45 AssocFn { called: bool },
50 impl AssocSuggestion {
51 fn action(&self) -> &'static str {
53 AssocSuggestion::Field => "use the available field",
54 AssocSuggestion::MethodWithSelf { called: true } => {
55 "call the method with the fully-qualified path"
57 AssocSuggestion::MethodWithSelf { called: false } => {
58 "refer to the method with the fully-qualified path"
60 AssocSuggestion::AssocFn { called: true } => "call the associated function",
61 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
62 AssocSuggestion::AssocConst => "use the associated `const`",
63 AssocSuggestion::AssocType => "use the associated type",
68 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
69 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
72 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
73 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
76 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
77 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
78 let variant_path = &suggestion.path;
79 let variant_path_string = path_names_to_string(variant_path);
81 let path_len = suggestion.path.segments.len();
82 let enum_path = ast::Path {
83 span: suggestion.path.span,
84 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
87 let enum_path_string = path_names_to_string(&enum_path);
89 (variant_path_string, enum_path_string)
92 /// Description of an elided lifetime.
93 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
94 pub(super) struct MissingLifetime {
95 /// Used to overwrite the resolution with the suggestion, to avoid cascasing errors.
97 /// Where to suggest adding the lifetime.
99 /// How the lifetime was introduced, to have the correct space and comma.
100 pub kind: MissingLifetimeKind,
101 /// Number of elided lifetimes, used for elision in path.
105 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
106 pub(super) enum MissingLifetimeKind {
107 /// An explicit `'_`.
109 /// An elided lifetime `&' ty`.
111 /// An elided lifetime in brackets with written brackets.
113 /// An elided lifetime with elided brackets.
117 /// Description of the lifetimes appearing in a function parameter.
118 /// This is used to provide a literal explanation to the elision failure.
119 #[derive(Clone, Debug)]
120 pub(super) struct ElisionFnParameter {
121 /// The index of the argument in the original definition.
123 /// The name of the argument if it's a simple ident.
124 pub ident: Option<Ident>,
125 /// The number of lifetimes in the parameter.
126 pub lifetime_count: usize,
127 /// The span of the parameter.
131 /// Description of lifetimes that appear as candidates for elision.
132 /// This is used to suggest introducing an explicit lifetime.
134 pub(super) enum LifetimeElisionCandidate {
135 /// This is not a real lifetime.
137 /// There is a named lifetime, we won't suggest anything.
139 Missing(MissingLifetime),
142 /// Only used for diagnostics.
146 fallback_label: String,
148 span_label: Option<(Span, &'static str)>,
150 suggestion: Option<(Span, &'static str, String)>,
155 Typo(TypoSuggestion),
156 Shadowed(Res, Option<Span>),
161 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
163 TypoCandidate::Typo(sugg) => Some(sugg),
164 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
169 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
170 fn def_span(&self, def_id: DefId) -> Option<Span> {
172 LOCAL_CRATE => self.r.opt_span(def_id),
173 _ => Some(self.r.cstore().get_span_untracked(def_id, self.r.session)),
181 source: PathSource<'_>,
184 // Make the base error.
185 let mut expected = source.descr_expected();
186 let path_str = Segment::names_to_string(path);
187 let item_str = path.last().unwrap().ident;
188 if let Some(res) = res {
190 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
191 fallback_label: format!("not a {expected}"),
193 span_label: match res {
194 Res::Def(kind, def_id) if kind == DefKind::TyParam => {
195 self.def_span(def_id).map(|span| (span, "found this type parameter"))
199 could_be_expr: match res {
200 Res::Def(DefKind::Fn, _) => {
201 // Verify whether this is a fn call or an Fn used as a type.
205 .span_to_snippet(span)
206 .map(|snippet| snippet.ends_with(')'))
210 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
215 | Res::Local(_) => true,
221 let item_span = path.last().unwrap().ident.span;
222 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
223 debug!(?self.diagnostic_metadata.current_impl_items);
224 debug!(?self.diagnostic_metadata.current_function);
225 let suggestion = if self.current_trait_ref.is_none()
226 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
227 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
228 && let Some(items) = self.diagnostic_metadata.current_impl_items
229 && let Some(item) = items.iter().find(|i| {
230 if let AssocItemKind::Fn(_) = &i.kind && i.ident.name == item_str.name
232 debug!(?item_str.name);
237 && let AssocItemKind::Fn(fn_) = &item.kind
240 let self_sugg = if fn_.sig.decl.has_self() { "self." } else { "Self::" };
242 item_span.shrink_to_lo(),
243 "consider using the associated function",
244 self_sugg.to_string()
249 (String::new(), "this scope".to_string(), suggestion)
250 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
251 if self.r.session.edition() > Edition::Edition2015 {
252 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
253 // which overrides all other expectations of item type
255 (String::new(), "the list of imported crates".to_string(), None)
257 (String::new(), "the crate root".to_string(), None)
259 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
260 (String::new(), "the crate root".to_string(), None)
262 let mod_path = &path[..path.len() - 1];
263 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
264 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
267 .map_or_else(String::new, |res| format!("{} ", res.descr()));
268 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
271 let (fallback_label, suggestion) = if path_str == "async"
272 && expected.starts_with("struct")
274 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
276 // check if we are in situation of typo like `True` instead of `true`.
277 let override_suggestion =
278 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
279 let item_typo = item_str.to_string().to_lowercase();
280 Some((item_span, "you may want to use a bool value instead", item_typo))
281 // FIXME(vincenzopalazzo): make the check smarter,
282 // and maybe expand with levenshtein distance checks
283 } else if item_str.as_str() == "printf" {
286 "you may have meant to use the `print` macro",
292 (format!("not found in {mod_str}"), override_suggestion)
296 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
300 could_be_expr: false,
306 /// Handles error reporting for `smart_resolve_path_fragment` function.
307 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
308 pub(crate) fn smart_resolve_report_errors(
312 source: PathSource<'_>,
314 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
315 debug!(?res, ?source);
316 let base_error = self.make_base_error(path, span, source, res);
317 let code = source.error_code(res.is_some());
319 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
321 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
323 if let Some((span, label)) = base_error.span_label {
324 err.span_label(span, label);
327 if let Some(ref sugg) = base_error.suggestion {
328 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
331 self.suggest_bare_struct_literal(&mut err);
333 if self.suggest_pattern_match_with_let(&mut err, source, span) {
335 err.span_label(base_error.span, &base_error.fallback_label);
336 return (err, Vec::new());
339 self.suggest_self_or_self_ref(&mut err, path, span);
340 self.detect_assoct_type_constraint_meant_as_path(&mut err, &base_error);
341 if self.suggest_self_ty(&mut err, source, path, span)
342 || self.suggest_self_value(&mut err, source, path, span)
344 return (err, Vec::new());
347 let (found, candidates) =
348 self.try_lookup_name_relaxed(&mut err, source, path, span, res, &base_error);
350 return (err, candidates);
353 if !self.type_ascription_suggestion(&mut err, base_error.span) {
355 self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
357 // if we have suggested using pattern matching, then don't add needless suggestions
359 fallback |= self.suggest_typo(&mut err, source, path, span, &base_error);
363 err.span_label(base_error.span, &base_error.fallback_label);
366 self.err_code_special_cases(&mut err, source, path, span);
371 fn detect_assoct_type_constraint_meant_as_path(
373 err: &mut Diagnostic,
374 base_error: &BaseError,
376 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
377 let TyKind::Path(_, path) = &ty.kind else { return; };
378 for segment in &path.segments {
379 let Some(params) = &segment.args else { continue; };
380 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
381 for param in ¶ms.args {
382 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
383 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
386 for bound in bounds {
387 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
392 if base_error.span == trait_ref.span {
393 err.span_suggestion_verbose(
394 constraint.ident.span.between(trait_ref.span),
395 "you might have meant to write a path instead of an associated type bound",
397 Applicability::MachineApplicable,
405 fn suggest_self_or_self_ref(&mut self, err: &mut Diagnostic, path: &[Segment], span: Span) {
406 if !self.self_type_is_available() {
409 let Some(path_last_segment) = path.last() else { return };
410 let item_str = path_last_segment.ident;
411 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
412 if ["this", "my"].contains(&item_str.as_str()) {
413 err.span_suggestion_short(
415 "you might have meant to use `self` here instead",
417 Applicability::MaybeIncorrect,
419 if !self.self_value_is_available(path[0].ident.span) {
420 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
421 &self.diagnostic_metadata.current_function
423 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
424 (param.span.shrink_to_lo(), "&self, ")
430 .span_through_char(*fn_span, '(')
435 err.span_suggestion_verbose(
437 "if you meant to use `self`, you are also missing a `self` receiver \
440 Applicability::MaybeIncorrect,
447 fn try_lookup_name_relaxed(
449 err: &mut Diagnostic,
450 source: PathSource<'_>,
454 base_error: &BaseError,
455 ) -> (bool, Vec<ImportSuggestion>) {
456 // Try to lookup name in more relaxed fashion for better error reporting.
457 let ident = path.last().unwrap().ident;
458 let is_expected = &|res| source.is_expected(res);
459 let ns = source.namespace();
460 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
461 let path_str = Segment::names_to_string(path);
462 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
463 let mut candidates = self
465 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
467 .filter(|ImportSuggestion { did, .. }| {
468 match (did, res.and_then(|res| res.opt_def_id())) {
469 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
473 .collect::<Vec<_>>();
474 let crate_def_id = CRATE_DEF_ID.to_def_id();
475 // Try to filter out intrinsics candidates, as long as we have
476 // some other candidates to suggest.
477 let intrinsic_candidates: Vec<_> = candidates
478 .drain_filter(|sugg| {
479 let path = path_names_to_string(&sugg.path);
480 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
483 if candidates.is_empty() {
484 // Put them back if we have no more candidates to suggest...
485 candidates.extend(intrinsic_candidates);
487 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
488 let mut enum_candidates: Vec<_> = self
490 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
492 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
493 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
495 if !enum_candidates.is_empty() {
496 if let (PathSource::Type, Some(span)) =
497 (source, self.diagnostic_metadata.current_type_ascription.last())
503 .type_ascription_path_suggestions
507 // Already reported this issue on the lhs of the type ascription.
508 err.downgrade_to_delayed_bug();
509 return (true, candidates);
513 enum_candidates.sort();
515 // Contextualize for E0412 "cannot find type", but don't belabor the point
516 // (that it's a variant) for E0573 "expected type, found variant".
517 let preamble = if res.is_none() {
518 let others = match enum_candidates.len() {
520 2 => " and 1 other".to_owned(),
521 n => format!(" and {} others", n),
523 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
527 let msg = format!("{}try using the variant's enum", preamble);
529 err.span_suggestions(
532 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
533 Applicability::MachineApplicable,
538 // Try Levenshtein algorithm.
540 self.lookup_typo_candidate(path, source.namespace(), is_expected).to_opt_suggestion();
541 if path.len() == 1 && self.self_type_is_available() {
542 if let Some(candidate) =
543 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
545 let self_is_available = self.self_value_is_available(path[0].ident.span);
547 AssocSuggestion::Field => {
548 if self_is_available {
551 "you might have meant to use the available field",
552 format!("self.{path_str}"),
553 Applicability::MachineApplicable,
556 err.span_label(span, "a field by this name exists in `Self`");
559 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
560 let msg = if called {
561 "you might have meant to call the method"
563 "you might have meant to refer to the method"
568 format!("self.{path_str}"),
569 Applicability::MachineApplicable,
572 AssocSuggestion::MethodWithSelf { .. }
573 | AssocSuggestion::AssocFn { .. }
574 | AssocSuggestion::AssocConst
575 | AssocSuggestion::AssocType => {
578 &format!("you might have meant to {}", candidate.action()),
579 format!("Self::{path_str}"),
580 Applicability::MachineApplicable,
584 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
585 return (true, candidates);
588 // If the first argument in call is `self` suggest calling a method.
589 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
590 let mut args_snippet = String::new();
591 if let Some(args_span) = args_span {
592 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
593 args_snippet = snippet;
599 &format!("try calling `{ident}` as a method"),
600 format!("self.{path_str}({args_snippet})"),
601 Applicability::MachineApplicable,
603 return (true, candidates);
607 // Try context-dependent help if relaxed lookup didn't work.
608 if let Some(res) = res {
609 if self.smart_resolve_context_dependent_help(
615 &base_error.fallback_label,
617 // We do this to avoid losing a secondary span when we override the main error span.
618 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
619 return (true, candidates);
623 // Try to find in last block rib
624 if let Some(rib) = &self.last_block_rib && let RibKind::NormalRibKind = rib.kind {
625 for (ident, &res) in &rib.bindings {
626 if let Res::Local(_) = res && path.len() == 1 &&
627 ident.span.eq_ctxt(path[0].ident.span) &&
628 ident.name == path[0].ident.name {
631 &format!("the binding `{}` is available in a different scope in the same function", path_str),
633 return (true, candidates);
638 return (false, candidates);
641 fn suggest_trait_and_bounds(
643 err: &mut Diagnostic,
644 source: PathSource<'_>,
647 base_error: &BaseError,
650 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
651 let mut fallback = false;
654 PathSource::Trait(AliasPossibility::Maybe),
655 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
657 ) = (source, res, is_macro)
659 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
661 let spans: Vec<Span> = bounds
663 .map(|bound| bound.span())
664 .filter(|&sp| sp != base_error.span)
667 let start_span = bounds[0].span();
668 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
669 let end_span = bounds.last().unwrap().span();
670 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
671 let last_bound_span = spans.last().cloned().unwrap();
672 let mut multi_span: MultiSpan = spans.clone().into();
674 let msg = if sp == last_bound_span {
676 "...because of {these} bound{s}",
677 these = pluralize!("this", bounds.len() - 1),
678 s = pluralize!(bounds.len() - 1),
683 multi_span.push_span_label(sp, msg);
685 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
688 "`+` is used to constrain a \"trait object\" type with lifetimes or \
689 auto-traits; structs and enums can't be bound in that way",
691 if bounds.iter().all(|bound| match bound {
692 ast::GenericBound::Outlives(_) => true,
693 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
695 let mut sugg = vec![];
696 if base_error.span != start_span {
697 sugg.push((start_span.until(base_error.span), String::new()));
699 if base_error.span != end_span {
700 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
703 err.multipart_suggestion(
704 "if you meant to use a type and not a trait here, remove the bounds",
706 Applicability::MaybeIncorrect,
712 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
718 err: &mut Diagnostic,
719 source: PathSource<'_>,
722 base_error: &BaseError,
724 let is_expected = &|res| source.is_expected(res);
725 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
726 let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
727 let is_in_same_file = &|sp1, sp2| {
728 let source_map = self.r.session.source_map();
729 let file1 = source_map.span_to_filename(sp1);
730 let file2 = source_map.span_to_filename(sp2);
733 // print 'you might have meant' if the candidate is (1) is a shadowed name with
734 // accessible definition and (2) either defined in the same crate as the typo
735 // (could be in a different file) or introduced in the same file as the typo
736 // (could belong to a different crate)
737 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
740 .map_or(false, |id| id.is_local() || is_in_same_file(span, sugg_span))
744 format!("you might have meant to refer to this {}", res.descr()),
748 let mut fallback = false;
749 let typo_sugg = typo_sugg.to_opt_suggestion();
750 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
752 match self.diagnostic_metadata.current_let_binding {
753 Some((pat_sp, Some(ty_sp), None))
754 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
756 err.span_suggestion_short(
757 pat_sp.between(ty_sp),
758 "use `=` if you meant to assign",
760 Applicability::MaybeIncorrect,
766 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
767 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
768 if !self.r.add_typo_suggestion(err, suggestion, ident_span) {
769 fallback = !self.let_binding_suggestion(err, ident_span);
775 fn err_code_special_cases(
777 err: &mut Diagnostic,
778 source: PathSource<'_>,
782 if let Some(err_code) = &err.code {
783 if err_code == &rustc_errors::error_code!(E0425) {
784 for label_rib in &self.label_ribs {
785 for (label_ident, node_id) in &label_rib.bindings {
786 let ident = path.last().unwrap().ident;
787 if format!("'{}", ident) == label_ident.to_string() {
788 err.span_label(label_ident.span, "a label with a similar name exists");
789 if let PathSource::Expr(Some(Expr {
790 kind: ExprKind::Break(None, Some(_)),
796 "use the similarly named label",
798 Applicability::MaybeIncorrect,
800 // Do not lint against unused label when we suggest them.
801 self.diagnostic_metadata.unused_labels.remove(node_id);
806 } else if err_code == &rustc_errors::error_code!(E0412) {
807 if let Some(correct) = Self::likely_rust_type(path) {
810 "perhaps you intended to use this type",
812 Applicability::MaybeIncorrect,
819 /// Emit special messages for unresolved `Self` and `self`.
822 err: &mut Diagnostic,
823 source: PathSource<'_>,
827 if !is_self_type(path, source.namespace()) {
830 err.code(rustc_errors::error_code!(E0411));
831 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
832 if let Some(item_kind) = self.diagnostic_metadata.current_item {
833 if !item_kind.ident.span.is_dummy() {
835 item_kind.ident.span,
837 "`Self` not allowed in {} {}",
838 item_kind.kind.article(),
839 item_kind.kind.descr()
847 fn suggest_self_value(
849 err: &mut Diagnostic,
850 source: PathSource<'_>,
854 if !is_self_value(path, source.namespace()) {
858 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
859 err.code(rustc_errors::error_code!(E0424));
864 "`self` value is a keyword and may not be bound to variables or shadowed"
866 _ => "`self` value is a keyword only available in methods with a `self` parameter",
869 let is_assoc_fn = self.self_type_is_available();
870 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
871 // The current function has a `self' parameter, but we were unable to resolve
872 // a reference to `self`. This can only happen if the `self` identifier we
873 // are resolving came from a different hygiene context.
874 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
875 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
877 let doesnt = if is_assoc_fn {
878 let (span, sugg) = fn_kind
882 .map(|p| (p.span.shrink_to_lo(), "&self, "))
884 // Try to look for the "(" after the function name, if possible.
885 // This avoids placing the suggestion into the visibility specifier.
888 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
893 .span_through_char(span, '(')
898 err.span_suggestion_verbose(
900 "add a `self` receiver parameter to make the associated `fn` a method",
902 Applicability::MaybeIncorrect,
908 if let Some(ident) = fn_kind.ident() {
911 &format!("this function {} have a `self` parameter", doesnt),
915 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
917 item_kind.ident.span,
919 "`self` not allowed in {} {}",
920 item_kind.kind.article(),
921 item_kind.kind.descr()
928 fn suggest_swapping_misplaced_self_ty_and_trait(
930 err: &mut Diagnostic,
931 source: PathSource<'_>,
935 if let Some((trait_ref, self_ty)) =
936 self.diagnostic_metadata.currently_processing_impl_trait.clone()
937 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
938 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
939 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
940 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
941 && trait_ref.path.span == span
942 && let PathSource::Trait(_) = source
943 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
944 && let Ok(self_ty_str) =
945 self.r.session.source_map().span_to_snippet(self_ty.span)
946 && let Ok(trait_ref_str) =
947 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
949 err.multipart_suggestion(
950 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
951 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
952 Applicability::MaybeIncorrect,
957 fn suggest_bare_struct_literal(&mut self, err: &mut Diagnostic) {
958 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
959 err.multipart_suggestion(
960 "you might have meant to write a `struct` literal",
962 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
963 (span.shrink_to_hi(), "}".to_string()),
965 Applicability::HasPlaceholders,
970 fn suggest_pattern_match_with_let(
972 err: &mut Diagnostic,
973 source: PathSource<'_>,
976 if let PathSource::Expr(_) = source &&
979 kind: ExprKind::Assign(lhs, _, _),
981 }) = self.diagnostic_metadata.in_if_condition {
982 // Icky heuristic so we don't suggest:
983 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
984 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
985 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
986 err.span_suggestion_verbose(
987 expr_span.shrink_to_lo(),
988 "you might have meant to use pattern matching",
990 Applicability::MaybeIncorrect,
998 fn get_single_associated_item(
1001 source: &PathSource<'_>,
1002 filter_fn: &impl Fn(Res) -> bool,
1003 ) -> Option<TypoSuggestion> {
1004 if let crate::PathSource::TraitItem(_) = source {
1005 let mod_path = &path[..path.len() - 1];
1006 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1007 self.resolve_path(mod_path, None, None)
1009 let resolutions = self.r.resolutions(module).borrow();
1010 let targets: Vec<_> =
1013 .filter_map(|(key, resolution)| {
1014 resolution.borrow().binding.map(|binding| binding.res()).and_then(
1015 |res| if filter_fn(res) { Some((key, res)) } else { None },
1019 if targets.len() == 1 {
1020 let target = targets[0];
1021 return Some(TypoSuggestion::single_item_from_ident(target.0.ident, target.1));
1028 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
1029 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
1030 // Detect that we are actually in a `where` predicate.
1031 let (bounded_ty, bounds, where_span) =
1032 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
1034 bound_generic_params,
1037 })) = self.diagnostic_metadata.current_where_predicate
1039 if !bound_generic_params.is_empty() {
1042 (bounded_ty, bounds, span)
1047 // Confirm that the target is an associated type.
1048 let (ty, position, path) = if let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind {
1049 // use this to verify that ident is a type param.
1050 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
1054 partial_res.full_res(),
1055 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1059 (&qself.ty, qself.position, path)
1064 let peeled_ty = ty.peel_refs();
1065 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
1066 // Confirm that the `SelfTy` is a type parameter.
1067 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1071 partial_res.full_res(),
1072 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1077 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
1078 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
1079 ) = (&type_param_path.segments[..], &bounds[..])
1081 if let [ast::PathSegment { ident, args: None, .. }] =
1082 &poly_trait_ref.trait_ref.path.segments[..]
1084 if ident.span == span {
1085 err.span_suggestion_verbose(
1087 &format!("constrain the associated type to `{}`", ident),
1093 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
1094 .unwrap_or_else(|_| constrain_ident.to_string()),
1095 path.segments[..position]
1097 .map(|segment| path_segment_to_string(segment))
1098 .collect::<Vec<_>>()
1100 path.segments[position..]
1102 .map(|segment| path_segment_to_string(segment))
1103 .collect::<Vec<_>>()
1107 Applicability::MaybeIncorrect,
1117 /// Check if the source is call expression and the first argument is `self`. If true,
1118 /// return the span of whole call and the span for all arguments expect the first one (`self`).
1119 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
1120 let mut has_self_arg = None;
1121 if let PathSource::Expr(Some(parent)) = source {
1122 match &parent.kind {
1123 ExprKind::Call(_, args) if !args.is_empty() => {
1124 let mut expr_kind = &args[0].kind;
1127 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1128 if arg_name.segments[0].ident.name == kw::SelfLower {
1129 let call_span = parent.span;
1130 let tail_args_span = if args.len() > 1 {
1133 args.last().unwrap().span.hi(),
1140 has_self_arg = Some((call_span, tail_args_span));
1144 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1155 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1156 // HACK(estebank): find a better way to figure out that this was a
1157 // parser issue where a struct literal is being used on an expression
1158 // where a brace being opened means a block is being started. Look
1159 // ahead for the next text to see if `span` is followed by a `{`.
1160 let sm = self.r.session.source_map();
1161 let sp = sm.span_look_ahead(span, None, Some(50));
1162 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
1163 // In case this could be a struct literal that needs to be surrounded
1164 // by parentheses, find the appropriate span.
1165 let closing_span = sm.span_look_ahead(span, Some("}"), Some(50));
1166 let closing_brace: Option<Span> = sm
1167 .span_to_snippet(closing_span)
1168 .map_or(None, |s| if s == "}" { Some(span.to(closing_span)) } else { None });
1169 (followed_by_brace, closing_brace)
1172 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
1174 /// Returns `true` if able to provide context-dependent help.
1175 fn smart_resolve_context_dependent_help(
1177 err: &mut Diagnostic,
1179 source: PathSource<'_>,
1182 fallback_label: &str,
1184 let ns = source.namespace();
1185 let is_expected = &|res| source.is_expected(res);
1187 let path_sep = |err: &mut Diagnostic, expr: &Expr, kind: DefKind| {
1188 const MESSAGE: &str = "use the path separator to refer to an item";
1190 let (lhs_span, rhs_span) = match &expr.kind {
1191 ExprKind::Field(base, ident) => (base.span, ident.span),
1192 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1193 (receiver.span, *span)
1198 if lhs_span.eq_ctxt(rhs_span) {
1199 err.span_suggestion(
1200 lhs_span.between(rhs_span),
1203 Applicability::MaybeIncorrect,
1206 } else if kind == DefKind::Struct
1207 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1208 && let Ok(snippet) = self.r.session.source_map().span_to_snippet(lhs_source_span)
1210 // The LHS is a type that originates from a macro call.
1211 // We have to add angle brackets around it.
1213 err.span_suggestion_verbose(
1214 lhs_source_span.until(rhs_span),
1216 format!("<{snippet}>::"),
1217 Applicability::MaybeIncorrect,
1221 // Either we were unable to obtain the source span / the snippet or
1222 // the LHS originates from a macro call and it is not a type and thus
1223 // there is no way to replace `.` with `::` and still somehow suggest
1230 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1232 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1233 | PathSource::TupleStruct(span, _) => {
1234 // We want the main underline to cover the suggested code as well for
1236 err.set_span(*span);
1243 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1244 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1247 PathSource::Expr(Some(
1248 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1249 )) if path_sep(err, &parent, DefKind::Struct) => {}
1255 | ExprKind::Binary(..)
1256 | ExprKind::Unary(..)
1258 | ExprKind::While(..)
1259 | ExprKind::ForLoop(..)
1260 | ExprKind::Match(..),
1263 ) if followed_by_brace => {
1264 if let Some(sp) = closing_brace {
1265 err.span_label(span, fallback_label);
1266 err.multipart_suggestion(
1267 "surround the struct literal with parentheses",
1269 (sp.shrink_to_lo(), "(".to_string()),
1270 (sp.shrink_to_hi(), ")".to_string()),
1272 Applicability::MaybeIncorrect,
1276 span, // Note the parentheses surrounding the suggestion below
1278 "you might want to surround a struct literal with parentheses: \
1279 `({} {{ /* fields */ }})`?",
1285 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1286 let span = find_span(&source, err);
1287 if let Some(span) = self.def_span(def_id) {
1288 err.span_label(span, &format!("`{}` defined here", path_str));
1290 let (tail, descr, applicability) = match source {
1291 PathSource::Pat | PathSource::TupleStruct(..) => {
1292 ("", "pattern", Applicability::MachineApplicable)
1294 _ => (": val", "literal", Applicability::HasPlaceholders),
1296 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1300 .map(|f| format!("{}{}", f.node, tail))
1301 .collect::<Vec<String>>()
1305 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1307 let pad = match self.r.field_names.get(&def_id) {
1308 Some(fields) if fields.is_empty() => "",
1311 err.span_suggestion(
1313 &format!("use struct {} syntax instead", descr),
1314 format!("{path_str} {{{pad}{fields}{pad}}}"),
1319 err.span_label(span, fallback_label);
1324 match (res, source) {
1326 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1327 PathSource::Expr(Some(Expr {
1328 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1330 | PathSource::Struct,
1332 err.span_label(span, fallback_label);
1333 err.span_suggestion_verbose(
1334 span.shrink_to_hi(),
1335 "use `!` to invoke the macro",
1337 Applicability::MaybeIncorrect,
1339 if path_str == "try" && span.rust_2015() {
1340 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1343 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1344 err.span_label(span, fallback_label);
1346 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1347 err.span_label(span, "type aliases cannot be used as traits");
1348 if self.r.session.is_nightly_build() {
1349 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1351 if let Some(span) = self.def_span(def_id) {
1352 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1353 // The span contains a type alias so we should be able to
1354 // replace `type` with `trait`.
1355 let snip = snip.replacen("type", "trait", 1);
1356 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1358 err.span_help(span, msg);
1366 Res::Def(kind @ (DefKind::Mod | DefKind::Trait), _),
1367 PathSource::Expr(Some(parent)),
1369 if !path_sep(err, &parent, kind) {
1374 Res::Def(DefKind::Enum, def_id),
1375 PathSource::TupleStruct(..) | PathSource::Expr(..),
1378 .diagnostic_metadata
1379 .current_type_ascription
1385 .type_ascription_path_suggestions
1391 err.downgrade_to_delayed_bug();
1392 // We already suggested changing `:` into `::` during parsing.
1396 self.suggest_using_enum_variant(err, source, def_id, span);
1398 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1399 let (ctor_def, ctor_vis, fields) =
1400 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1401 if let PathSource::Expr(Some(parent)) = source {
1402 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1403 bad_struct_syntax_suggestion(def_id);
1409 bad_struct_syntax_suggestion(def_id);
1413 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1414 if !is_expected(ctor_def) || is_accessible {
1418 let field_spans = match source {
1419 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1420 PathSource::TupleStruct(_, pattern_spans) => {
1421 err.set_primary_message(
1422 "cannot match against a tuple struct which contains private fields",
1425 // Use spans of the tuple struct pattern.
1426 Some(Vec::from(pattern_spans))
1428 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1429 _ if source.is_call() => {
1430 err.set_primary_message(
1431 "cannot initialize a tuple struct which contains private fields",
1434 // Use spans of the tuple struct definition.
1438 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1443 if let Some(spans) =
1444 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1446 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1447 .filter(|(vis, _)| {
1448 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1450 .map(|(_, span)| *span)
1453 if non_visible_spans.len() > 0 {
1454 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
1455 err.multipart_suggestion_verbose(
1457 "consider making the field{} publicly accessible",
1458 pluralize!(fields.len())
1460 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
1461 Applicability::MaybeIncorrect,
1465 let mut m: MultiSpan = non_visible_spans.clone().into();
1468 .for_each(|s| m.push_span_label(s, "private field"));
1469 err.span_note(m, "constructor is not visible here due to private fields");
1475 err.span_label(span, "constructor is not visible here due to private fields");
1477 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
1478 bad_struct_syntax_suggestion(def_id);
1480 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1482 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1483 let span = find_span(&source, err);
1484 if let Some(span) = self.def_span(def_id) {
1485 err.span_label(span, &format!("`{}` defined here", path_str));
1487 err.span_suggestion(
1489 "use this syntax instead",
1491 Applicability::MaybeIncorrect,
1497 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
1498 let def_id = self.r.parent(ctor_def_id);
1499 if let Some(span) = self.def_span(def_id) {
1500 err.span_label(span, &format!("`{}` defined here", path_str));
1502 let fields = self.r.field_names.get(&def_id).map_or_else(
1503 || "/* fields */".to_string(),
1504 |fields| vec!["_"; fields.len()].join(", "),
1506 err.span_suggestion(
1508 "use the tuple variant pattern syntax instead",
1509 format!("{}({})", path_str, fields),
1510 Applicability::HasPlaceholders,
1513 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
1514 err.span_label(span, fallback_label);
1515 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1517 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1518 err.note("can't use a type alias as a constructor");
1525 /// Given the target `ident` and `kind`, search for the similarly named associated item
1526 /// in `self.current_trait_ref`.
1527 pub(crate) fn find_similarly_named_assoc_item(
1530 kind: &AssocItemKind,
1531 ) -> Option<Symbol> {
1532 let (module, _) = self.current_trait_ref.as_ref()?;
1533 if ident == kw::Underscore {
1534 // We do nothing for `_`.
1538 let resolutions = self.r.resolutions(module);
1539 let targets = resolutions
1542 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1543 .filter(|(_, res)| match (kind, res) {
1544 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1545 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1546 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
1549 .map(|(key, _)| key.ident.name)
1550 .collect::<Vec<_>>();
1552 find_best_match_for_name(&targets, ident, None)
1555 fn lookup_assoc_candidate<FilterFn>(
1559 filter_fn: FilterFn,
1561 ) -> Option<AssocSuggestion>
1563 FilterFn: Fn(Res) -> bool,
1565 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1567 TyKind::Path(None, _) => Some(t.id),
1568 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1569 // This doesn't handle the remaining `Ty` variants as they are not
1570 // that commonly the self_type, it might be interesting to provide
1571 // support for those in future.
1575 // Fields are generally expected in the same contexts as locals.
1576 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1577 if let Some(node_id) =
1578 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1580 // Look for a field with the same name in the current self_type.
1581 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1582 if let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) =
1583 resolution.full_res()
1585 if let Some(field_names) = self.r.field_names.get(&did) {
1586 if field_names.iter().any(|&field_name| ident.name == field_name.node) {
1587 return Some(AssocSuggestion::Field);
1595 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1596 for assoc_item in items {
1597 if assoc_item.ident == ident {
1598 return Some(match &assoc_item.kind {
1599 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1600 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1601 AssocSuggestion::MethodWithSelf { called }
1603 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
1604 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
1605 ast::AssocItemKind::MacCall(_) => continue,
1611 // Look for associated items in the current trait.
1612 if let Some((module, _)) = self.current_trait_ref {
1613 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1614 ModuleOrUniformRoot::Module(module),
1619 let res = binding.res();
1621 if self.r.has_self.contains(&res.def_id()) {
1622 return Some(AssocSuggestion::MethodWithSelf { called });
1625 Res::Def(DefKind::AssocFn, _) => {
1626 return Some(AssocSuggestion::AssocFn { called });
1628 Res::Def(DefKind::AssocConst, _) => {
1629 return Some(AssocSuggestion::AssocConst);
1631 Res::Def(DefKind::AssocTy, _) => {
1632 return Some(AssocSuggestion::AssocType);
1644 fn lookup_typo_candidate(
1648 filter_fn: &impl Fn(Res) -> bool,
1649 ) -> TypoCandidate {
1650 let mut names = Vec::new();
1651 if path.len() == 1 {
1652 let mut ctxt = path.last().unwrap().ident.span.ctxt();
1654 // Search in lexical scope.
1655 // Walk backwards up the ribs in scope and collect candidates.
1656 for rib in self.ribs[ns].iter().rev() {
1657 let rib_ctxt = if rib.kind.contains_params() {
1658 ctxt.normalize_to_macros_2_0()
1660 ctxt.normalize_to_macro_rules()
1663 // Locals and type parameters
1664 for (ident, &res) in &rib.bindings {
1665 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
1666 names.push(TypoSuggestion::typo_from_ident(*ident, res));
1670 if let RibKind::MacroDefinition(def) = rib.kind && def == self.r.macro_def(ctxt) {
1671 // If an invocation of this macro created `ident`, give up on `ident`
1672 // and switch to `ident`'s source from the macro definition.
1678 if let RibKind::ModuleRibKind(module) = rib.kind {
1679 // Items from this module
1680 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
1682 if let ModuleKind::Block = module.kind {
1683 // We can see through blocks
1685 // Items from the prelude
1686 if !module.no_implicit_prelude {
1687 let extern_prelude = self.r.extern_prelude.clone();
1688 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1691 .maybe_process_path_extern(ident.name)
1692 .and_then(|crate_id| {
1694 Res::Def(DefKind::Mod, crate_id.as_def_id());
1696 if filter_fn(crate_mod) {
1697 Some(TypoSuggestion::typo_from_ident(*ident, crate_mod))
1704 if let Some(prelude) = self.r.prelude {
1705 self.r.add_module_candidates(prelude, &mut names, &filter_fn, None);
1712 // Add primitive types to the mix
1713 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1714 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1715 TypoSuggestion::typo_from_name(prim_ty.name(), Res::PrimTy(*prim_ty))
1719 // Search in module.
1720 let mod_path = &path[..path.len() - 1];
1721 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1722 self.resolve_path(mod_path, Some(TypeNS), None)
1724 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
1728 let name = path[path.len() - 1].ident.name;
1729 // Make sure error reporting is deterministic.
1730 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1732 match find_best_match_for_name(
1733 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1738 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found) else {
1739 return TypoCandidate::None;
1742 TypoCandidate::Shadowed(sugg.res, sugg.span)
1744 TypoCandidate::Typo(sugg)
1747 _ => TypoCandidate::None,
1751 // Returns the name of the Rust type approximately corresponding to
1752 // a type name in another programming language.
1753 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1754 let name = path[path.len() - 1].ident.as_str();
1755 // Common Java types
1757 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1758 "short" => sym::i16,
1759 "Bool" => sym::bool,
1760 "Boolean" => sym::bool,
1761 "boolean" => sym::bool,
1764 "float" => sym::f32,
1765 "double" => sym::f64,
1770 /// Only used in a specific case of type ascription suggestions
1771 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1772 let sm = self.r.session.source_map();
1773 start.to(sm.next_point(start))
1776 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1777 let sm = self.r.session.source_map();
1778 let base_snippet = sm.span_to_snippet(base_span);
1779 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1780 if let Ok(snippet) = sm.span_to_snippet(sp) {
1781 let len = snippet.trim_end().len() as u32;
1782 if snippet.trim() == ":" {
1784 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1785 let mut show_label = true;
1786 if sm.is_multiline(sp) {
1787 err.span_suggestion_short(
1789 "maybe you meant to write `;` here",
1791 Applicability::MaybeIncorrect,
1794 let after_colon_sp =
1795 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1796 if snippet.len() == 1 {
1798 err.span_suggestion(
1800 "maybe you meant to write a path separator here",
1802 Applicability::MaybeIncorrect,
1809 .type_ascription_path_suggestions
1813 err.downgrade_to_delayed_bug();
1816 if let Ok(base_snippet) = base_snippet {
1817 // Try to find an assignment
1818 let eq_span = sm.span_look_ahead(after_colon_sp, Some("="), Some(50));
1819 if let Ok(ref snippet) = sm.span_to_snippet(eq_span) && snippet == "=" {
1820 err.span_suggestion(
1822 "maybe you meant to write an assignment here",
1823 format!("let {}", base_snippet),
1824 Applicability::MaybeIncorrect,
1833 "expecting a type here because of type ascription",
1843 // try to give a suggestion for this pattern: `name = blah`, which is common in other languages
1844 // suggest `let name = blah` to introduce a new binding
1845 fn let_binding_suggestion(&mut self, err: &mut Diagnostic, ident_span: Span) -> bool {
1846 if let Some(Expr { kind: ExprKind::Assign(lhs, .. ), .. }) = self.diagnostic_metadata.in_assignment &&
1847 let ast::ExprKind::Path(None, _) = lhs.kind {
1848 if !ident_span.from_expansion() {
1849 err.span_suggestion_verbose(
1850 ident_span.shrink_to_lo(),
1851 "you might have meant to introduce a new binding",
1853 Applicability::MaybeIncorrect,
1861 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1862 let mut result = None;
1863 let mut seen_modules = FxHashSet::default();
1864 let mut worklist = vec![(self.r.graph_root, ThinVec::new())];
1866 while let Some((in_module, path_segments)) = worklist.pop() {
1867 // abort if the module is already found
1868 if result.is_some() {
1872 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1873 // abort if the module is already found or if name_binding is private external
1874 if result.is_some() || !name_binding.vis.is_visible_locally() {
1877 if let Some(module) = name_binding.module() {
1879 let mut path_segments = path_segments.clone();
1880 path_segments.push(ast::PathSegment::from_ident(ident));
1881 let module_def_id = module.def_id();
1882 if module_def_id == def_id {
1884 Path { span: name_binding.span, segments: path_segments, tokens: None };
1896 // add the module to the lookup
1897 if seen_modules.insert(module_def_id) {
1898 worklist.push((module, path_segments));
1908 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1909 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1910 let mut variants = Vec::new();
1911 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1912 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1913 let mut segms = enum_import_suggestion.path.segments.clone();
1914 segms.push(ast::PathSegment::from_ident(ident));
1915 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1916 variants.push((path, def_id, kind));
1923 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1924 fn suggest_using_enum_variant(
1926 err: &mut Diagnostic,
1927 source: PathSource<'_>,
1931 let Some(variants) = self.collect_enum_ctors(def_id) else {
1932 err.note("you might have meant to use one of the enum's variants");
1936 let suggest_only_tuple_variants =
1937 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1938 if suggest_only_tuple_variants {
1939 // Suggest only tuple variants regardless of whether they have fields and do not
1940 // suggest path with added parentheses.
1941 let suggestable_variants = variants
1943 .filter(|(.., kind)| *kind == CtorKind::Fn)
1944 .map(|(variant, ..)| path_names_to_string(variant))
1945 .collect::<Vec<_>>();
1947 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1949 let source_msg = if source.is_call() {
1951 } else if matches!(source, PathSource::TupleStruct(..)) {
1957 if !suggestable_variants.is_empty() {
1958 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1959 format!("try {} the enum's variant", source_msg)
1961 format!("try {} one of the enum's variants", source_msg)
1964 err.span_suggestions(
1967 suggestable_variants,
1968 Applicability::MaybeIncorrect,
1972 // If the enum has no tuple variants..
1973 if non_suggestable_variant_count == variants.len() {
1974 err.help(&format!("the enum has no tuple variants {}", source_msg));
1977 // If there are also non-tuple variants..
1978 if non_suggestable_variant_count == 1 {
1980 "you might have meant {} the enum's non-tuple variant",
1983 } else if non_suggestable_variant_count >= 1 {
1985 "you might have meant {} one of the enum's non-tuple variants",
1990 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
1991 let def_id = self.r.parent(ctor_def_id);
1992 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1994 CtorKind::Const => false,
1995 CtorKind::Fn if has_no_fields => false,
2000 let suggestable_variants = variants
2002 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
2003 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2004 .map(|(variant, kind)| match kind {
2005 CtorKind::Const => variant,
2006 CtorKind::Fn => format!("({}())", variant),
2008 .collect::<Vec<_>>();
2009 let no_suggestable_variant = suggestable_variants.is_empty();
2011 if !no_suggestable_variant {
2012 let msg = if suggestable_variants.len() == 1 {
2013 "you might have meant to use the following enum variant"
2015 "you might have meant to use one of the following enum variants"
2018 err.span_suggestions(
2021 suggestable_variants,
2022 Applicability::MaybeIncorrect,
2026 let suggestable_variants_with_placeholders = variants
2028 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
2029 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2030 .filter_map(|(variant, kind)| match kind {
2031 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
2034 .collect::<Vec<_>>();
2036 if !suggestable_variants_with_placeholders.is_empty() {
2038 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
2039 (true, 1) => "the following enum variant is available",
2040 (true, _) => "the following enum variants are available",
2041 (false, 1) => "alternatively, the following enum variant is available",
2043 "alternatively, the following enum variants are also available"
2047 err.span_suggestions(
2050 suggestable_variants_with_placeholders,
2051 Applicability::HasPlaceholders,
2056 if def_id.is_local() {
2057 if let Some(span) = self.def_span(def_id) {
2058 err.span_note(span, "the enum is defined here");
2063 pub(crate) fn report_missing_type_error(
2066 ) -> Option<(Span, &'static str, String, Applicability)> {
2067 let (ident, span) = match path {
2069 if !segment.has_generic_args
2070 && segment.ident.name != kw::SelfUpper
2071 && segment.ident.name != kw::Dyn =>
2073 (segment.ident.to_string(), segment.ident.span)
2077 let mut iter = ident.chars().map(|c| c.is_uppercase());
2078 let single_uppercase_char =
2079 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
2080 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
2083 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
2084 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
2085 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
2090 kind @ ItemKind::Fn(..)
2091 | kind @ ItemKind::Enum(..)
2092 | kind @ ItemKind::Struct(..)
2093 | kind @ ItemKind::Union(..),
2098 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
2099 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
2100 | (Some(Item { kind, .. }), false, _) => {
2101 // Likely missing type parameter.
2102 if let Some(generics) = kind.generics() {
2103 if span.overlaps(generics.span) {
2104 // Avoid the following:
2105 // error[E0405]: cannot find trait `A` in this scope
2106 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
2108 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
2109 // | ^- help: you might be missing a type parameter: `, A`
2111 // | not found in this scope
2114 let msg = "you might be missing a type parameter";
2115 let (span, sugg) = if let [.., param] = &generics.params[..] {
2116 let span = if let [.., bound] = ¶m.bounds[..] {
2118 } else if let GenericParam {
2119 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
2121 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
2125 (span, format!(", {}", ident))
2127 (generics.span, format!("<{}>", ident))
2129 // Do not suggest if this is coming from macro expansion.
2130 if span.can_be_used_for_suggestions() {
2132 span.shrink_to_hi(),
2135 Applicability::MaybeIncorrect,
2145 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
2146 /// optionally returning the closest match and whether it is reachable.
2147 pub(crate) fn suggestion_for_label_in_rib(
2151 ) -> Option<LabelSuggestion> {
2152 // Are ribs from this `rib_index` within scope?
2153 let within_scope = self.is_label_valid_from_rib(rib_index);
2155 let rib = &self.label_ribs[rib_index];
2159 .filter(|(id, _)| id.span.eq_ctxt(label.span))
2160 .map(|(id, _)| id.name)
2161 .collect::<Vec<Symbol>>();
2163 find_best_match_for_name(&names, label.name, None).map(|symbol| {
2164 // Upon finding a similar name, get the ident that it was from - the span
2165 // contained within helps make a useful diagnostic. In addition, determine
2166 // whether this candidate is within scope.
2167 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
2168 (*ident, within_scope)
2172 pub(crate) fn maybe_report_lifetime_uses(
2174 generics_span: Span,
2175 params: &[ast::GenericParam],
2177 for (param_index, param) in params.iter().enumerate() {
2178 let GenericParamKind::Lifetime = param.kind else { continue };
2180 let def_id = self.r.local_def_id(param.id);
2182 let use_set = self.lifetime_uses.remove(&def_id);
2184 "Use set for {:?}({:?} at {:?}) is {:?}",
2185 def_id, param.ident, param.ident.span, use_set
2188 let deletion_span = || {
2189 if params.len() == 1 {
2190 // if sole lifetime, remove the entire `<>` brackets
2192 } else if param_index == 0 {
2193 // if removing within `<>` brackets, we also want to
2194 // delete a leading or trailing comma as appropriate
2196 param.span().find_ancestor_inside(generics_span),
2197 params[param_index + 1].span().find_ancestor_inside(generics_span),
2199 (Some(param_span), Some(next_param_span)) => {
2200 Some(param_span.to(next_param_span.shrink_to_lo()))
2205 // if removing within `<>` brackets, we also want to
2206 // delete a leading or trailing comma as appropriate
2208 param.span().find_ancestor_inside(generics_span),
2209 params[param_index - 1].span().find_ancestor_inside(generics_span),
2211 (Some(param_span), Some(prev_param_span)) => {
2212 Some(prev_param_span.shrink_to_hi().to(param_span))
2219 Some(LifetimeUseSet::Many) => {}
2220 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
2221 debug!(?param.ident, ?param.ident.span, ?use_span);
2223 let elidable = matches!(use_ctxt, LifetimeCtxt::Ref);
2225 let deletion_span = deletion_span();
2226 self.r.lint_buffer.buffer_lint_with_diagnostic(
2227 lint::builtin::SINGLE_USE_LIFETIMES,
2230 &format!("lifetime parameter `{}` only used once", param.ident),
2231 lint::BuiltinLintDiagnostics::SingleUseLifetime {
2232 param_span: param.ident.span,
2233 use_span: Some((use_span, elidable)),
2239 debug!(?param.ident, ?param.ident.span);
2241 let deletion_span = deletion_span();
2242 self.r.lint_buffer.buffer_lint_with_diagnostic(
2243 lint::builtin::UNUSED_LIFETIMES,
2246 &format!("lifetime parameter `{}` never used", param.ident),
2247 lint::BuiltinLintDiagnostics::SingleUseLifetime {
2248 param_span: param.ident.span,
2258 pub(crate) fn emit_undeclared_lifetime_error(
2260 lifetime_ref: &ast::Lifetime,
2261 outer_lifetime_ref: Option<Ident>,
2263 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
2264 let mut err = if let Some(outer) = outer_lifetime_ref {
2265 let mut err = struct_span_err!(
2267 lifetime_ref.ident.span,
2269 "can't use generic parameters from outer item",
2271 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
2272 err.span_label(outer.span, "lifetime parameter from outer item");
2275 let mut err = struct_span_err!(
2277 lifetime_ref.ident.span,
2279 "use of undeclared lifetime name `{}`",
2282 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2285 self.suggest_introducing_lifetime(
2287 Some(lifetime_ref.ident.name.as_str()),
2288 |err, _, span, message, suggestion| {
2289 err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect);
2296 fn suggest_introducing_lifetime(
2298 err: &mut Diagnostic,
2300 suggest: impl Fn(&mut Diagnostic, bool, Span, &str, String) -> bool,
2302 let mut suggest_note = true;
2303 for rib in self.lifetime_ribs.iter().rev() {
2304 let mut should_continue = true;
2306 LifetimeRibKind::Generics { binder: _, span, kind } => {
2307 if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name {
2308 suggest_note = false; // Avoid displaying the same help multiple times.
2312 "lifetime `{}` is missing in item created through this procedural macro",
2319 let higher_ranked = matches!(
2321 LifetimeBinderKind::BareFnType
2322 | LifetimeBinderKind::PolyTrait
2323 | LifetimeBinderKind::WhereBound
2325 let (span, sugg) = if span.is_empty() {
2328 if higher_ranked { "for" } else { "" },
2329 name.unwrap_or("'a"),
2330 if higher_ranked { " " } else { "" },
2335 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2336 let sugg = format!("{}, ", name.unwrap_or("'a"));
2340 let message = format!(
2341 "consider making the {} lifetime-generic with a new `{}` lifetime",
2343 name.unwrap_or("'a"),
2345 should_continue = suggest(err, true, span, &message, sugg);
2347 "for more information on higher-ranked polymorphism, visit \
2348 https://doc.rust-lang.org/nomicon/hrtb.html",
2350 } else if let Some(name) = name {
2351 let message = format!("consider introducing lifetime `{}` here", name);
2352 should_continue = suggest(err, false, span, &message, sugg);
2354 let message = "consider introducing a named lifetime parameter";
2355 should_continue = suggest(err, false, span, &message, sugg);
2358 LifetimeRibKind::Item => break,
2361 if !should_continue {
2367 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2370 lifetime_ref.ident.span,
2372 "use of non-static lifetime `{}` in const generic",
2376 "for more information, see issue #74052 \
2377 <https://github.com/rust-lang/rust/issues/74052>",
2382 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2383 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2384 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2385 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2387 lifetime_ref: &ast::Lifetime,
2389 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2390 if !feature_active {
2392 &self.r.session.parse_sess,
2393 sym::generic_const_exprs,
2394 lifetime_ref.ident.span,
2395 "a non-static lifetime is not allowed in a `const`",
2401 pub(crate) fn report_missing_lifetime_specifiers(
2403 lifetime_refs: Vec<MissingLifetime>,
2404 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2405 ) -> ErrorGuaranteed {
2406 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
2407 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
2409 let mut err = struct_span_err!(
2413 "missing lifetime specifier{}",
2414 pluralize!(num_lifetimes)
2416 self.add_missing_lifetime_specifiers_label(
2419 function_param_lifetimes,
2424 fn add_missing_lifetime_specifiers_label(
2426 err: &mut Diagnostic,
2427 lifetime_refs: Vec<MissingLifetime>,
2428 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2430 for < in &lifetime_refs {
2434 "expected {} lifetime parameter{}",
2435 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
2436 pluralize!(lt.count),
2441 let mut in_scope_lifetimes: Vec<_> = self
2445 .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item))
2446 .flat_map(|rib| rib.bindings.iter())
2447 .map(|(&ident, &res)| (ident, res))
2448 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
2450 debug!(?in_scope_lifetimes);
2452 debug!(?function_param_lifetimes);
2453 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
2454 let elided_len = param_lifetimes.len();
2455 let num_params = params.len();
2457 let mut m = String::new();
2459 for (i, info) in params.iter().enumerate() {
2460 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
2461 debug_assert_ne!(lifetime_count, 0);
2463 err.span_label(span, "");
2466 if i + 1 < num_params {
2468 } else if num_params == 2 {
2471 m.push_str(", or ");
2475 let help_name = if let Some(ident) = ident {
2476 format!("`{}`", ident)
2478 format!("argument {}", index + 1)
2481 if lifetime_count == 1 {
2482 m.push_str(&help_name[..])
2484 m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..])
2488 if num_params == 0 {
2490 "this function's return type contains a borrowed value, \
2491 but there is no value for it to be borrowed from",
2493 if in_scope_lifetimes.is_empty() {
2494 in_scope_lifetimes = vec![(
2495 Ident::with_dummy_span(kw::StaticLifetime),
2496 (DUMMY_NODE_ID, LifetimeRes::Static),
2499 } else if elided_len == 0 {
2501 "this function's return type contains a borrowed value with \
2502 an elided lifetime, but the lifetime cannot be derived from \
2505 if in_scope_lifetimes.is_empty() {
2506 in_scope_lifetimes = vec![(
2507 Ident::with_dummy_span(kw::StaticLifetime),
2508 (DUMMY_NODE_ID, LifetimeRes::Static),
2511 } else if num_params == 1 {
2513 "this function's return type contains a borrowed value, \
2514 but the signature does not say which {} it is borrowed from",
2519 "this function's return type contains a borrowed value, \
2520 but the signature does not say whether it is borrowed from {}",
2526 let existing_name = match &in_scope_lifetimes[..] {
2527 [] => Symbol::intern("'a"),
2528 [(existing, _)] => existing.name,
2529 _ => Symbol::intern("'lifetime"),
2532 let mut spans_suggs: Vec<_> = Vec::new();
2533 let build_sugg = |lt: MissingLifetime| match lt.kind {
2534 MissingLifetimeKind::Underscore => {
2535 debug_assert_eq!(lt.count, 1);
2536 (lt.span, existing_name.to_string())
2538 MissingLifetimeKind::Ampersand => {
2539 debug_assert_eq!(lt.count, 1);
2540 (lt.span.shrink_to_hi(), format!("{} ", existing_name))
2542 MissingLifetimeKind::Comma => {
2543 let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
2547 (lt.span.shrink_to_hi(), sugg)
2549 MissingLifetimeKind::Brackets => {
2550 let sugg: String = std::iter::once("<")
2552 std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
2556 (lt.span.shrink_to_hi(), sugg)
2559 for < in &lifetime_refs {
2560 spans_suggs.push(build_sugg(lt));
2562 debug!(?spans_suggs);
2563 match in_scope_lifetimes.len() {
2565 if let Some((param_lifetimes, _)) = function_param_lifetimes {
2566 for lt in param_lifetimes {
2567 spans_suggs.push(build_sugg(lt))
2570 self.suggest_introducing_lifetime(
2573 |err, higher_ranked, span, message, intro_sugg| {
2574 err.multipart_suggestion_verbose(
2576 std::iter::once((span, intro_sugg))
2577 .chain(spans_suggs.iter().cloned())
2579 Applicability::MaybeIncorrect,
2586 err.multipart_suggestion_verbose(
2587 &format!("consider using the `{}` lifetime", existing_name),
2589 Applicability::MaybeIncorrect,
2592 // Record as using the suggested resolution.
2593 let (_, (_, res)) = in_scope_lifetimes[0];
2594 for < in &lifetime_refs {
2595 self.r.lifetimes_res_map.insert(lt.id, res);
2599 let lifetime_spans: Vec<_> =
2600 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
2601 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2603 if spans_suggs.len() > 0 {
2604 // This happens when we have `Foo<T>` where we point at the space before `T`,
2605 // but this can be confusing so we give a suggestion with placeholders.
2606 err.multipart_suggestion_verbose(
2607 "consider using one of the available lifetimes here",
2609 Applicability::HasPlaceholders,
2617 /// Report lifetime/lifetime shadowing as an error.
2618 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2619 let mut err = struct_span_err!(
2623 "lifetime name `{}` shadows a lifetime name that is already in scope",
2626 err.span_label(orig.span, "first declared here");
2627 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2631 /// Shadowing involving a label is only a warning for historical reasons.
2632 //FIXME: make this a proper lint.
2633 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2634 let name = shadower.name;
2635 let shadower = shadower.span;
2636 let mut err = sess.struct_span_warn(
2638 &format!("label name `{}` shadows a label name that is already in scope", name),
2640 err.span_label(orig, "first declared here");
2641 err.span_label(shadower, format!("label `{}` already in scope", name));