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 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_session::lint;
25 use rustc_session::parse::feature_err;
26 use rustc_session::Session;
27 use rustc_span::edition::Edition;
28 use rustc_span::hygiene::MacroKind;
29 use rustc_span::lev_distance::find_best_match_for_name;
30 use rustc_span::symbol::{kw, sym, Ident, Symbol};
31 use rustc_span::{BytePos, Span};
38 type Res = def::Res<ast::NodeId>;
40 /// A field or associated item from self type suggested in case of resolution failure.
41 enum AssocSuggestion {
49 impl AssocSuggestion {
50 fn action(&self) -> &'static str {
52 AssocSuggestion::Field => "use the available field",
53 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
54 AssocSuggestion::AssocFn => "call the associated function",
55 AssocSuggestion::AssocConst => "use the associated `const`",
56 AssocSuggestion::AssocType => "use the associated type",
61 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
62 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
65 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
66 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
69 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
70 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
71 let variant_path = &suggestion.path;
72 let variant_path_string = path_names_to_string(variant_path);
74 let path_len = suggestion.path.segments.len();
75 let enum_path = ast::Path {
76 span: suggestion.path.span,
77 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
80 let enum_path_string = path_names_to_string(&enum_path);
82 (variant_path_string, enum_path_string)
85 /// Description of an elided lifetime.
86 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
87 pub(super) struct MissingLifetime {
88 /// Used to overwrite the resolution with the suggestion, to avoid cascasing errors.
90 /// Where to suggest adding the lifetime.
92 /// How the lifetime was introduced, to have the correct space and comma.
93 pub kind: MissingLifetimeKind,
94 /// Number of elided lifetimes, used for elision in path.
98 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
99 pub(super) enum MissingLifetimeKind {
100 /// An explicit `'_`.
102 /// An elided lifetime `&' ty`.
104 /// An elided lifetime in brackets with written brackets.
106 /// An elided lifetime with elided brackets.
110 /// Description of the lifetimes appearing in a function parameter.
111 /// This is used to provide a literal explanation to the elision failure.
112 #[derive(Clone, Debug)]
113 pub(super) struct ElisionFnParameter {
114 /// The index of the argument in the original definition.
116 /// The name of the argument if it's a simple ident.
117 pub ident: Option<Ident>,
118 /// The number of lifetimes in the parameter.
119 pub lifetime_count: usize,
120 /// The span of the parameter.
124 /// Description of lifetimes that appear as candidates for elision.
125 /// This is used to suggest introducing an explicit lifetime.
127 pub(super) enum LifetimeElisionCandidate {
128 /// This is not a real lifetime.
130 /// There is a named lifetime, we won't suggest anything.
132 Missing(MissingLifetime),
135 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
136 fn def_span(&self, def_id: DefId) -> Option<Span> {
138 LOCAL_CRATE => self.r.opt_span(def_id),
139 _ => Some(self.r.cstore().get_span_untracked(def_id, self.r.session)),
143 /// Handles error reporting for `smart_resolve_path_fragment` function.
144 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
145 pub(crate) fn smart_resolve_report_errors(
149 source: PathSource<'_>,
151 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
152 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
153 let ns = source.namespace();
154 let is_expected = &|res| source.is_expected(res);
155 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
157 debug!(?res, ?source);
159 // Make the base error.
160 struct BaseError<'a> {
162 fallback_label: String,
165 suggestion: Option<(Span, &'a str, String)>,
167 let mut expected = source.descr_expected();
168 let path_str = Segment::names_to_string(path);
169 let item_str = path.last().unwrap().ident;
170 let base_error = if let Some(res) = res {
172 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
173 fallback_label: format!("not a {expected}"),
175 could_be_expr: match res {
176 Res::Def(DefKind::Fn, _) => {
177 // Verify whether this is a fn call or an Fn used as a type.
181 .span_to_snippet(span)
182 .map(|snippet| snippet.ends_with(')'))
186 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
191 | Res::Local(_) => true,
197 let item_span = path.last().unwrap().ident.span;
198 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
199 debug!(?self.diagnostic_metadata.current_impl_items);
200 debug!(?self.diagnostic_metadata.current_function);
201 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
202 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
203 && self.current_trait_ref.is_none()
204 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
205 && let Some(item) = items.iter().find(|i| {
206 if let AssocItemKind::Fn(fn_) = &i.kind
207 && !fn_.sig.decl.has_self()
208 && i.ident.name == item_str.name
210 debug!(?item_str.name);
211 debug!(?fn_.sig.decl.inputs);
219 "consider using the associated function",
220 format!("Self::{}", item.ident)
225 (String::new(), "this scope".to_string(), suggestion)
226 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
227 if self.r.session.edition() > Edition::Edition2015 {
228 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
229 // which overrides all other expectations of item type
231 (String::new(), "the list of imported crates".to_string(), None)
233 (String::new(), "the crate root".to_string(), None)
235 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
236 (String::new(), "the crate root".to_string(), None)
238 let mod_path = &path[..path.len() - 1];
239 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
240 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
243 .map_or_else(String::new, |res| format!("{} ", res.descr()));
244 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
247 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
248 fallback_label: if path_str == "async" && expected.starts_with("struct") {
249 "`async` blocks are only allowed in Rust 2018 or later".to_string()
251 format!("not found in {mod_str}")
254 could_be_expr: false,
259 let code = source.error_code(res.is_some());
261 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
263 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
265 if let Some(sugg) = base_error.suggestion {
266 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
269 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
270 err.multipart_suggestion(
271 "you might have meant to write a `struct` literal",
273 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
274 (span.shrink_to_hi(), "}".to_string()),
276 Applicability::HasPlaceholders,
279 match (source, self.diagnostic_metadata.in_if_condition) {
282 Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }),
284 // Icky heuristic so we don't suggest:
285 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
286 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
287 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
288 err.span_suggestion_verbose(
289 expr_span.shrink_to_lo(),
290 "you might have meant to use pattern matching",
292 Applicability::MaybeIncorrect,
299 let is_assoc_fn = self.self_type_is_available();
300 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
301 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
302 err.span_suggestion_short(
304 "you might have meant to use `self` here instead",
306 Applicability::MaybeIncorrect,
308 if !self.self_value_is_available(path[0].ident.span) {
309 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
310 &self.diagnostic_metadata.current_function
312 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
313 (param.span.shrink_to_lo(), "&self, ")
319 .span_through_char(*fn_span, '(')
324 err.span_suggestion_verbose(
326 "if you meant to use `self`, you are also missing a `self` receiver \
329 Applicability::MaybeIncorrect,
335 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
337 // Emit special messages for unresolved `Self` and `self`.
338 if is_self_type(path, ns) {
339 err.code(rustc_errors::error_code!(E0411));
342 "`Self` is only available in impls, traits, and type definitions".to_string(),
344 if let Some(item_kind) = self.diagnostic_metadata.current_item {
346 item_kind.ident.span,
348 "`Self` not allowed in {} {}",
349 item_kind.kind.article(),
350 item_kind.kind.descr()
354 return (err, Vec::new());
356 if is_self_value(path, ns) {
357 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
359 err.code(rustc_errors::error_code!(E0424));
360 err.span_label(span, match source {
361 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed",
362 _ => "`self` value is a keyword only available in methods with a `self` parameter",
364 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
365 // The current function has a `self' parameter, but we were unable to resolve
366 // a reference to `self`. This can only happen if the `self` identifier we
367 // are resolving came from a different hygiene context.
368 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
369 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
371 let doesnt = if is_assoc_fn {
372 let (span, sugg) = fn_kind
376 .map(|p| (p.span.shrink_to_lo(), "&self, "))
378 // Try to look for the "(" after the function name, if possible.
379 // This avoids placing the suggestion into the visibility specifier.
382 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
387 .span_through_char(span, '(')
392 err.span_suggestion_verbose(
394 "add a `self` receiver parameter to make the associated `fn` a method",
396 Applicability::MaybeIncorrect,
402 if let Some(ident) = fn_kind.ident() {
405 &format!("this function {} have a `self` parameter", doesnt),
409 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
411 item_kind.ident.span,
413 "`self` not allowed in {} {}",
414 item_kind.kind.article(),
415 item_kind.kind.descr()
419 return (err, Vec::new());
422 // Try to lookup name in more relaxed fashion for better error reporting.
423 let ident = path.last().unwrap().ident;
424 let mut candidates = self
426 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
428 .filter(|ImportSuggestion { did, .. }| {
429 match (did, res.and_then(|res| res.opt_def_id())) {
430 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
434 .collect::<Vec<_>>();
435 let crate_def_id = CRATE_DEF_ID.to_def_id();
436 // Try to filter out intrinsics candidates, as long as we have
437 // some other candidates to suggest.
438 let intrinsic_candidates: Vec<_> = candidates
439 .drain_filter(|sugg| {
440 let path = path_names_to_string(&sugg.path);
441 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
444 if candidates.is_empty() {
445 // Put them back if we have no more candidates to suggest...
446 candidates.extend(intrinsic_candidates);
448 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
449 let mut enum_candidates: Vec<_> = self
451 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
453 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
454 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
456 if !enum_candidates.is_empty() {
457 if let (PathSource::Type, Some(span)) =
458 (source, self.diagnostic_metadata.current_type_ascription.last())
464 .type_ascription_path_suggestions
468 // Already reported this issue on the lhs of the type ascription.
470 return (err, candidates);
474 enum_candidates.sort();
476 // Contextualize for E0412 "cannot find type", but don't belabor the point
477 // (that it's a variant) for E0573 "expected type, found variant".
478 let preamble = if res.is_none() {
479 let others = match enum_candidates.len() {
481 2 => " and 1 other".to_owned(),
482 n => format!(" and {} others", n),
484 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
488 let msg = format!("{}try using the variant's enum", preamble);
490 err.span_suggestions(
493 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
494 Applicability::MachineApplicable,
498 // Try Levenshtein algorithm.
499 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
500 if path.len() == 1 && self.self_type_is_available() {
501 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
502 let self_is_available = self.self_value_is_available(path[0].ident.span);
504 AssocSuggestion::Field => {
505 if self_is_available {
508 "you might have meant to use the available field",
509 format!("self.{path_str}"),
510 Applicability::MachineApplicable,
513 err.span_label(span, "a field by this name exists in `Self`");
516 AssocSuggestion::MethodWithSelf if self_is_available => {
519 "you might have meant to call the method",
520 format!("self.{path_str}"),
521 Applicability::MachineApplicable,
524 AssocSuggestion::MethodWithSelf
525 | AssocSuggestion::AssocFn
526 | AssocSuggestion::AssocConst
527 | AssocSuggestion::AssocType => {
530 &format!("you might have meant to {}", candidate.action()),
531 format!("Self::{path_str}"),
532 Applicability::MachineApplicable,
536 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
537 return (err, candidates);
540 // If the first argument in call is `self` suggest calling a method.
541 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
542 let mut args_snippet = String::new();
543 if let Some(args_span) = args_span {
544 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
545 args_snippet = snippet;
551 &format!("try calling `{ident}` as a method"),
552 format!("self.{path_str}({args_snippet})"),
553 Applicability::MachineApplicable,
555 return (err, candidates);
559 // Try context-dependent help if relaxed lookup didn't work.
560 if let Some(res) = res {
561 if self.smart_resolve_context_dependent_help(
567 &base_error.fallback_label,
569 // We do this to avoid losing a secondary span when we override the main error span.
570 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
571 return (err, candidates);
576 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
577 if !self.type_ascription_suggestion(&mut err, base_error.span) {
578 let mut fallback = false;
580 PathSource::Trait(AliasPossibility::Maybe),
581 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
583 ) = (source, res, is_macro)
585 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
587 let spans: Vec<Span> = bounds
589 .map(|bound| bound.span())
590 .filter(|&sp| sp != base_error.span)
593 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
594 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
595 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
596 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
597 let last_bound_span = spans.last().cloned().unwrap();
598 let mut multi_span: MultiSpan = spans.clone().into();
600 let msg = if sp == last_bound_span {
602 "...because of {these} bound{s}",
603 these = pluralize!("this", bounds.len() - 1),
604 s = pluralize!(bounds.len() - 1),
609 multi_span.push_span_label(sp, msg);
612 .push_span_label(base_error.span, "expected this type to be a trait...");
615 "`+` is used to constrain a \"trait object\" type with lifetimes or \
616 auto-traits; structs and enums can't be bound in that way",
618 if bounds.iter().all(|bound| match bound {
619 ast::GenericBound::Outlives(_) => true,
620 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
622 let mut sugg = vec![];
623 if base_error.span != start_span {
624 sugg.push((start_span.until(base_error.span), String::new()));
626 if base_error.span != end_span {
627 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
630 err.multipart_suggestion(
631 "if you meant to use a type and not a trait here, remove the bounds",
633 Applicability::MaybeIncorrect,
639 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
641 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
643 match self.diagnostic_metadata.current_let_binding {
644 Some((pat_sp, Some(ty_sp), None))
645 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
647 err.span_suggestion_short(
648 pat_sp.between(ty_sp),
649 "use `=` if you meant to assign",
651 Applicability::MaybeIncorrect,
657 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
658 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
659 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
663 err.span_label(base_error.span, base_error.fallback_label);
666 if let Some(err_code) = &err.code {
667 if err_code == &rustc_errors::error_code!(E0425) {
668 for label_rib in &self.label_ribs {
669 for (label_ident, node_id) in &label_rib.bindings {
670 if format!("'{}", ident) == label_ident.to_string() {
671 err.span_label(label_ident.span, "a label with a similar name exists");
672 if let PathSource::Expr(Some(Expr {
673 kind: ExprKind::Break(None, Some(_)),
679 "use the similarly named label",
681 Applicability::MaybeIncorrect,
683 // Do not lint against unused label when we suggest them.
684 self.diagnostic_metadata.unused_labels.remove(node_id);
689 } else if err_code == &rustc_errors::error_code!(E0412) {
690 if let Some(correct) = Self::likely_rust_type(path) {
693 "perhaps you intended to use this type",
695 Applicability::MaybeIncorrect,
704 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
705 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
706 let TyKind::Path(_, path) = &ty.kind else { return; };
707 for segment in &path.segments {
708 let Some(params) = &segment.args else { continue; };
709 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
710 for param in ¶ms.args {
711 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
712 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
715 for bound in bounds {
716 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
721 if base_span == trait_ref.span {
722 err.span_suggestion_verbose(
723 constraint.ident.span.between(trait_ref.span),
724 "you might have meant to write a path instead of an associated type bound",
726 Applicability::MachineApplicable,
734 fn suggest_swapping_misplaced_self_ty_and_trait(
736 err: &mut Diagnostic,
737 source: PathSource<'_>,
741 if let Some((trait_ref, self_ty)) =
742 self.diagnostic_metadata.currently_processing_impl_trait.clone()
743 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
744 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
745 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
746 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
747 && trait_ref.path.span == span
748 && let PathSource::Trait(_) = source
749 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
750 && let Ok(self_ty_str) =
751 self.r.session.source_map().span_to_snippet(self_ty.span)
752 && let Ok(trait_ref_str) =
753 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
755 err.multipart_suggestion(
756 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
757 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
758 Applicability::MaybeIncorrect,
763 fn get_single_associated_item(
766 source: &PathSource<'_>,
767 filter_fn: &impl Fn(Res) -> bool,
768 ) -> Option<TypoSuggestion> {
769 if let crate::PathSource::TraitItem(_) = source {
770 let mod_path = &path[..path.len() - 1];
771 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
772 self.resolve_path(mod_path, None, None)
774 let resolutions = self.r.resolutions(module).borrow();
775 let targets: Vec<_> =
778 .filter_map(|(key, resolution)| {
779 resolution.borrow().binding.map(|binding| binding.res()).and_then(
780 |res| if filter_fn(res) { Some((key, res)) } else { None },
784 if targets.len() == 1 {
785 let target = targets[0];
786 return Some(TypoSuggestion::single_item_from_res(
796 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
797 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
798 // Detect that we are actually in a `where` predicate.
799 let (bounded_ty, bounds, where_span) =
800 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
802 bound_generic_params,
805 })) = self.diagnostic_metadata.current_where_predicate
807 if !bound_generic_params.is_empty() {
810 (bounded_ty, bounds, span)
815 // Confirm that the target is an associated type.
816 let (ty, position, path) = if let ast::TyKind::Path(
817 Some(ast::QSelf { ty, position, .. }),
821 // use this to verify that ident is a type param.
822 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
826 partial_res.base_res(),
827 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
828 ) && partial_res.unresolved_segments() == 0)
837 let peeled_ty = ty.peel_refs();
838 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
839 // Confirm that the `SelfTy` is a type parameter.
840 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
844 partial_res.base_res(),
845 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
846 ) && partial_res.unresolved_segments() == 0)
851 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
852 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
853 ) = (&type_param_path.segments[..], &bounds[..])
855 if let [ast::PathSegment { ident, args: None, .. }] =
856 &poly_trait_ref.trait_ref.path.segments[..]
858 if ident.span == span {
859 err.span_suggestion_verbose(
861 &format!("constrain the associated type to `{}`", ident),
867 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
868 .unwrap_or_else(|_| constrain_ident.to_string()),
869 path.segments[..*position]
871 .map(|segment| path_segment_to_string(segment))
874 path.segments[*position..]
876 .map(|segment| path_segment_to_string(segment))
881 Applicability::MaybeIncorrect,
891 /// Check if the source is call expression and the first argument is `self`. If true,
892 /// return the span of whole call and the span for all arguments expect the first one (`self`).
893 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
894 let mut has_self_arg = None;
895 if let PathSource::Expr(Some(parent)) = source {
897 ExprKind::Call(_, args) if !args.is_empty() => {
898 let mut expr_kind = &args[0].kind;
901 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
902 if arg_name.segments[0].ident.name == kw::SelfLower {
903 let call_span = parent.span;
904 let tail_args_span = if args.len() > 1 {
907 args.last().unwrap().span.hi(),
914 has_self_arg = Some((call_span, tail_args_span));
918 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
929 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
930 // HACK(estebank): find a better way to figure out that this was a
931 // parser issue where a struct literal is being used on an expression
932 // where a brace being opened means a block is being started. Look
933 // ahead for the next text to see if `span` is followed by a `{`.
934 let sm = self.r.session.source_map();
937 sp = sm.next_point(sp);
938 match sm.span_to_snippet(sp) {
940 if snippet.chars().any(|c| !c.is_whitespace()) {
947 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
948 // In case this could be a struct literal that needs to be surrounded
949 // by parentheses, find the appropriate span.
951 let mut closing_brace = None;
953 sp = sm.next_point(sp);
954 match sm.span_to_snippet(sp) {
957 closing_brace = Some(span.to(sp));
964 // The bigger the span, the more likely we're incorrect --
965 // bound it to 100 chars long.
970 (followed_by_brace, closing_brace)
973 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
975 /// Returns `true` if able to provide context-dependent help.
976 fn smart_resolve_context_dependent_help(
978 err: &mut Diagnostic,
980 source: PathSource<'_>,
983 fallback_label: &str,
985 let ns = source.namespace();
986 let is_expected = &|res| source.is_expected(res);
988 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
989 ExprKind::Field(_, ident) => {
992 "use the path separator to refer to an item",
993 format!("{}::{}", path_str, ident),
994 Applicability::MaybeIncorrect,
998 ExprKind::MethodCall(ref segment, ..) => {
999 let span = expr.span.with_hi(segment.ident.span.hi());
1000 err.span_suggestion(
1002 "use the path separator to refer to an item",
1003 format!("{}::{}", path_str, segment.ident),
1004 Applicability::MaybeIncorrect,
1011 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1013 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1014 | PathSource::TupleStruct(span, _) => {
1015 // We want the main underline to cover the suggested code as well for
1017 err.set_span(*span);
1024 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1025 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1028 PathSource::Expr(Some(
1029 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1030 )) if path_sep(err, &parent) => {}
1036 | ExprKind::Binary(..)
1037 | ExprKind::Unary(..)
1039 | ExprKind::While(..)
1040 | ExprKind::ForLoop(..)
1041 | ExprKind::Match(..),
1044 ) if followed_by_brace => {
1045 if let Some(sp) = closing_brace {
1046 err.span_label(span, fallback_label);
1047 err.multipart_suggestion(
1048 "surround the struct literal with parentheses",
1050 (sp.shrink_to_lo(), "(".to_string()),
1051 (sp.shrink_to_hi(), ")".to_string()),
1053 Applicability::MaybeIncorrect,
1057 span, // Note the parentheses surrounding the suggestion below
1059 "you might want to surround a struct literal with parentheses: \
1060 `({} {{ /* fields */ }})`?",
1066 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1067 let span = find_span(&source, err);
1068 if let Some(span) = self.def_span(def_id) {
1069 err.span_label(span, &format!("`{}` defined here", path_str));
1071 let (tail, descr, applicability) = match source {
1072 PathSource::Pat | PathSource::TupleStruct(..) => {
1073 ("", "pattern", Applicability::MachineApplicable)
1075 _ => (": val", "literal", Applicability::HasPlaceholders),
1077 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1081 .map(|f| format!("{}{}", f.node, tail))
1082 .collect::<Vec<String>>()
1086 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1088 let pad = match self.r.field_names.get(&def_id) {
1089 Some(fields) if fields.is_empty() => "",
1092 err.span_suggestion(
1094 &format!("use struct {} syntax instead", descr),
1095 format!("{path_str} {{{pad}{fields}{pad}}}"),
1100 err.span_label(span, fallback_label);
1105 match (res, source) {
1107 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1108 PathSource::Expr(Some(Expr {
1109 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1111 | PathSource::Struct,
1113 err.span_label(span, fallback_label);
1114 err.span_suggestion_verbose(
1115 span.shrink_to_hi(),
1116 "use `!` to invoke the macro",
1118 Applicability::MaybeIncorrect,
1120 if path_str == "try" && span.rust_2015() {
1121 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1124 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1125 err.span_label(span, fallback_label);
1127 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1128 err.span_label(span, "type aliases cannot be used as traits");
1129 if self.r.session.is_nightly_build() {
1130 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1132 if let Some(span) = self.def_span(def_id) {
1133 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1134 // The span contains a type alias so we should be able to
1135 // replace `type` with `trait`.
1136 let snip = snip.replacen("type", "trait", 1);
1137 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1139 err.span_help(span, msg);
1146 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1147 if !path_sep(err, &parent) {
1152 Res::Def(DefKind::Enum, def_id),
1153 PathSource::TupleStruct(..) | PathSource::Expr(..),
1156 .diagnostic_metadata
1157 .current_type_ascription
1163 .type_ascription_path_suggestions
1169 err.downgrade_to_delayed_bug();
1170 // We already suggested changing `:` into `::` during parsing.
1174 self.suggest_using_enum_variant(err, source, def_id, span);
1176 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1177 let (ctor_def, ctor_vis, fields) =
1178 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1179 if let PathSource::Expr(Some(parent)) = source {
1180 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1181 bad_struct_syntax_suggestion(def_id);
1187 bad_struct_syntax_suggestion(def_id);
1191 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1192 if !is_expected(ctor_def) || is_accessible {
1196 let field_spans = match source {
1197 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1198 PathSource::TupleStruct(_, pattern_spans) => {
1199 err.set_primary_message(
1200 "cannot match against a tuple struct which contains private fields",
1203 // Use spans of the tuple struct pattern.
1204 Some(Vec::from(pattern_spans))
1206 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1207 _ if source.is_call() => {
1208 err.set_primary_message(
1209 "cannot initialize a tuple struct which contains private fields",
1212 // Use spans of the tuple struct definition.
1216 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1221 if let Some(spans) =
1222 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1224 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1225 .filter(|(vis, _)| {
1226 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1228 .map(|(_, span)| *span)
1231 if non_visible_spans.len() > 0 {
1232 let mut m: MultiSpan = non_visible_spans.clone().into();
1235 .for_each(|s| m.push_span_label(s, "private field"));
1236 err.span_note(m, "constructor is not visible here due to private fields");
1242 err.span_label(span, "constructor is not visible here due to private fields");
1246 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1250 ) if ns == ValueNS => {
1251 bad_struct_syntax_suggestion(def_id);
1253 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1255 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1256 let span = find_span(&source, err);
1257 if let Some(span) = self.def_span(def_id) {
1258 err.span_label(span, &format!("`{}` defined here", path_str));
1260 err.span_suggestion(
1262 "use this syntax instead",
1264 Applicability::MaybeIncorrect,
1270 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1271 if let Some(span) = self.def_span(def_id) {
1272 err.span_label(span, &format!("`{}` defined here", path_str));
1274 let fields = self.r.field_names.get(&def_id).map_or_else(
1275 || "/* fields */".to_string(),
1276 |fields| vec!["_"; fields.len()].join(", "),
1278 err.span_suggestion(
1280 "use the tuple variant pattern syntax instead",
1281 format!("{}({})", path_str, fields),
1282 Applicability::HasPlaceholders,
1285 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1286 err.span_label(span, fallback_label);
1287 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1289 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1290 err.note("can't use a type alias as a constructor");
1297 /// Given the target `ident` and `kind`, search for the similarly named associated item
1298 /// in `self.current_trait_ref`.
1299 pub(crate) fn find_similarly_named_assoc_item(
1302 kind: &AssocItemKind,
1303 ) -> Option<Symbol> {
1304 let (module, _) = self.current_trait_ref.as_ref()?;
1305 if ident == kw::Underscore {
1306 // We do nothing for `_`.
1310 let resolutions = self.r.resolutions(module);
1311 let targets = resolutions
1314 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1315 .filter(|(_, res)| match (kind, res) {
1316 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1317 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1318 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1321 .map(|(key, _)| key.ident.name)
1322 .collect::<Vec<_>>();
1324 find_best_match_for_name(&targets, ident, None)
1327 fn lookup_assoc_candidate<FilterFn>(
1331 filter_fn: FilterFn,
1332 ) -> Option<AssocSuggestion>
1334 FilterFn: Fn(Res) -> bool,
1336 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1338 TyKind::Path(None, _) => Some(t.id),
1339 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1340 // This doesn't handle the remaining `Ty` variants as they are not
1341 // that commonly the self_type, it might be interesting to provide
1342 // support for those in future.
1347 // Fields are generally expected in the same contexts as locals.
1348 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1349 if let Some(node_id) =
1350 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1352 // Look for a field with the same name in the current self_type.
1353 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1354 match resolution.base_res() {
1355 Res::Def(DefKind::Struct | DefKind::Union, did)
1356 if resolution.unresolved_segments() == 0 =>
1358 if let Some(field_names) = self.r.field_names.get(&did) {
1361 .any(|&field_name| ident.name == field_name.node)
1363 return Some(AssocSuggestion::Field);
1373 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1374 for assoc_item in items {
1375 if assoc_item.ident == ident {
1376 return Some(match &assoc_item.kind {
1377 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1378 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1379 AssocSuggestion::MethodWithSelf
1381 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1382 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1383 ast::AssocItemKind::MacCall(_) => continue,
1389 // Look for associated items in the current trait.
1390 if let Some((module, _)) = self.current_trait_ref {
1391 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1392 ModuleOrUniformRoot::Module(module),
1397 let res = binding.res();
1399 if self.r.has_self.contains(&res.def_id()) {
1400 return Some(AssocSuggestion::MethodWithSelf);
1403 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1404 Res::Def(DefKind::AssocConst, _) => {
1405 return Some(AssocSuggestion::AssocConst);
1407 Res::Def(DefKind::AssocTy, _) => {
1408 return Some(AssocSuggestion::AssocType);
1420 fn lookup_typo_candidate(
1424 filter_fn: &impl Fn(Res) -> bool,
1425 ) -> Option<TypoSuggestion> {
1426 let mut names = Vec::new();
1427 if path.len() == 1 {
1428 // Search in lexical scope.
1429 // Walk backwards up the ribs in scope and collect candidates.
1430 for rib in self.ribs[ns].iter().rev() {
1431 // Locals and type parameters
1432 for (ident, &res) in &rib.bindings {
1434 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1438 if let RibKind::ModuleRibKind(module) = rib.kind {
1439 // Items from this module
1440 self.r.add_module_candidates(module, &mut names, &filter_fn);
1442 if let ModuleKind::Block = module.kind {
1443 // We can see through blocks
1445 // Items from the prelude
1446 if !module.no_implicit_prelude {
1447 let extern_prelude = self.r.extern_prelude.clone();
1448 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1449 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1452 Res::Def(DefKind::Mod, crate_id.as_def_id());
1454 if filter_fn(crate_mod) {
1455 Some(TypoSuggestion::typo_from_res(
1456 ident.name, crate_mod,
1465 if let Some(prelude) = self.r.prelude {
1466 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1473 // Add primitive types to the mix
1474 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1475 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1476 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1480 // Search in module.
1481 let mod_path = &path[..path.len() - 1];
1482 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1483 self.resolve_path(mod_path, Some(TypeNS), None)
1485 self.r.add_module_candidates(module, &mut names, &filter_fn);
1489 let name = path[path.len() - 1].ident.name;
1490 // Make sure error reporting is deterministic.
1491 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1493 match find_best_match_for_name(
1494 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1498 Some(found) if found != name => {
1499 names.into_iter().find(|suggestion| suggestion.candidate == found)
1505 // Returns the name of the Rust type approximately corresponding to
1506 // a type name in another programming language.
1507 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1508 let name = path[path.len() - 1].ident.as_str();
1509 // Common Java types
1511 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1512 "short" => sym::i16,
1513 "Bool" => sym::bool,
1514 "Boolean" => sym::bool,
1515 "boolean" => sym::bool,
1518 "float" => sym::f32,
1519 "double" => sym::f64,
1524 /// Only used in a specific case of type ascription suggestions
1525 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1526 let sm = self.r.session.source_map();
1527 start.to(sm.next_point(start))
1530 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1531 let sm = self.r.session.source_map();
1532 let base_snippet = sm.span_to_snippet(base_span);
1533 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1534 if let Ok(snippet) = sm.span_to_snippet(sp) {
1535 let len = snippet.trim_end().len() as u32;
1536 if snippet.trim() == ":" {
1538 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1539 let mut show_label = true;
1540 if sm.is_multiline(sp) {
1541 err.span_suggestion_short(
1543 "maybe you meant to write `;` here",
1545 Applicability::MaybeIncorrect,
1548 let after_colon_sp =
1549 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1550 if snippet.len() == 1 {
1552 err.span_suggestion(
1554 "maybe you meant to write a path separator here",
1556 Applicability::MaybeIncorrect,
1563 .type_ascription_path_suggestions
1567 err.downgrade_to_delayed_bug();
1570 if let Ok(base_snippet) = base_snippet {
1571 let mut sp = after_colon_sp;
1573 // Try to find an assignment
1574 sp = sm.next_point(sp);
1575 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1577 Ok(ref x) if x.as_str() == "=" => {
1578 err.span_suggestion(
1580 "maybe you meant to write an assignment here",
1581 format!("let {}", base_snippet),
1582 Applicability::MaybeIncorrect,
1587 Ok(ref x) if x.as_str() == "\n" => break,
1597 "expecting a type here because of type ascription",
1607 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1608 let mut result = None;
1609 let mut seen_modules = FxHashSet::default();
1610 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1612 while let Some((in_module, path_segments)) = worklist.pop() {
1613 // abort if the module is already found
1614 if result.is_some() {
1618 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1619 // abort if the module is already found or if name_binding is private external
1620 if result.is_some() || !name_binding.vis.is_visible_locally() {
1623 if let Some(module) = name_binding.module() {
1625 let mut path_segments = path_segments.clone();
1626 path_segments.push(ast::PathSegment::from_ident(ident));
1627 let module_def_id = module.def_id();
1628 if module_def_id == def_id {
1630 Path { span: name_binding.span, segments: path_segments, tokens: None };
1642 // add the module to the lookup
1643 if seen_modules.insert(module_def_id) {
1644 worklist.push((module, path_segments));
1654 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1655 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1656 let mut variants = Vec::new();
1657 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1658 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1659 let mut segms = enum_import_suggestion.path.segments.clone();
1660 segms.push(ast::PathSegment::from_ident(ident));
1661 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1662 variants.push((path, def_id, kind));
1669 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1670 fn suggest_using_enum_variant(
1672 err: &mut Diagnostic,
1673 source: PathSource<'_>,
1677 let Some(variants) = self.collect_enum_ctors(def_id) else {
1678 err.note("you might have meant to use one of the enum's variants");
1682 let suggest_only_tuple_variants =
1683 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1684 if suggest_only_tuple_variants {
1685 // Suggest only tuple variants regardless of whether they have fields and do not
1686 // suggest path with added parentheses.
1687 let suggestable_variants = variants
1689 .filter(|(.., kind)| *kind == CtorKind::Fn)
1690 .map(|(variant, ..)| path_names_to_string(variant))
1691 .collect::<Vec<_>>();
1693 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1695 let source_msg = if source.is_call() {
1697 } else if matches!(source, PathSource::TupleStruct(..)) {
1703 if !suggestable_variants.is_empty() {
1704 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1705 format!("try {} the enum's variant", source_msg)
1707 format!("try {} one of the enum's variants", source_msg)
1710 err.span_suggestions(
1713 suggestable_variants.into_iter(),
1714 Applicability::MaybeIncorrect,
1718 // If the enum has no tuple variants..
1719 if non_suggestable_variant_count == variants.len() {
1720 err.help(&format!("the enum has no tuple variants {}", source_msg));
1723 // If there are also non-tuple variants..
1724 if non_suggestable_variant_count == 1 {
1726 "you might have meant {} the enum's non-tuple variant",
1729 } else if non_suggestable_variant_count >= 1 {
1731 "you might have meant {} one of the enum's non-tuple variants",
1736 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1737 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1739 CtorKind::Const => false,
1740 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1745 let mut suggestable_variants = variants
1747 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1748 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1749 .map(|(variant, kind)| match kind {
1750 CtorKind::Const => variant,
1751 CtorKind::Fn => format!("({}())", variant),
1752 CtorKind::Fictive => format!("({} {{}})", variant),
1754 .collect::<Vec<_>>();
1756 if !suggestable_variants.is_empty() {
1757 let msg = if suggestable_variants.len() == 1 {
1758 "you might have meant to use the following enum variant"
1760 "you might have meant to use one of the following enum variants"
1763 err.span_suggestions(
1766 suggestable_variants.drain(..),
1767 Applicability::MaybeIncorrect,
1771 let suggestable_variants_with_placeholders = variants
1773 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1774 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1775 .filter_map(|(variant, kind)| match kind {
1776 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1777 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1780 .collect::<Vec<_>>();
1782 if !suggestable_variants_with_placeholders.is_empty() {
1784 suggestable_variants.is_empty(),
1785 suggestable_variants_with_placeholders.len(),
1787 (true, 1) => "the following enum variant is available",
1788 (true, _) => "the following enum variants are available",
1789 (false, 1) => "alternatively, the following enum variant is available",
1790 (false, _) => "alternatively, the following enum variants are also available",
1793 err.span_suggestions(
1796 suggestable_variants_with_placeholders.into_iter(),
1797 Applicability::HasPlaceholders,
1802 if def_id.is_local() {
1803 if let Some(span) = self.def_span(def_id) {
1804 err.span_note(span, "the enum is defined here");
1809 pub(crate) fn report_missing_type_error(
1812 ) -> Option<(Span, &'static str, String, Applicability)> {
1813 let (ident, span) = match path {
1814 [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
1815 (segment.ident.to_string(), segment.ident.span)
1819 let mut iter = ident.chars().map(|c| c.is_uppercase());
1820 let single_uppercase_char =
1821 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1822 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1825 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1826 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1827 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1832 kind @ ItemKind::Fn(..)
1833 | kind @ ItemKind::Enum(..)
1834 | kind @ ItemKind::Struct(..)
1835 | kind @ ItemKind::Union(..),
1840 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1841 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1842 | (Some(Item { kind, .. }), false, _) => {
1843 // Likely missing type parameter.
1844 if let Some(generics) = kind.generics() {
1845 if span.overlaps(generics.span) {
1846 // Avoid the following:
1847 // error[E0405]: cannot find trait `A` in this scope
1848 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1850 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1851 // | ^- help: you might be missing a type parameter: `, A`
1853 // | not found in this scope
1856 let msg = "you might be missing a type parameter";
1857 let (span, sugg) = if let [.., param] = &generics.params[..] {
1858 let span = if let [.., bound] = ¶m.bounds[..] {
1860 } else if let GenericParam {
1861 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1863 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1867 (span, format!(", {}", ident))
1869 (generics.span, format!("<{}>", ident))
1871 // Do not suggest if this is coming from macro expansion.
1872 if span.can_be_used_for_suggestions() {
1874 span.shrink_to_hi(),
1877 Applicability::MaybeIncorrect,
1887 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1888 /// optionally returning the closest match and whether it is reachable.
1889 pub(crate) fn suggestion_for_label_in_rib(
1893 ) -> Option<LabelSuggestion> {
1894 // Are ribs from this `rib_index` within scope?
1895 let within_scope = self.is_label_valid_from_rib(rib_index);
1897 let rib = &self.label_ribs[rib_index];
1901 .filter(|(id, _)| id.span.eq_ctxt(label.span))
1902 .map(|(id, _)| id.name)
1903 .collect::<Vec<Symbol>>();
1905 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1906 // Upon finding a similar name, get the ident that it was from - the span
1907 // contained within helps make a useful diagnostic. In addition, determine
1908 // whether this candidate is within scope.
1909 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1910 (*ident, within_scope)
1914 pub(crate) fn maybe_report_lifetime_uses(
1916 generics_span: Span,
1917 params: &[ast::GenericParam],
1919 for (param_index, param) in params.iter().enumerate() {
1920 let GenericParamKind::Lifetime = param.kind else { continue };
1922 let def_id = self.r.local_def_id(param.id);
1924 let use_set = self.lifetime_uses.remove(&def_id);
1926 "Use set for {:?}({:?} at {:?}) is {:?}",
1927 def_id, param.ident, param.ident.span, use_set
1930 let deletion_span = || {
1931 if params.len() == 1 {
1932 // if sole lifetime, remove the entire `<>` brackets
1934 } else if param_index == 0 {
1935 // if removing within `<>` brackets, we also want to
1936 // delete a leading or trailing comma as appropriate
1937 param.span().to(params[param_index + 1].span().shrink_to_lo())
1939 // if removing within `<>` brackets, we also want to
1940 // delete a leading or trailing comma as appropriate
1941 params[param_index - 1].span().shrink_to_hi().to(param.span())
1945 Some(LifetimeUseSet::Many) => {}
1946 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1947 debug!(?param.ident, ?param.ident.span, ?use_span);
1949 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1951 let deletion_span = deletion_span();
1952 self.r.lint_buffer.buffer_lint_with_diagnostic(
1953 lint::builtin::SINGLE_USE_LIFETIMES,
1956 &format!("lifetime parameter `{}` only used once", param.ident),
1957 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1958 param_span: param.ident.span,
1959 use_span: Some((use_span, elidable)),
1965 debug!(?param.ident, ?param.ident.span);
1967 let deletion_span = deletion_span();
1968 self.r.lint_buffer.buffer_lint_with_diagnostic(
1969 lint::builtin::UNUSED_LIFETIMES,
1972 &format!("lifetime parameter `{}` never used", param.ident),
1973 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1974 param_span: param.ident.span,
1984 pub(crate) fn emit_undeclared_lifetime_error(
1986 lifetime_ref: &ast::Lifetime,
1987 outer_lifetime_ref: Option<Ident>,
1989 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1990 let mut err = if let Some(outer) = outer_lifetime_ref {
1991 let mut err = struct_span_err!(
1993 lifetime_ref.ident.span,
1995 "can't use generic parameters from outer item",
1997 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1998 err.span_label(outer.span, "lifetime parameter from outer item");
2001 let mut err = struct_span_err!(
2003 lifetime_ref.ident.span,
2005 "use of undeclared lifetime name `{}`",
2008 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2011 self.suggest_introducing_lifetime(
2013 Some(lifetime_ref.ident.name.as_str()),
2014 |err, _, span, message, suggestion| {
2015 err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect);
2022 fn suggest_introducing_lifetime(
2024 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
2026 suggest: impl Fn(&mut DiagnosticBuilder<'_, ErrorGuaranteed>, bool, Span, &str, String) -> bool,
2028 let mut suggest_note = true;
2029 for rib in self.lifetime_ribs.iter().rev() {
2030 let mut should_continue = true;
2032 LifetimeRibKind::Generics { binder: _, span, kind } => {
2033 if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name {
2034 suggest_note = false; // Avoid displaying the same help multiple times.
2038 "lifetime `{}` is missing in item created through this procedural macro",
2045 let higher_ranked = matches!(
2047 LifetimeBinderKind::BareFnType
2048 | LifetimeBinderKind::PolyTrait
2049 | LifetimeBinderKind::WhereBound
2051 let (span, sugg) = if span.is_empty() {
2054 if higher_ranked { "for" } else { "" },
2055 name.unwrap_or("'a"),
2056 if higher_ranked { " " } else { "" },
2061 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2062 let sugg = format!("{}, ", name.unwrap_or("'a"));
2066 let message = format!(
2067 "consider making the {} lifetime-generic with a new `{}` lifetime",
2069 name.unwrap_or("'a"),
2071 should_continue = suggest(err, true, span, &message, sugg);
2073 "for more information on higher-ranked polymorphism, visit \
2074 https://doc.rust-lang.org/nomicon/hrtb.html",
2076 } else if let Some(name) = name {
2077 let message = format!("consider introducing lifetime `{}` here", name);
2078 should_continue = suggest(err, false, span, &message, sugg);
2080 let message = format!("consider introducing a named lifetime parameter");
2081 should_continue = suggest(err, false, span, &message, sugg);
2084 LifetimeRibKind::Item => break,
2087 if !should_continue {
2093 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2096 lifetime_ref.ident.span,
2098 "use of non-static lifetime `{}` in const generic",
2102 "for more information, see issue #74052 \
2103 <https://github.com/rust-lang/rust/issues/74052>",
2108 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2109 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2110 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2111 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2113 lifetime_ref: &ast::Lifetime,
2115 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2116 if !feature_active {
2118 &self.r.session.parse_sess,
2119 sym::generic_const_exprs,
2120 lifetime_ref.ident.span,
2121 "a non-static lifetime is not allowed in a `const`",
2127 pub(crate) fn report_missing_lifetime_specifiers(
2129 lifetime_refs: Vec<MissingLifetime>,
2130 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2131 ) -> ErrorGuaranteed {
2132 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
2133 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
2135 let mut err = struct_span_err!(
2139 "missing lifetime specifier{}",
2140 pluralize!(num_lifetimes)
2142 self.add_missing_lifetime_specifiers_label(
2145 function_param_lifetimes,
2150 pub(crate) fn add_missing_lifetime_specifiers_label(
2152 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
2153 lifetime_refs: Vec<MissingLifetime>,
2154 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2156 for < in &lifetime_refs {
2160 "expected {} lifetime parameter{}",
2161 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
2162 pluralize!(lt.count),
2167 let mut in_scope_lifetimes: Vec<_> = self
2171 .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item))
2172 .flat_map(|rib| rib.bindings.iter())
2173 .map(|(&ident, &res)| (ident, res))
2174 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
2176 debug!(?in_scope_lifetimes);
2178 debug!(?function_param_lifetimes);
2179 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
2180 let elided_len = param_lifetimes.len();
2181 let num_params = params.len();
2183 let mut m = String::new();
2185 for (i, info) in params.iter().enumerate() {
2186 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
2187 debug_assert_ne!(lifetime_count, 0);
2189 err.span_label(span, "");
2192 if i + 1 < num_params {
2194 } else if num_params == 2 {
2197 m.push_str(", or ");
2201 let help_name = if let Some(ident) = ident {
2202 format!("`{}`", ident)
2204 format!("argument {}", index + 1)
2207 if lifetime_count == 1 {
2208 m.push_str(&help_name[..])
2210 m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..])
2214 if num_params == 0 {
2216 "this function's return type contains a borrowed value, \
2217 but there is no value for it to be borrowed from",
2219 if in_scope_lifetimes.is_empty() {
2220 in_scope_lifetimes = vec![(
2221 Ident::with_dummy_span(kw::StaticLifetime),
2222 (DUMMY_NODE_ID, LifetimeRes::Static),
2225 } else if elided_len == 0 {
2227 "this function's return type contains a borrowed value with \
2228 an elided lifetime, but the lifetime cannot be derived from \
2231 if in_scope_lifetimes.is_empty() {
2232 in_scope_lifetimes = vec![(
2233 Ident::with_dummy_span(kw::StaticLifetime),
2234 (DUMMY_NODE_ID, LifetimeRes::Static),
2237 } else if num_params == 1 {
2239 "this function's return type contains a borrowed value, \
2240 but the signature does not say which {} it is borrowed from",
2245 "this function's return type contains a borrowed value, \
2246 but the signature does not say whether it is borrowed from {}",
2252 let existing_name = match &in_scope_lifetimes[..] {
2253 [] => Symbol::intern("'a"),
2254 [(existing, _)] => existing.name,
2255 _ => Symbol::intern("'lifetime"),
2258 let mut spans_suggs: Vec<_> = Vec::new();
2259 let build_sugg = |lt: MissingLifetime| match lt.kind {
2260 MissingLifetimeKind::Underscore => {
2261 debug_assert_eq!(lt.count, 1);
2262 (lt.span, existing_name.to_string())
2264 MissingLifetimeKind::Ampersand => {
2265 debug_assert_eq!(lt.count, 1);
2266 (lt.span.shrink_to_hi(), format!("{} ", existing_name))
2268 MissingLifetimeKind::Comma => {
2269 let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
2273 (lt.span.shrink_to_hi(), sugg)
2275 MissingLifetimeKind::Brackets => {
2276 let sugg: String = std::iter::once("<")
2278 std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
2282 (lt.span.shrink_to_hi(), sugg)
2285 for < in &lifetime_refs {
2286 spans_suggs.push(build_sugg(lt));
2288 debug!(?spans_suggs);
2289 match in_scope_lifetimes.len() {
2291 if let Some((param_lifetimes, _)) = function_param_lifetimes {
2292 for lt in param_lifetimes {
2293 spans_suggs.push(build_sugg(lt))
2296 self.suggest_introducing_lifetime(
2299 |err, higher_ranked, span, message, intro_sugg| {
2300 err.multipart_suggestion_verbose(
2302 std::iter::once((span, intro_sugg))
2303 .chain(spans_suggs.clone())
2305 Applicability::MaybeIncorrect,
2312 err.multipart_suggestion_verbose(
2313 &format!("consider using the `{}` lifetime", existing_name),
2315 Applicability::MaybeIncorrect,
2318 // Record as using the suggested resolution.
2319 let (_, (_, res)) = in_scope_lifetimes[0];
2320 for < in &lifetime_refs {
2321 self.r.lifetimes_res_map.insert(lt.id, res);
2325 let lifetime_spans: Vec<_> =
2326 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
2327 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2329 if spans_suggs.len() > 0 {
2330 // This happens when we have `Foo<T>` where we point at the space before `T`,
2331 // but this can be confusing so we give a suggestion with placeholders.
2332 err.multipart_suggestion_verbose(
2333 "consider using one of the available lifetimes here",
2335 Applicability::HasPlaceholders,
2343 /// Report lifetime/lifetime shadowing as an error.
2344 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2345 let mut err = struct_span_err!(
2349 "lifetime name `{}` shadows a lifetime name that is already in scope",
2352 err.span_label(orig.span, "first declared here");
2353 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2357 /// Shadowing involving a label is only a warning for historical reasons.
2358 //FIXME: make this a proper lint.
2359 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2360 let name = shadower.name;
2361 let shadower = shadower.span;
2362 let mut err = sess.struct_span_warn(
2364 &format!("label name `{}` shadows a label name that is already in scope", name),
2366 err.span_label(orig, "first declared here");
2367 err.span_label(shadower, format!("label `{}` already in scope", name));