1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
4 use crate::late::{LifetimeBinderKind, LifetimeRibKind, LifetimeUseSet};
5 use crate::path_names_to_string;
6 use crate::{Module, ModuleKind, ModuleOrUniformRoot};
7 use crate::{PathResult, PathSource, Segment};
9 use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt};
11 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
12 NodeId, Path, Ty, TyKind,
14 use rustc_ast_lowering::ResolverAstLowering;
15 use rustc_ast_pretty::pprust::path_segment_to_string;
16 use rustc_data_structures::fx::FxHashSet;
18 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
22 use rustc_hir::def::Namespace::{self, *};
23 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
24 use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
25 use rustc_hir::PrimTy;
26 use rustc_session::lint;
27 use rustc_session::parse::feature_err;
28 use rustc_span::edition::Edition;
29 use rustc_span::hygiene::MacroKind;
30 use rustc_span::lev_distance::find_best_match_for_name;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{BytePos, Span, DUMMY_SP};
39 type Res = def::Res<ast::NodeId>;
41 /// A field or associated item from self type suggested in case of resolution failure.
42 enum AssocSuggestion {
50 impl AssocSuggestion {
51 fn action(&self) -> &'static str {
53 AssocSuggestion::Field => "use the available field",
54 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
55 AssocSuggestion::AssocFn => "call the associated function",
56 AssocSuggestion::AssocConst => "use the associated `const`",
57 AssocSuggestion::AssocType => "use the associated type",
62 pub(crate) enum MissingLifetimeSpot<'tcx> {
63 Generics(&'tcx hir::Generics<'tcx>),
64 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
68 pub(crate) enum ForLifetimeSpanType {
75 impl ForLifetimeSpanType {
76 pub(crate) fn descr(&self) -> &'static str {
78 Self::BoundEmpty | Self::BoundTail => "bound",
79 Self::TypeEmpty | Self::TypeTail => "type",
83 pub(crate) fn suggestion(&self, sugg: &str) -> String {
85 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
86 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
91 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &&'tcx hir::Generics<'tcx> {
92 fn into(self) -> MissingLifetimeSpot<'tcx> {
93 MissingLifetimeSpot::Generics(self)
97 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
98 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
101 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
102 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
105 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
106 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
107 let variant_path = &suggestion.path;
108 let variant_path_string = path_names_to_string(variant_path);
110 let path_len = suggestion.path.segments.len();
111 let enum_path = ast::Path {
112 span: suggestion.path.span,
113 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
116 let enum_path_string = path_names_to_string(&enum_path);
118 (variant_path_string, enum_path_string)
121 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
122 fn def_span(&self, def_id: DefId) -> Option<Span> {
124 LOCAL_CRATE => self.r.opt_span(def_id),
129 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
134 /// Handles error reporting for `smart_resolve_path_fragment` function.
135 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
136 pub(crate) fn smart_resolve_report_errors(
140 source: PathSource<'_>,
142 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
143 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
144 let ns = source.namespace();
145 let is_expected = &|res| source.is_expected(res);
146 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
148 // Make the base error.
149 struct BaseError<'a> {
151 fallback_label: String,
154 suggestion: Option<(Span, &'a str, String)>,
156 let mut expected = source.descr_expected();
157 let path_str = Segment::names_to_string(path);
158 let item_str = path.last().unwrap().ident;
159 let base_error = if let Some(res) = res {
161 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
162 fallback_label: format!("not a {expected}"),
164 could_be_expr: match res {
165 Res::Def(DefKind::Fn, _) => {
166 // Verify whether this is a fn call or an Fn used as a type.
170 .span_to_snippet(span)
171 .map(|snippet| snippet.ends_with(')'))
175 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
180 | Res::Local(_) => true,
186 let item_span = path.last().unwrap().ident.span;
187 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
188 debug!(?self.diagnostic_metadata.current_impl_items);
189 debug!(?self.diagnostic_metadata.current_function);
190 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
191 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
192 && self.current_trait_ref.is_none()
193 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
194 && let Some(item) = items.iter().find(|i| {
195 if let AssocItemKind::Fn(fn_) = &i.kind
196 && !fn_.sig.decl.has_self()
197 && i.ident.name == item_str.name
199 debug!(?item_str.name);
200 debug!(?fn_.sig.decl.inputs);
208 "consider using the associated function",
209 format!("Self::{}", item.ident)
214 (String::new(), "this scope".to_string(), suggestion)
215 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
216 if self.r.session.edition() > Edition::Edition2015 {
217 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
218 // which overrides all other expectations of item type
220 (String::new(), "the list of imported crates".to_string(), None)
222 (String::new(), "the crate root".to_string(), None)
224 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
225 (String::new(), "the crate root".to_string(), None)
227 let mod_path = &path[..path.len() - 1];
228 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
229 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
232 .map_or_else(String::new, |res| format!("{} ", res.descr()));
233 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
236 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
237 fallback_label: if path_str == "async" && expected.starts_with("struct") {
238 "`async` blocks are only allowed in Rust 2018 or later".to_string()
240 format!("not found in {mod_str}")
243 could_be_expr: false,
248 let code = source.error_code(res.is_some());
250 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
252 if let Some(sugg) = base_error.suggestion {
253 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
256 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
257 err.multipart_suggestion(
258 "you might have meant to write a `struct` literal",
260 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
261 (span.shrink_to_hi(), "}".to_string()),
263 Applicability::HasPlaceholders,
266 match (source, self.diagnostic_metadata.in_if_condition) {
267 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
268 err.span_suggestion_verbose(
270 "you might have meant to use pattern matching",
272 Applicability::MaybeIncorrect,
278 let is_assoc_fn = self.self_type_is_available();
279 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
280 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
281 err.span_suggestion_short(
283 "you might have meant to use `self` here instead",
285 Applicability::MaybeIncorrect,
287 if !self.self_value_is_available(path[0].ident.span) {
288 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
289 &self.diagnostic_metadata.current_function
291 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
292 (param.span.shrink_to_lo(), "&self, ")
298 .span_through_char(*fn_span, '(')
303 err.span_suggestion_verbose(
305 "if you meant to use `self`, you are also missing a `self` receiver \
308 Applicability::MaybeIncorrect,
314 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
316 // Emit special messages for unresolved `Self` and `self`.
317 if is_self_type(path, ns) {
318 err.code(rustc_errors::error_code!(E0411));
321 "`Self` is only available in impls, traits, and type definitions".to_string(),
323 return (err, Vec::new());
325 if is_self_value(path, ns) {
326 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
328 err.code(rustc_errors::error_code!(E0424));
329 err.span_label(span, match source {
330 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
332 _ => "`self` value is a keyword only available in methods with a `self` parameter"
335 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
336 // The current function has a `self' parameter, but we were unable to resolve
337 // a reference to `self`. This can only happen if the `self` identifier we
338 // are resolving came from a different hygiene context.
339 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
340 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
342 let doesnt = if is_assoc_fn {
343 let (span, sugg) = fn_kind
347 .map(|p| (p.span.shrink_to_lo(), "&self, "))
349 // Try to look for the "(" after the function name, if possible.
350 // This avoids placing the suggestion into the visibility specifier.
353 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
358 .span_through_char(span, '(')
363 err.span_suggestion_verbose(
365 "add a `self` receiver parameter to make the associated `fn` a method",
367 Applicability::MaybeIncorrect,
373 if let Some(ident) = fn_kind.ident() {
376 &format!("this function {} have a `self` parameter", doesnt),
381 return (err, Vec::new());
384 // Try to lookup name in more relaxed fashion for better error reporting.
385 let ident = path.last().unwrap().ident;
386 let candidates = self
388 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
390 .filter(|ImportSuggestion { did, .. }| {
391 match (did, res.and_then(|res| res.opt_def_id())) {
392 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
396 .collect::<Vec<_>>();
397 let crate_def_id = CRATE_DEF_ID.to_def_id();
398 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
399 let mut enum_candidates: Vec<_> = self
401 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
403 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
404 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
406 if !enum_candidates.is_empty() {
407 if let (PathSource::Type, Some(span)) =
408 (source, self.diagnostic_metadata.current_type_ascription.last())
414 .type_ascription_path_suggestions
418 // Already reported this issue on the lhs of the type ascription.
420 return (err, candidates);
424 enum_candidates.sort();
426 // Contextualize for E0412 "cannot find type", but don't belabor the point
427 // (that it's a variant) for E0573 "expected type, found variant".
428 let preamble = if res.is_none() {
429 let others = match enum_candidates.len() {
431 2 => " and 1 other".to_owned(),
432 n => format!(" and {} others", n),
434 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
438 let msg = format!("{}try using the variant's enum", preamble);
440 err.span_suggestions(
443 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
444 Applicability::MachineApplicable,
448 if path.len() == 1 && self.self_type_is_available() {
449 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
450 let self_is_available = self.self_value_is_available(path[0].ident.span);
452 AssocSuggestion::Field => {
453 if self_is_available {
456 "you might have meant to use the available field",
457 format!("self.{}", path_str),
458 Applicability::MachineApplicable,
461 err.span_label(span, "a field by this name exists in `Self`");
464 AssocSuggestion::MethodWithSelf if self_is_available => {
467 "you might have meant to call the method",
468 format!("self.{}", path_str),
469 Applicability::MachineApplicable,
472 AssocSuggestion::MethodWithSelf
473 | AssocSuggestion::AssocFn
474 | AssocSuggestion::AssocConst
475 | AssocSuggestion::AssocType => {
478 &format!("you might have meant to {}", candidate.action()),
479 format!("Self::{}", path_str),
480 Applicability::MachineApplicable,
484 return (err, candidates);
487 // If the first argument in call is `self` suggest calling a method.
488 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
489 let mut args_snippet = String::new();
490 if let Some(args_span) = args_span {
491 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
492 args_snippet = snippet;
498 &format!("try calling `{}` as a method", ident),
499 format!("self.{}({})", path_str, args_snippet),
500 Applicability::MachineApplicable,
502 return (err, candidates);
506 // Try Levenshtein algorithm.
507 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
508 // Try context-dependent help if relaxed lookup didn't work.
509 if let Some(res) = res {
510 if self.smart_resolve_context_dependent_help(
516 &base_error.fallback_label,
518 // We do this to avoid losing a secondary span when we override the main error span.
519 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
520 return (err, candidates);
525 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
526 if !self.type_ascription_suggestion(&mut err, base_error.span) {
527 let mut fallback = false;
529 PathSource::Trait(AliasPossibility::Maybe),
530 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
532 ) = (source, res, is_macro)
534 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
536 let spans: Vec<Span> = bounds
538 .map(|bound| bound.span())
539 .filter(|&sp| sp != base_error.span)
542 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
543 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
544 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
545 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
546 let last_bound_span = spans.last().cloned().unwrap();
547 let mut multi_span: MultiSpan = spans.clone().into();
549 let msg = if sp == last_bound_span {
551 "...because of {these} bound{s}",
552 these = pluralize!("this", bounds.len() - 1),
553 s = pluralize!(bounds.len() - 1),
558 multi_span.push_span_label(sp, msg);
560 multi_span.push_span_label(
562 "expected this type to be a trait...".to_string(),
566 "`+` is used to constrain a \"trait object\" type with lifetimes or \
567 auto-traits; structs and enums can't be bound in that way",
569 if bounds.iter().all(|bound| match bound {
570 ast::GenericBound::Outlives(_) => true,
571 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
573 let mut sugg = vec![];
574 if base_error.span != start_span {
575 sugg.push((start_span.until(base_error.span), String::new()));
577 if base_error.span != end_span {
578 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
581 err.multipart_suggestion(
582 "if you meant to use a type and not a trait here, remove the bounds",
584 Applicability::MaybeIncorrect,
590 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
592 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
594 match self.diagnostic_metadata.current_let_binding {
595 Some((pat_sp, Some(ty_sp), None))
596 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
598 err.span_suggestion_short(
599 pat_sp.between(ty_sp),
600 "use `=` if you meant to assign",
602 Applicability::MaybeIncorrect,
608 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
609 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
610 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
614 err.span_label(base_error.span, base_error.fallback_label);
617 if let Some(err_code) = &err.code {
618 if err_code == &rustc_errors::error_code!(E0425) {
619 for label_rib in &self.label_ribs {
620 for (label_ident, node_id) in &label_rib.bindings {
621 if format!("'{}", ident) == label_ident.to_string() {
622 err.span_label(label_ident.span, "a label with a similar name exists");
623 if let PathSource::Expr(Some(Expr {
624 kind: ExprKind::Break(None, Some(_)),
630 "use the similarly named label",
631 label_ident.name.to_string(),
632 Applicability::MaybeIncorrect,
634 // Do not lint against unused label when we suggest them.
635 self.diagnostic_metadata.unused_labels.remove(node_id);
640 } else if err_code == &rustc_errors::error_code!(E0412) {
641 if let Some(correct) = Self::likely_rust_type(path) {
644 "perhaps you intended to use this type",
646 Applicability::MaybeIncorrect,
655 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
656 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
657 let TyKind::Path(_, path) = &ty.kind else { return; };
658 for segment in &path.segments {
659 let Some(params) = &segment.args else { continue; };
660 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
661 for param in ¶ms.args {
662 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
663 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
666 for bound in bounds {
667 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
672 if base_span == trait_ref.span {
673 err.span_suggestion_verbose(
674 constraint.ident.span.between(trait_ref.span),
675 "you might have meant to write a path instead of an associated type bound",
677 Applicability::MachineApplicable,
685 fn get_single_associated_item(
688 source: &PathSource<'_>,
689 filter_fn: &impl Fn(Res) -> bool,
690 ) -> Option<TypoSuggestion> {
691 if let crate::PathSource::TraitItem(_) = source {
692 let mod_path = &path[..path.len() - 1];
693 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
694 self.resolve_path(mod_path, None, None)
696 let resolutions = self.r.resolutions(module).borrow();
697 let targets: Vec<_> =
700 .filter_map(|(key, resolution)| {
701 resolution.borrow().binding.map(|binding| binding.res()).and_then(
702 |res| if filter_fn(res) { Some((key, res)) } else { None },
706 if targets.len() == 1 {
707 let target = targets[0];
708 return Some(TypoSuggestion::single_item_from_res(
718 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
719 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
720 // Detect that we are actually in a `where` predicate.
721 let (bounded_ty, bounds, where_span) =
722 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
724 bound_generic_params,
727 })) = self.diagnostic_metadata.current_where_predicate
729 if !bound_generic_params.is_empty() {
732 (bounded_ty, bounds, span)
737 // Confirm that the target is an associated type.
738 let (ty, position, path) = if let ast::TyKind::Path(
739 Some(ast::QSelf { ty, position, .. }),
743 // use this to verify that ident is a type param.
744 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
748 partial_res.base_res(),
749 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
750 ) && partial_res.unresolved_segments() == 0)
759 let peeled_ty = ty.peel_refs();
760 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
761 // Confirm that the `SelfTy` is a type parameter.
762 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
766 partial_res.base_res(),
767 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
768 ) && partial_res.unresolved_segments() == 0)
773 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
774 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
775 ) = (&type_param_path.segments[..], &bounds[..])
777 if let [ast::PathSegment { ident, args: None, .. }] =
778 &poly_trait_ref.trait_ref.path.segments[..]
780 if ident.span == span {
781 err.span_suggestion_verbose(
783 &format!("constrain the associated type to `{}`", ident),
789 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
790 .unwrap_or_else(|_| constrain_ident.to_string()),
791 path.segments[..*position]
793 .map(|segment| path_segment_to_string(segment))
796 path.segments[*position..]
798 .map(|segment| path_segment_to_string(segment))
803 Applicability::MaybeIncorrect,
813 /// Check if the source is call expression and the first argument is `self`. If true,
814 /// return the span of whole call and the span for all arguments expect the first one (`self`).
815 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
816 let mut has_self_arg = None;
817 if let PathSource::Expr(Some(parent)) = source {
819 ExprKind::Call(_, args) if !args.is_empty() => {
820 let mut expr_kind = &args[0].kind;
823 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
824 if arg_name.segments[0].ident.name == kw::SelfLower {
825 let call_span = parent.span;
826 let tail_args_span = if args.len() > 1 {
829 args.last().unwrap().span.hi(),
836 has_self_arg = Some((call_span, tail_args_span));
840 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
851 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
852 // HACK(estebank): find a better way to figure out that this was a
853 // parser issue where a struct literal is being used on an expression
854 // where a brace being opened means a block is being started. Look
855 // ahead for the next text to see if `span` is followed by a `{`.
856 let sm = self.r.session.source_map();
859 sp = sm.next_point(sp);
860 match sm.span_to_snippet(sp) {
862 if snippet.chars().any(|c| !c.is_whitespace()) {
869 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
870 // In case this could be a struct literal that needs to be surrounded
871 // by parentheses, find the appropriate span.
873 let mut closing_brace = None;
875 sp = sm.next_point(sp);
876 match sm.span_to_snippet(sp) {
879 closing_brace = Some(span.to(sp));
886 // The bigger the span, the more likely we're incorrect --
887 // bound it to 100 chars long.
892 (followed_by_brace, closing_brace)
895 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
897 /// Returns `true` if able to provide context-dependent help.
898 fn smart_resolve_context_dependent_help(
900 err: &mut Diagnostic,
902 source: PathSource<'_>,
905 fallback_label: &str,
907 let ns = source.namespace();
908 let is_expected = &|res| source.is_expected(res);
910 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
911 ExprKind::Field(_, ident) => {
914 "use the path separator to refer to an item",
915 format!("{}::{}", path_str, ident),
916 Applicability::MaybeIncorrect,
920 ExprKind::MethodCall(ref segment, ..) => {
921 let span = expr.span.with_hi(segment.ident.span.hi());
924 "use the path separator to refer to an item",
925 format!("{}::{}", path_str, segment.ident),
926 Applicability::MaybeIncorrect,
933 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
935 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
936 | PathSource::TupleStruct(span, _) => {
937 // We want the main underline to cover the suggested code as well for
946 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
947 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
950 PathSource::Expr(Some(
951 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
952 )) if path_sep(err, &parent) => {}
958 | ExprKind::Binary(..)
959 | ExprKind::Unary(..)
961 | ExprKind::While(..)
962 | ExprKind::ForLoop(..)
963 | ExprKind::Match(..),
966 ) if followed_by_brace => {
967 if let Some(sp) = closing_brace {
968 err.span_label(span, fallback_label);
969 err.multipart_suggestion(
970 "surround the struct literal with parentheses",
972 (sp.shrink_to_lo(), "(".to_string()),
973 (sp.shrink_to_hi(), ")".to_string()),
975 Applicability::MaybeIncorrect,
979 span, // Note the parentheses surrounding the suggestion below
981 "you might want to surround a struct literal with parentheses: \
982 `({} {{ /* fields */ }})`?",
988 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
989 let span = find_span(&source, err);
990 if let Some(span) = self.def_span(def_id) {
991 err.span_label(span, &format!("`{}` defined here", path_str));
993 let (tail, descr, applicability) = match source {
994 PathSource::Pat | PathSource::TupleStruct(..) => {
995 ("", "pattern", Applicability::MachineApplicable)
997 _ => (": val", "literal", Applicability::HasPlaceholders),
999 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1003 .map(|f| format!("{}{}", f.node, tail))
1004 .collect::<Vec<String>>()
1008 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1010 let pad = match self.r.field_names.get(&def_id) {
1011 Some(fields) if fields.is_empty() => "",
1014 err.span_suggestion(
1016 &format!("use struct {} syntax instead", descr),
1017 format!("{path_str} {{{pad}{fields}{pad}}}"),
1022 err.span_label(span, fallback_label);
1027 match (res, source) {
1029 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1030 PathSource::Expr(Some(Expr {
1031 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1033 | PathSource::Struct,
1035 err.span_label(span, fallback_label);
1036 err.span_suggestion_verbose(
1037 span.shrink_to_hi(),
1038 "use `!` to invoke the macro",
1040 Applicability::MaybeIncorrect,
1042 if path_str == "try" && span.rust_2015() {
1043 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1046 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1047 err.span_label(span, fallback_label);
1049 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1050 err.span_label(span, "type aliases cannot be used as traits");
1051 if self.r.session.is_nightly_build() {
1052 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1054 if let Some(span) = self.def_span(def_id) {
1055 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1056 // The span contains a type alias so we should be able to
1057 // replace `type` with `trait`.
1058 let snip = snip.replacen("type", "trait", 1);
1059 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1061 err.span_help(span, msg);
1068 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1069 if !path_sep(err, &parent) {
1074 Res::Def(DefKind::Enum, def_id),
1075 PathSource::TupleStruct(..) | PathSource::Expr(..),
1078 .diagnostic_metadata
1079 .current_type_ascription
1085 .type_ascription_path_suggestions
1091 err.downgrade_to_delayed_bug();
1092 // We already suggested changing `:` into `::` during parsing.
1096 self.suggest_using_enum_variant(err, source, def_id, span);
1098 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1099 let (ctor_def, ctor_vis, fields) =
1100 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1101 if let PathSource::Expr(Some(parent)) = source {
1102 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1103 bad_struct_syntax_suggestion(def_id);
1109 bad_struct_syntax_suggestion(def_id);
1113 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1114 if !is_expected(ctor_def) || is_accessible {
1118 let field_spans = match source {
1119 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1120 PathSource::TupleStruct(_, pattern_spans) => {
1121 err.set_primary_message(
1122 "cannot match against a tuple struct which contains private fields",
1125 // Use spans of the tuple struct pattern.
1126 Some(Vec::from(pattern_spans))
1128 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1129 _ if source.is_call() => {
1130 err.set_primary_message(
1131 "cannot initialize a tuple struct which contains private fields",
1134 // Use spans of the tuple struct definition.
1138 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1143 if let Some(spans) =
1144 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1146 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1147 .filter(|(vis, _)| {
1148 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1150 .map(|(_, span)| *span)
1153 if non_visible_spans.len() > 0 {
1154 let mut m: MultiSpan = non_visible_spans.clone().into();
1157 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1158 err.span_note(m, "constructor is not visible here due to private fields");
1166 "constructor is not visible here due to private fields".to_string(),
1171 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1175 ) if ns == ValueNS => {
1176 bad_struct_syntax_suggestion(def_id);
1178 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1180 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1181 let span = find_span(&source, err);
1182 if let Some(span) = self.def_span(def_id) {
1183 err.span_label(span, &format!("`{}` defined here", path_str));
1185 err.span_suggestion(
1187 "use this syntax instead",
1188 path_str.to_string(),
1189 Applicability::MaybeIncorrect,
1195 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1196 if let Some(span) = self.def_span(def_id) {
1197 err.span_label(span, &format!("`{}` defined here", path_str));
1199 let fields = self.r.field_names.get(&def_id).map_or_else(
1200 || "/* fields */".to_string(),
1201 |fields| vec!["_"; fields.len()].join(", "),
1203 err.span_suggestion(
1205 "use the tuple variant pattern syntax instead",
1206 format!("{}({})", path_str, fields),
1207 Applicability::HasPlaceholders,
1210 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1211 err.span_label(span, fallback_label);
1212 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1214 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1215 err.note("can't use a type alias as a constructor");
1222 /// Given the target `ident` and `kind`, search for the similarly named associated item
1223 /// in `self.current_trait_ref`.
1224 pub(crate) fn find_similarly_named_assoc_item(
1227 kind: &AssocItemKind,
1228 ) -> Option<Symbol> {
1229 let (module, _) = self.current_trait_ref.as_ref()?;
1230 if ident == kw::Underscore {
1231 // We do nothing for `_`.
1235 let resolutions = self.r.resolutions(module);
1236 let targets = resolutions
1239 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1240 .filter(|(_, res)| match (kind, res) {
1241 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1242 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1243 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1246 .map(|(key, _)| key.ident.name)
1247 .collect::<Vec<_>>();
1249 find_best_match_for_name(&targets, ident, None)
1252 fn lookup_assoc_candidate<FilterFn>(
1256 filter_fn: FilterFn,
1257 ) -> Option<AssocSuggestion>
1259 FilterFn: Fn(Res) -> bool,
1261 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1263 TyKind::Path(None, _) => Some(t.id),
1264 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1265 // This doesn't handle the remaining `Ty` variants as they are not
1266 // that commonly the self_type, it might be interesting to provide
1267 // support for those in future.
1272 // Fields are generally expected in the same contexts as locals.
1273 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1274 if let Some(node_id) =
1275 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1277 // Look for a field with the same name in the current self_type.
1278 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1279 match resolution.base_res() {
1280 Res::Def(DefKind::Struct | DefKind::Union, did)
1281 if resolution.unresolved_segments() == 0 =>
1283 if let Some(field_names) = self.r.field_names.get(&did) {
1286 .any(|&field_name| ident.name == field_name.node)
1288 return Some(AssocSuggestion::Field);
1298 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1299 for assoc_item in items {
1300 if assoc_item.ident == ident {
1301 return Some(match &assoc_item.kind {
1302 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1303 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1304 AssocSuggestion::MethodWithSelf
1306 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1307 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1308 ast::AssocItemKind::MacCall(_) => continue,
1314 // Look for associated items in the current trait.
1315 if let Some((module, _)) = self.current_trait_ref {
1316 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1317 ModuleOrUniformRoot::Module(module),
1322 let res = binding.res();
1324 if self.r.has_self.contains(&res.def_id()) {
1325 return Some(AssocSuggestion::MethodWithSelf);
1328 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1329 Res::Def(DefKind::AssocConst, _) => {
1330 return Some(AssocSuggestion::AssocConst);
1332 Res::Def(DefKind::AssocTy, _) => {
1333 return Some(AssocSuggestion::AssocType);
1345 fn lookup_typo_candidate(
1349 filter_fn: &impl Fn(Res) -> bool,
1350 ) -> Option<TypoSuggestion> {
1351 let mut names = Vec::new();
1352 if path.len() == 1 {
1353 // Search in lexical scope.
1354 // Walk backwards up the ribs in scope and collect candidates.
1355 for rib in self.ribs[ns].iter().rev() {
1356 // Locals and type parameters
1357 for (ident, &res) in &rib.bindings {
1359 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1363 if let RibKind::ModuleRibKind(module) = rib.kind {
1364 // Items from this module
1365 self.r.add_module_candidates(module, &mut names, &filter_fn);
1367 if let ModuleKind::Block(..) = module.kind {
1368 // We can see through blocks
1370 // Items from the prelude
1371 if !module.no_implicit_prelude {
1372 let extern_prelude = self.r.extern_prelude.clone();
1373 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1374 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1377 Res::Def(DefKind::Mod, crate_id.as_def_id());
1379 if filter_fn(crate_mod) {
1380 Some(TypoSuggestion::typo_from_res(
1381 ident.name, crate_mod,
1390 if let Some(prelude) = self.r.prelude {
1391 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1398 // Add primitive types to the mix
1399 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1400 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1401 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1405 // Search in module.
1406 let mod_path = &path[..path.len() - 1];
1407 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1408 self.resolve_path(mod_path, Some(TypeNS), None)
1410 self.r.add_module_candidates(module, &mut names, &filter_fn);
1414 let name = path[path.len() - 1].ident.name;
1415 // Make sure error reporting is deterministic.
1416 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1418 match find_best_match_for_name(
1419 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1423 Some(found) if found != name => {
1424 names.into_iter().find(|suggestion| suggestion.candidate == found)
1430 // Returns the name of the Rust type approximately corresponding to
1431 // a type name in another programming language.
1432 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1433 let name = path[path.len() - 1].ident.as_str();
1434 // Common Java types
1436 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1437 "short" => sym::i16,
1438 "boolean" => sym::bool,
1441 "float" => sym::f32,
1442 "double" => sym::f64,
1447 /// Only used in a specific case of type ascription suggestions
1448 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1449 let sm = self.r.session.source_map();
1450 start.to(sm.next_point(start))
1453 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1454 let sm = self.r.session.source_map();
1455 let base_snippet = sm.span_to_snippet(base_span);
1456 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1457 if let Ok(snippet) = sm.span_to_snippet(sp) {
1458 let len = snippet.trim_end().len() as u32;
1459 if snippet.trim() == ":" {
1461 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1462 let mut show_label = true;
1463 if sm.is_multiline(sp) {
1464 err.span_suggestion_short(
1466 "maybe you meant to write `;` here",
1468 Applicability::MaybeIncorrect,
1471 let after_colon_sp =
1472 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1473 if snippet.len() == 1 {
1475 err.span_suggestion(
1477 "maybe you meant to write a path separator here",
1479 Applicability::MaybeIncorrect,
1486 .type_ascription_path_suggestions
1490 err.downgrade_to_delayed_bug();
1493 if let Ok(base_snippet) = base_snippet {
1494 let mut sp = after_colon_sp;
1496 // Try to find an assignment
1497 sp = sm.next_point(sp);
1498 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1500 Ok(ref x) if x.as_str() == "=" => {
1501 err.span_suggestion(
1503 "maybe you meant to write an assignment here",
1504 format!("let {}", base_snippet),
1505 Applicability::MaybeIncorrect,
1510 Ok(ref x) if x.as_str() == "\n" => break,
1520 "expecting a type here because of type ascription",
1530 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1531 let mut result = None;
1532 let mut seen_modules = FxHashSet::default();
1533 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1535 while let Some((in_module, path_segments)) = worklist.pop() {
1536 // abort if the module is already found
1537 if result.is_some() {
1541 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1542 // abort if the module is already found or if name_binding is private external
1543 if result.is_some() || !name_binding.vis.is_visible_locally() {
1546 if let Some(module) = name_binding.module() {
1548 let mut path_segments = path_segments.clone();
1549 path_segments.push(ast::PathSegment::from_ident(ident));
1550 let module_def_id = module.def_id();
1551 if module_def_id == def_id {
1553 Path { span: name_binding.span, segments: path_segments, tokens: None };
1565 // add the module to the lookup
1566 if seen_modules.insert(module_def_id) {
1567 worklist.push((module, path_segments));
1577 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1578 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1579 let mut variants = Vec::new();
1580 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1581 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1582 let mut segms = enum_import_suggestion.path.segments.clone();
1583 segms.push(ast::PathSegment::from_ident(ident));
1584 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1585 variants.push((path, def_id, kind));
1592 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1593 fn suggest_using_enum_variant(
1595 err: &mut Diagnostic,
1596 source: PathSource<'_>,
1600 let Some(variants) = self.collect_enum_ctors(def_id) else {
1601 err.note("you might have meant to use one of the enum's variants");
1605 let suggest_only_tuple_variants =
1606 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1607 if suggest_only_tuple_variants {
1608 // Suggest only tuple variants regardless of whether they have fields and do not
1609 // suggest path with added parentheses.
1610 let suggestable_variants = variants
1612 .filter(|(.., kind)| *kind == CtorKind::Fn)
1613 .map(|(variant, ..)| path_names_to_string(variant))
1614 .collect::<Vec<_>>();
1616 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1618 let source_msg = if source.is_call() {
1620 } else if matches!(source, PathSource::TupleStruct(..)) {
1626 if !suggestable_variants.is_empty() {
1627 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1628 format!("try {} the enum's variant", source_msg)
1630 format!("try {} one of the enum's variants", source_msg)
1633 err.span_suggestions(
1636 suggestable_variants.into_iter(),
1637 Applicability::MaybeIncorrect,
1641 // If the enum has no tuple variants..
1642 if non_suggestable_variant_count == variants.len() {
1643 err.help(&format!("the enum has no tuple variants {}", source_msg));
1646 // If there are also non-tuple variants..
1647 if non_suggestable_variant_count == 1 {
1649 "you might have meant {} the enum's non-tuple variant",
1652 } else if non_suggestable_variant_count >= 1 {
1654 "you might have meant {} one of the enum's non-tuple variants",
1659 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1660 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1662 CtorKind::Const => false,
1663 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1668 let mut suggestable_variants = variants
1670 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1671 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1672 .map(|(variant, kind)| match kind {
1673 CtorKind::Const => variant,
1674 CtorKind::Fn => format!("({}())", variant),
1675 CtorKind::Fictive => format!("({} {{}})", variant),
1677 .collect::<Vec<_>>();
1679 if !suggestable_variants.is_empty() {
1680 let msg = if suggestable_variants.len() == 1 {
1681 "you might have meant to use the following enum variant"
1683 "you might have meant to use one of the following enum variants"
1686 err.span_suggestions(
1689 suggestable_variants.drain(..),
1690 Applicability::MaybeIncorrect,
1694 let suggestable_variants_with_placeholders = variants
1696 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1697 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1698 .filter_map(|(variant, kind)| match kind {
1699 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1700 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1703 .collect::<Vec<_>>();
1705 if !suggestable_variants_with_placeholders.is_empty() {
1707 suggestable_variants.is_empty(),
1708 suggestable_variants_with_placeholders.len(),
1710 (true, 1) => "the following enum variant is available",
1711 (true, _) => "the following enum variants are available",
1712 (false, 1) => "alternatively, the following enum variant is available",
1713 (false, _) => "alternatively, the following enum variants are also available",
1716 err.span_suggestions(
1719 suggestable_variants_with_placeholders.into_iter(),
1720 Applicability::HasPlaceholders,
1725 if def_id.is_local() {
1726 if let Some(span) = self.def_span(def_id) {
1727 err.span_note(span, "the enum is defined here");
1732 pub(crate) fn report_missing_type_error(
1735 ) -> Option<(Span, &'static str, String, Applicability)> {
1736 let (ident, span) = match path {
1737 [segment] if !segment.has_generic_args => {
1738 (segment.ident.to_string(), segment.ident.span)
1742 let mut iter = ident.chars().map(|c| c.is_uppercase());
1743 let single_uppercase_char =
1744 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1745 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1748 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1749 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1750 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1755 kind @ ItemKind::Fn(..)
1756 | kind @ ItemKind::Enum(..)
1757 | kind @ ItemKind::Struct(..)
1758 | kind @ ItemKind::Union(..),
1763 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1764 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1765 | (Some(Item { kind, .. }), false, _) => {
1766 // Likely missing type parameter.
1767 if let Some(generics) = kind.generics() {
1768 if span.overlaps(generics.span) {
1769 // Avoid the following:
1770 // error[E0405]: cannot find trait `A` in this scope
1771 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1773 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1774 // | ^- help: you might be missing a type parameter: `, A`
1776 // | not found in this scope
1779 let msg = "you might be missing a type parameter";
1780 let (span, sugg) = if let [.., param] = &generics.params[..] {
1781 let span = if let [.., bound] = ¶m.bounds[..] {
1783 } else if let GenericParam {
1784 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1786 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1790 (span, format!(", {}", ident))
1792 (generics.span, format!("<{}>", ident))
1794 // Do not suggest if this is coming from macro expansion.
1795 if span.can_be_used_for_suggestions() {
1797 span.shrink_to_hi(),
1800 Applicability::MaybeIncorrect,
1810 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1811 /// optionally returning the closest match and whether it is reachable.
1812 pub(crate) fn suggestion_for_label_in_rib(
1816 ) -> Option<LabelSuggestion> {
1817 // Are ribs from this `rib_index` within scope?
1818 let within_scope = self.is_label_valid_from_rib(rib_index);
1820 let rib = &self.label_ribs[rib_index];
1824 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1825 .map(|(id, _)| id.name)
1826 .collect::<Vec<Symbol>>();
1828 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1829 // Upon finding a similar name, get the ident that it was from - the span
1830 // contained within helps make a useful diagnostic. In addition, determine
1831 // whether this candidate is within scope.
1832 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1833 (*ident, within_scope)
1837 pub(crate) fn maybe_report_lifetime_uses(
1839 generics_span: Span,
1840 params: &[ast::GenericParam],
1842 for (param_index, param) in params.iter().enumerate() {
1843 let GenericParamKind::Lifetime = param.kind else { continue };
1845 let def_id = self.r.local_def_id(param.id);
1847 let use_set = self.lifetime_uses.remove(&def_id);
1849 "Use set for {:?}({:?} at {:?}) is {:?}",
1850 def_id, param.ident, param.ident.span, use_set
1853 let deletion_span = || {
1854 if params.len() == 1 {
1855 // if sole lifetime, remove the entire `<>` brackets
1857 } else if param_index == 0 {
1858 // if removing within `<>` brackets, we also want to
1859 // delete a leading or trailing comma as appropriate
1860 param.span().to(params[param_index + 1].span().shrink_to_lo())
1862 // if removing within `<>` brackets, we also want to
1863 // delete a leading or trailing comma as appropriate
1864 params[param_index - 1].span().shrink_to_hi().to(param.span())
1868 Some(LifetimeUseSet::Many) => {}
1869 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1870 debug!(?param.ident, ?param.ident.span, ?use_span);
1872 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1874 let deletion_span = deletion_span();
1875 self.r.lint_buffer.buffer_lint_with_diagnostic(
1876 lint::builtin::SINGLE_USE_LIFETIMES,
1879 &format!("lifetime parameter `{}` only used once", param.ident),
1880 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1881 param_span: param.ident.span,
1882 use_span: Some((use_span, elidable)),
1888 debug!(?param.ident, ?param.ident.span);
1890 let deletion_span = deletion_span();
1891 self.r.lint_buffer.buffer_lint_with_diagnostic(
1892 lint::builtin::UNUSED_LIFETIMES,
1895 &format!("lifetime parameter `{}` never used", param.ident),
1896 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1897 param_span: param.ident.span,
1907 pub(crate) fn emit_undeclared_lifetime_error(
1909 lifetime_ref: &ast::Lifetime,
1910 outer_lifetime_ref: Option<Ident>,
1912 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1913 let mut err = if let Some(outer) = outer_lifetime_ref {
1914 let mut err = struct_span_err!(
1916 lifetime_ref.ident.span,
1918 "can't use generic parameters from outer item",
1920 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1921 err.span_label(outer.span, "lifetime parameter from outer item");
1924 let mut err = struct_span_err!(
1926 lifetime_ref.ident.span,
1928 "use of undeclared lifetime name `{}`",
1931 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
1934 let mut suggest_note = true;
1936 for rib in self.lifetime_ribs.iter().rev() {
1938 LifetimeRibKind::Generics { binder: _, span, kind } => {
1939 if !span.can_be_used_for_suggestions() && suggest_note {
1940 suggest_note = false; // Avoid displaying the same help multiple times.
1944 "lifetime `{}` is missing in item created through this procedural macro",
1951 let higher_ranked = matches!(
1953 LifetimeBinderKind::BareFnType
1954 | LifetimeBinderKind::PolyTrait
1955 | LifetimeBinderKind::WhereBound
1957 let (span, sugg) = if span.is_empty() {
1960 if higher_ranked { "for" } else { "" },
1962 if higher_ranked { " " } else { "" },
1967 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
1968 let sugg = format!("{}, ", lifetime_ref.ident);
1972 err.span_suggestion(
1975 "consider making the {} lifetime-generic with a new `{}` lifetime",
1980 Applicability::MaybeIncorrect,
1983 "for more information on higher-ranked polymorphism, visit \
1984 https://doc.rust-lang.org/nomicon/hrtb.html",
1987 err.span_suggestion(
1989 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
1991 Applicability::MaybeIncorrect,
1995 LifetimeRibKind::Item => break,
2003 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2006 lifetime_ref.ident.span,
2008 "use of non-static lifetime `{}` in const generic",
2012 "for more information, see issue #74052 \
2013 <https://github.com/rust-lang/rust/issues/74052>",
2018 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2019 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2020 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2021 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2023 lifetime_ref: &ast::Lifetime,
2025 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2026 if !feature_active {
2028 &self.r.session.parse_sess,
2029 sym::generic_const_exprs,
2030 lifetime_ref.ident.span,
2031 "a non-static lifetime is not allowed in a `const`",
2038 impl<'tcx> LifetimeContext<'_, 'tcx> {
2039 pub(crate) fn report_missing_lifetime_specifiers(
2043 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2048 "missing lifetime specifier{}",
2053 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
2054 pub(crate) fn report_elision_failure(
2056 diag: &mut Diagnostic,
2057 params: &[ElisionFailureInfo],
2059 let mut m = String::new();
2060 let len = params.len();
2062 let elided_params: Vec<_> =
2063 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2065 let elided_len = elided_params.len();
2067 for (i, info) in elided_params.into_iter().enumerate() {
2068 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2071 diag.span_label(span, "");
2072 let help_name = if let Some(ident) =
2073 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2075 format!("`{}`", ident)
2077 format!("argument {}", index + 1)
2085 "one of {}'s {} {}lifetimes",
2088 if have_bound_regions { "free " } else { "" }
2093 if elided_len == 2 && i == 0 {
2095 } else if i + 2 == elided_len {
2096 m.push_str(", or ");
2097 } else if i != elided_len - 1 {
2104 "this function's return type contains a borrowed value, \
2105 but there is no value for it to be borrowed from",
2108 } else if elided_len == 0 {
2110 "this function's return type contains a borrowed value with \
2111 an elided lifetime, but the lifetime cannot be derived from \
2115 } else if elided_len == 1 {
2117 "this function's return type contains a borrowed value, \
2118 but the signature does not say which {} it is borrowed from",
2124 "this function's return type contains a borrowed value, \
2125 but the signature does not say whether it is borrowed from {}",
2132 pub(crate) fn is_trait_ref_fn_scope(
2134 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
2136 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2138 self.tcx.lang_items().fn_once_trait(),
2139 self.tcx.lang_items().fn_trait(),
2140 self.tcx.lang_items().fn_mut_trait(),
2142 .contains(&Some(did))
2144 let (span, span_type) = match &trait_ref.bound_generic_params {
2145 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2146 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2148 self.missing_named_lifetime_spots
2149 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2156 pub(crate) fn add_missing_lifetime_specifiers_label(
2158 err: &mut Diagnostic,
2159 mut spans_with_counts: Vec<(Span, usize)>,
2160 lifetime_names: &FxHashSet<Symbol>,
2161 lifetime_spans: Vec<Span>,
2162 params: &[ElisionFailureInfo],
2164 let snippets: Vec<Option<String>> = spans_with_counts
2166 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2169 // Empty generics are marked with a span of "<", but since from now on
2170 // that information is in the snippets it can be removed from the spans.
2171 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2172 if snippet.as_deref() == Some("<") {
2173 *span = span.shrink_to_hi();
2177 for &(span, count) in &spans_with_counts {
2181 "expected {} lifetime parameter{}",
2182 if count == 1 { "named".to_string() } else { count.to_string() },
2188 let suggest_existing =
2189 |err: &mut Diagnostic,
2191 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2192 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2193 self.missing_named_lifetime_spots.iter().rev().next()
2195 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2196 // using `'a`, but also introduce the concept of HRLTs by suggesting
2197 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2198 let mut introduce_suggestion = vec![];
2200 let a_to_z_repeat_n = |n| {
2201 (b'a'..=b'z').map(move |c| {
2202 let mut s = '\''.to_string();
2203 s.extend(std::iter::repeat(char::from(c)).take(n));
2208 // If all single char lifetime names are present, we wrap around and double the chars.
2210 .flat_map(a_to_z_repeat_n)
2211 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2214 "consider making the {} lifetime-generic with a new `{}` lifetime",
2219 "for more information on higher-ranked polymorphism, visit \
2220 https://doc.rust-lang.org/nomicon/hrtb.html",
2222 let for_sugg = span_type.suggestion(<_name);
2223 for param in params {
2224 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2226 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2227 introduce_suggestion
2228 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2229 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2230 introduce_suggestion
2231 .push((param.span, format!("&{} {}", lt_name, stripped)));
2235 introduce_suggestion.push((*for_span, for_sugg));
2236 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2237 if let Some(formatter) = formatter {
2238 introduce_suggestion.push((*span, formatter(<_name)));
2241 err.multipart_suggestion_verbose(
2243 introduce_suggestion,
2244 Applicability::MaybeIncorrect,
2248 let spans_suggs: Vec<_> = formatters
2250 .zip(spans_with_counts.iter())
2251 .filter_map(|(formatter, (span, _))| {
2252 if let Some(formatter) = formatter {
2253 Some((*span, formatter(name)))
2259 if spans_suggs.is_empty() {
2260 // If all the spans come from macros, we cannot extract snippets and then
2261 // `formatters` only contains None and `spans_suggs` is empty.
2264 err.multipart_suggestion_verbose(
2266 "consider using the `{}` lifetime",
2267 lifetime_names.iter().next().unwrap()
2270 Applicability::MaybeIncorrect,
2273 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2274 for missing in self.missing_named_lifetime_spots.iter().rev() {
2275 let mut introduce_suggestion = vec![];
2278 introduce_suggestion.push(match missing {
2279 MissingLifetimeSpot::Generics(generics) => {
2280 if generics.span == DUMMY_SP {
2281 // Account for malformed generics in the HIR. This shouldn't happen,
2282 // but if we make a mistake elsewhere, mainly by keeping something in
2283 // `missing_named_lifetime_spots` that we shouldn't, like associated
2284 // `const`s or making a mistake in the AST lowering we would provide
2285 // nonsensical suggestions. Guard against that by skipping these.
2289 msg = "consider introducing a named lifetime parameter".to_string();
2290 should_break = true;
2291 if let Some(param) = generics.params.iter().find(|p| {
2294 hir::GenericParamKind::Type { synthetic: true, .. }
2295 | hir::GenericParamKind::Lifetime {
2296 kind: hir::LifetimeParamKind::Elided
2300 (param.span.shrink_to_lo(), "'a, ".to_string())
2302 (generics.span, "<'a>".to_string())
2305 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2307 "consider making the {} lifetime-generic with a new `'a` lifetime",
2310 should_break = false;
2312 "for more information on higher-ranked polymorphism, visit \
2313 https://doc.rust-lang.org/nomicon/hrtb.html",
2315 (*span, span_type.suggestion("'a"))
2317 MissingLifetimeSpot::Static => {
2318 let mut spans_suggs = Vec::new();
2319 for ((span, count), snippet) in
2320 spans_with_counts.iter().copied().zip(snippets.iter())
2322 let (span, sugg) = match snippet.as_deref() {
2323 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2324 Some("'_") => (span, "'static".to_owned()),
2325 Some(snippet) if !snippet.ends_with('>') => {
2329 std::iter::repeat("'static")
2331 .collect::<Vec<_>>()
2334 } else if snippet == "<" || snippet == "(" {
2336 span.shrink_to_hi(),
2337 std::iter::repeat("'static")
2339 .collect::<Vec<_>>()
2344 span.shrink_to_hi(),
2347 std::iter::repeat("'static")
2349 .collect::<Vec<_>>()
2357 spans_suggs.push((span, sugg.to_string()));
2359 err.multipart_suggestion_verbose(
2360 "consider using the `'static` lifetime",
2362 Applicability::MaybeIncorrect,
2368 struct Lifetime(Span, String);
2370 fn is_unnamed(&self) -> bool {
2371 self.1.starts_with('&') && !self.1.starts_with("&'")
2373 fn is_underscore(&self) -> bool {
2374 self.1.starts_with("&'_ ")
2376 fn is_named(&self) -> bool {
2377 self.1.starts_with("&'")
2379 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2383 self.is_underscore(),
2385 sugg.starts_with('&'),
2387 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2388 (true, _, _, true) => {
2389 (self.span_unnamed_borrow(), sugg[1..].to_string())
2391 (_, true, _, false) => {
2392 (self.span_underscore_borrow(), sugg.trim().to_string())
2394 (_, true, _, true) => {
2395 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2397 (_, _, true, false) => {
2398 (self.span_named_borrow(), sugg.trim().to_string())
2400 (_, _, true, true) => {
2401 (self.span_named_borrow(), sugg[1..].trim().to_string())
2407 fn span_unnamed_borrow(&self) -> Span {
2408 let lo = self.0.lo() + BytePos(1);
2409 self.0.with_lo(lo).with_hi(lo)
2411 fn span_named_borrow(&self) -> Span {
2412 let lo = self.0.lo() + BytePos(1);
2415 fn span_underscore_borrow(&self) -> Span {
2416 let lo = self.0.lo() + BytePos(1);
2417 let hi = lo + BytePos(2);
2418 self.0.with_lo(lo).with_hi(hi)
2422 for param in params {
2423 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2424 if let Some((span, sugg)) =
2425 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2427 introduce_suggestion.push((span, sugg));
2431 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2432 |((span, _), sugg)| match &sugg {
2433 Some(sugg) => Some((span, sugg.to_string())),
2437 let (span, sugg) = self
2441 .span_to_snippet(span)
2443 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2444 .unwrap_or((span, sugg));
2445 introduce_suggestion.push((span, sugg.to_string()));
2447 err.multipart_suggestion_verbose(
2449 introduce_suggestion,
2450 Applicability::MaybeIncorrect,
2458 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2459 match &lifetime_names[..] {
2461 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2462 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2464 suggs.push(match snippet.as_deref() {
2465 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2466 Some("'_") => Some(Box::new(|n| n.to_string())),
2467 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2468 Some("<") => Some(Box::new(move |n| {
2469 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2471 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2475 std::iter::repeat(name.to_string())
2477 .collect::<Vec<_>>()
2484 suggest_existing(err, name.as_str(), suggs);
2487 let mut suggs = Vec::new();
2488 for (snippet, (_, count)) in
2489 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2491 suggs.push(match snippet.as_deref() {
2492 Some("&") => Some("&'a ".to_string()),
2493 Some("'_") => Some("'a".to_string()),
2495 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2498 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2500 Some(snippet) => Some(format!(
2503 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2508 suggest_new(err, suggs);
2510 lts if lts.len() > 1 => {
2511 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2513 let mut spans_suggs: Vec<_> = Vec::new();
2514 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2515 match snippet.as_deref() {
2516 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2517 Some("&") => spans_suggs
2518 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2523 if spans_suggs.len() > 0 {
2524 // This happens when we have `Foo<T>` where we point at the space before `T`,
2525 // but this can be confusing so we give a suggestion with placeholders.
2526 err.multipart_suggestion_verbose(
2527 "consider using one of the available lifetimes here",
2529 Applicability::HasPlaceholders,
2533 _ => unreachable!(),