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),
143 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
148 /// Handles error reporting for `smart_resolve_path_fragment` function.
149 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
150 pub(crate) fn smart_resolve_report_errors(
154 source: PathSource<'_>,
156 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
157 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
158 let ns = source.namespace();
159 let is_expected = &|res| source.is_expected(res);
160 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
162 debug!(?res, ?source);
164 // Make the base error.
165 struct BaseError<'a> {
167 fallback_label: String,
170 suggestion: Option<(Span, &'a str, String)>,
172 let mut expected = source.descr_expected();
173 let path_str = Segment::names_to_string(path);
174 let item_str = path.last().unwrap().ident;
175 let base_error = if let Some(res) = res {
177 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
178 fallback_label: format!("not a {expected}"),
180 could_be_expr: match res {
181 Res::Def(DefKind::Fn, _) => {
182 // Verify whether this is a fn call or an Fn used as a type.
186 .span_to_snippet(span)
187 .map(|snippet| snippet.ends_with(')'))
191 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
196 | Res::Local(_) => true,
202 let item_span = path.last().unwrap().ident.span;
203 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
204 debug!(?self.diagnostic_metadata.current_impl_items);
205 debug!(?self.diagnostic_metadata.current_function);
206 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
207 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
208 && self.current_trait_ref.is_none()
209 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
210 && let Some(item) = items.iter().find(|i| {
211 if let AssocItemKind::Fn(fn_) = &i.kind
212 && !fn_.sig.decl.has_self()
213 && i.ident.name == item_str.name
215 debug!(?item_str.name);
216 debug!(?fn_.sig.decl.inputs);
224 "consider using the associated function",
225 format!("Self::{}", item.ident)
230 (String::new(), "this scope".to_string(), suggestion)
231 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
232 if self.r.session.edition() > Edition::Edition2015 {
233 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
234 // which overrides all other expectations of item type
236 (String::new(), "the list of imported crates".to_string(), None)
238 (String::new(), "the crate root".to_string(), None)
240 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
241 (String::new(), "the crate root".to_string(), None)
243 let mod_path = &path[..path.len() - 1];
244 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
245 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
248 .map_or_else(String::new, |res| format!("{} ", res.descr()));
249 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
252 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
253 fallback_label: if path_str == "async" && expected.starts_with("struct") {
254 "`async` blocks are only allowed in Rust 2018 or later".to_string()
256 format!("not found in {mod_str}")
259 could_be_expr: false,
264 let code = source.error_code(res.is_some());
266 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
268 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
270 if let Some(sugg) = base_error.suggestion {
271 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
274 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
275 err.multipart_suggestion(
276 "you might have meant to write a `struct` literal",
278 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
279 (span.shrink_to_hi(), "}".to_string()),
281 Applicability::HasPlaceholders,
284 match (source, self.diagnostic_metadata.in_if_condition) {
287 Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }),
289 // Icky heuristic so we don't suggest:
290 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
291 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
292 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
293 err.span_suggestion_verbose(
294 expr_span.shrink_to_lo(),
295 "you might have meant to use pattern matching",
297 Applicability::MaybeIncorrect,
304 let is_assoc_fn = self.self_type_is_available();
305 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
306 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
307 err.span_suggestion_short(
309 "you might have meant to use `self` here instead",
311 Applicability::MaybeIncorrect,
313 if !self.self_value_is_available(path[0].ident.span) {
314 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
315 &self.diagnostic_metadata.current_function
317 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
318 (param.span.shrink_to_lo(), "&self, ")
324 .span_through_char(*fn_span, '(')
329 err.span_suggestion_verbose(
331 "if you meant to use `self`, you are also missing a `self` receiver \
334 Applicability::MaybeIncorrect,
340 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
342 // Emit special messages for unresolved `Self` and `self`.
343 if is_self_type(path, ns) {
344 err.code(rustc_errors::error_code!(E0411));
347 "`Self` is only available in impls, traits, and type definitions".to_string(),
349 if let Some(item_kind) = self.diagnostic_metadata.current_item {
351 item_kind.ident.span,
353 "`Self` not allowed in {} {}",
354 item_kind.kind.article(),
355 item_kind.kind.descr()
359 return (err, Vec::new());
361 if is_self_value(path, ns) {
362 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
364 err.code(rustc_errors::error_code!(E0424));
365 err.span_label(span, match source {
366 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed",
367 _ => "`self` value is a keyword only available in methods with a `self` parameter",
369 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
370 // The current function has a `self' parameter, but we were unable to resolve
371 // a reference to `self`. This can only happen if the `self` identifier we
372 // are resolving came from a different hygiene context.
373 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
374 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
376 let doesnt = if is_assoc_fn {
377 let (span, sugg) = fn_kind
381 .map(|p| (p.span.shrink_to_lo(), "&self, "))
383 // Try to look for the "(" after the function name, if possible.
384 // This avoids placing the suggestion into the visibility specifier.
387 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
392 .span_through_char(span, '(')
397 err.span_suggestion_verbose(
399 "add a `self` receiver parameter to make the associated `fn` a method",
401 Applicability::MaybeIncorrect,
407 if let Some(ident) = fn_kind.ident() {
410 &format!("this function {} have a `self` parameter", doesnt),
414 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
416 item_kind.ident.span,
418 "`self` not allowed in {} {}",
419 item_kind.kind.article(),
420 item_kind.kind.descr()
424 return (err, Vec::new());
427 // Try to lookup name in more relaxed fashion for better error reporting.
428 let ident = path.last().unwrap().ident;
429 let mut candidates = self
431 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
433 .filter(|ImportSuggestion { did, .. }| {
434 match (did, res.and_then(|res| res.opt_def_id())) {
435 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
439 .collect::<Vec<_>>();
440 let crate_def_id = CRATE_DEF_ID.to_def_id();
441 // Try to filter out intrinsics candidates, as long as we have
442 // some other candidates to suggest.
443 let intrinsic_candidates: Vec<_> = candidates
444 .drain_filter(|sugg| {
445 let path = path_names_to_string(&sugg.path);
446 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
449 if candidates.is_empty() {
450 // Put them back if we have no more candidates to suggest...
451 candidates.extend(intrinsic_candidates);
453 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
454 let mut enum_candidates: Vec<_> = self
456 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
458 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
459 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
461 if !enum_candidates.is_empty() {
462 if let (PathSource::Type, Some(span)) =
463 (source, self.diagnostic_metadata.current_type_ascription.last())
469 .type_ascription_path_suggestions
473 // Already reported this issue on the lhs of the type ascription.
475 return (err, candidates);
479 enum_candidates.sort();
481 // Contextualize for E0412 "cannot find type", but don't belabor the point
482 // (that it's a variant) for E0573 "expected type, found variant".
483 let preamble = if res.is_none() {
484 let others = match enum_candidates.len() {
486 2 => " and 1 other".to_owned(),
487 n => format!(" and {} others", n),
489 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
493 let msg = format!("{}try using the variant's enum", preamble);
495 err.span_suggestions(
498 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
499 Applicability::MachineApplicable,
503 // Try Levenshtein algorithm.
504 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
505 if path.len() == 1 && self.self_type_is_available() {
506 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
507 let self_is_available = self.self_value_is_available(path[0].ident.span);
509 AssocSuggestion::Field => {
510 if self_is_available {
513 "you might have meant to use the available field",
514 format!("self.{path_str}"),
515 Applicability::MachineApplicable,
518 err.span_label(span, "a field by this name exists in `Self`");
521 AssocSuggestion::MethodWithSelf if self_is_available => {
524 "you might have meant to call the method",
525 format!("self.{path_str}"),
526 Applicability::MachineApplicable,
529 AssocSuggestion::MethodWithSelf
530 | AssocSuggestion::AssocFn
531 | AssocSuggestion::AssocConst
532 | AssocSuggestion::AssocType => {
535 &format!("you might have meant to {}", candidate.action()),
536 format!("Self::{path_str}"),
537 Applicability::MachineApplicable,
541 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
542 return (err, candidates);
545 // If the first argument in call is `self` suggest calling a method.
546 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
547 let mut args_snippet = String::new();
548 if let Some(args_span) = args_span {
549 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
550 args_snippet = snippet;
556 &format!("try calling `{ident}` as a method"),
557 format!("self.{path_str}({args_snippet})"),
558 Applicability::MachineApplicable,
560 return (err, candidates);
564 // Try context-dependent help if relaxed lookup didn't work.
565 if let Some(res) = res {
566 if self.smart_resolve_context_dependent_help(
572 &base_error.fallback_label,
574 // We do this to avoid losing a secondary span when we override the main error span.
575 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
576 return (err, candidates);
581 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
582 if !self.type_ascription_suggestion(&mut err, base_error.span) {
583 let mut fallback = false;
585 PathSource::Trait(AliasPossibility::Maybe),
586 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
588 ) = (source, res, is_macro)
590 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
592 let spans: Vec<Span> = bounds
594 .map(|bound| bound.span())
595 .filter(|&sp| sp != base_error.span)
598 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
599 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
600 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
601 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
602 let last_bound_span = spans.last().cloned().unwrap();
603 let mut multi_span: MultiSpan = spans.clone().into();
605 let msg = if sp == last_bound_span {
607 "...because of {these} bound{s}",
608 these = pluralize!("this", bounds.len() - 1),
609 s = pluralize!(bounds.len() - 1),
614 multi_span.push_span_label(sp, msg);
617 .push_span_label(base_error.span, "expected this type to be a trait...");
620 "`+` is used to constrain a \"trait object\" type with lifetimes or \
621 auto-traits; structs and enums can't be bound in that way",
623 if bounds.iter().all(|bound| match bound {
624 ast::GenericBound::Outlives(_) => true,
625 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
627 let mut sugg = vec![];
628 if base_error.span != start_span {
629 sugg.push((start_span.until(base_error.span), String::new()));
631 if base_error.span != end_span {
632 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
635 err.multipart_suggestion(
636 "if you meant to use a type and not a trait here, remove the bounds",
638 Applicability::MaybeIncorrect,
644 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
646 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
648 match self.diagnostic_metadata.current_let_binding {
649 Some((pat_sp, Some(ty_sp), None))
650 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
652 err.span_suggestion_short(
653 pat_sp.between(ty_sp),
654 "use `=` if you meant to assign",
656 Applicability::MaybeIncorrect,
662 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
663 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
664 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
668 err.span_label(base_error.span, base_error.fallback_label);
671 if let Some(err_code) = &err.code {
672 if err_code == &rustc_errors::error_code!(E0425) {
673 for label_rib in &self.label_ribs {
674 for (label_ident, node_id) in &label_rib.bindings {
675 if format!("'{}", ident) == label_ident.to_string() {
676 err.span_label(label_ident.span, "a label with a similar name exists");
677 if let PathSource::Expr(Some(Expr {
678 kind: ExprKind::Break(None, Some(_)),
684 "use the similarly named label",
686 Applicability::MaybeIncorrect,
688 // Do not lint against unused label when we suggest them.
689 self.diagnostic_metadata.unused_labels.remove(node_id);
694 } else if err_code == &rustc_errors::error_code!(E0412) {
695 if let Some(correct) = Self::likely_rust_type(path) {
698 "perhaps you intended to use this type",
700 Applicability::MaybeIncorrect,
709 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
710 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
711 let TyKind::Path(_, path) = &ty.kind else { return; };
712 for segment in &path.segments {
713 let Some(params) = &segment.args else { continue; };
714 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
715 for param in ¶ms.args {
716 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
717 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
720 for bound in bounds {
721 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
726 if base_span == trait_ref.span {
727 err.span_suggestion_verbose(
728 constraint.ident.span.between(trait_ref.span),
729 "you might have meant to write a path instead of an associated type bound",
731 Applicability::MachineApplicable,
739 fn suggest_swapping_misplaced_self_ty_and_trait(
741 err: &mut Diagnostic,
742 source: PathSource<'_>,
746 if let Some((trait_ref, self_ty)) =
747 self.diagnostic_metadata.currently_processing_impl_trait.clone()
748 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
749 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
750 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
751 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
752 && trait_ref.path.span == span
753 && let PathSource::Trait(_) = source
754 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
755 && let Ok(self_ty_str) =
756 self.r.session.source_map().span_to_snippet(self_ty.span)
757 && let Ok(trait_ref_str) =
758 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
760 err.multipart_suggestion(
761 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
762 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
763 Applicability::MaybeIncorrect,
768 fn get_single_associated_item(
771 source: &PathSource<'_>,
772 filter_fn: &impl Fn(Res) -> bool,
773 ) -> Option<TypoSuggestion> {
774 if let crate::PathSource::TraitItem(_) = source {
775 let mod_path = &path[..path.len() - 1];
776 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
777 self.resolve_path(mod_path, None, None)
779 let resolutions = self.r.resolutions(module).borrow();
780 let targets: Vec<_> =
783 .filter_map(|(key, resolution)| {
784 resolution.borrow().binding.map(|binding| binding.res()).and_then(
785 |res| if filter_fn(res) { Some((key, res)) } else { None },
789 if targets.len() == 1 {
790 let target = targets[0];
791 return Some(TypoSuggestion::single_item_from_res(
801 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
802 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
803 // Detect that we are actually in a `where` predicate.
804 let (bounded_ty, bounds, where_span) =
805 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
807 bound_generic_params,
810 })) = self.diagnostic_metadata.current_where_predicate
812 if !bound_generic_params.is_empty() {
815 (bounded_ty, bounds, span)
820 // Confirm that the target is an associated type.
821 let (ty, position, path) = if let ast::TyKind::Path(
822 Some(ast::QSelf { ty, position, .. }),
826 // use this to verify that ident is a type param.
827 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
831 partial_res.base_res(),
832 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
833 ) && partial_res.unresolved_segments() == 0)
842 let peeled_ty = ty.peel_refs();
843 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
844 // Confirm that the `SelfTy` is a type parameter.
845 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
849 partial_res.base_res(),
850 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
851 ) && partial_res.unresolved_segments() == 0)
856 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
857 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
858 ) = (&type_param_path.segments[..], &bounds[..])
860 if let [ast::PathSegment { ident, args: None, .. }] =
861 &poly_trait_ref.trait_ref.path.segments[..]
863 if ident.span == span {
864 err.span_suggestion_verbose(
866 &format!("constrain the associated type to `{}`", ident),
872 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
873 .unwrap_or_else(|_| constrain_ident.to_string()),
874 path.segments[..*position]
876 .map(|segment| path_segment_to_string(segment))
879 path.segments[*position..]
881 .map(|segment| path_segment_to_string(segment))
886 Applicability::MaybeIncorrect,
896 /// Check if the source is call expression and the first argument is `self`. If true,
897 /// return the span of whole call and the span for all arguments expect the first one (`self`).
898 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
899 let mut has_self_arg = None;
900 if let PathSource::Expr(Some(parent)) = source {
902 ExprKind::Call(_, args) if !args.is_empty() => {
903 let mut expr_kind = &args[0].kind;
906 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
907 if arg_name.segments[0].ident.name == kw::SelfLower {
908 let call_span = parent.span;
909 let tail_args_span = if args.len() > 1 {
912 args.last().unwrap().span.hi(),
919 has_self_arg = Some((call_span, tail_args_span));
923 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
934 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
935 // HACK(estebank): find a better way to figure out that this was a
936 // parser issue where a struct literal is being used on an expression
937 // where a brace being opened means a block is being started. Look
938 // ahead for the next text to see if `span` is followed by a `{`.
939 let sm = self.r.session.source_map();
942 sp = sm.next_point(sp);
943 match sm.span_to_snippet(sp) {
945 if snippet.chars().any(|c| !c.is_whitespace()) {
952 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
953 // In case this could be a struct literal that needs to be surrounded
954 // by parentheses, find the appropriate span.
956 let mut closing_brace = None;
958 sp = sm.next_point(sp);
959 match sm.span_to_snippet(sp) {
962 closing_brace = Some(span.to(sp));
969 // The bigger the span, the more likely we're incorrect --
970 // bound it to 100 chars long.
975 (followed_by_brace, closing_brace)
978 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
980 /// Returns `true` if able to provide context-dependent help.
981 fn smart_resolve_context_dependent_help(
983 err: &mut Diagnostic,
985 source: PathSource<'_>,
988 fallback_label: &str,
990 let ns = source.namespace();
991 let is_expected = &|res| source.is_expected(res);
993 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
994 ExprKind::Field(_, ident) => {
997 "use the path separator to refer to an item",
998 format!("{}::{}", path_str, ident),
999 Applicability::MaybeIncorrect,
1003 ExprKind::MethodCall(ref segment, ..) => {
1004 let span = expr.span.with_hi(segment.ident.span.hi());
1005 err.span_suggestion(
1007 "use the path separator to refer to an item",
1008 format!("{}::{}", path_str, segment.ident),
1009 Applicability::MaybeIncorrect,
1016 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1018 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1019 | PathSource::TupleStruct(span, _) => {
1020 // We want the main underline to cover the suggested code as well for
1022 err.set_span(*span);
1029 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1030 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1033 PathSource::Expr(Some(
1034 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1035 )) if path_sep(err, &parent) => {}
1041 | ExprKind::Binary(..)
1042 | ExprKind::Unary(..)
1044 | ExprKind::While(..)
1045 | ExprKind::ForLoop(..)
1046 | ExprKind::Match(..),
1049 ) if followed_by_brace => {
1050 if let Some(sp) = closing_brace {
1051 err.span_label(span, fallback_label);
1052 err.multipart_suggestion(
1053 "surround the struct literal with parentheses",
1055 (sp.shrink_to_lo(), "(".to_string()),
1056 (sp.shrink_to_hi(), ")".to_string()),
1058 Applicability::MaybeIncorrect,
1062 span, // Note the parentheses surrounding the suggestion below
1064 "you might want to surround a struct literal with parentheses: \
1065 `({} {{ /* fields */ }})`?",
1071 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1072 let span = find_span(&source, err);
1073 if let Some(span) = self.def_span(def_id) {
1074 err.span_label(span, &format!("`{}` defined here", path_str));
1076 let (tail, descr, applicability) = match source {
1077 PathSource::Pat | PathSource::TupleStruct(..) => {
1078 ("", "pattern", Applicability::MachineApplicable)
1080 _ => (": val", "literal", Applicability::HasPlaceholders),
1082 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1086 .map(|f| format!("{}{}", f.node, tail))
1087 .collect::<Vec<String>>()
1091 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1093 let pad = match self.r.field_names.get(&def_id) {
1094 Some(fields) if fields.is_empty() => "",
1097 err.span_suggestion(
1099 &format!("use struct {} syntax instead", descr),
1100 format!("{path_str} {{{pad}{fields}{pad}}}"),
1105 err.span_label(span, fallback_label);
1110 match (res, source) {
1112 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1113 PathSource::Expr(Some(Expr {
1114 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1116 | PathSource::Struct,
1118 err.span_label(span, fallback_label);
1119 err.span_suggestion_verbose(
1120 span.shrink_to_hi(),
1121 "use `!` to invoke the macro",
1123 Applicability::MaybeIncorrect,
1125 if path_str == "try" && span.rust_2015() {
1126 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1129 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1130 err.span_label(span, fallback_label);
1132 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1133 err.span_label(span, "type aliases cannot be used as traits");
1134 if self.r.session.is_nightly_build() {
1135 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1137 if let Some(span) = self.def_span(def_id) {
1138 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1139 // The span contains a type alias so we should be able to
1140 // replace `type` with `trait`.
1141 let snip = snip.replacen("type", "trait", 1);
1142 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1144 err.span_help(span, msg);
1151 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1152 if !path_sep(err, &parent) {
1157 Res::Def(DefKind::Enum, def_id),
1158 PathSource::TupleStruct(..) | PathSource::Expr(..),
1161 .diagnostic_metadata
1162 .current_type_ascription
1168 .type_ascription_path_suggestions
1174 err.downgrade_to_delayed_bug();
1175 // We already suggested changing `:` into `::` during parsing.
1179 self.suggest_using_enum_variant(err, source, def_id, span);
1181 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1182 let (ctor_def, ctor_vis, fields) =
1183 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1184 if let PathSource::Expr(Some(parent)) = source {
1185 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1186 bad_struct_syntax_suggestion(def_id);
1192 bad_struct_syntax_suggestion(def_id);
1196 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1197 if !is_expected(ctor_def) || is_accessible {
1201 let field_spans = match source {
1202 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1203 PathSource::TupleStruct(_, pattern_spans) => {
1204 err.set_primary_message(
1205 "cannot match against a tuple struct which contains private fields",
1208 // Use spans of the tuple struct pattern.
1209 Some(Vec::from(pattern_spans))
1211 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1212 _ if source.is_call() => {
1213 err.set_primary_message(
1214 "cannot initialize a tuple struct which contains private fields",
1217 // Use spans of the tuple struct definition.
1221 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1226 if let Some(spans) =
1227 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1229 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1230 .filter(|(vis, _)| {
1231 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1233 .map(|(_, span)| *span)
1236 if non_visible_spans.len() > 0 {
1237 let mut m: MultiSpan = non_visible_spans.clone().into();
1240 .for_each(|s| m.push_span_label(s, "private field"));
1241 err.span_note(m, "constructor is not visible here due to private fields");
1247 err.span_label(span, "constructor is not visible here due to private fields");
1251 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1255 ) if ns == ValueNS => {
1256 bad_struct_syntax_suggestion(def_id);
1258 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1260 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1261 let span = find_span(&source, err);
1262 if let Some(span) = self.def_span(def_id) {
1263 err.span_label(span, &format!("`{}` defined here", path_str));
1265 err.span_suggestion(
1267 "use this syntax instead",
1269 Applicability::MaybeIncorrect,
1275 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1276 if let Some(span) = self.def_span(def_id) {
1277 err.span_label(span, &format!("`{}` defined here", path_str));
1279 let fields = self.r.field_names.get(&def_id).map_or_else(
1280 || "/* fields */".to_string(),
1281 |fields| vec!["_"; fields.len()].join(", "),
1283 err.span_suggestion(
1285 "use the tuple variant pattern syntax instead",
1286 format!("{}({})", path_str, fields),
1287 Applicability::HasPlaceholders,
1290 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1291 err.span_label(span, fallback_label);
1292 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1294 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1295 err.note("can't use a type alias as a constructor");
1302 /// Given the target `ident` and `kind`, search for the similarly named associated item
1303 /// in `self.current_trait_ref`.
1304 pub(crate) fn find_similarly_named_assoc_item(
1307 kind: &AssocItemKind,
1308 ) -> Option<Symbol> {
1309 let (module, _) = self.current_trait_ref.as_ref()?;
1310 if ident == kw::Underscore {
1311 // We do nothing for `_`.
1315 let resolutions = self.r.resolutions(module);
1316 let targets = resolutions
1319 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1320 .filter(|(_, res)| match (kind, res) {
1321 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1322 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1323 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1326 .map(|(key, _)| key.ident.name)
1327 .collect::<Vec<_>>();
1329 find_best_match_for_name(&targets, ident, None)
1332 fn lookup_assoc_candidate<FilterFn>(
1336 filter_fn: FilterFn,
1337 ) -> Option<AssocSuggestion>
1339 FilterFn: Fn(Res) -> bool,
1341 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1343 TyKind::Path(None, _) => Some(t.id),
1344 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1345 // This doesn't handle the remaining `Ty` variants as they are not
1346 // that commonly the self_type, it might be interesting to provide
1347 // support for those in future.
1352 // Fields are generally expected in the same contexts as locals.
1353 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1354 if let Some(node_id) =
1355 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1357 // Look for a field with the same name in the current self_type.
1358 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1359 match resolution.base_res() {
1360 Res::Def(DefKind::Struct | DefKind::Union, did)
1361 if resolution.unresolved_segments() == 0 =>
1363 if let Some(field_names) = self.r.field_names.get(&did) {
1366 .any(|&field_name| ident.name == field_name.node)
1368 return Some(AssocSuggestion::Field);
1378 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1379 for assoc_item in items {
1380 if assoc_item.ident == ident {
1381 return Some(match &assoc_item.kind {
1382 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1383 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1384 AssocSuggestion::MethodWithSelf
1386 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1387 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1388 ast::AssocItemKind::MacCall(_) => continue,
1394 // Look for associated items in the current trait.
1395 if let Some((module, _)) = self.current_trait_ref {
1396 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1397 ModuleOrUniformRoot::Module(module),
1402 let res = binding.res();
1404 if self.r.has_self.contains(&res.def_id()) {
1405 return Some(AssocSuggestion::MethodWithSelf);
1408 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1409 Res::Def(DefKind::AssocConst, _) => {
1410 return Some(AssocSuggestion::AssocConst);
1412 Res::Def(DefKind::AssocTy, _) => {
1413 return Some(AssocSuggestion::AssocType);
1425 fn lookup_typo_candidate(
1429 filter_fn: &impl Fn(Res) -> bool,
1430 ) -> Option<TypoSuggestion> {
1431 let mut names = Vec::new();
1432 if path.len() == 1 {
1433 // Search in lexical scope.
1434 // Walk backwards up the ribs in scope and collect candidates.
1435 for rib in self.ribs[ns].iter().rev() {
1436 // Locals and type parameters
1437 for (ident, &res) in &rib.bindings {
1439 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1443 if let RibKind::ModuleRibKind(module) = rib.kind {
1444 // Items from this module
1445 self.r.add_module_candidates(module, &mut names, &filter_fn);
1447 if let ModuleKind::Block(..) = module.kind {
1448 // We can see through blocks
1450 // Items from the prelude
1451 if !module.no_implicit_prelude {
1452 let extern_prelude = self.r.extern_prelude.clone();
1453 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1454 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1457 Res::Def(DefKind::Mod, crate_id.as_def_id());
1459 if filter_fn(crate_mod) {
1460 Some(TypoSuggestion::typo_from_res(
1461 ident.name, crate_mod,
1470 if let Some(prelude) = self.r.prelude {
1471 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1478 // Add primitive types to the mix
1479 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1480 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1481 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1485 // Search in module.
1486 let mod_path = &path[..path.len() - 1];
1487 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1488 self.resolve_path(mod_path, Some(TypeNS), None)
1490 self.r.add_module_candidates(module, &mut names, &filter_fn);
1494 let name = path[path.len() - 1].ident.name;
1495 // Make sure error reporting is deterministic.
1496 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1498 match find_best_match_for_name(
1499 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1503 Some(found) if found != name => {
1504 names.into_iter().find(|suggestion| suggestion.candidate == found)
1510 // Returns the name of the Rust type approximately corresponding to
1511 // a type name in another programming language.
1512 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1513 let name = path[path.len() - 1].ident.as_str();
1514 // Common Java types
1516 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1517 "short" => sym::i16,
1518 "Bool" => sym::bool,
1519 "Boolean" => sym::bool,
1520 "boolean" => sym::bool,
1523 "float" => sym::f32,
1524 "double" => sym::f64,
1529 /// Only used in a specific case of type ascription suggestions
1530 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1531 let sm = self.r.session.source_map();
1532 start.to(sm.next_point(start))
1535 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1536 let sm = self.r.session.source_map();
1537 let base_snippet = sm.span_to_snippet(base_span);
1538 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1539 if let Ok(snippet) = sm.span_to_snippet(sp) {
1540 let len = snippet.trim_end().len() as u32;
1541 if snippet.trim() == ":" {
1543 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1544 let mut show_label = true;
1545 if sm.is_multiline(sp) {
1546 err.span_suggestion_short(
1548 "maybe you meant to write `;` here",
1550 Applicability::MaybeIncorrect,
1553 let after_colon_sp =
1554 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1555 if snippet.len() == 1 {
1557 err.span_suggestion(
1559 "maybe you meant to write a path separator here",
1561 Applicability::MaybeIncorrect,
1568 .type_ascription_path_suggestions
1572 err.downgrade_to_delayed_bug();
1575 if let Ok(base_snippet) = base_snippet {
1576 let mut sp = after_colon_sp;
1578 // Try to find an assignment
1579 sp = sm.next_point(sp);
1580 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1582 Ok(ref x) if x.as_str() == "=" => {
1583 err.span_suggestion(
1585 "maybe you meant to write an assignment here",
1586 format!("let {}", base_snippet),
1587 Applicability::MaybeIncorrect,
1592 Ok(ref x) if x.as_str() == "\n" => break,
1602 "expecting a type here because of type ascription",
1612 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1613 let mut result = None;
1614 let mut seen_modules = FxHashSet::default();
1615 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1617 while let Some((in_module, path_segments)) = worklist.pop() {
1618 // abort if the module is already found
1619 if result.is_some() {
1623 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1624 // abort if the module is already found or if name_binding is private external
1625 if result.is_some() || !name_binding.vis.is_visible_locally() {
1628 if let Some(module) = name_binding.module() {
1630 let mut path_segments = path_segments.clone();
1631 path_segments.push(ast::PathSegment::from_ident(ident));
1632 let module_def_id = module.def_id();
1633 if module_def_id == def_id {
1635 Path { span: name_binding.span, segments: path_segments, tokens: None };
1647 // add the module to the lookup
1648 if seen_modules.insert(module_def_id) {
1649 worklist.push((module, path_segments));
1659 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1660 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1661 let mut variants = Vec::new();
1662 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1663 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1664 let mut segms = enum_import_suggestion.path.segments.clone();
1665 segms.push(ast::PathSegment::from_ident(ident));
1666 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1667 variants.push((path, def_id, kind));
1674 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1675 fn suggest_using_enum_variant(
1677 err: &mut Diagnostic,
1678 source: PathSource<'_>,
1682 let Some(variants) = self.collect_enum_ctors(def_id) else {
1683 err.note("you might have meant to use one of the enum's variants");
1687 let suggest_only_tuple_variants =
1688 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1689 if suggest_only_tuple_variants {
1690 // Suggest only tuple variants regardless of whether they have fields and do not
1691 // suggest path with added parentheses.
1692 let suggestable_variants = variants
1694 .filter(|(.., kind)| *kind == CtorKind::Fn)
1695 .map(|(variant, ..)| path_names_to_string(variant))
1696 .collect::<Vec<_>>();
1698 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1700 let source_msg = if source.is_call() {
1702 } else if matches!(source, PathSource::TupleStruct(..)) {
1708 if !suggestable_variants.is_empty() {
1709 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1710 format!("try {} the enum's variant", source_msg)
1712 format!("try {} one of the enum's variants", source_msg)
1715 err.span_suggestions(
1718 suggestable_variants.into_iter(),
1719 Applicability::MaybeIncorrect,
1723 // If the enum has no tuple variants..
1724 if non_suggestable_variant_count == variants.len() {
1725 err.help(&format!("the enum has no tuple variants {}", source_msg));
1728 // If there are also non-tuple variants..
1729 if non_suggestable_variant_count == 1 {
1731 "you might have meant {} the enum's non-tuple variant",
1734 } else if non_suggestable_variant_count >= 1 {
1736 "you might have meant {} one of the enum's non-tuple variants",
1741 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1742 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1744 CtorKind::Const => false,
1745 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1750 let mut suggestable_variants = variants
1752 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1753 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1754 .map(|(variant, kind)| match kind {
1755 CtorKind::Const => variant,
1756 CtorKind::Fn => format!("({}())", variant),
1757 CtorKind::Fictive => format!("({} {{}})", variant),
1759 .collect::<Vec<_>>();
1761 if !suggestable_variants.is_empty() {
1762 let msg = if suggestable_variants.len() == 1 {
1763 "you might have meant to use the following enum variant"
1765 "you might have meant to use one of the following enum variants"
1768 err.span_suggestions(
1771 suggestable_variants.drain(..),
1772 Applicability::MaybeIncorrect,
1776 let suggestable_variants_with_placeholders = variants
1778 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1779 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1780 .filter_map(|(variant, kind)| match kind {
1781 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1782 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1785 .collect::<Vec<_>>();
1787 if !suggestable_variants_with_placeholders.is_empty() {
1789 suggestable_variants.is_empty(),
1790 suggestable_variants_with_placeholders.len(),
1792 (true, 1) => "the following enum variant is available",
1793 (true, _) => "the following enum variants are available",
1794 (false, 1) => "alternatively, the following enum variant is available",
1795 (false, _) => "alternatively, the following enum variants are also available",
1798 err.span_suggestions(
1801 suggestable_variants_with_placeholders.into_iter(),
1802 Applicability::HasPlaceholders,
1807 if def_id.is_local() {
1808 if let Some(span) = self.def_span(def_id) {
1809 err.span_note(span, "the enum is defined here");
1814 pub(crate) fn report_missing_type_error(
1817 ) -> Option<(Span, &'static str, String, Applicability)> {
1818 let (ident, span) = match path {
1819 [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
1820 (segment.ident.to_string(), segment.ident.span)
1824 let mut iter = ident.chars().map(|c| c.is_uppercase());
1825 let single_uppercase_char =
1826 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1827 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1830 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1831 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1832 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1837 kind @ ItemKind::Fn(..)
1838 | kind @ ItemKind::Enum(..)
1839 | kind @ ItemKind::Struct(..)
1840 | kind @ ItemKind::Union(..),
1845 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1846 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1847 | (Some(Item { kind, .. }), false, _) => {
1848 // Likely missing type parameter.
1849 if let Some(generics) = kind.generics() {
1850 if span.overlaps(generics.span) {
1851 // Avoid the following:
1852 // error[E0405]: cannot find trait `A` in this scope
1853 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1855 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1856 // | ^- help: you might be missing a type parameter: `, A`
1858 // | not found in this scope
1861 let msg = "you might be missing a type parameter";
1862 let (span, sugg) = if let [.., param] = &generics.params[..] {
1863 let span = if let [.., bound] = ¶m.bounds[..] {
1865 } else if let GenericParam {
1866 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1868 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1872 (span, format!(", {}", ident))
1874 (generics.span, format!("<{}>", ident))
1876 // Do not suggest if this is coming from macro expansion.
1877 if span.can_be_used_for_suggestions() {
1879 span.shrink_to_hi(),
1882 Applicability::MaybeIncorrect,
1892 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1893 /// optionally returning the closest match and whether it is reachable.
1894 pub(crate) fn suggestion_for_label_in_rib(
1898 ) -> Option<LabelSuggestion> {
1899 // Are ribs from this `rib_index` within scope?
1900 let within_scope = self.is_label_valid_from_rib(rib_index);
1902 let rib = &self.label_ribs[rib_index];
1906 .filter(|(id, _)| id.span.eq_ctxt(label.span))
1907 .map(|(id, _)| id.name)
1908 .collect::<Vec<Symbol>>();
1910 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1911 // Upon finding a similar name, get the ident that it was from - the span
1912 // contained within helps make a useful diagnostic. In addition, determine
1913 // whether this candidate is within scope.
1914 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1915 (*ident, within_scope)
1919 pub(crate) fn maybe_report_lifetime_uses(
1921 generics_span: Span,
1922 params: &[ast::GenericParam],
1924 for (param_index, param) in params.iter().enumerate() {
1925 let GenericParamKind::Lifetime = param.kind else { continue };
1927 let def_id = self.r.local_def_id(param.id);
1929 let use_set = self.lifetime_uses.remove(&def_id);
1931 "Use set for {:?}({:?} at {:?}) is {:?}",
1932 def_id, param.ident, param.ident.span, use_set
1935 let deletion_span = || {
1936 if params.len() == 1 {
1937 // if sole lifetime, remove the entire `<>` brackets
1939 } else if param_index == 0 {
1940 // if removing within `<>` brackets, we also want to
1941 // delete a leading or trailing comma as appropriate
1942 param.span().to(params[param_index + 1].span().shrink_to_lo())
1944 // if removing within `<>` brackets, we also want to
1945 // delete a leading or trailing comma as appropriate
1946 params[param_index - 1].span().shrink_to_hi().to(param.span())
1950 Some(LifetimeUseSet::Many) => {}
1951 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1952 debug!(?param.ident, ?param.ident.span, ?use_span);
1954 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1956 let deletion_span = deletion_span();
1957 self.r.lint_buffer.buffer_lint_with_diagnostic(
1958 lint::builtin::SINGLE_USE_LIFETIMES,
1961 &format!("lifetime parameter `{}` only used once", param.ident),
1962 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1963 param_span: param.ident.span,
1964 use_span: Some((use_span, elidable)),
1970 debug!(?param.ident, ?param.ident.span);
1972 let deletion_span = deletion_span();
1973 self.r.lint_buffer.buffer_lint_with_diagnostic(
1974 lint::builtin::UNUSED_LIFETIMES,
1977 &format!("lifetime parameter `{}` never used", param.ident),
1978 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1979 param_span: param.ident.span,
1989 pub(crate) fn emit_undeclared_lifetime_error(
1991 lifetime_ref: &ast::Lifetime,
1992 outer_lifetime_ref: Option<Ident>,
1994 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1995 let mut err = if let Some(outer) = outer_lifetime_ref {
1996 let mut err = struct_span_err!(
1998 lifetime_ref.ident.span,
2000 "can't use generic parameters from outer item",
2002 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
2003 err.span_label(outer.span, "lifetime parameter from outer item");
2006 let mut err = struct_span_err!(
2008 lifetime_ref.ident.span,
2010 "use of undeclared lifetime name `{}`",
2013 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2016 self.suggest_introducing_lifetime(
2018 Some(lifetime_ref.ident.name.as_str()),
2019 |err, _, span, message, suggestion| {
2020 err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect);
2027 fn suggest_introducing_lifetime(
2029 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
2031 suggest: impl Fn(&mut DiagnosticBuilder<'_, ErrorGuaranteed>, bool, Span, &str, String) -> bool,
2033 let mut suggest_note = true;
2034 for rib in self.lifetime_ribs.iter().rev() {
2035 let mut should_continue = true;
2037 LifetimeRibKind::Generics { binder: _, span, kind } => {
2038 if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name {
2039 suggest_note = false; // Avoid displaying the same help multiple times.
2043 "lifetime `{}` is missing in item created through this procedural macro",
2050 let higher_ranked = matches!(
2052 LifetimeBinderKind::BareFnType
2053 | LifetimeBinderKind::PolyTrait
2054 | LifetimeBinderKind::WhereBound
2056 let (span, sugg) = if span.is_empty() {
2059 if higher_ranked { "for" } else { "" },
2060 name.unwrap_or("'a"),
2061 if higher_ranked { " " } else { "" },
2066 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2067 let sugg = format!("{}, ", name.unwrap_or("'a"));
2071 let message = format!(
2072 "consider making the {} lifetime-generic with a new `{}` lifetime",
2074 name.unwrap_or("'a"),
2076 should_continue = suggest(err, true, span, &message, sugg);
2078 "for more information on higher-ranked polymorphism, visit \
2079 https://doc.rust-lang.org/nomicon/hrtb.html",
2081 } else if let Some(name) = name {
2082 let message = format!("consider introducing lifetime `{}` here", name);
2083 should_continue = suggest(err, false, span, &message, sugg);
2085 let message = format!("consider introducing a named lifetime parameter");
2086 should_continue = suggest(err, false, span, &message, sugg);
2089 LifetimeRibKind::Item => break,
2092 if !should_continue {
2098 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2101 lifetime_ref.ident.span,
2103 "use of non-static lifetime `{}` in const generic",
2107 "for more information, see issue #74052 \
2108 <https://github.com/rust-lang/rust/issues/74052>",
2113 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2114 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2115 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2116 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2118 lifetime_ref: &ast::Lifetime,
2120 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2121 if !feature_active {
2123 &self.r.session.parse_sess,
2124 sym::generic_const_exprs,
2125 lifetime_ref.ident.span,
2126 "a non-static lifetime is not allowed in a `const`",
2132 pub(crate) fn report_missing_lifetime_specifiers(
2134 lifetime_refs: Vec<MissingLifetime>,
2135 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2136 ) -> ErrorGuaranteed {
2137 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
2138 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
2140 let mut err = struct_span_err!(
2144 "missing lifetime specifier{}",
2145 pluralize!(num_lifetimes)
2147 self.add_missing_lifetime_specifiers_label(
2150 function_param_lifetimes,
2155 pub(crate) fn add_missing_lifetime_specifiers_label(
2157 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
2158 lifetime_refs: Vec<MissingLifetime>,
2159 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2161 for < in &lifetime_refs {
2165 "expected {} lifetime parameter{}",
2166 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
2167 pluralize!(lt.count),
2172 let mut in_scope_lifetimes: Vec<_> = self
2176 .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item))
2177 .flat_map(|rib| rib.bindings.iter())
2178 .map(|(&ident, &res)| (ident, res))
2179 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
2181 debug!(?in_scope_lifetimes);
2183 debug!(?function_param_lifetimes);
2184 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
2185 let elided_len = param_lifetimes.len();
2186 let num_params = params.len();
2188 let mut m = String::new();
2190 for (i, info) in params.iter().enumerate() {
2191 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
2192 debug_assert_ne!(lifetime_count, 0);
2194 err.span_label(span, "");
2197 if i + 1 < num_params {
2199 } else if num_params == 2 {
2202 m.push_str(", or ");
2206 let help_name = if let Some(ident) = ident {
2207 format!("`{}`", ident)
2209 format!("argument {}", index + 1)
2212 if lifetime_count == 1 {
2213 m.push_str(&help_name[..])
2215 m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..])
2219 if num_params == 0 {
2221 "this function's return type contains a borrowed value, \
2222 but there is no value for it to be borrowed from",
2224 if in_scope_lifetimes.is_empty() {
2225 in_scope_lifetimes = vec![(
2226 Ident::with_dummy_span(kw::StaticLifetime),
2227 (DUMMY_NODE_ID, LifetimeRes::Static),
2230 } else if elided_len == 0 {
2232 "this function's return type contains a borrowed value with \
2233 an elided lifetime, but the lifetime cannot be derived from \
2236 if in_scope_lifetimes.is_empty() {
2237 in_scope_lifetimes = vec![(
2238 Ident::with_dummy_span(kw::StaticLifetime),
2239 (DUMMY_NODE_ID, LifetimeRes::Static),
2242 } else if num_params == 1 {
2244 "this function's return type contains a borrowed value, \
2245 but the signature does not say which {} it is borrowed from",
2250 "this function's return type contains a borrowed value, \
2251 but the signature does not say whether it is borrowed from {}",
2257 let existing_name = match &in_scope_lifetimes[..] {
2258 [] => Symbol::intern("'a"),
2259 [(existing, _)] => existing.name,
2260 _ => Symbol::intern("'lifetime"),
2263 let mut spans_suggs: Vec<_> = Vec::new();
2264 let build_sugg = |lt: MissingLifetime| match lt.kind {
2265 MissingLifetimeKind::Underscore => {
2266 debug_assert_eq!(lt.count, 1);
2267 (lt.span, existing_name.to_string())
2269 MissingLifetimeKind::Ampersand => {
2270 debug_assert_eq!(lt.count, 1);
2271 (lt.span.shrink_to_hi(), format!("{} ", existing_name))
2273 MissingLifetimeKind::Comma => {
2274 let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
2278 (lt.span.shrink_to_hi(), sugg)
2280 MissingLifetimeKind::Brackets => {
2281 let sugg: String = std::iter::once("<")
2283 std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
2287 (lt.span.shrink_to_hi(), sugg)
2290 for < in &lifetime_refs {
2291 spans_suggs.push(build_sugg(lt));
2293 debug!(?spans_suggs);
2294 match in_scope_lifetimes.len() {
2296 if let Some((param_lifetimes, _)) = function_param_lifetimes {
2297 for lt in param_lifetimes {
2298 spans_suggs.push(build_sugg(lt))
2301 self.suggest_introducing_lifetime(
2304 |err, higher_ranked, span, message, intro_sugg| {
2305 err.multipart_suggestion_verbose(
2307 std::iter::once((span, intro_sugg))
2308 .chain(spans_suggs.clone())
2310 Applicability::MaybeIncorrect,
2317 err.multipart_suggestion_verbose(
2318 &format!("consider using the `{}` lifetime", existing_name),
2320 Applicability::MaybeIncorrect,
2323 // Record as using the suggested resolution.
2324 let (_, (_, res)) = in_scope_lifetimes[0];
2325 for < in &lifetime_refs {
2326 self.r.lifetimes_res_map.insert(lt.id, res);
2330 let lifetime_spans: Vec<_> =
2331 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
2332 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2334 if spans_suggs.len() > 0 {
2335 // This happens when we have `Foo<T>` where we point at the space before `T`,
2336 // but this can be confusing so we give a suggestion with placeholders.
2337 err.multipart_suggestion_verbose(
2338 "consider using one of the available lifetimes here",
2340 Applicability::HasPlaceholders,
2348 /// Report lifetime/lifetime shadowing as an error.
2349 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2350 let mut err = struct_span_err!(
2354 "lifetime name `{}` shadows a lifetime name that is already in scope",
2357 err.span_label(orig.span, "first declared here");
2358 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2362 /// Shadowing involving a label is only a warning for historical reasons.
2363 //FIXME: make this a proper lint.
2364 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2365 let name = shadower.name;
2366 let shadower = shadower.span;
2367 let mut err = sess.struct_span_warn(
2369 &format!("label name `{}` shadows a label name that is already in scope", name),
2371 err.span_label(orig, "first declared here");
2372 err.span_label(shadower, format!("label `{}` already in scope", name));