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();
282 "you may want to use a bool value instead",
283 format!("{}", item_typo),
285 // FIXME(vincenzopalazzo): make the check smarter,
286 // and maybe expand with levenshtein distance checks
287 } else if item_str.as_str() == "printf" {
290 "you may have meant to use the `print` macro",
296 (format!("not found in {mod_str}"), override_suggestion)
300 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
304 could_be_expr: false,
310 /// Handles error reporting for `smart_resolve_path_fragment` function.
311 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
312 pub(crate) fn smart_resolve_report_errors(
316 source: PathSource<'_>,
318 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
319 debug!(?res, ?source);
320 let base_error = self.make_base_error(path, span, source, res);
321 let code = source.error_code(res.is_some());
323 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
325 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
327 if let Some((span, label)) = base_error.span_label {
328 err.span_label(span, label);
331 if let Some(ref sugg) = base_error.suggestion {
332 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
335 self.suggest_bare_struct_literal(&mut err);
337 if self.suggest_pattern_match_with_let(&mut err, source, span) {
339 err.span_label(base_error.span, &base_error.fallback_label);
340 return (err, Vec::new());
343 self.suggest_self_or_self_ref(&mut err, path, span);
344 self.detect_assoct_type_constraint_meant_as_path(&mut err, &base_error);
345 if self.suggest_self_ty(&mut err, source, path, span)
346 || self.suggest_self_value(&mut err, source, path, span)
348 return (err, Vec::new());
351 let (found, candidates) =
352 self.try_lookup_name_relaxed(&mut err, source, path, span, res, &base_error);
354 return (err, candidates);
357 if !self.type_ascription_suggestion(&mut err, base_error.span) {
359 self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
361 // if we have suggested using pattern matching, then don't add needless suggestions
363 fallback |= self.suggest_typo(&mut err, source, path, span, &base_error);
367 err.span_label(base_error.span, &base_error.fallback_label);
370 self.err_code_special_cases(&mut err, source, path, span);
375 fn detect_assoct_type_constraint_meant_as_path(
377 err: &mut Diagnostic,
378 base_error: &BaseError,
380 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
381 let TyKind::Path(_, path) = &ty.kind else { return; };
382 for segment in &path.segments {
383 let Some(params) = &segment.args else { continue; };
384 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
385 for param in ¶ms.args {
386 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
387 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
390 for bound in bounds {
391 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
396 if base_error.span == trait_ref.span {
397 err.span_suggestion_verbose(
398 constraint.ident.span.between(trait_ref.span),
399 "you might have meant to write a path instead of an associated type bound",
401 Applicability::MachineApplicable,
409 fn suggest_self_or_self_ref(&mut self, err: &mut Diagnostic, path: &[Segment], span: Span) {
410 if !self.self_type_is_available() {
413 let Some(path_last_segment) = path.last() else { return };
414 let item_str = path_last_segment.ident;
415 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
416 if ["this", "my"].contains(&item_str.as_str()) {
417 err.span_suggestion_short(
419 "you might have meant to use `self` here instead",
421 Applicability::MaybeIncorrect,
423 if !self.self_value_is_available(path[0].ident.span) {
424 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
425 &self.diagnostic_metadata.current_function
427 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
428 (param.span.shrink_to_lo(), "&self, ")
434 .span_through_char(*fn_span, '(')
439 err.span_suggestion_verbose(
441 "if you meant to use `self`, you are also missing a `self` receiver \
444 Applicability::MaybeIncorrect,
451 fn try_lookup_name_relaxed(
453 err: &mut Diagnostic,
454 source: PathSource<'_>,
458 base_error: &BaseError,
459 ) -> (bool, Vec<ImportSuggestion>) {
460 // Try to lookup name in more relaxed fashion for better error reporting.
461 let ident = path.last().unwrap().ident;
462 let is_expected = &|res| source.is_expected(res);
463 let ns = source.namespace();
464 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
465 let path_str = Segment::names_to_string(path);
466 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
467 let mut candidates = self
469 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
471 .filter(|ImportSuggestion { did, .. }| {
472 match (did, res.and_then(|res| res.opt_def_id())) {
473 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
477 .collect::<Vec<_>>();
478 let crate_def_id = CRATE_DEF_ID.to_def_id();
479 // Try to filter out intrinsics candidates, as long as we have
480 // some other candidates to suggest.
481 let intrinsic_candidates: Vec<_> = candidates
482 .drain_filter(|sugg| {
483 let path = path_names_to_string(&sugg.path);
484 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
487 if candidates.is_empty() {
488 // Put them back if we have no more candidates to suggest...
489 candidates.extend(intrinsic_candidates);
491 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
492 let mut enum_candidates: Vec<_> = self
494 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
496 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
497 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
499 if !enum_candidates.is_empty() {
500 if let (PathSource::Type, Some(span)) =
501 (source, self.diagnostic_metadata.current_type_ascription.last())
507 .type_ascription_path_suggestions
511 // Already reported this issue on the lhs of the type ascription.
512 err.downgrade_to_delayed_bug();
513 return (true, candidates);
517 enum_candidates.sort();
519 // Contextualize for E0412 "cannot find type", but don't belabor the point
520 // (that it's a variant) for E0573 "expected type, found variant".
521 let preamble = if res.is_none() {
522 let others = match enum_candidates.len() {
524 2 => " and 1 other".to_owned(),
525 n => format!(" and {} others", n),
527 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
531 let msg = format!("{}try using the variant's enum", preamble);
533 err.span_suggestions(
536 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
537 Applicability::MachineApplicable,
542 // Try Levenshtein algorithm.
544 self.lookup_typo_candidate(path, source.namespace(), is_expected).to_opt_suggestion();
545 if path.len() == 1 && self.self_type_is_available() {
546 if let Some(candidate) =
547 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
549 let self_is_available = self.self_value_is_available(path[0].ident.span);
551 AssocSuggestion::Field => {
552 if self_is_available {
555 "you might have meant to use the available field",
556 format!("self.{path_str}"),
557 Applicability::MachineApplicable,
560 err.span_label(span, "a field by this name exists in `Self`");
563 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
564 let msg = if called {
565 "you might have meant to call the method"
567 "you might have meant to refer to the method"
572 format!("self.{path_str}"),
573 Applicability::MachineApplicable,
576 AssocSuggestion::MethodWithSelf { .. }
577 | AssocSuggestion::AssocFn { .. }
578 | AssocSuggestion::AssocConst
579 | AssocSuggestion::AssocType => {
582 &format!("you might have meant to {}", candidate.action()),
583 format!("Self::{path_str}"),
584 Applicability::MachineApplicable,
588 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
589 return (true, candidates);
592 // If the first argument in call is `self` suggest calling a method.
593 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
594 let mut args_snippet = String::new();
595 if let Some(args_span) = args_span {
596 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
597 args_snippet = snippet;
603 &format!("try calling `{ident}` as a method"),
604 format!("self.{path_str}({args_snippet})"),
605 Applicability::MachineApplicable,
607 return (true, candidates);
611 // Try context-dependent help if relaxed lookup didn't work.
612 if let Some(res) = res {
613 if self.smart_resolve_context_dependent_help(
619 &base_error.fallback_label,
621 // We do this to avoid losing a secondary span when we override the main error span.
622 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
623 return (true, candidates);
626 return (false, candidates);
629 fn suggest_trait_and_bounds(
631 err: &mut Diagnostic,
632 source: PathSource<'_>,
635 base_error: &BaseError,
638 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
639 let mut fallback = false;
642 PathSource::Trait(AliasPossibility::Maybe),
643 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
645 ) = (source, res, is_macro)
647 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
649 let spans: Vec<Span> = bounds
651 .map(|bound| bound.span())
652 .filter(|&sp| sp != base_error.span)
655 let start_span = bounds[0].span();
656 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
657 let end_span = bounds.last().unwrap().span();
658 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
659 let last_bound_span = spans.last().cloned().unwrap();
660 let mut multi_span: MultiSpan = spans.clone().into();
662 let msg = if sp == last_bound_span {
664 "...because of {these} bound{s}",
665 these = pluralize!("this", bounds.len() - 1),
666 s = pluralize!(bounds.len() - 1),
671 multi_span.push_span_label(sp, msg);
673 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
676 "`+` is used to constrain a \"trait object\" type with lifetimes or \
677 auto-traits; structs and enums can't be bound in that way",
679 if bounds.iter().all(|bound| match bound {
680 ast::GenericBound::Outlives(_) => true,
681 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
683 let mut sugg = vec![];
684 if base_error.span != start_span {
685 sugg.push((start_span.until(base_error.span), String::new()));
687 if base_error.span != end_span {
688 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
691 err.multipart_suggestion(
692 "if you meant to use a type and not a trait here, remove the bounds",
694 Applicability::MaybeIncorrect,
700 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
706 err: &mut Diagnostic,
707 source: PathSource<'_>,
710 base_error: &BaseError,
712 let is_expected = &|res| source.is_expected(res);
713 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
714 let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
715 let is_in_same_file = &|sp1, sp2| {
716 let source_map = self.r.session.source_map();
717 let file1 = source_map.span_to_filename(sp1);
718 let file2 = source_map.span_to_filename(sp2);
721 // print 'you might have meant' if the candidate is (1) is a shadowed name with
722 // accessible definition and (2) either defined in the same crate as the typo
723 // (could be in a different file) or introduced in the same file as the typo
724 // (could belong to a different crate)
725 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
728 .map_or(false, |id| id.is_local() || is_in_same_file(span, sugg_span))
732 format!("you might have meant to refer to this {}", res.descr()),
736 let mut fallback = false;
737 let typo_sugg = typo_sugg.to_opt_suggestion();
738 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
740 match self.diagnostic_metadata.current_let_binding {
741 Some((pat_sp, Some(ty_sp), None))
742 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
744 err.span_suggestion_short(
745 pat_sp.between(ty_sp),
746 "use `=` if you meant to assign",
748 Applicability::MaybeIncorrect,
754 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
755 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
756 if !self.r.add_typo_suggestion(err, suggestion, ident_span) {
757 fallback = !self.let_binding_suggestion(err, ident_span);
763 fn err_code_special_cases(
765 err: &mut Diagnostic,
766 source: PathSource<'_>,
770 if let Some(err_code) = &err.code {
771 if err_code == &rustc_errors::error_code!(E0425) {
772 for label_rib in &self.label_ribs {
773 for (label_ident, node_id) in &label_rib.bindings {
774 let ident = path.last().unwrap().ident;
775 if format!("'{}", ident) == label_ident.to_string() {
776 err.span_label(label_ident.span, "a label with a similar name exists");
777 if let PathSource::Expr(Some(Expr {
778 kind: ExprKind::Break(None, Some(_)),
784 "use the similarly named label",
786 Applicability::MaybeIncorrect,
788 // Do not lint against unused label when we suggest them.
789 self.diagnostic_metadata.unused_labels.remove(node_id);
794 } else if err_code == &rustc_errors::error_code!(E0412) {
795 if let Some(correct) = Self::likely_rust_type(path) {
798 "perhaps you intended to use this type",
800 Applicability::MaybeIncorrect,
807 /// Emit special messages for unresolved `Self` and `self`.
810 err: &mut Diagnostic,
811 source: PathSource<'_>,
815 if !is_self_type(path, source.namespace()) {
818 err.code(rustc_errors::error_code!(E0411));
819 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
820 if let Some(item_kind) = self.diagnostic_metadata.current_item {
821 if !item_kind.ident.span.is_dummy() {
823 item_kind.ident.span,
825 "`Self` not allowed in {} {}",
826 item_kind.kind.article(),
827 item_kind.kind.descr()
835 fn suggest_self_value(
837 err: &mut Diagnostic,
838 source: PathSource<'_>,
842 if !is_self_value(path, source.namespace()) {
846 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
847 err.code(rustc_errors::error_code!(E0424));
852 "`self` value is a keyword and may not be bound to variables or shadowed"
854 _ => "`self` value is a keyword only available in methods with a `self` parameter",
857 let is_assoc_fn = self.self_type_is_available();
858 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
859 // The current function has a `self' parameter, but we were unable to resolve
860 // a reference to `self`. This can only happen if the `self` identifier we
861 // are resolving came from a different hygiene context.
862 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
863 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
865 let doesnt = if is_assoc_fn {
866 let (span, sugg) = fn_kind
870 .map(|p| (p.span.shrink_to_lo(), "&self, "))
872 // Try to look for the "(" after the function name, if possible.
873 // This avoids placing the suggestion into the visibility specifier.
876 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
881 .span_through_char(span, '(')
886 err.span_suggestion_verbose(
888 "add a `self` receiver parameter to make the associated `fn` a method",
890 Applicability::MaybeIncorrect,
896 if let Some(ident) = fn_kind.ident() {
899 &format!("this function {} have a `self` parameter", doesnt),
903 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
905 item_kind.ident.span,
907 "`self` not allowed in {} {}",
908 item_kind.kind.article(),
909 item_kind.kind.descr()
916 fn suggest_swapping_misplaced_self_ty_and_trait(
918 err: &mut Diagnostic,
919 source: PathSource<'_>,
923 if let Some((trait_ref, self_ty)) =
924 self.diagnostic_metadata.currently_processing_impl_trait.clone()
925 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
926 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
927 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
928 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
929 && trait_ref.path.span == span
930 && let PathSource::Trait(_) = source
931 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
932 && let Ok(self_ty_str) =
933 self.r.session.source_map().span_to_snippet(self_ty.span)
934 && let Ok(trait_ref_str) =
935 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
937 err.multipart_suggestion(
938 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
939 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
940 Applicability::MaybeIncorrect,
945 fn suggest_bare_struct_literal(&mut self, err: &mut Diagnostic) {
946 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
947 err.multipart_suggestion(
948 "you might have meant to write a `struct` literal",
950 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
951 (span.shrink_to_hi(), "}".to_string()),
953 Applicability::HasPlaceholders,
958 fn suggest_pattern_match_with_let(
960 err: &mut Diagnostic,
961 source: PathSource<'_>,
964 if let PathSource::Expr(_) = source &&
967 kind: ExprKind::Assign(lhs, _, _),
969 }) = self.diagnostic_metadata.in_if_condition {
970 // Icky heuristic so we don't suggest:
971 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
972 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
973 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
974 err.span_suggestion_verbose(
975 expr_span.shrink_to_lo(),
976 "you might have meant to use pattern matching",
978 Applicability::MaybeIncorrect,
986 fn get_single_associated_item(
989 source: &PathSource<'_>,
990 filter_fn: &impl Fn(Res) -> bool,
991 ) -> Option<TypoSuggestion> {
992 if let crate::PathSource::TraitItem(_) = source {
993 let mod_path = &path[..path.len() - 1];
994 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
995 self.resolve_path(mod_path, None, None)
997 let resolutions = self.r.resolutions(module).borrow();
998 let targets: Vec<_> =
1001 .filter_map(|(key, resolution)| {
1002 resolution.borrow().binding.map(|binding| binding.res()).and_then(
1003 |res| if filter_fn(res) { Some((key, res)) } else { None },
1007 if targets.len() == 1 {
1008 let target = targets[0];
1009 return Some(TypoSuggestion::single_item_from_ident(target.0.ident, target.1));
1016 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
1017 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
1018 // Detect that we are actually in a `where` predicate.
1019 let (bounded_ty, bounds, where_span) =
1020 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
1022 bound_generic_params,
1025 })) = self.diagnostic_metadata.current_where_predicate
1027 if !bound_generic_params.is_empty() {
1030 (bounded_ty, bounds, span)
1035 // Confirm that the target is an associated type.
1036 let (ty, position, path) = if let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind {
1037 // use this to verify that ident is a type param.
1038 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
1042 partial_res.full_res(),
1043 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1047 (&qself.ty, qself.position, path)
1052 let peeled_ty = ty.peel_refs();
1053 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
1054 // Confirm that the `SelfTy` is a type parameter.
1055 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1059 partial_res.full_res(),
1060 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1065 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
1066 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
1067 ) = (&type_param_path.segments[..], &bounds[..])
1069 if let [ast::PathSegment { ident, args: None, .. }] =
1070 &poly_trait_ref.trait_ref.path.segments[..]
1072 if ident.span == span {
1073 err.span_suggestion_verbose(
1075 &format!("constrain the associated type to `{}`", ident),
1081 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
1082 .unwrap_or_else(|_| constrain_ident.to_string()),
1083 path.segments[..position]
1085 .map(|segment| path_segment_to_string(segment))
1086 .collect::<Vec<_>>()
1088 path.segments[position..]
1090 .map(|segment| path_segment_to_string(segment))
1091 .collect::<Vec<_>>()
1095 Applicability::MaybeIncorrect,
1105 /// Check if the source is call expression and the first argument is `self`. If true,
1106 /// return the span of whole call and the span for all arguments expect the first one (`self`).
1107 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
1108 let mut has_self_arg = None;
1109 if let PathSource::Expr(Some(parent)) = source {
1110 match &parent.kind {
1111 ExprKind::Call(_, args) if !args.is_empty() => {
1112 let mut expr_kind = &args[0].kind;
1115 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1116 if arg_name.segments[0].ident.name == kw::SelfLower {
1117 let call_span = parent.span;
1118 let tail_args_span = if args.len() > 1 {
1121 args.last().unwrap().span.hi(),
1128 has_self_arg = Some((call_span, tail_args_span));
1132 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1143 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1144 // HACK(estebank): find a better way to figure out that this was a
1145 // parser issue where a struct literal is being used on an expression
1146 // where a brace being opened means a block is being started. Look
1147 // ahead for the next text to see if `span` is followed by a `{`.
1148 let sm = self.r.session.source_map();
1149 let sp = sm.span_look_ahead(span, None, Some(50));
1150 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
1151 // In case this could be a struct literal that needs to be surrounded
1152 // by parentheses, find the appropriate span.
1153 let closing_span = sm.span_look_ahead(span, Some("}"), Some(50));
1154 let closing_brace: Option<Span> = sm
1155 .span_to_snippet(closing_span)
1156 .map_or(None, |s| if s == "}" { Some(span.to(closing_span)) } else { None });
1157 (followed_by_brace, closing_brace)
1160 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
1162 /// Returns `true` if able to provide context-dependent help.
1163 fn smart_resolve_context_dependent_help(
1165 err: &mut Diagnostic,
1167 source: PathSource<'_>,
1170 fallback_label: &str,
1172 let ns = source.namespace();
1173 let is_expected = &|res| source.is_expected(res);
1175 let path_sep = |err: &mut Diagnostic, expr: &Expr, kind: DefKind| {
1176 const MESSAGE: &str = "use the path separator to refer to an item";
1178 let (lhs_span, rhs_span) = match &expr.kind {
1179 ExprKind::Field(base, ident) => (base.span, ident.span),
1180 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1181 (receiver.span, *span)
1186 if lhs_span.eq_ctxt(rhs_span) {
1187 err.span_suggestion(
1188 lhs_span.between(rhs_span),
1191 Applicability::MaybeIncorrect,
1194 } else if kind == DefKind::Struct
1195 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1196 && let Ok(snippet) = self.r.session.source_map().span_to_snippet(lhs_source_span)
1198 // The LHS is a type that originates from a macro call.
1199 // We have to add angle brackets around it.
1201 err.span_suggestion_verbose(
1202 lhs_source_span.until(rhs_span),
1204 format!("<{snippet}>::"),
1205 Applicability::MaybeIncorrect,
1209 // Either we were unable to obtain the source span / the snippet or
1210 // the LHS originates from a macro call and it is not a type and thus
1211 // there is no way to replace `.` with `::` and still somehow suggest
1218 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1220 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1221 | PathSource::TupleStruct(span, _) => {
1222 // We want the main underline to cover the suggested code as well for
1224 err.set_span(*span);
1231 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1232 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1235 PathSource::Expr(Some(
1236 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1237 )) if path_sep(err, &parent, DefKind::Struct) => {}
1243 | ExprKind::Binary(..)
1244 | ExprKind::Unary(..)
1246 | ExprKind::While(..)
1247 | ExprKind::ForLoop(..)
1248 | ExprKind::Match(..),
1251 ) if followed_by_brace => {
1252 if let Some(sp) = closing_brace {
1253 err.span_label(span, fallback_label);
1254 err.multipart_suggestion(
1255 "surround the struct literal with parentheses",
1257 (sp.shrink_to_lo(), "(".to_string()),
1258 (sp.shrink_to_hi(), ")".to_string()),
1260 Applicability::MaybeIncorrect,
1264 span, // Note the parentheses surrounding the suggestion below
1266 "you might want to surround a struct literal with parentheses: \
1267 `({} {{ /* fields */ }})`?",
1273 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1274 let span = find_span(&source, err);
1275 if let Some(span) = self.def_span(def_id) {
1276 err.span_label(span, &format!("`{}` defined here", path_str));
1278 let (tail, descr, applicability) = match source {
1279 PathSource::Pat | PathSource::TupleStruct(..) => {
1280 ("", "pattern", Applicability::MachineApplicable)
1282 _ => (": val", "literal", Applicability::HasPlaceholders),
1284 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1288 .map(|f| format!("{}{}", f.node, tail))
1289 .collect::<Vec<String>>()
1293 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1295 let pad = match self.r.field_names.get(&def_id) {
1296 Some(fields) if fields.is_empty() => "",
1299 err.span_suggestion(
1301 &format!("use struct {} syntax instead", descr),
1302 format!("{path_str} {{{pad}{fields}{pad}}}"),
1307 err.span_label(span, fallback_label);
1312 match (res, source) {
1314 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1315 PathSource::Expr(Some(Expr {
1316 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1318 | PathSource::Struct,
1320 err.span_label(span, fallback_label);
1321 err.span_suggestion_verbose(
1322 span.shrink_to_hi(),
1323 "use `!` to invoke the macro",
1325 Applicability::MaybeIncorrect,
1327 if path_str == "try" && span.rust_2015() {
1328 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1331 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1332 err.span_label(span, fallback_label);
1334 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1335 err.span_label(span, "type aliases cannot be used as traits");
1336 if self.r.session.is_nightly_build() {
1337 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1339 if let Some(span) = self.def_span(def_id) {
1340 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1341 // The span contains a type alias so we should be able to
1342 // replace `type` with `trait`.
1343 let snip = snip.replacen("type", "trait", 1);
1344 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1346 err.span_help(span, msg);
1354 Res::Def(kind @ (DefKind::Mod | DefKind::Trait), _),
1355 PathSource::Expr(Some(parent)),
1357 if !path_sep(err, &parent, kind) {
1362 Res::Def(DefKind::Enum, def_id),
1363 PathSource::TupleStruct(..) | PathSource::Expr(..),
1366 .diagnostic_metadata
1367 .current_type_ascription
1373 .type_ascription_path_suggestions
1379 err.downgrade_to_delayed_bug();
1380 // We already suggested changing `:` into `::` during parsing.
1384 self.suggest_using_enum_variant(err, source, def_id, span);
1386 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1387 let (ctor_def, ctor_vis, fields) =
1388 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1389 if let PathSource::Expr(Some(parent)) = source {
1390 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1391 bad_struct_syntax_suggestion(def_id);
1397 bad_struct_syntax_suggestion(def_id);
1401 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1402 if !is_expected(ctor_def) || is_accessible {
1406 let field_spans = match source {
1407 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1408 PathSource::TupleStruct(_, pattern_spans) => {
1409 err.set_primary_message(
1410 "cannot match against a tuple struct which contains private fields",
1413 // Use spans of the tuple struct pattern.
1414 Some(Vec::from(pattern_spans))
1416 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1417 _ if source.is_call() => {
1418 err.set_primary_message(
1419 "cannot initialize a tuple struct which contains private fields",
1422 // Use spans of the tuple struct definition.
1426 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1431 if let Some(spans) =
1432 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1434 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1435 .filter(|(vis, _)| {
1436 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1438 .map(|(_, span)| *span)
1441 if non_visible_spans.len() > 0 {
1442 let mut m: MultiSpan = non_visible_spans.clone().into();
1445 .for_each(|s| m.push_span_label(s, "private field"));
1446 err.span_note(m, "constructor is not visible here due to private fields");
1452 err.span_label(span, "constructor is not visible here due to private fields");
1454 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
1455 bad_struct_syntax_suggestion(def_id);
1457 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1459 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1460 let span = find_span(&source, err);
1461 if let Some(span) = self.def_span(def_id) {
1462 err.span_label(span, &format!("`{}` defined here", path_str));
1464 err.span_suggestion(
1466 "use this syntax instead",
1468 Applicability::MaybeIncorrect,
1474 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
1475 let def_id = self.r.parent(ctor_def_id);
1476 if let Some(span) = self.def_span(def_id) {
1477 err.span_label(span, &format!("`{}` defined here", path_str));
1479 let fields = self.r.field_names.get(&def_id).map_or_else(
1480 || "/* fields */".to_string(),
1481 |fields| vec!["_"; fields.len()].join(", "),
1483 err.span_suggestion(
1485 "use the tuple variant pattern syntax instead",
1486 format!("{}({})", path_str, fields),
1487 Applicability::HasPlaceholders,
1490 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
1491 err.span_label(span, fallback_label);
1492 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1494 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1495 err.note("can't use a type alias as a constructor");
1502 /// Given the target `ident` and `kind`, search for the similarly named associated item
1503 /// in `self.current_trait_ref`.
1504 pub(crate) fn find_similarly_named_assoc_item(
1507 kind: &AssocItemKind,
1508 ) -> Option<Symbol> {
1509 let (module, _) = self.current_trait_ref.as_ref()?;
1510 if ident == kw::Underscore {
1511 // We do nothing for `_`.
1515 let resolutions = self.r.resolutions(module);
1516 let targets = resolutions
1519 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1520 .filter(|(_, res)| match (kind, res) {
1521 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1522 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1523 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
1526 .map(|(key, _)| key.ident.name)
1527 .collect::<Vec<_>>();
1529 find_best_match_for_name(&targets, ident, None)
1532 fn lookup_assoc_candidate<FilterFn>(
1536 filter_fn: FilterFn,
1538 ) -> Option<AssocSuggestion>
1540 FilterFn: Fn(Res) -> bool,
1542 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1544 TyKind::Path(None, _) => Some(t.id),
1545 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1546 // This doesn't handle the remaining `Ty` variants as they are not
1547 // that commonly the self_type, it might be interesting to provide
1548 // support for those in future.
1552 // Fields are generally expected in the same contexts as locals.
1553 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1554 if let Some(node_id) =
1555 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1557 // Look for a field with the same name in the current self_type.
1558 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1559 if let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) =
1560 resolution.full_res()
1562 if let Some(field_names) = self.r.field_names.get(&did) {
1563 if field_names.iter().any(|&field_name| ident.name == field_name.node) {
1564 return Some(AssocSuggestion::Field);
1572 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1573 for assoc_item in items {
1574 if assoc_item.ident == ident {
1575 return Some(match &assoc_item.kind {
1576 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1577 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1578 AssocSuggestion::MethodWithSelf { called }
1580 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
1581 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
1582 ast::AssocItemKind::MacCall(_) => continue,
1588 // Look for associated items in the current trait.
1589 if let Some((module, _)) = self.current_trait_ref {
1590 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1591 ModuleOrUniformRoot::Module(module),
1596 let res = binding.res();
1598 if self.r.has_self.contains(&res.def_id()) {
1599 return Some(AssocSuggestion::MethodWithSelf { called });
1602 Res::Def(DefKind::AssocFn, _) => {
1603 return Some(AssocSuggestion::AssocFn { called });
1605 Res::Def(DefKind::AssocConst, _) => {
1606 return Some(AssocSuggestion::AssocConst);
1608 Res::Def(DefKind::AssocTy, _) => {
1609 return Some(AssocSuggestion::AssocType);
1621 fn lookup_typo_candidate(
1625 filter_fn: &impl Fn(Res) -> bool,
1626 ) -> TypoCandidate {
1627 let mut names = Vec::new();
1628 if path.len() == 1 {
1629 let mut ctxt = path.last().unwrap().ident.span.ctxt();
1631 // Search in lexical scope.
1632 // Walk backwards up the ribs in scope and collect candidates.
1633 for rib in self.ribs[ns].iter().rev() {
1634 let rib_ctxt = if rib.kind.contains_params() {
1635 ctxt.normalize_to_macros_2_0()
1637 ctxt.normalize_to_macro_rules()
1640 // Locals and type parameters
1641 for (ident, &res) in &rib.bindings {
1642 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
1643 names.push(TypoSuggestion::typo_from_ident(*ident, res));
1647 if let RibKind::MacroDefinition(def) = rib.kind && def == self.r.macro_def(ctxt) {
1648 // If an invocation of this macro created `ident`, give up on `ident`
1649 // and switch to `ident`'s source from the macro definition.
1655 if let RibKind::ModuleRibKind(module) = rib.kind {
1656 // Items from this module
1657 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
1659 if let ModuleKind::Block = module.kind {
1660 // We can see through blocks
1662 // Items from the prelude
1663 if !module.no_implicit_prelude {
1664 let extern_prelude = self.r.extern_prelude.clone();
1665 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1668 .maybe_process_path_extern(ident.name)
1669 .and_then(|crate_id| {
1671 Res::Def(DefKind::Mod, crate_id.as_def_id());
1673 if filter_fn(crate_mod) {
1674 Some(TypoSuggestion::typo_from_ident(*ident, crate_mod))
1681 if let Some(prelude) = self.r.prelude {
1682 self.r.add_module_candidates(prelude, &mut names, &filter_fn, None);
1689 // Add primitive types to the mix
1690 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1691 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1692 TypoSuggestion::typo_from_name(prim_ty.name(), Res::PrimTy(*prim_ty))
1696 // Search in module.
1697 let mod_path = &path[..path.len() - 1];
1698 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1699 self.resolve_path(mod_path, Some(TypeNS), None)
1701 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
1705 let name = path[path.len() - 1].ident.name;
1706 // Make sure error reporting is deterministic.
1707 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1709 match find_best_match_for_name(
1710 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1715 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found) else {
1716 return TypoCandidate::None;
1719 TypoCandidate::Shadowed(sugg.res, sugg.span)
1721 TypoCandidate::Typo(sugg)
1724 _ => TypoCandidate::None,
1728 // Returns the name of the Rust type approximately corresponding to
1729 // a type name in another programming language.
1730 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1731 let name = path[path.len() - 1].ident.as_str();
1732 // Common Java types
1734 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1735 "short" => sym::i16,
1736 "Bool" => sym::bool,
1737 "Boolean" => sym::bool,
1738 "boolean" => sym::bool,
1741 "float" => sym::f32,
1742 "double" => sym::f64,
1747 /// Only used in a specific case of type ascription suggestions
1748 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1749 let sm = self.r.session.source_map();
1750 start.to(sm.next_point(start))
1753 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1754 let sm = self.r.session.source_map();
1755 let base_snippet = sm.span_to_snippet(base_span);
1756 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1757 if let Ok(snippet) = sm.span_to_snippet(sp) {
1758 let len = snippet.trim_end().len() as u32;
1759 if snippet.trim() == ":" {
1761 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1762 let mut show_label = true;
1763 if sm.is_multiline(sp) {
1764 err.span_suggestion_short(
1766 "maybe you meant to write `;` here",
1768 Applicability::MaybeIncorrect,
1771 let after_colon_sp =
1772 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1773 if snippet.len() == 1 {
1775 err.span_suggestion(
1777 "maybe you meant to write a path separator here",
1779 Applicability::MaybeIncorrect,
1786 .type_ascription_path_suggestions
1790 err.downgrade_to_delayed_bug();
1793 if let Ok(base_snippet) = base_snippet {
1794 // Try to find an assignment
1795 let eq_span = sm.span_look_ahead(after_colon_sp, Some("="), Some(50));
1796 if let Ok(ref snippet) = sm.span_to_snippet(eq_span) && snippet == "=" {
1797 err.span_suggestion(
1799 "maybe you meant to write an assignment here",
1800 format!("let {}", base_snippet),
1801 Applicability::MaybeIncorrect,
1810 "expecting a type here because of type ascription",
1820 // try to give a suggestion for this pattern: `name = blah`, which is common in other languages
1821 // suggest `let name = blah` to introduce a new binding
1822 fn let_binding_suggestion(&mut self, err: &mut Diagnostic, ident_span: Span) -> bool {
1823 if let Some(Expr { kind: ExprKind::Assign(lhs, .. ), .. }) = self.diagnostic_metadata.in_assignment &&
1824 let ast::ExprKind::Path(None, _) = lhs.kind {
1825 if !ident_span.from_expansion() {
1826 err.span_suggestion_verbose(
1827 ident_span.shrink_to_lo(),
1828 "you might have meant to introduce a new binding",
1830 Applicability::MaybeIncorrect,
1838 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1839 let mut result = None;
1840 let mut seen_modules = FxHashSet::default();
1841 let mut worklist = vec![(self.r.graph_root, ThinVec::new())];
1843 while let Some((in_module, path_segments)) = worklist.pop() {
1844 // abort if the module is already found
1845 if result.is_some() {
1849 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1850 // abort if the module is already found or if name_binding is private external
1851 if result.is_some() || !name_binding.vis.is_visible_locally() {
1854 if let Some(module) = name_binding.module() {
1856 let mut path_segments = path_segments.clone();
1857 path_segments.push(ast::PathSegment::from_ident(ident));
1858 let module_def_id = module.def_id();
1859 if module_def_id == def_id {
1861 Path { span: name_binding.span, segments: path_segments, tokens: None };
1873 // add the module to the lookup
1874 if seen_modules.insert(module_def_id) {
1875 worklist.push((module, path_segments));
1885 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1886 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1887 let mut variants = Vec::new();
1888 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1889 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1890 let mut segms = enum_import_suggestion.path.segments.clone();
1891 segms.push(ast::PathSegment::from_ident(ident));
1892 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1893 variants.push((path, def_id, kind));
1900 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1901 fn suggest_using_enum_variant(
1903 err: &mut Diagnostic,
1904 source: PathSource<'_>,
1908 let Some(variants) = self.collect_enum_ctors(def_id) else {
1909 err.note("you might have meant to use one of the enum's variants");
1913 let suggest_only_tuple_variants =
1914 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1915 if suggest_only_tuple_variants {
1916 // Suggest only tuple variants regardless of whether they have fields and do not
1917 // suggest path with added parentheses.
1918 let suggestable_variants = variants
1920 .filter(|(.., kind)| *kind == CtorKind::Fn)
1921 .map(|(variant, ..)| path_names_to_string(variant))
1922 .collect::<Vec<_>>();
1924 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1926 let source_msg = if source.is_call() {
1928 } else if matches!(source, PathSource::TupleStruct(..)) {
1934 if !suggestable_variants.is_empty() {
1935 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1936 format!("try {} the enum's variant", source_msg)
1938 format!("try {} one of the enum's variants", source_msg)
1941 err.span_suggestions(
1944 suggestable_variants,
1945 Applicability::MaybeIncorrect,
1949 // If the enum has no tuple variants..
1950 if non_suggestable_variant_count == variants.len() {
1951 err.help(&format!("the enum has no tuple variants {}", source_msg));
1954 // If there are also non-tuple variants..
1955 if non_suggestable_variant_count == 1 {
1957 "you might have meant {} the enum's non-tuple variant",
1960 } else if non_suggestable_variant_count >= 1 {
1962 "you might have meant {} one of the enum's non-tuple variants",
1967 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
1968 let def_id = self.r.parent(ctor_def_id);
1969 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1971 CtorKind::Const => false,
1972 CtorKind::Fn if has_no_fields => false,
1977 let suggestable_variants = variants
1979 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1980 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1981 .map(|(variant, kind)| match kind {
1982 CtorKind::Const => variant,
1983 CtorKind::Fn => format!("({}())", variant),
1985 .collect::<Vec<_>>();
1986 let no_suggestable_variant = suggestable_variants.is_empty();
1988 if !no_suggestable_variant {
1989 let msg = if suggestable_variants.len() == 1 {
1990 "you might have meant to use the following enum variant"
1992 "you might have meant to use one of the following enum variants"
1995 err.span_suggestions(
1998 suggestable_variants,
1999 Applicability::MaybeIncorrect,
2003 let suggestable_variants_with_placeholders = variants
2005 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
2006 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2007 .filter_map(|(variant, kind)| match kind {
2008 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
2011 .collect::<Vec<_>>();
2013 if !suggestable_variants_with_placeholders.is_empty() {
2015 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
2016 (true, 1) => "the following enum variant is available",
2017 (true, _) => "the following enum variants are available",
2018 (false, 1) => "alternatively, the following enum variant is available",
2020 "alternatively, the following enum variants are also available"
2024 err.span_suggestions(
2027 suggestable_variants_with_placeholders,
2028 Applicability::HasPlaceholders,
2033 if def_id.is_local() {
2034 if let Some(span) = self.def_span(def_id) {
2035 err.span_note(span, "the enum is defined here");
2040 pub(crate) fn report_missing_type_error(
2043 ) -> Option<(Span, &'static str, String, Applicability)> {
2044 let (ident, span) = match path {
2045 [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
2046 (segment.ident.to_string(), segment.ident.span)
2050 let mut iter = ident.chars().map(|c| c.is_uppercase());
2051 let single_uppercase_char =
2052 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
2053 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
2056 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
2057 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
2058 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
2063 kind @ ItemKind::Fn(..)
2064 | kind @ ItemKind::Enum(..)
2065 | kind @ ItemKind::Struct(..)
2066 | kind @ ItemKind::Union(..),
2071 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
2072 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
2073 | (Some(Item { kind, .. }), false, _) => {
2074 // Likely missing type parameter.
2075 if let Some(generics) = kind.generics() {
2076 if span.overlaps(generics.span) {
2077 // Avoid the following:
2078 // error[E0405]: cannot find trait `A` in this scope
2079 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
2081 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
2082 // | ^- help: you might be missing a type parameter: `, A`
2084 // | not found in this scope
2087 let msg = "you might be missing a type parameter";
2088 let (span, sugg) = if let [.., param] = &generics.params[..] {
2089 let span = if let [.., bound] = ¶m.bounds[..] {
2091 } else if let GenericParam {
2092 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
2094 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
2098 (span, format!(", {}", ident))
2100 (generics.span, format!("<{}>", ident))
2102 // Do not suggest if this is coming from macro expansion.
2103 if span.can_be_used_for_suggestions() {
2105 span.shrink_to_hi(),
2108 Applicability::MaybeIncorrect,
2118 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
2119 /// optionally returning the closest match and whether it is reachable.
2120 pub(crate) fn suggestion_for_label_in_rib(
2124 ) -> Option<LabelSuggestion> {
2125 // Are ribs from this `rib_index` within scope?
2126 let within_scope = self.is_label_valid_from_rib(rib_index);
2128 let rib = &self.label_ribs[rib_index];
2132 .filter(|(id, _)| id.span.eq_ctxt(label.span))
2133 .map(|(id, _)| id.name)
2134 .collect::<Vec<Symbol>>();
2136 find_best_match_for_name(&names, label.name, None).map(|symbol| {
2137 // Upon finding a similar name, get the ident that it was from - the span
2138 // contained within helps make a useful diagnostic. In addition, determine
2139 // whether this candidate is within scope.
2140 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
2141 (*ident, within_scope)
2145 pub(crate) fn maybe_report_lifetime_uses(
2147 generics_span: Span,
2148 params: &[ast::GenericParam],
2150 for (param_index, param) in params.iter().enumerate() {
2151 let GenericParamKind::Lifetime = param.kind else { continue };
2153 let def_id = self.r.local_def_id(param.id);
2155 let use_set = self.lifetime_uses.remove(&def_id);
2157 "Use set for {:?}({:?} at {:?}) is {:?}",
2158 def_id, param.ident, param.ident.span, use_set
2161 let deletion_span = || {
2162 if params.len() == 1 {
2163 // if sole lifetime, remove the entire `<>` brackets
2165 } else if param_index == 0 {
2166 // if removing within `<>` brackets, we also want to
2167 // delete a leading or trailing comma as appropriate
2168 param.span().to(params[param_index + 1].span().shrink_to_lo())
2170 // if removing within `<>` brackets, we also want to
2171 // delete a leading or trailing comma as appropriate
2172 params[param_index - 1].span().shrink_to_hi().to(param.span())
2176 Some(LifetimeUseSet::Many) => {}
2177 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
2178 debug!(?param.ident, ?param.ident.span, ?use_span);
2180 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
2182 let deletion_span = deletion_span();
2183 self.r.lint_buffer.buffer_lint_with_diagnostic(
2184 lint::builtin::SINGLE_USE_LIFETIMES,
2187 &format!("lifetime parameter `{}` only used once", param.ident),
2188 lint::BuiltinLintDiagnostics::SingleUseLifetime {
2189 param_span: param.ident.span,
2190 use_span: Some((use_span, elidable)),
2196 debug!(?param.ident, ?param.ident.span);
2198 let deletion_span = deletion_span();
2199 self.r.lint_buffer.buffer_lint_with_diagnostic(
2200 lint::builtin::UNUSED_LIFETIMES,
2203 &format!("lifetime parameter `{}` never used", param.ident),
2204 lint::BuiltinLintDiagnostics::SingleUseLifetime {
2205 param_span: param.ident.span,
2215 pub(crate) fn emit_undeclared_lifetime_error(
2217 lifetime_ref: &ast::Lifetime,
2218 outer_lifetime_ref: Option<Ident>,
2220 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
2221 let mut err = if let Some(outer) = outer_lifetime_ref {
2222 let mut err = struct_span_err!(
2224 lifetime_ref.ident.span,
2226 "can't use generic parameters from outer item",
2228 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
2229 err.span_label(outer.span, "lifetime parameter from outer item");
2232 let mut err = struct_span_err!(
2234 lifetime_ref.ident.span,
2236 "use of undeclared lifetime name `{}`",
2239 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2242 self.suggest_introducing_lifetime(
2244 Some(lifetime_ref.ident.name.as_str()),
2245 |err, _, span, message, suggestion| {
2246 err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect);
2253 fn suggest_introducing_lifetime(
2255 err: &mut Diagnostic,
2257 suggest: impl Fn(&mut Diagnostic, bool, Span, &str, String) -> bool,
2259 let mut suggest_note = true;
2260 for rib in self.lifetime_ribs.iter().rev() {
2261 let mut should_continue = true;
2263 LifetimeRibKind::Generics { binder: _, span, kind } => {
2264 if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name {
2265 suggest_note = false; // Avoid displaying the same help multiple times.
2269 "lifetime `{}` is missing in item created through this procedural macro",
2276 let higher_ranked = matches!(
2278 LifetimeBinderKind::BareFnType
2279 | LifetimeBinderKind::PolyTrait
2280 | LifetimeBinderKind::WhereBound
2282 let (span, sugg) = if span.is_empty() {
2285 if higher_ranked { "for" } else { "" },
2286 name.unwrap_or("'a"),
2287 if higher_ranked { " " } else { "" },
2292 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2293 let sugg = format!("{}, ", name.unwrap_or("'a"));
2297 let message = format!(
2298 "consider making the {} lifetime-generic with a new `{}` lifetime",
2300 name.unwrap_or("'a"),
2302 should_continue = suggest(err, true, span, &message, sugg);
2304 "for more information on higher-ranked polymorphism, visit \
2305 https://doc.rust-lang.org/nomicon/hrtb.html",
2307 } else if let Some(name) = name {
2308 let message = format!("consider introducing lifetime `{}` here", name);
2309 should_continue = suggest(err, false, span, &message, sugg);
2311 let message = format!("consider introducing a named lifetime parameter");
2312 should_continue = suggest(err, false, span, &message, sugg);
2315 LifetimeRibKind::Item => break,
2318 if !should_continue {
2324 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2327 lifetime_ref.ident.span,
2329 "use of non-static lifetime `{}` in const generic",
2333 "for more information, see issue #74052 \
2334 <https://github.com/rust-lang/rust/issues/74052>",
2339 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2340 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2341 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2342 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2344 lifetime_ref: &ast::Lifetime,
2346 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2347 if !feature_active {
2349 &self.r.session.parse_sess,
2350 sym::generic_const_exprs,
2351 lifetime_ref.ident.span,
2352 "a non-static lifetime is not allowed in a `const`",
2358 pub(crate) fn report_missing_lifetime_specifiers(
2360 lifetime_refs: Vec<MissingLifetime>,
2361 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2362 ) -> ErrorGuaranteed {
2363 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
2364 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
2366 let mut err = struct_span_err!(
2370 "missing lifetime specifier{}",
2371 pluralize!(num_lifetimes)
2373 self.add_missing_lifetime_specifiers_label(
2376 function_param_lifetimes,
2381 fn add_missing_lifetime_specifiers_label(
2383 err: &mut Diagnostic,
2384 lifetime_refs: Vec<MissingLifetime>,
2385 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2387 for < in &lifetime_refs {
2391 "expected {} lifetime parameter{}",
2392 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
2393 pluralize!(lt.count),
2398 let mut in_scope_lifetimes: Vec<_> = self
2402 .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item))
2403 .flat_map(|rib| rib.bindings.iter())
2404 .map(|(&ident, &res)| (ident, res))
2405 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
2407 debug!(?in_scope_lifetimes);
2409 debug!(?function_param_lifetimes);
2410 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
2411 let elided_len = param_lifetimes.len();
2412 let num_params = params.len();
2414 let mut m = String::new();
2416 for (i, info) in params.iter().enumerate() {
2417 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
2418 debug_assert_ne!(lifetime_count, 0);
2420 err.span_label(span, "");
2423 if i + 1 < num_params {
2425 } else if num_params == 2 {
2428 m.push_str(", or ");
2432 let help_name = if let Some(ident) = ident {
2433 format!("`{}`", ident)
2435 format!("argument {}", index + 1)
2438 if lifetime_count == 1 {
2439 m.push_str(&help_name[..])
2441 m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..])
2445 if num_params == 0 {
2447 "this function's return type contains a borrowed value, \
2448 but there is no value for it to be borrowed from",
2450 if in_scope_lifetimes.is_empty() {
2451 in_scope_lifetimes = vec![(
2452 Ident::with_dummy_span(kw::StaticLifetime),
2453 (DUMMY_NODE_ID, LifetimeRes::Static),
2456 } else if elided_len == 0 {
2458 "this function's return type contains a borrowed value with \
2459 an elided lifetime, but the lifetime cannot be derived from \
2462 if in_scope_lifetimes.is_empty() {
2463 in_scope_lifetimes = vec![(
2464 Ident::with_dummy_span(kw::StaticLifetime),
2465 (DUMMY_NODE_ID, LifetimeRes::Static),
2468 } else if num_params == 1 {
2470 "this function's return type contains a borrowed value, \
2471 but the signature does not say which {} it is borrowed from",
2476 "this function's return type contains a borrowed value, \
2477 but the signature does not say whether it is borrowed from {}",
2483 let existing_name = match &in_scope_lifetimes[..] {
2484 [] => Symbol::intern("'a"),
2485 [(existing, _)] => existing.name,
2486 _ => Symbol::intern("'lifetime"),
2489 let mut spans_suggs: Vec<_> = Vec::new();
2490 let build_sugg = |lt: MissingLifetime| match lt.kind {
2491 MissingLifetimeKind::Underscore => {
2492 debug_assert_eq!(lt.count, 1);
2493 (lt.span, existing_name.to_string())
2495 MissingLifetimeKind::Ampersand => {
2496 debug_assert_eq!(lt.count, 1);
2497 (lt.span.shrink_to_hi(), format!("{} ", existing_name))
2499 MissingLifetimeKind::Comma => {
2500 let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
2504 (lt.span.shrink_to_hi(), sugg)
2506 MissingLifetimeKind::Brackets => {
2507 let sugg: String = std::iter::once("<")
2509 std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
2513 (lt.span.shrink_to_hi(), sugg)
2516 for < in &lifetime_refs {
2517 spans_suggs.push(build_sugg(lt));
2519 debug!(?spans_suggs);
2520 match in_scope_lifetimes.len() {
2522 if let Some((param_lifetimes, _)) = function_param_lifetimes {
2523 for lt in param_lifetimes {
2524 spans_suggs.push(build_sugg(lt))
2527 self.suggest_introducing_lifetime(
2530 |err, higher_ranked, span, message, intro_sugg| {
2531 err.multipart_suggestion_verbose(
2533 std::iter::once((span, intro_sugg))
2534 .chain(spans_suggs.iter().cloned())
2536 Applicability::MaybeIncorrect,
2543 err.multipart_suggestion_verbose(
2544 &format!("consider using the `{}` lifetime", existing_name),
2546 Applicability::MaybeIncorrect,
2549 // Record as using the suggested resolution.
2550 let (_, (_, res)) = in_scope_lifetimes[0];
2551 for < in &lifetime_refs {
2552 self.r.lifetimes_res_map.insert(lt.id, res);
2556 let lifetime_spans: Vec<_> =
2557 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
2558 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2560 if spans_suggs.len() > 0 {
2561 // This happens when we have `Foo<T>` where we point at the space before `T`,
2562 // but this can be confusing so we give a suggestion with placeholders.
2563 err.multipart_suggestion_verbose(
2564 "consider using one of the available lifetimes here",
2566 Applicability::HasPlaceholders,
2574 /// Report lifetime/lifetime shadowing as an error.
2575 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2576 let mut err = struct_span_err!(
2580 "lifetime name `{}` shadows a lifetime name that is already in scope",
2583 err.span_label(orig.span, "first declared here");
2584 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2588 /// Shadowing involving a label is only a warning for historical reasons.
2589 //FIXME: make this a proper lint.
2590 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2591 let name = shadower.name;
2592 let shadower = shadower.span;
2593 let mut err = sess.struct_span_warn(
2595 &format!("label name `{}` shadows a label name that is already in scope", name),
2597 err.span_label(orig, "first declared here");
2598 err.span_label(shadower, format!("label `{}` already in scope", name));