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};
36 type Res = def::Res<ast::NodeId>;
38 /// A field or associated item from self type suggested in case of resolution failure.
39 enum AssocSuggestion {
47 impl AssocSuggestion {
48 fn action(&self) -> &'static str {
50 AssocSuggestion::Field => "use the available field",
51 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
52 AssocSuggestion::AssocFn => "call the associated function",
53 AssocSuggestion::AssocConst => "use the associated `const`",
54 AssocSuggestion::AssocType => "use the associated type",
59 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
60 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
63 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
64 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
67 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
68 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
69 let variant_path = &suggestion.path;
70 let variant_path_string = path_names_to_string(variant_path);
72 let path_len = suggestion.path.segments.len();
73 let enum_path = ast::Path {
74 span: suggestion.path.span,
75 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
78 let enum_path_string = path_names_to_string(&enum_path);
80 (variant_path_string, enum_path_string)
83 /// Description of an elided lifetime.
84 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
85 pub(super) struct MissingLifetime {
86 /// Used to overwrite the resolution with the suggestion, to avoid cascasing errors.
88 /// Where to suggest adding the lifetime.
90 /// How the lifetime was introduced, to have the correct space and comma.
91 pub kind: MissingLifetimeKind,
92 /// Number of elided lifetimes, used for elision in path.
96 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
97 pub(super) enum MissingLifetimeKind {
100 /// An elided lifetime `&' ty`.
102 /// An elided lifetime in brackets with written brackets.
104 /// An elided lifetime with elided brackets.
108 /// Description of the lifetimes appearing in a function parameter.
109 /// This is used to provide a literal explanation to the elision failure.
110 #[derive(Clone, Debug)]
111 pub(super) struct ElisionFnParameter {
112 /// The index of the argument in the original definition.
114 /// The name of the argument if it's a simple ident.
115 pub ident: Option<Ident>,
116 /// The number of lifetimes in the parameter.
117 pub lifetime_count: usize,
118 /// The span of the parameter.
122 /// Description of lifetimes that appear as candidates for elision.
123 /// This is used to suggest introducing an explicit lifetime.
125 pub(super) enum LifetimeElisionCandidate {
126 /// This is not a real lifetime.
128 /// There is a named lifetime, we won't suggest anything.
130 Missing(MissingLifetime),
133 /// Only used for diagnostics.
136 fallback_label: String,
138 span_label: Option<(Span, &'static str)>,
140 suggestion: Option<(Span, &'static str, String)>,
143 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
144 fn def_span(&self, def_id: DefId) -> Option<Span> {
146 LOCAL_CRATE => self.r.opt_span(def_id),
147 _ => Some(self.r.cstore().get_span_untracked(def_id, self.r.session)),
155 source: PathSource<'_>,
158 // Make the base error.
159 let mut expected = source.descr_expected();
160 let path_str = Segment::names_to_string(path);
161 let item_str = path.last().unwrap().ident;
162 if let Some(res) = res {
164 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
165 fallback_label: format!("not a {expected}"),
167 span_label: match res {
168 Res::Def(kind, def_id) if kind == DefKind::TyParam => {
169 self.def_span(def_id).map(|span| (span, "found this type parameter"))
173 could_be_expr: match res {
174 Res::Def(DefKind::Fn, _) => {
175 // Verify whether this is a fn call or an Fn used as a type.
179 .span_to_snippet(span)
180 .map(|snippet| snippet.ends_with(')'))
184 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
189 | Res::Local(_) => true,
195 let item_span = path.last().unwrap().ident.span;
196 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
197 debug!(?self.diagnostic_metadata.current_impl_items);
198 debug!(?self.diagnostic_metadata.current_function);
199 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
200 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
201 && self.current_trait_ref.is_none()
202 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
203 && let Some(item) = items.iter().find(|i| {
204 if let AssocItemKind::Fn(fn_) = &i.kind
205 && !fn_.sig.decl.has_self()
206 && i.ident.name == item_str.name
208 debug!(?item_str.name);
209 debug!(?fn_.sig.decl.inputs);
217 "consider using the associated function",
218 format!("Self::{}", item.ident)
223 (String::new(), "this scope".to_string(), suggestion)
224 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
225 if self.r.session.edition() > Edition::Edition2015 {
226 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
227 // which overrides all other expectations of item type
229 (String::new(), "the list of imported crates".to_string(), None)
231 (String::new(), "the crate root".to_string(), None)
233 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
234 (String::new(), "the crate root".to_string(), None)
236 let mod_path = &path[..path.len() - 1];
237 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
238 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
241 .map_or_else(String::new, |res| format!("{} ", res.descr()));
242 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
245 let (fallback_label, suggestion) = if path_str == "async"
246 && expected.starts_with("struct")
248 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
250 // check if we are in situation of typo like `True` instead of `true`.
251 let override_suggestion =
252 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
253 let item_typo = item_str.to_string().to_lowercase();
256 "you may want to use a bool value instead",
257 format!("{}", item_typo),
262 (format!("not found in {mod_str}"), override_suggestion)
266 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
270 could_be_expr: false,
276 /// Handles error reporting for `smart_resolve_path_fragment` function.
277 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
278 pub(crate) fn smart_resolve_report_errors(
282 source: PathSource<'_>,
284 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
285 debug!(?res, ?source);
286 let base_error = self.make_base_error(path, span, source, res);
287 let code = source.error_code(res.is_some());
289 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
291 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
293 if let Some((span, label)) = base_error.span_label {
294 err.span_label(span, label);
297 if let Some(ref sugg) = base_error.suggestion {
298 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
301 self.suggest_bare_struct_literal(&mut err);
302 self.suggest_pattern_match_with_let(&mut err, source, span);
304 self.suggest_self_or_self_ref(&mut err, path, span);
305 self.detect_assoct_type_constraint_meant_as_path(&mut err, &base_error);
306 if self.suggest_self_ty(&mut err, source, path, span)
307 || self.suggest_self_value(&mut err, source, path, span)
309 return (err, Vec::new());
312 let (found, candidates) =
313 self.try_lookup_name_relaxed(&mut err, source, path, span, res, &base_error);
315 return (err, candidates);
318 if !self.type_ascription_suggestion(&mut err, base_error.span) {
320 self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
321 fallback |= self.suggest_typo(&mut err, source, path, span, &base_error);
324 err.span_label(base_error.span, &base_error.fallback_label);
327 self.err_code_special_cases(&mut err, source, path, span);
332 fn detect_assoct_type_constraint_meant_as_path(
334 err: &mut Diagnostic,
335 base_error: &BaseError,
337 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
338 let TyKind::Path(_, path) = &ty.kind else { return; };
339 for segment in &path.segments {
340 let Some(params) = &segment.args else { continue; };
341 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
342 for param in ¶ms.args {
343 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
344 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
347 for bound in bounds {
348 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
353 if base_error.span == trait_ref.span {
354 err.span_suggestion_verbose(
355 constraint.ident.span.between(trait_ref.span),
356 "you might have meant to write a path instead of an associated type bound",
358 Applicability::MachineApplicable,
366 fn suggest_self_or_self_ref(&mut self, err: &mut Diagnostic, path: &[Segment], span: Span) {
367 let is_assoc_fn = self.self_type_is_available();
368 let Some(path_last_segment) = path.last() else { return };
369 let item_str = path_last_segment.ident;
370 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
371 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
372 err.span_suggestion_short(
374 "you might have meant to use `self` here instead",
376 Applicability::MaybeIncorrect,
378 if !self.self_value_is_available(path[0].ident.span) {
379 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
380 &self.diagnostic_metadata.current_function
382 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
383 (param.span.shrink_to_lo(), "&self, ")
389 .span_through_char(*fn_span, '(')
394 err.span_suggestion_verbose(
396 "if you meant to use `self`, you are also missing a `self` receiver \
399 Applicability::MaybeIncorrect,
406 fn try_lookup_name_relaxed(
408 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
409 source: PathSource<'_>,
413 base_error: &BaseError,
414 ) -> (bool, Vec<ImportSuggestion>) {
415 // Try to lookup name in more relaxed fashion for better error reporting.
416 let ident = path.last().unwrap().ident;
417 let is_expected = &|res| source.is_expected(res);
418 let ns = source.namespace();
419 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
420 let path_str = Segment::names_to_string(path);
421 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
423 let mut candidates = self
425 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
427 .filter(|ImportSuggestion { did, .. }| {
428 match (did, res.and_then(|res| res.opt_def_id())) {
429 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
433 .collect::<Vec<_>>();
434 let crate_def_id = CRATE_DEF_ID.to_def_id();
435 // Try to filter out intrinsics candidates, as long as we have
436 // some other candidates to suggest.
437 let intrinsic_candidates: Vec<_> = candidates
438 .drain_filter(|sugg| {
439 let path = path_names_to_string(&sugg.path);
440 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
443 if candidates.is_empty() {
444 // Put them back if we have no more candidates to suggest...
445 candidates.extend(intrinsic_candidates);
447 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
448 let mut enum_candidates: Vec<_> = self
450 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
452 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
453 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
455 if !enum_candidates.is_empty() {
456 if let (PathSource::Type, Some(span)) =
457 (source, self.diagnostic_metadata.current_type_ascription.last())
463 .type_ascription_path_suggestions
467 // Already reported this issue on the lhs of the type ascription.
469 return (true, candidates);
473 enum_candidates.sort();
475 // Contextualize for E0412 "cannot find type", but don't belabor the point
476 // (that it's a variant) for E0573 "expected type, found variant".
477 let preamble = if res.is_none() {
478 let others = match enum_candidates.len() {
480 2 => " and 1 other".to_owned(),
481 n => format!(" and {} others", n),
483 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
487 let msg = format!("{}try using the variant's enum", preamble);
489 err.span_suggestions(
492 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
493 Applicability::MachineApplicable,
498 // Try Levenshtein algorithm.
499 let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), 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(err, typo_sugg, ident_span);
537 return (true, 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 (true, 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(err, typo_sugg, ident_span);
571 return (true, candidates);
574 return (false, candidates);
577 fn suggest_trait_and_bounds(
579 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
580 source: PathSource<'_>,
583 base_error: &BaseError,
586 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
587 let mut fallback = false;
590 PathSource::Trait(AliasPossibility::Maybe),
591 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
593 ) = (source, res, is_macro)
595 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
597 let spans: Vec<Span> = bounds
599 .map(|bound| bound.span())
600 .filter(|&sp| sp != base_error.span)
603 let start_span = bounds[0].span();
604 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
605 let end_span = bounds.last().unwrap().span();
606 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
607 let last_bound_span = spans.last().cloned().unwrap();
608 let mut multi_span: MultiSpan = spans.clone().into();
610 let msg = if sp == last_bound_span {
612 "...because of {these} bound{s}",
613 these = pluralize!("this", bounds.len() - 1),
614 s = pluralize!(bounds.len() - 1),
619 multi_span.push_span_label(sp, msg);
621 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
624 "`+` is used to constrain a \"trait object\" type with lifetimes or \
625 auto-traits; structs and enums can't be bound in that way",
627 if bounds.iter().all(|bound| match bound {
628 ast::GenericBound::Outlives(_) => true,
629 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
631 let mut sugg = vec![];
632 if base_error.span != start_span {
633 sugg.push((start_span.until(base_error.span), String::new()));
635 if base_error.span != end_span {
636 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
639 err.multipart_suggestion(
640 "if you meant to use a type and not a trait here, remove the bounds",
642 Applicability::MaybeIncorrect,
648 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
654 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
655 source: PathSource<'_>,
658 base_error: &BaseError,
660 let is_expected = &|res| source.is_expected(res);
661 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
662 let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
663 let mut fallback = false;
664 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
666 match self.diagnostic_metadata.current_let_binding {
667 Some((pat_sp, Some(ty_sp), None))
668 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
670 err.span_suggestion_short(
671 pat_sp.between(ty_sp),
672 "use `=` if you meant to assign",
674 Applicability::MaybeIncorrect,
680 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
681 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
682 self.r.add_typo_suggestion(err, suggestion, ident_span);
687 fn err_code_special_cases(
689 err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
690 source: PathSource<'_>,
694 if let Some(err_code) = &err.code {
695 if err_code == &rustc_errors::error_code!(E0425) {
696 for label_rib in &self.label_ribs {
697 for (label_ident, node_id) in &label_rib.bindings {
698 let ident = path.last().unwrap().ident;
699 if format!("'{}", ident) == label_ident.to_string() {
700 err.span_label(label_ident.span, "a label with a similar name exists");
701 if let PathSource::Expr(Some(Expr {
702 kind: ExprKind::Break(None, Some(_)),
708 "use the similarly named label",
710 Applicability::MaybeIncorrect,
712 // Do not lint against unused label when we suggest them.
713 self.diagnostic_metadata.unused_labels.remove(node_id);
718 } else if err_code == &rustc_errors::error_code!(E0412) {
719 if let Some(correct) = Self::likely_rust_type(path) {
722 "perhaps you intended to use this type",
724 Applicability::MaybeIncorrect,
731 /// Emit special messages for unresolved `Self` and `self`.
734 err: &mut Diagnostic,
735 source: PathSource<'_>,
739 if !is_self_type(path, source.namespace()) {
742 err.code(rustc_errors::error_code!(E0411));
745 "`Self` is only available in impls, traits, and type definitions".to_string(),
747 if let Some(item_kind) = self.diagnostic_metadata.current_item {
749 item_kind.ident.span,
751 "`Self` not allowed in {} {}",
752 item_kind.kind.article(),
753 item_kind.kind.descr()
760 fn suggest_self_value(
762 err: &mut Diagnostic,
763 source: PathSource<'_>,
767 if !is_self_value(path, source.namespace()) {
771 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
772 err.code(rustc_errors::error_code!(E0424));
777 "`self` value is a keyword and may not be bound to variables or shadowed"
779 _ => "`self` value is a keyword only available in methods with a `self` parameter",
782 let is_assoc_fn = self.self_type_is_available();
783 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
784 // The current function has a `self' parameter, but we were unable to resolve
785 // a reference to `self`. This can only happen if the `self` identifier we
786 // are resolving came from a different hygiene context.
787 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
788 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
790 let doesnt = if is_assoc_fn {
791 let (span, sugg) = fn_kind
795 .map(|p| (p.span.shrink_to_lo(), "&self, "))
797 // Try to look for the "(" after the function name, if possible.
798 // This avoids placing the suggestion into the visibility specifier.
801 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
806 .span_through_char(span, '(')
811 err.span_suggestion_verbose(
813 "add a `self` receiver parameter to make the associated `fn` a method",
815 Applicability::MaybeIncorrect,
821 if let Some(ident) = fn_kind.ident() {
824 &format!("this function {} have a `self` parameter", doesnt),
828 } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
830 item_kind.ident.span,
832 "`self` not allowed in {} {}",
833 item_kind.kind.article(),
834 item_kind.kind.descr()
841 fn suggest_swapping_misplaced_self_ty_and_trait(
843 err: &mut Diagnostic,
844 source: PathSource<'_>,
848 if let Some((trait_ref, self_ty)) =
849 self.diagnostic_metadata.currently_processing_impl_trait.clone()
850 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
851 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
852 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
853 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
854 && trait_ref.path.span == span
855 && let PathSource::Trait(_) = source
856 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
857 && let Ok(self_ty_str) =
858 self.r.session.source_map().span_to_snippet(self_ty.span)
859 && let Ok(trait_ref_str) =
860 self.r.session.source_map().span_to_snippet(trait_ref.path.span)
862 err.multipart_suggestion(
863 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
864 vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
865 Applicability::MaybeIncorrect,
870 fn suggest_bare_struct_literal(&mut self, err: &mut Diagnostic) {
871 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
872 err.multipart_suggestion(
873 "you might have meant to write a `struct` literal",
875 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
876 (span.shrink_to_hi(), "}".to_string()),
878 Applicability::HasPlaceholders,
883 fn suggest_pattern_match_with_let(
885 err: &mut Diagnostic,
886 source: PathSource<'_>,
889 if let PathSource::Expr(_) = source &&
892 kind: ExprKind::Assign(lhs, _, _),
894 }) = self.diagnostic_metadata.in_if_condition {
895 // Icky heuristic so we don't suggest:
896 // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
897 // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
898 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
899 err.span_suggestion_verbose(
900 expr_span.shrink_to_lo(),
901 "you might have meant to use pattern matching",
903 Applicability::MaybeIncorrect,
909 fn get_single_associated_item(
912 source: &PathSource<'_>,
913 filter_fn: &impl Fn(Res) -> bool,
914 ) -> Option<TypoSuggestion> {
915 if let crate::PathSource::TraitItem(_) = source {
916 let mod_path = &path[..path.len() - 1];
917 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
918 self.resolve_path(mod_path, None, None)
920 let resolutions = self.r.resolutions(module).borrow();
921 let targets: Vec<_> =
924 .filter_map(|(key, resolution)| {
925 resolution.borrow().binding.map(|binding| binding.res()).and_then(
926 |res| if filter_fn(res) { Some((key, res)) } else { None },
930 if targets.len() == 1 {
931 let target = targets[0];
932 return Some(TypoSuggestion::single_item_from_res(
942 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
943 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
944 // Detect that we are actually in a `where` predicate.
945 let (bounded_ty, bounds, where_span) =
946 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
948 bound_generic_params,
951 })) = self.diagnostic_metadata.current_where_predicate
953 if !bound_generic_params.is_empty() {
956 (bounded_ty, bounds, span)
961 // Confirm that the target is an associated type.
962 let (ty, position, path) = if let ast::TyKind::Path(
963 Some(ast::QSelf { ty, position, .. }),
967 // use this to verify that ident is a type param.
968 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
972 partial_res.base_res(),
973 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
974 ) && partial_res.unresolved_segments() == 0)
983 let peeled_ty = ty.peel_refs();
984 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
985 // Confirm that the `SelfTy` is a type parameter.
986 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
990 partial_res.base_res(),
991 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
992 ) && partial_res.unresolved_segments() == 0)
997 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
998 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
999 ) = (&type_param_path.segments[..], &bounds[..])
1001 if let [ast::PathSegment { ident, args: None, .. }] =
1002 &poly_trait_ref.trait_ref.path.segments[..]
1004 if ident.span == span {
1005 err.span_suggestion_verbose(
1007 &format!("constrain the associated type to `{}`", ident),
1013 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
1014 .unwrap_or_else(|_| constrain_ident.to_string()),
1015 path.segments[..*position]
1017 .map(|segment| path_segment_to_string(segment))
1018 .collect::<Vec<_>>()
1020 path.segments[*position..]
1022 .map(|segment| path_segment_to_string(segment))
1023 .collect::<Vec<_>>()
1027 Applicability::MaybeIncorrect,
1037 /// Check if the source is call expression and the first argument is `self`. If true,
1038 /// return the span of whole call and the span for all arguments expect the first one (`self`).
1039 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
1040 let mut has_self_arg = None;
1041 if let PathSource::Expr(Some(parent)) = source {
1042 match &parent.kind {
1043 ExprKind::Call(_, args) if !args.is_empty() => {
1044 let mut expr_kind = &args[0].kind;
1047 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1048 if arg_name.segments[0].ident.name == kw::SelfLower {
1049 let call_span = parent.span;
1050 let tail_args_span = if args.len() > 1 {
1053 args.last().unwrap().span.hi(),
1060 has_self_arg = Some((call_span, tail_args_span));
1064 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1075 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1076 // HACK(estebank): find a better way to figure out that this was a
1077 // parser issue where a struct literal is being used on an expression
1078 // where a brace being opened means a block is being started. Look
1079 // ahead for the next text to see if `span` is followed by a `{`.
1080 let sm = self.r.session.source_map();
1083 sp = sm.next_point(sp);
1084 match sm.span_to_snippet(sp) {
1085 Ok(ref snippet) => {
1086 if snippet.chars().any(|c| !c.is_whitespace()) {
1093 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
1094 // In case this could be a struct literal that needs to be surrounded
1095 // by parentheses, find the appropriate span.
1097 let mut closing_brace = None;
1099 sp = sm.next_point(sp);
1100 match sm.span_to_snippet(sp) {
1101 Ok(ref snippet) => {
1103 closing_brace = Some(span.to(sp));
1110 // The bigger the span, the more likely we're incorrect --
1111 // bound it to 100 chars long.
1116 (followed_by_brace, closing_brace)
1119 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
1121 /// Returns `true` if able to provide context-dependent help.
1122 fn smart_resolve_context_dependent_help(
1124 err: &mut Diagnostic,
1126 source: PathSource<'_>,
1129 fallback_label: &str,
1131 let ns = source.namespace();
1132 let is_expected = &|res| source.is_expected(res);
1134 let path_sep = |err: &mut Diagnostic, expr: &Expr, kind: DefKind| {
1135 const MESSAGE: &str = "use the path separator to refer to an item";
1137 let (lhs_span, rhs_span) = match &expr.kind {
1138 ExprKind::Field(base, ident) => (base.span, ident.span),
1139 ExprKind::MethodCall(_, receiver, _, span) => (receiver.span, *span),
1143 if lhs_span.eq_ctxt(rhs_span) {
1144 err.span_suggestion(
1145 lhs_span.between(rhs_span),
1148 Applicability::MaybeIncorrect,
1151 } else if kind == DefKind::Struct
1152 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1153 && let Ok(snippet) = self.r.session.source_map().span_to_snippet(lhs_source_span)
1155 // The LHS is a type that originates from a macro call.
1156 // We have to add angle brackets around it.
1158 err.span_suggestion_verbose(
1159 lhs_source_span.until(rhs_span),
1161 format!("<{snippet}>::"),
1162 Applicability::MaybeIncorrect,
1166 // Either we were unable to obtain the source span / the snippet or
1167 // the LHS originates from a macro call and it is not a type and thus
1168 // there is no way to replace `.` with `::` and still somehow suggest
1175 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
1177 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1178 | PathSource::TupleStruct(span, _) => {
1179 // We want the main underline to cover the suggested code as well for
1181 err.set_span(*span);
1188 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
1189 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
1192 PathSource::Expr(Some(
1193 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1194 )) if path_sep(err, &parent, DefKind::Struct) => {}
1200 | ExprKind::Binary(..)
1201 | ExprKind::Unary(..)
1203 | ExprKind::While(..)
1204 | ExprKind::ForLoop(..)
1205 | ExprKind::Match(..),
1208 ) if followed_by_brace => {
1209 if let Some(sp) = closing_brace {
1210 err.span_label(span, fallback_label);
1211 err.multipart_suggestion(
1212 "surround the struct literal with parentheses",
1214 (sp.shrink_to_lo(), "(".to_string()),
1215 (sp.shrink_to_hi(), ")".to_string()),
1217 Applicability::MaybeIncorrect,
1221 span, // Note the parentheses surrounding the suggestion below
1223 "you might want to surround a struct literal with parentheses: \
1224 `({} {{ /* fields */ }})`?",
1230 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1231 let span = find_span(&source, err);
1232 if let Some(span) = self.def_span(def_id) {
1233 err.span_label(span, &format!("`{}` defined here", path_str));
1235 let (tail, descr, applicability) = match source {
1236 PathSource::Pat | PathSource::TupleStruct(..) => {
1237 ("", "pattern", Applicability::MachineApplicable)
1239 _ => (": val", "literal", Applicability::HasPlaceholders),
1241 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1245 .map(|f| format!("{}{}", f.node, tail))
1246 .collect::<Vec<String>>()
1250 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1252 let pad = match self.r.field_names.get(&def_id) {
1253 Some(fields) if fields.is_empty() => "",
1256 err.span_suggestion(
1258 &format!("use struct {} syntax instead", descr),
1259 format!("{path_str} {{{pad}{fields}{pad}}}"),
1264 err.span_label(span, fallback_label);
1269 match (res, source) {
1271 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1272 PathSource::Expr(Some(Expr {
1273 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1275 | PathSource::Struct,
1277 err.span_label(span, fallback_label);
1278 err.span_suggestion_verbose(
1279 span.shrink_to_hi(),
1280 "use `!` to invoke the macro",
1282 Applicability::MaybeIncorrect,
1284 if path_str == "try" && span.rust_2015() {
1285 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1288 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1289 err.span_label(span, fallback_label);
1291 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1292 err.span_label(span, "type aliases cannot be used as traits");
1293 if self.r.session.is_nightly_build() {
1294 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1296 if let Some(span) = self.def_span(def_id) {
1297 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1298 // The span contains a type alias so we should be able to
1299 // replace `type` with `trait`.
1300 let snip = snip.replacen("type", "trait", 1);
1301 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1303 err.span_help(span, msg);
1311 Res::Def(kind @ (DefKind::Mod | DefKind::Trait), _),
1312 PathSource::Expr(Some(parent)),
1314 if !path_sep(err, &parent, kind) {
1319 Res::Def(DefKind::Enum, def_id),
1320 PathSource::TupleStruct(..) | PathSource::Expr(..),
1323 .diagnostic_metadata
1324 .current_type_ascription
1330 .type_ascription_path_suggestions
1336 err.downgrade_to_delayed_bug();
1337 // We already suggested changing `:` into `::` during parsing.
1341 self.suggest_using_enum_variant(err, source, def_id, span);
1343 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1344 let (ctor_def, ctor_vis, fields) =
1345 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1346 if let PathSource::Expr(Some(parent)) = source {
1347 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1348 bad_struct_syntax_suggestion(def_id);
1354 bad_struct_syntax_suggestion(def_id);
1358 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1359 if !is_expected(ctor_def) || is_accessible {
1363 let field_spans = match source {
1364 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1365 PathSource::TupleStruct(_, pattern_spans) => {
1366 err.set_primary_message(
1367 "cannot match against a tuple struct which contains private fields",
1370 // Use spans of the tuple struct pattern.
1371 Some(Vec::from(pattern_spans))
1373 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1374 _ if source.is_call() => {
1375 err.set_primary_message(
1376 "cannot initialize a tuple struct which contains private fields",
1379 // Use spans of the tuple struct definition.
1383 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1388 if let Some(spans) =
1389 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1391 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1392 .filter(|(vis, _)| {
1393 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1395 .map(|(_, span)| *span)
1398 if non_visible_spans.len() > 0 {
1399 let mut m: MultiSpan = non_visible_spans.clone().into();
1402 .for_each(|s| m.push_span_label(s, "private field"));
1403 err.span_note(m, "constructor is not visible here due to private fields");
1409 err.span_label(span, "constructor is not visible here due to private fields");
1413 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1417 ) if ns == ValueNS => {
1418 bad_struct_syntax_suggestion(def_id);
1420 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1422 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1423 let span = find_span(&source, err);
1424 if let Some(span) = self.def_span(def_id) {
1425 err.span_label(span, &format!("`{}` defined here", path_str));
1427 err.span_suggestion(
1429 "use this syntax instead",
1431 Applicability::MaybeIncorrect,
1437 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1438 if let Some(span) = self.def_span(def_id) {
1439 err.span_label(span, &format!("`{}` defined here", path_str));
1441 let fields = self.r.field_names.get(&def_id).map_or_else(
1442 || "/* fields */".to_string(),
1443 |fields| vec!["_"; fields.len()].join(", "),
1445 err.span_suggestion(
1447 "use the tuple variant pattern syntax instead",
1448 format!("{}({})", path_str, fields),
1449 Applicability::HasPlaceholders,
1452 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
1453 err.span_label(span, fallback_label);
1454 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1456 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1457 err.note("can't use a type alias as a constructor");
1464 /// Given the target `ident` and `kind`, search for the similarly named associated item
1465 /// in `self.current_trait_ref`.
1466 pub(crate) fn find_similarly_named_assoc_item(
1469 kind: &AssocItemKind,
1470 ) -> Option<Symbol> {
1471 let (module, _) = self.current_trait_ref.as_ref()?;
1472 if ident == kw::Underscore {
1473 // We do nothing for `_`.
1477 let resolutions = self.r.resolutions(module);
1478 let targets = resolutions
1481 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1482 .filter(|(_, res)| match (kind, res) {
1483 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1484 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1485 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1488 .map(|(key, _)| key.ident.name)
1489 .collect::<Vec<_>>();
1491 find_best_match_for_name(&targets, ident, None)
1494 fn lookup_assoc_candidate<FilterFn>(
1498 filter_fn: FilterFn,
1499 ) -> Option<AssocSuggestion>
1501 FilterFn: Fn(Res) -> bool,
1503 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1505 TyKind::Path(None, _) => Some(t.id),
1506 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1507 // This doesn't handle the remaining `Ty` variants as they are not
1508 // that commonly the self_type, it might be interesting to provide
1509 // support for those in future.
1514 // Fields are generally expected in the same contexts as locals.
1515 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1516 if let Some(node_id) =
1517 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1519 // Look for a field with the same name in the current self_type.
1520 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1521 match resolution.base_res() {
1522 Res::Def(DefKind::Struct | DefKind::Union, did)
1523 if resolution.unresolved_segments() == 0 =>
1525 if let Some(field_names) = self.r.field_names.get(&did) {
1528 .any(|&field_name| ident.name == field_name.node)
1530 return Some(AssocSuggestion::Field);
1540 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1541 for assoc_item in items {
1542 if assoc_item.ident == ident {
1543 return Some(match &assoc_item.kind {
1544 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1545 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1546 AssocSuggestion::MethodWithSelf
1548 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1549 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1550 ast::AssocItemKind::MacCall(_) => continue,
1556 // Look for associated items in the current trait.
1557 if let Some((module, _)) = self.current_trait_ref {
1558 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1559 ModuleOrUniformRoot::Module(module),
1564 let res = binding.res();
1566 if self.r.has_self.contains(&res.def_id()) {
1567 return Some(AssocSuggestion::MethodWithSelf);
1570 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1571 Res::Def(DefKind::AssocConst, _) => {
1572 return Some(AssocSuggestion::AssocConst);
1574 Res::Def(DefKind::AssocTy, _) => {
1575 return Some(AssocSuggestion::AssocType);
1587 fn lookup_typo_candidate(
1591 filter_fn: &impl Fn(Res) -> bool,
1592 ) -> Option<TypoSuggestion> {
1593 let mut names = Vec::new();
1594 if path.len() == 1 {
1595 // Search in lexical scope.
1596 // Walk backwards up the ribs in scope and collect candidates.
1597 for rib in self.ribs[ns].iter().rev() {
1598 // Locals and type parameters
1599 for (ident, &res) in &rib.bindings {
1601 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1605 if let RibKind::ModuleRibKind(module) = rib.kind {
1606 // Items from this module
1607 self.r.add_module_candidates(module, &mut names, &filter_fn);
1609 if let ModuleKind::Block = module.kind {
1610 // We can see through blocks
1612 // Items from the prelude
1613 if !module.no_implicit_prelude {
1614 let extern_prelude = self.r.extern_prelude.clone();
1615 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1616 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1619 Res::Def(DefKind::Mod, crate_id.as_def_id());
1621 if filter_fn(crate_mod) {
1622 Some(TypoSuggestion::typo_from_res(
1623 ident.name, crate_mod,
1632 if let Some(prelude) = self.r.prelude {
1633 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1640 // Add primitive types to the mix
1641 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1642 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1643 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1647 // Search in module.
1648 let mod_path = &path[..path.len() - 1];
1649 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1650 self.resolve_path(mod_path, Some(TypeNS), None)
1652 self.r.add_module_candidates(module, &mut names, &filter_fn);
1656 let name = path[path.len() - 1].ident.name;
1657 // Make sure error reporting is deterministic.
1658 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1660 match find_best_match_for_name(
1661 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1665 Some(found) if found != name => {
1666 names.into_iter().find(|suggestion| suggestion.candidate == found)
1672 // Returns the name of the Rust type approximately corresponding to
1673 // a type name in another programming language.
1674 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1675 let name = path[path.len() - 1].ident.as_str();
1676 // Common Java types
1678 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1679 "short" => sym::i16,
1680 "Bool" => sym::bool,
1681 "Boolean" => sym::bool,
1682 "boolean" => sym::bool,
1685 "float" => sym::f32,
1686 "double" => sym::f64,
1691 /// Only used in a specific case of type ascription suggestions
1692 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1693 let sm = self.r.session.source_map();
1694 start.to(sm.next_point(start))
1697 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1698 let sm = self.r.session.source_map();
1699 let base_snippet = sm.span_to_snippet(base_span);
1700 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1701 if let Ok(snippet) = sm.span_to_snippet(sp) {
1702 let len = snippet.trim_end().len() as u32;
1703 if snippet.trim() == ":" {
1705 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1706 let mut show_label = true;
1707 if sm.is_multiline(sp) {
1708 err.span_suggestion_short(
1710 "maybe you meant to write `;` here",
1712 Applicability::MaybeIncorrect,
1715 let after_colon_sp =
1716 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1717 if snippet.len() == 1 {
1719 err.span_suggestion(
1721 "maybe you meant to write a path separator here",
1723 Applicability::MaybeIncorrect,
1730 .type_ascription_path_suggestions
1734 err.downgrade_to_delayed_bug();
1737 if let Ok(base_snippet) = base_snippet {
1738 let mut sp = after_colon_sp;
1740 // Try to find an assignment
1741 sp = sm.next_point(sp);
1742 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1744 Ok(ref x) if x.as_str() == "=" => {
1745 err.span_suggestion(
1747 "maybe you meant to write an assignment here",
1748 format!("let {}", base_snippet),
1749 Applicability::MaybeIncorrect,
1754 Ok(ref x) if x.as_str() == "\n" => break,
1764 "expecting a type here because of type ascription",
1774 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1775 let mut result = None;
1776 let mut seen_modules = FxHashSet::default();
1777 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1779 while let Some((in_module, path_segments)) = worklist.pop() {
1780 // abort if the module is already found
1781 if result.is_some() {
1785 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1786 // abort if the module is already found or if name_binding is private external
1787 if result.is_some() || !name_binding.vis.is_visible_locally() {
1790 if let Some(module) = name_binding.module() {
1792 let mut path_segments = path_segments.clone();
1793 path_segments.push(ast::PathSegment::from_ident(ident));
1794 let module_def_id = module.def_id();
1795 if module_def_id == def_id {
1797 Path { span: name_binding.span, segments: path_segments, tokens: None };
1809 // add the module to the lookup
1810 if seen_modules.insert(module_def_id) {
1811 worklist.push((module, path_segments));
1821 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1822 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1823 let mut variants = Vec::new();
1824 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1825 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1826 let mut segms = enum_import_suggestion.path.segments.clone();
1827 segms.push(ast::PathSegment::from_ident(ident));
1828 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1829 variants.push((path, def_id, kind));
1836 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1837 fn suggest_using_enum_variant(
1839 err: &mut Diagnostic,
1840 source: PathSource<'_>,
1844 let Some(variants) = self.collect_enum_ctors(def_id) else {
1845 err.note("you might have meant to use one of the enum's variants");
1849 let suggest_only_tuple_variants =
1850 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1851 if suggest_only_tuple_variants {
1852 // Suggest only tuple variants regardless of whether they have fields and do not
1853 // suggest path with added parentheses.
1854 let suggestable_variants = variants
1856 .filter(|(.., kind)| *kind == CtorKind::Fn)
1857 .map(|(variant, ..)| path_names_to_string(variant))
1858 .collect::<Vec<_>>();
1860 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1862 let source_msg = if source.is_call() {
1864 } else if matches!(source, PathSource::TupleStruct(..)) {
1870 if !suggestable_variants.is_empty() {
1871 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1872 format!("try {} the enum's variant", source_msg)
1874 format!("try {} one of the enum's variants", source_msg)
1877 err.span_suggestions(
1880 suggestable_variants.into_iter(),
1881 Applicability::MaybeIncorrect,
1885 // If the enum has no tuple variants..
1886 if non_suggestable_variant_count == variants.len() {
1887 err.help(&format!("the enum has no tuple variants {}", source_msg));
1890 // If there are also non-tuple variants..
1891 if non_suggestable_variant_count == 1 {
1893 "you might have meant {} the enum's non-tuple variant",
1896 } else if non_suggestable_variant_count >= 1 {
1898 "you might have meant {} one of the enum's non-tuple variants",
1903 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1904 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1906 CtorKind::Const => false,
1907 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1912 let suggestable_variants = variants
1914 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1915 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1916 .map(|(variant, kind)| match kind {
1917 CtorKind::Const => variant,
1918 CtorKind::Fn => format!("({}())", variant),
1919 CtorKind::Fictive => format!("({} {{}})", variant),
1921 .collect::<Vec<_>>();
1922 let no_suggestable_variant = suggestable_variants.is_empty();
1924 if !no_suggestable_variant {
1925 let msg = if suggestable_variants.len() == 1 {
1926 "you might have meant to use the following enum variant"
1928 "you might have meant to use one of the following enum variants"
1931 err.span_suggestions(
1934 suggestable_variants.into_iter(),
1935 Applicability::MaybeIncorrect,
1939 let suggestable_variants_with_placeholders = variants
1941 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1942 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1943 .filter_map(|(variant, kind)| match kind {
1944 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1945 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1948 .collect::<Vec<_>>();
1950 if !suggestable_variants_with_placeholders.is_empty() {
1952 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
1953 (true, 1) => "the following enum variant is available",
1954 (true, _) => "the following enum variants are available",
1955 (false, 1) => "alternatively, the following enum variant is available",
1957 "alternatively, the following enum variants are also available"
1961 err.span_suggestions(
1964 suggestable_variants_with_placeholders.into_iter(),
1965 Applicability::HasPlaceholders,
1970 if def_id.is_local() {
1971 if let Some(span) = self.def_span(def_id) {
1972 err.span_note(span, "the enum is defined here");
1977 pub(crate) fn report_missing_type_error(
1980 ) -> Option<(Span, &'static str, String, Applicability)> {
1981 let (ident, span) = match path {
1982 [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
1983 (segment.ident.to_string(), segment.ident.span)
1987 let mut iter = ident.chars().map(|c| c.is_uppercase());
1988 let single_uppercase_char =
1989 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1990 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1993 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1994 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1995 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
2000 kind @ ItemKind::Fn(..)
2001 | kind @ ItemKind::Enum(..)
2002 | kind @ ItemKind::Struct(..)
2003 | kind @ ItemKind::Union(..),
2008 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
2009 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
2010 | (Some(Item { kind, .. }), false, _) => {
2011 // Likely missing type parameter.
2012 if let Some(generics) = kind.generics() {
2013 if span.overlaps(generics.span) {
2014 // Avoid the following:
2015 // error[E0405]: cannot find trait `A` in this scope
2016 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
2018 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
2019 // | ^- help: you might be missing a type parameter: `, A`
2021 // | not found in this scope
2024 let msg = "you might be missing a type parameter";
2025 let (span, sugg) = if let [.., param] = &generics.params[..] {
2026 let span = if let [.., bound] = ¶m.bounds[..] {
2028 } else if let GenericParam {
2029 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
2031 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
2035 (span, format!(", {}", ident))
2037 (generics.span, format!("<{}>", ident))
2039 // Do not suggest if this is coming from macro expansion.
2040 if span.can_be_used_for_suggestions() {
2042 span.shrink_to_hi(),
2045 Applicability::MaybeIncorrect,
2055 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
2056 /// optionally returning the closest match and whether it is reachable.
2057 pub(crate) fn suggestion_for_label_in_rib(
2061 ) -> Option<LabelSuggestion> {
2062 // Are ribs from this `rib_index` within scope?
2063 let within_scope = self.is_label_valid_from_rib(rib_index);
2065 let rib = &self.label_ribs[rib_index];
2069 .filter(|(id, _)| id.span.eq_ctxt(label.span))
2070 .map(|(id, _)| id.name)
2071 .collect::<Vec<Symbol>>();
2073 find_best_match_for_name(&names, label.name, None).map(|symbol| {
2074 // Upon finding a similar name, get the ident that it was from - the span
2075 // contained within helps make a useful diagnostic. In addition, determine
2076 // whether this candidate is within scope.
2077 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
2078 (*ident, within_scope)
2082 pub(crate) fn maybe_report_lifetime_uses(
2084 generics_span: Span,
2085 params: &[ast::GenericParam],
2087 for (param_index, param) in params.iter().enumerate() {
2088 let GenericParamKind::Lifetime = param.kind else { continue };
2090 let def_id = self.r.local_def_id(param.id);
2092 let use_set = self.lifetime_uses.remove(&def_id);
2094 "Use set for {:?}({:?} at {:?}) is {:?}",
2095 def_id, param.ident, param.ident.span, use_set
2098 let deletion_span = || {
2099 if params.len() == 1 {
2100 // if sole lifetime, remove the entire `<>` brackets
2102 } else if param_index == 0 {
2103 // if removing within `<>` brackets, we also want to
2104 // delete a leading or trailing comma as appropriate
2105 param.span().to(params[param_index + 1].span().shrink_to_lo())
2107 // if removing within `<>` brackets, we also want to
2108 // delete a leading or trailing comma as appropriate
2109 params[param_index - 1].span().shrink_to_hi().to(param.span())
2113 Some(LifetimeUseSet::Many) => {}
2114 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
2115 debug!(?param.ident, ?param.ident.span, ?use_span);
2117 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
2119 let deletion_span = deletion_span();
2120 self.r.lint_buffer.buffer_lint_with_diagnostic(
2121 lint::builtin::SINGLE_USE_LIFETIMES,
2124 &format!("lifetime parameter `{}` only used once", param.ident),
2125 lint::BuiltinLintDiagnostics::SingleUseLifetime {
2126 param_span: param.ident.span,
2127 use_span: Some((use_span, elidable)),
2133 debug!(?param.ident, ?param.ident.span);
2135 let deletion_span = deletion_span();
2136 self.r.lint_buffer.buffer_lint_with_diagnostic(
2137 lint::builtin::UNUSED_LIFETIMES,
2140 &format!("lifetime parameter `{}` never used", param.ident),
2141 lint::BuiltinLintDiagnostics::SingleUseLifetime {
2142 param_span: param.ident.span,
2152 pub(crate) fn emit_undeclared_lifetime_error(
2154 lifetime_ref: &ast::Lifetime,
2155 outer_lifetime_ref: Option<Ident>,
2157 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
2158 let mut err = if let Some(outer) = outer_lifetime_ref {
2159 let mut err = struct_span_err!(
2161 lifetime_ref.ident.span,
2163 "can't use generic parameters from outer item",
2165 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
2166 err.span_label(outer.span, "lifetime parameter from outer item");
2169 let mut err = struct_span_err!(
2171 lifetime_ref.ident.span,
2173 "use of undeclared lifetime name `{}`",
2176 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
2179 self.suggest_introducing_lifetime(
2181 Some(lifetime_ref.ident.name.as_str()),
2182 |err, _, span, message, suggestion| {
2183 err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect);
2190 fn suggest_introducing_lifetime(
2192 err: &mut Diagnostic,
2194 suggest: impl Fn(&mut Diagnostic, bool, Span, &str, String) -> bool,
2196 let mut suggest_note = true;
2197 for rib in self.lifetime_ribs.iter().rev() {
2198 let mut should_continue = true;
2200 LifetimeRibKind::Generics { binder: _, span, kind } => {
2201 if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name {
2202 suggest_note = false; // Avoid displaying the same help multiple times.
2206 "lifetime `{}` is missing in item created through this procedural macro",
2213 let higher_ranked = matches!(
2215 LifetimeBinderKind::BareFnType
2216 | LifetimeBinderKind::PolyTrait
2217 | LifetimeBinderKind::WhereBound
2219 let (span, sugg) = if span.is_empty() {
2222 if higher_ranked { "for" } else { "" },
2223 name.unwrap_or("'a"),
2224 if higher_ranked { " " } else { "" },
2229 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
2230 let sugg = format!("{}, ", name.unwrap_or("'a"));
2234 let message = format!(
2235 "consider making the {} lifetime-generic with a new `{}` lifetime",
2237 name.unwrap_or("'a"),
2239 should_continue = suggest(err, true, span, &message, sugg);
2241 "for more information on higher-ranked polymorphism, visit \
2242 https://doc.rust-lang.org/nomicon/hrtb.html",
2244 } else if let Some(name) = name {
2245 let message = format!("consider introducing lifetime `{}` here", name);
2246 should_continue = suggest(err, false, span, &message, sugg);
2248 let message = format!("consider introducing a named lifetime parameter");
2249 should_continue = suggest(err, false, span, &message, sugg);
2252 LifetimeRibKind::Item => break,
2255 if !should_continue {
2261 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2264 lifetime_ref.ident.span,
2266 "use of non-static lifetime `{}` in const generic",
2270 "for more information, see issue #74052 \
2271 <https://github.com/rust-lang/rust/issues/74052>",
2276 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2277 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2278 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2279 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2281 lifetime_ref: &ast::Lifetime,
2283 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2284 if !feature_active {
2286 &self.r.session.parse_sess,
2287 sym::generic_const_exprs,
2288 lifetime_ref.ident.span,
2289 "a non-static lifetime is not allowed in a `const`",
2295 pub(crate) fn report_missing_lifetime_specifiers(
2297 lifetime_refs: Vec<MissingLifetime>,
2298 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2299 ) -> ErrorGuaranteed {
2300 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
2301 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
2303 let mut err = struct_span_err!(
2307 "missing lifetime specifier{}",
2308 pluralize!(num_lifetimes)
2310 self.add_missing_lifetime_specifiers_label(
2313 function_param_lifetimes,
2318 fn add_missing_lifetime_specifiers_label(
2320 err: &mut Diagnostic,
2321 lifetime_refs: Vec<MissingLifetime>,
2322 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
2324 for < in &lifetime_refs {
2328 "expected {} lifetime parameter{}",
2329 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
2330 pluralize!(lt.count),
2335 let mut in_scope_lifetimes: Vec<_> = self
2339 .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item))
2340 .flat_map(|rib| rib.bindings.iter())
2341 .map(|(&ident, &res)| (ident, res))
2342 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
2344 debug!(?in_scope_lifetimes);
2346 debug!(?function_param_lifetimes);
2347 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
2348 let elided_len = param_lifetimes.len();
2349 let num_params = params.len();
2351 let mut m = String::new();
2353 for (i, info) in params.iter().enumerate() {
2354 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
2355 debug_assert_ne!(lifetime_count, 0);
2357 err.span_label(span, "");
2360 if i + 1 < num_params {
2362 } else if num_params == 2 {
2365 m.push_str(", or ");
2369 let help_name = if let Some(ident) = ident {
2370 format!("`{}`", ident)
2372 format!("argument {}", index + 1)
2375 if lifetime_count == 1 {
2376 m.push_str(&help_name[..])
2378 m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..])
2382 if num_params == 0 {
2384 "this function's return type contains a borrowed value, \
2385 but there is no value for it to be borrowed from",
2387 if in_scope_lifetimes.is_empty() {
2388 in_scope_lifetimes = vec![(
2389 Ident::with_dummy_span(kw::StaticLifetime),
2390 (DUMMY_NODE_ID, LifetimeRes::Static),
2393 } else if elided_len == 0 {
2395 "this function's return type contains a borrowed value with \
2396 an elided lifetime, but the lifetime cannot be derived from \
2399 if in_scope_lifetimes.is_empty() {
2400 in_scope_lifetimes = vec![(
2401 Ident::with_dummy_span(kw::StaticLifetime),
2402 (DUMMY_NODE_ID, LifetimeRes::Static),
2405 } else if num_params == 1 {
2407 "this function's return type contains a borrowed value, \
2408 but the signature does not say which {} it is borrowed from",
2413 "this function's return type contains a borrowed value, \
2414 but the signature does not say whether it is borrowed from {}",
2420 let existing_name = match &in_scope_lifetimes[..] {
2421 [] => Symbol::intern("'a"),
2422 [(existing, _)] => existing.name,
2423 _ => Symbol::intern("'lifetime"),
2426 let mut spans_suggs: Vec<_> = Vec::new();
2427 let build_sugg = |lt: MissingLifetime| match lt.kind {
2428 MissingLifetimeKind::Underscore => {
2429 debug_assert_eq!(lt.count, 1);
2430 (lt.span, existing_name.to_string())
2432 MissingLifetimeKind::Ampersand => {
2433 debug_assert_eq!(lt.count, 1);
2434 (lt.span.shrink_to_hi(), format!("{} ", existing_name))
2436 MissingLifetimeKind::Comma => {
2437 let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
2441 (lt.span.shrink_to_hi(), sugg)
2443 MissingLifetimeKind::Brackets => {
2444 let sugg: String = std::iter::once("<")
2446 std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
2450 (lt.span.shrink_to_hi(), sugg)
2453 for < in &lifetime_refs {
2454 spans_suggs.push(build_sugg(lt));
2456 debug!(?spans_suggs);
2457 match in_scope_lifetimes.len() {
2459 if let Some((param_lifetimes, _)) = function_param_lifetimes {
2460 for lt in param_lifetimes {
2461 spans_suggs.push(build_sugg(lt))
2464 self.suggest_introducing_lifetime(
2467 |err, higher_ranked, span, message, intro_sugg| {
2468 err.multipart_suggestion_verbose(
2470 std::iter::once((span, intro_sugg))
2471 .chain(spans_suggs.iter().cloned())
2473 Applicability::MaybeIncorrect,
2480 err.multipart_suggestion_verbose(
2481 &format!("consider using the `{}` lifetime", existing_name),
2483 Applicability::MaybeIncorrect,
2486 // Record as using the suggested resolution.
2487 let (_, (_, res)) = in_scope_lifetimes[0];
2488 for < in &lifetime_refs {
2489 self.r.lifetimes_res_map.insert(lt.id, res);
2493 let lifetime_spans: Vec<_> =
2494 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
2495 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2497 if spans_suggs.len() > 0 {
2498 // This happens when we have `Foo<T>` where we point at the space before `T`,
2499 // but this can be confusing so we give a suggestion with placeholders.
2500 err.multipart_suggestion_verbose(
2501 "consider using one of the available lifetimes here",
2503 Applicability::HasPlaceholders,
2511 /// Report lifetime/lifetime shadowing as an error.
2512 pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2513 let mut err = struct_span_err!(
2517 "lifetime name `{}` shadows a lifetime name that is already in scope",
2520 err.span_label(orig.span, "first declared here");
2521 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2525 /// Shadowing involving a label is only a warning for historical reasons.
2526 //FIXME: make this a proper lint.
2527 pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
2528 let name = shadower.name;
2529 let shadower = shadower.span;
2530 let mut err = sess.struct_span_warn(
2532 &format!("label name `{}` shadows a label name that is already in scope", name),
2534 err.span_label(orig, "first declared here");
2535 err.span_label(shadower, format!("label `{}` already in scope", name));