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 // Try Levenshtein algorithm.
449 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
450 if path.len() == 1 && self.self_type_is_available() {
451 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
452 let self_is_available = self.self_value_is_available(path[0].ident.span);
454 AssocSuggestion::Field => {
455 if self_is_available {
458 "you might have meant to use the available field",
459 format!("self.{path_str}"),
460 Applicability::MachineApplicable,
463 err.span_label(span, "a field by this name exists in `Self`");
466 AssocSuggestion::MethodWithSelf if self_is_available => {
469 "you might have meant to call the method",
470 format!("self.{path_str}"),
471 Applicability::MachineApplicable,
474 AssocSuggestion::MethodWithSelf
475 | AssocSuggestion::AssocFn
476 | AssocSuggestion::AssocConst
477 | AssocSuggestion::AssocType => {
480 &format!("you might have meant to {}", candidate.action()),
481 format!("Self::{path_str}"),
482 Applicability::MachineApplicable,
486 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
487 return (err, candidates);
490 // If the first argument in call is `self` suggest calling a method.
491 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
492 let mut args_snippet = String::new();
493 if let Some(args_span) = args_span {
494 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
495 args_snippet = snippet;
501 &format!("try calling `{ident}` as a method"),
502 format!("self.{path_str}({args_snippet})"),
503 Applicability::MachineApplicable,
505 return (err, candidates);
509 // Try context-dependent help if relaxed lookup didn't work.
510 if let Some(res) = res {
511 if self.smart_resolve_context_dependent_help(
517 &base_error.fallback_label,
519 // We do this to avoid losing a secondary span when we override the main error span.
520 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
521 return (err, candidates);
526 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
527 if !self.type_ascription_suggestion(&mut err, base_error.span) {
528 let mut fallback = false;
530 PathSource::Trait(AliasPossibility::Maybe),
531 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
533 ) = (source, res, is_macro)
535 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
537 let spans: Vec<Span> = bounds
539 .map(|bound| bound.span())
540 .filter(|&sp| sp != base_error.span)
543 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
544 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
545 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
546 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
547 let last_bound_span = spans.last().cloned().unwrap();
548 let mut multi_span: MultiSpan = spans.clone().into();
550 let msg = if sp == last_bound_span {
552 "...because of {these} bound{s}",
553 these = pluralize!("this", bounds.len() - 1),
554 s = pluralize!(bounds.len() - 1),
559 multi_span.push_span_label(sp, msg);
561 multi_span.push_span_label(
563 "expected this type to be a trait...".to_string(),
567 "`+` is used to constrain a \"trait object\" type with lifetimes or \
568 auto-traits; structs and enums can't be bound in that way",
570 if bounds.iter().all(|bound| match bound {
571 ast::GenericBound::Outlives(_) => true,
572 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
574 let mut sugg = vec![];
575 if base_error.span != start_span {
576 sugg.push((start_span.until(base_error.span), String::new()));
578 if base_error.span != end_span {
579 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
582 err.multipart_suggestion(
583 "if you meant to use a type and not a trait here, remove the bounds",
585 Applicability::MaybeIncorrect,
591 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
593 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
595 match self.diagnostic_metadata.current_let_binding {
596 Some((pat_sp, Some(ty_sp), None))
597 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
599 err.span_suggestion_short(
600 pat_sp.between(ty_sp),
601 "use `=` if you meant to assign",
603 Applicability::MaybeIncorrect,
609 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
610 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
611 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
615 err.span_label(base_error.span, base_error.fallback_label);
618 if let Some(err_code) = &err.code {
619 if err_code == &rustc_errors::error_code!(E0425) {
620 for label_rib in &self.label_ribs {
621 for (label_ident, node_id) in &label_rib.bindings {
622 if format!("'{}", ident) == label_ident.to_string() {
623 err.span_label(label_ident.span, "a label with a similar name exists");
624 if let PathSource::Expr(Some(Expr {
625 kind: ExprKind::Break(None, Some(_)),
631 "use the similarly named label",
632 label_ident.name.to_string(),
633 Applicability::MaybeIncorrect,
635 // Do not lint against unused label when we suggest them.
636 self.diagnostic_metadata.unused_labels.remove(node_id);
641 } else if err_code == &rustc_errors::error_code!(E0412) {
642 if let Some(correct) = Self::likely_rust_type(path) {
645 "perhaps you intended to use this type",
647 Applicability::MaybeIncorrect,
656 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
657 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
658 let TyKind::Path(_, path) = &ty.kind else { return; };
659 for segment in &path.segments {
660 let Some(params) = &segment.args else { continue; };
661 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
662 for param in ¶ms.args {
663 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
664 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
667 for bound in bounds {
668 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
673 if base_span == trait_ref.span {
674 err.span_suggestion_verbose(
675 constraint.ident.span.between(trait_ref.span),
676 "you might have meant to write a path instead of an associated type bound",
678 Applicability::MachineApplicable,
686 fn get_single_associated_item(
689 source: &PathSource<'_>,
690 filter_fn: &impl Fn(Res) -> bool,
691 ) -> Option<TypoSuggestion> {
692 if let crate::PathSource::TraitItem(_) = source {
693 let mod_path = &path[..path.len() - 1];
694 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
695 self.resolve_path(mod_path, None, None)
697 let resolutions = self.r.resolutions(module).borrow();
698 let targets: Vec<_> =
701 .filter_map(|(key, resolution)| {
702 resolution.borrow().binding.map(|binding| binding.res()).and_then(
703 |res| if filter_fn(res) { Some((key, res)) } else { None },
707 if targets.len() == 1 {
708 let target = targets[0];
709 return Some(TypoSuggestion::single_item_from_res(
719 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
720 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
721 // Detect that we are actually in a `where` predicate.
722 let (bounded_ty, bounds, where_span) =
723 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
725 bound_generic_params,
728 })) = self.diagnostic_metadata.current_where_predicate
730 if !bound_generic_params.is_empty() {
733 (bounded_ty, bounds, span)
738 // Confirm that the target is an associated type.
739 let (ty, position, path) = if let ast::TyKind::Path(
740 Some(ast::QSelf { ty, position, .. }),
744 // use this to verify that ident is a type param.
745 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
749 partial_res.base_res(),
750 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
751 ) && partial_res.unresolved_segments() == 0)
760 let peeled_ty = ty.peel_refs();
761 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
762 // Confirm that the `SelfTy` is a type parameter.
763 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
767 partial_res.base_res(),
768 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
769 ) && partial_res.unresolved_segments() == 0)
774 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
775 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
776 ) = (&type_param_path.segments[..], &bounds[..])
778 if let [ast::PathSegment { ident, args: None, .. }] =
779 &poly_trait_ref.trait_ref.path.segments[..]
781 if ident.span == span {
782 err.span_suggestion_verbose(
784 &format!("constrain the associated type to `{}`", ident),
790 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
791 .unwrap_or_else(|_| constrain_ident.to_string()),
792 path.segments[..*position]
794 .map(|segment| path_segment_to_string(segment))
797 path.segments[*position..]
799 .map(|segment| path_segment_to_string(segment))
804 Applicability::MaybeIncorrect,
814 /// Check if the source is call expression and the first argument is `self`. If true,
815 /// return the span of whole call and the span for all arguments expect the first one (`self`).
816 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
817 let mut has_self_arg = None;
818 if let PathSource::Expr(Some(parent)) = source {
820 ExprKind::Call(_, args) if !args.is_empty() => {
821 let mut expr_kind = &args[0].kind;
824 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
825 if arg_name.segments[0].ident.name == kw::SelfLower {
826 let call_span = parent.span;
827 let tail_args_span = if args.len() > 1 {
830 args.last().unwrap().span.hi(),
837 has_self_arg = Some((call_span, tail_args_span));
841 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
852 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
853 // HACK(estebank): find a better way to figure out that this was a
854 // parser issue where a struct literal is being used on an expression
855 // where a brace being opened means a block is being started. Look
856 // ahead for the next text to see if `span` is followed by a `{`.
857 let sm = self.r.session.source_map();
860 sp = sm.next_point(sp);
861 match sm.span_to_snippet(sp) {
863 if snippet.chars().any(|c| !c.is_whitespace()) {
870 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
871 // In case this could be a struct literal that needs to be surrounded
872 // by parentheses, find the appropriate span.
874 let mut closing_brace = None;
876 sp = sm.next_point(sp);
877 match sm.span_to_snippet(sp) {
880 closing_brace = Some(span.to(sp));
887 // The bigger the span, the more likely we're incorrect --
888 // bound it to 100 chars long.
893 (followed_by_brace, closing_brace)
896 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
898 /// Returns `true` if able to provide context-dependent help.
899 fn smart_resolve_context_dependent_help(
901 err: &mut Diagnostic,
903 source: PathSource<'_>,
906 fallback_label: &str,
908 let ns = source.namespace();
909 let is_expected = &|res| source.is_expected(res);
911 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
912 ExprKind::Field(_, ident) => {
915 "use the path separator to refer to an item",
916 format!("{}::{}", path_str, ident),
917 Applicability::MaybeIncorrect,
921 ExprKind::MethodCall(ref segment, ..) => {
922 let span = expr.span.with_hi(segment.ident.span.hi());
925 "use the path separator to refer to an item",
926 format!("{}::{}", path_str, segment.ident),
927 Applicability::MaybeIncorrect,
934 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
936 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
937 | PathSource::TupleStruct(span, _) => {
938 // We want the main underline to cover the suggested code as well for
947 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
948 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
951 PathSource::Expr(Some(
952 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
953 )) if path_sep(err, &parent) => {}
959 | ExprKind::Binary(..)
960 | ExprKind::Unary(..)
962 | ExprKind::While(..)
963 | ExprKind::ForLoop(..)
964 | ExprKind::Match(..),
967 ) if followed_by_brace => {
968 if let Some(sp) = closing_brace {
969 err.span_label(span, fallback_label);
970 err.multipart_suggestion(
971 "surround the struct literal with parentheses",
973 (sp.shrink_to_lo(), "(".to_string()),
974 (sp.shrink_to_hi(), ")".to_string()),
976 Applicability::MaybeIncorrect,
980 span, // Note the parentheses surrounding the suggestion below
982 "you might want to surround a struct literal with parentheses: \
983 `({} {{ /* fields */ }})`?",
989 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
990 let span = find_span(&source, err);
991 if let Some(span) = self.def_span(def_id) {
992 err.span_label(span, &format!("`{}` defined here", path_str));
994 let (tail, descr, applicability) = match source {
995 PathSource::Pat | PathSource::TupleStruct(..) => {
996 ("", "pattern", Applicability::MachineApplicable)
998 _ => (": val", "literal", Applicability::HasPlaceholders),
1000 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1004 .map(|f| format!("{}{}", f.node, tail))
1005 .collect::<Vec<String>>()
1009 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1011 let pad = match self.r.field_names.get(&def_id) {
1012 Some(fields) if fields.is_empty() => "",
1015 err.span_suggestion(
1017 &format!("use struct {} syntax instead", descr),
1018 format!("{path_str} {{{pad}{fields}{pad}}}"),
1023 err.span_label(span, fallback_label);
1028 match (res, source) {
1030 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1031 PathSource::Expr(Some(Expr {
1032 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1034 | PathSource::Struct,
1036 err.span_label(span, fallback_label);
1037 err.span_suggestion_verbose(
1038 span.shrink_to_hi(),
1039 "use `!` to invoke the macro",
1041 Applicability::MaybeIncorrect,
1043 if path_str == "try" && span.rust_2015() {
1044 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1047 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1048 err.span_label(span, fallback_label);
1050 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1051 err.span_label(span, "type aliases cannot be used as traits");
1052 if self.r.session.is_nightly_build() {
1053 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1055 if let Some(span) = self.def_span(def_id) {
1056 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1057 // The span contains a type alias so we should be able to
1058 // replace `type` with `trait`.
1059 let snip = snip.replacen("type", "trait", 1);
1060 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1062 err.span_help(span, msg);
1069 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1070 if !path_sep(err, &parent) {
1075 Res::Def(DefKind::Enum, def_id),
1076 PathSource::TupleStruct(..) | PathSource::Expr(..),
1079 .diagnostic_metadata
1080 .current_type_ascription
1086 .type_ascription_path_suggestions
1092 err.downgrade_to_delayed_bug();
1093 // We already suggested changing `:` into `::` during parsing.
1097 self.suggest_using_enum_variant(err, source, def_id, span);
1099 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1100 let (ctor_def, ctor_vis, fields) =
1101 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1102 if let PathSource::Expr(Some(parent)) = source {
1103 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1104 bad_struct_syntax_suggestion(def_id);
1110 bad_struct_syntax_suggestion(def_id);
1114 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1115 if !is_expected(ctor_def) || is_accessible {
1119 let field_spans = match source {
1120 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1121 PathSource::TupleStruct(_, pattern_spans) => {
1122 err.set_primary_message(
1123 "cannot match against a tuple struct which contains private fields",
1126 // Use spans of the tuple struct pattern.
1127 Some(Vec::from(pattern_spans))
1129 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1130 _ if source.is_call() => {
1131 err.set_primary_message(
1132 "cannot initialize a tuple struct which contains private fields",
1135 // Use spans of the tuple struct definition.
1139 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1144 if let Some(spans) =
1145 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1147 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1148 .filter(|(vis, _)| {
1149 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1151 .map(|(_, span)| *span)
1154 if non_visible_spans.len() > 0 {
1155 let mut m: MultiSpan = non_visible_spans.clone().into();
1158 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1159 err.span_note(m, "constructor is not visible here due to private fields");
1167 "constructor is not visible here due to private fields".to_string(),
1172 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1176 ) if ns == ValueNS => {
1177 bad_struct_syntax_suggestion(def_id);
1179 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1181 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1182 let span = find_span(&source, err);
1183 if let Some(span) = self.def_span(def_id) {
1184 err.span_label(span, &format!("`{}` defined here", path_str));
1186 err.span_suggestion(
1188 "use this syntax instead",
1189 path_str.to_string(),
1190 Applicability::MaybeIncorrect,
1196 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1197 if let Some(span) = self.def_span(def_id) {
1198 err.span_label(span, &format!("`{}` defined here", path_str));
1200 let fields = self.r.field_names.get(&def_id).map_or_else(
1201 || "/* fields */".to_string(),
1202 |fields| vec!["_"; fields.len()].join(", "),
1204 err.span_suggestion(
1206 "use the tuple variant pattern syntax instead",
1207 format!("{}({})", path_str, fields),
1208 Applicability::HasPlaceholders,
1211 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1212 err.span_label(span, fallback_label);
1213 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1215 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1216 err.note("can't use a type alias as a constructor");
1223 /// Given the target `ident` and `kind`, search for the similarly named associated item
1224 /// in `self.current_trait_ref`.
1225 pub(crate) fn find_similarly_named_assoc_item(
1228 kind: &AssocItemKind,
1229 ) -> Option<Symbol> {
1230 let (module, _) = self.current_trait_ref.as_ref()?;
1231 if ident == kw::Underscore {
1232 // We do nothing for `_`.
1236 let resolutions = self.r.resolutions(module);
1237 let targets = resolutions
1240 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1241 .filter(|(_, res)| match (kind, res) {
1242 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1243 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1244 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1247 .map(|(key, _)| key.ident.name)
1248 .collect::<Vec<_>>();
1250 find_best_match_for_name(&targets, ident, None)
1253 fn lookup_assoc_candidate<FilterFn>(
1257 filter_fn: FilterFn,
1258 ) -> Option<AssocSuggestion>
1260 FilterFn: Fn(Res) -> bool,
1262 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1264 TyKind::Path(None, _) => Some(t.id),
1265 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1266 // This doesn't handle the remaining `Ty` variants as they are not
1267 // that commonly the self_type, it might be interesting to provide
1268 // support for those in future.
1273 // Fields are generally expected in the same contexts as locals.
1274 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1275 if let Some(node_id) =
1276 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1278 // Look for a field with the same name in the current self_type.
1279 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1280 match resolution.base_res() {
1281 Res::Def(DefKind::Struct | DefKind::Union, did)
1282 if resolution.unresolved_segments() == 0 =>
1284 if let Some(field_names) = self.r.field_names.get(&did) {
1287 .any(|&field_name| ident.name == field_name.node)
1289 return Some(AssocSuggestion::Field);
1299 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1300 for assoc_item in items {
1301 if assoc_item.ident == ident {
1302 return Some(match &assoc_item.kind {
1303 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1304 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1305 AssocSuggestion::MethodWithSelf
1307 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1308 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1309 ast::AssocItemKind::MacCall(_) => continue,
1315 // Look for associated items in the current trait.
1316 if let Some((module, _)) = self.current_trait_ref {
1317 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1318 ModuleOrUniformRoot::Module(module),
1323 let res = binding.res();
1325 if self.r.has_self.contains(&res.def_id()) {
1326 return Some(AssocSuggestion::MethodWithSelf);
1329 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1330 Res::Def(DefKind::AssocConst, _) => {
1331 return Some(AssocSuggestion::AssocConst);
1333 Res::Def(DefKind::AssocTy, _) => {
1334 return Some(AssocSuggestion::AssocType);
1346 fn lookup_typo_candidate(
1350 filter_fn: &impl Fn(Res) -> bool,
1351 ) -> Option<TypoSuggestion> {
1352 let mut names = Vec::new();
1353 if path.len() == 1 {
1354 // Search in lexical scope.
1355 // Walk backwards up the ribs in scope and collect candidates.
1356 for rib in self.ribs[ns].iter().rev() {
1357 // Locals and type parameters
1358 for (ident, &res) in &rib.bindings {
1360 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1364 if let RibKind::ModuleRibKind(module) = rib.kind {
1365 // Items from this module
1366 self.r.add_module_candidates(module, &mut names, &filter_fn);
1368 if let ModuleKind::Block(..) = module.kind {
1369 // We can see through blocks
1371 // Items from the prelude
1372 if !module.no_implicit_prelude {
1373 let extern_prelude = self.r.extern_prelude.clone();
1374 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1375 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1378 Res::Def(DefKind::Mod, crate_id.as_def_id());
1380 if filter_fn(crate_mod) {
1381 Some(TypoSuggestion::typo_from_res(
1382 ident.name, crate_mod,
1391 if let Some(prelude) = self.r.prelude {
1392 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1399 // Add primitive types to the mix
1400 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1401 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1402 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1406 // Search in module.
1407 let mod_path = &path[..path.len() - 1];
1408 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1409 self.resolve_path(mod_path, Some(TypeNS), None)
1411 self.r.add_module_candidates(module, &mut names, &filter_fn);
1415 let name = path[path.len() - 1].ident.name;
1416 // Make sure error reporting is deterministic.
1417 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1419 match find_best_match_for_name(
1420 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1424 Some(found) if found != name => {
1425 names.into_iter().find(|suggestion| suggestion.candidate == found)
1431 // Returns the name of the Rust type approximately corresponding to
1432 // a type name in another programming language.
1433 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1434 let name = path[path.len() - 1].ident.as_str();
1435 // Common Java types
1437 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1438 "short" => sym::i16,
1439 "boolean" => sym::bool,
1442 "float" => sym::f32,
1443 "double" => sym::f64,
1448 /// Only used in a specific case of type ascription suggestions
1449 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1450 let sm = self.r.session.source_map();
1451 start.to(sm.next_point(start))
1454 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1455 let sm = self.r.session.source_map();
1456 let base_snippet = sm.span_to_snippet(base_span);
1457 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1458 if let Ok(snippet) = sm.span_to_snippet(sp) {
1459 let len = snippet.trim_end().len() as u32;
1460 if snippet.trim() == ":" {
1462 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1463 let mut show_label = true;
1464 if sm.is_multiline(sp) {
1465 err.span_suggestion_short(
1467 "maybe you meant to write `;` here",
1469 Applicability::MaybeIncorrect,
1472 let after_colon_sp =
1473 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1474 if snippet.len() == 1 {
1476 err.span_suggestion(
1478 "maybe you meant to write a path separator here",
1480 Applicability::MaybeIncorrect,
1487 .type_ascription_path_suggestions
1491 err.downgrade_to_delayed_bug();
1494 if let Ok(base_snippet) = base_snippet {
1495 let mut sp = after_colon_sp;
1497 // Try to find an assignment
1498 sp = sm.next_point(sp);
1499 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1501 Ok(ref x) if x.as_str() == "=" => {
1502 err.span_suggestion(
1504 "maybe you meant to write an assignment here",
1505 format!("let {}", base_snippet),
1506 Applicability::MaybeIncorrect,
1511 Ok(ref x) if x.as_str() == "\n" => break,
1521 "expecting a type here because of type ascription",
1531 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1532 let mut result = None;
1533 let mut seen_modules = FxHashSet::default();
1534 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1536 while let Some((in_module, path_segments)) = worklist.pop() {
1537 // abort if the module is already found
1538 if result.is_some() {
1542 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1543 // abort if the module is already found or if name_binding is private external
1544 if result.is_some() || !name_binding.vis.is_visible_locally() {
1547 if let Some(module) = name_binding.module() {
1549 let mut path_segments = path_segments.clone();
1550 path_segments.push(ast::PathSegment::from_ident(ident));
1551 let module_def_id = module.def_id();
1552 if module_def_id == def_id {
1554 Path { span: name_binding.span, segments: path_segments, tokens: None };
1566 // add the module to the lookup
1567 if seen_modules.insert(module_def_id) {
1568 worklist.push((module, path_segments));
1578 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1579 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1580 let mut variants = Vec::new();
1581 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1582 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1583 let mut segms = enum_import_suggestion.path.segments.clone();
1584 segms.push(ast::PathSegment::from_ident(ident));
1585 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1586 variants.push((path, def_id, kind));
1593 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1594 fn suggest_using_enum_variant(
1596 err: &mut Diagnostic,
1597 source: PathSource<'_>,
1601 let Some(variants) = self.collect_enum_ctors(def_id) else {
1602 err.note("you might have meant to use one of the enum's variants");
1606 let suggest_only_tuple_variants =
1607 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1608 if suggest_only_tuple_variants {
1609 // Suggest only tuple variants regardless of whether they have fields and do not
1610 // suggest path with added parentheses.
1611 let suggestable_variants = variants
1613 .filter(|(.., kind)| *kind == CtorKind::Fn)
1614 .map(|(variant, ..)| path_names_to_string(variant))
1615 .collect::<Vec<_>>();
1617 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1619 let source_msg = if source.is_call() {
1621 } else if matches!(source, PathSource::TupleStruct(..)) {
1627 if !suggestable_variants.is_empty() {
1628 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1629 format!("try {} the enum's variant", source_msg)
1631 format!("try {} one of the enum's variants", source_msg)
1634 err.span_suggestions(
1637 suggestable_variants.into_iter(),
1638 Applicability::MaybeIncorrect,
1642 // If the enum has no tuple variants..
1643 if non_suggestable_variant_count == variants.len() {
1644 err.help(&format!("the enum has no tuple variants {}", source_msg));
1647 // If there are also non-tuple variants..
1648 if non_suggestable_variant_count == 1 {
1650 "you might have meant {} the enum's non-tuple variant",
1653 } else if non_suggestable_variant_count >= 1 {
1655 "you might have meant {} one of the enum's non-tuple variants",
1660 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1661 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1663 CtorKind::Const => false,
1664 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1669 let mut suggestable_variants = variants
1671 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1672 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1673 .map(|(variant, kind)| match kind {
1674 CtorKind::Const => variant,
1675 CtorKind::Fn => format!("({}())", variant),
1676 CtorKind::Fictive => format!("({} {{}})", variant),
1678 .collect::<Vec<_>>();
1680 if !suggestable_variants.is_empty() {
1681 let msg = if suggestable_variants.len() == 1 {
1682 "you might have meant to use the following enum variant"
1684 "you might have meant to use one of the following enum variants"
1687 err.span_suggestions(
1690 suggestable_variants.drain(..),
1691 Applicability::MaybeIncorrect,
1695 let suggestable_variants_with_placeholders = variants
1697 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1698 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1699 .filter_map(|(variant, kind)| match kind {
1700 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1701 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1704 .collect::<Vec<_>>();
1706 if !suggestable_variants_with_placeholders.is_empty() {
1708 suggestable_variants.is_empty(),
1709 suggestable_variants_with_placeholders.len(),
1711 (true, 1) => "the following enum variant is available",
1712 (true, _) => "the following enum variants are available",
1713 (false, 1) => "alternatively, the following enum variant is available",
1714 (false, _) => "alternatively, the following enum variants are also available",
1717 err.span_suggestions(
1720 suggestable_variants_with_placeholders.into_iter(),
1721 Applicability::HasPlaceholders,
1726 if def_id.is_local() {
1727 if let Some(span) = self.def_span(def_id) {
1728 err.span_note(span, "the enum is defined here");
1733 pub(crate) fn report_missing_type_error(
1736 ) -> Option<(Span, &'static str, String, Applicability)> {
1737 let (ident, span) = match path {
1738 [segment] if !segment.has_generic_args => {
1739 (segment.ident.to_string(), segment.ident.span)
1743 let mut iter = ident.chars().map(|c| c.is_uppercase());
1744 let single_uppercase_char =
1745 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1746 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1749 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1750 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1751 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1756 kind @ ItemKind::Fn(..)
1757 | kind @ ItemKind::Enum(..)
1758 | kind @ ItemKind::Struct(..)
1759 | kind @ ItemKind::Union(..),
1764 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1765 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1766 | (Some(Item { kind, .. }), false, _) => {
1767 // Likely missing type parameter.
1768 if let Some(generics) = kind.generics() {
1769 if span.overlaps(generics.span) {
1770 // Avoid the following:
1771 // error[E0405]: cannot find trait `A` in this scope
1772 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1774 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1775 // | ^- help: you might be missing a type parameter: `, A`
1777 // | not found in this scope
1780 let msg = "you might be missing a type parameter";
1781 let (span, sugg) = if let [.., param] = &generics.params[..] {
1782 let span = if let [.., bound] = ¶m.bounds[..] {
1784 } else if let GenericParam {
1785 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1787 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1791 (span, format!(", {}", ident))
1793 (generics.span, format!("<{}>", ident))
1795 // Do not suggest if this is coming from macro expansion.
1796 if span.can_be_used_for_suggestions() {
1798 span.shrink_to_hi(),
1801 Applicability::MaybeIncorrect,
1811 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1812 /// optionally returning the closest match and whether it is reachable.
1813 pub(crate) fn suggestion_for_label_in_rib(
1817 ) -> Option<LabelSuggestion> {
1818 // Are ribs from this `rib_index` within scope?
1819 let within_scope = self.is_label_valid_from_rib(rib_index);
1821 let rib = &self.label_ribs[rib_index];
1825 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1826 .map(|(id, _)| id.name)
1827 .collect::<Vec<Symbol>>();
1829 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1830 // Upon finding a similar name, get the ident that it was from - the span
1831 // contained within helps make a useful diagnostic. In addition, determine
1832 // whether this candidate is within scope.
1833 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1834 (*ident, within_scope)
1838 pub(crate) fn maybe_report_lifetime_uses(
1840 generics_span: Span,
1841 params: &[ast::GenericParam],
1843 for (param_index, param) in params.iter().enumerate() {
1844 let GenericParamKind::Lifetime = param.kind else { continue };
1846 let def_id = self.r.local_def_id(param.id);
1848 let use_set = self.lifetime_uses.remove(&def_id);
1850 "Use set for {:?}({:?} at {:?}) is {:?}",
1851 def_id, param.ident, param.ident.span, use_set
1854 let deletion_span = || {
1855 if params.len() == 1 {
1856 // if sole lifetime, remove the entire `<>` brackets
1858 } else if param_index == 0 {
1859 // if removing within `<>` brackets, we also want to
1860 // delete a leading or trailing comma as appropriate
1861 param.span().to(params[param_index + 1].span().shrink_to_lo())
1863 // if removing within `<>` brackets, we also want to
1864 // delete a leading or trailing comma as appropriate
1865 params[param_index - 1].span().shrink_to_hi().to(param.span())
1869 Some(LifetimeUseSet::Many) => {}
1870 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1871 debug!(?param.ident, ?param.ident.span, ?use_span);
1873 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1875 let deletion_span = deletion_span();
1876 self.r.lint_buffer.buffer_lint_with_diagnostic(
1877 lint::builtin::SINGLE_USE_LIFETIMES,
1880 &format!("lifetime parameter `{}` only used once", param.ident),
1881 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1882 param_span: param.ident.span,
1883 use_span: Some((use_span, elidable)),
1889 debug!(?param.ident, ?param.ident.span);
1891 let deletion_span = deletion_span();
1892 self.r.lint_buffer.buffer_lint_with_diagnostic(
1893 lint::builtin::UNUSED_LIFETIMES,
1896 &format!("lifetime parameter `{}` never used", param.ident),
1897 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1898 param_span: param.ident.span,
1908 pub(crate) fn emit_undeclared_lifetime_error(
1910 lifetime_ref: &ast::Lifetime,
1911 outer_lifetime_ref: Option<Ident>,
1913 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1914 let mut err = if let Some(outer) = outer_lifetime_ref {
1915 let mut err = struct_span_err!(
1917 lifetime_ref.ident.span,
1919 "can't use generic parameters from outer item",
1921 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1922 err.span_label(outer.span, "lifetime parameter from outer item");
1925 let mut err = struct_span_err!(
1927 lifetime_ref.ident.span,
1929 "use of undeclared lifetime name `{}`",
1932 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
1935 let mut suggest_note = true;
1937 for rib in self.lifetime_ribs.iter().rev() {
1939 LifetimeRibKind::Generics { binder: _, span, kind } => {
1940 if !span.can_be_used_for_suggestions() && suggest_note {
1941 suggest_note = false; // Avoid displaying the same help multiple times.
1945 "lifetime `{}` is missing in item created through this procedural macro",
1952 let higher_ranked = matches!(
1954 LifetimeBinderKind::BareFnType
1955 | LifetimeBinderKind::PolyTrait
1956 | LifetimeBinderKind::WhereBound
1958 let (span, sugg) = if span.is_empty() {
1961 if higher_ranked { "for" } else { "" },
1963 if higher_ranked { " " } else { "" },
1968 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
1969 let sugg = format!("{}, ", lifetime_ref.ident);
1973 err.span_suggestion(
1976 "consider making the {} lifetime-generic with a new `{}` lifetime",
1981 Applicability::MaybeIncorrect,
1984 "for more information on higher-ranked polymorphism, visit \
1985 https://doc.rust-lang.org/nomicon/hrtb.html",
1988 err.span_suggestion(
1990 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
1992 Applicability::MaybeIncorrect,
1996 LifetimeRibKind::Item => break,
2004 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2007 lifetime_ref.ident.span,
2009 "use of non-static lifetime `{}` in const generic",
2013 "for more information, see issue #74052 \
2014 <https://github.com/rust-lang/rust/issues/74052>",
2019 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2020 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2021 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2022 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2024 lifetime_ref: &ast::Lifetime,
2026 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2027 if !feature_active {
2029 &self.r.session.parse_sess,
2030 sym::generic_const_exprs,
2031 lifetime_ref.ident.span,
2032 "a non-static lifetime is not allowed in a `const`",
2039 impl<'tcx> LifetimeContext<'_, 'tcx> {
2040 pub(crate) fn report_missing_lifetime_specifiers(
2044 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2049 "missing lifetime specifier{}",
2054 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
2055 pub(crate) fn report_elision_failure(
2057 diag: &mut Diagnostic,
2058 params: &[ElisionFailureInfo],
2060 let mut m = String::new();
2061 let len = params.len();
2063 let elided_params: Vec<_> =
2064 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2066 let elided_len = elided_params.len();
2068 for (i, info) in elided_params.into_iter().enumerate() {
2069 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2072 diag.span_label(span, "");
2073 let help_name = if let Some(ident) =
2074 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2076 format!("`{}`", ident)
2078 format!("argument {}", index + 1)
2086 "one of {}'s {} {}lifetimes",
2089 if have_bound_regions { "free " } else { "" }
2094 if elided_len == 2 && i == 0 {
2096 } else if i + 2 == elided_len {
2097 m.push_str(", or ");
2098 } else if i != elided_len - 1 {
2105 "this function's return type contains a borrowed value, \
2106 but there is no value for it to be borrowed from",
2109 } else if elided_len == 0 {
2111 "this function's return type contains a borrowed value with \
2112 an elided lifetime, but the lifetime cannot be derived from \
2116 } else if elided_len == 1 {
2118 "this function's return type contains a borrowed value, \
2119 but the signature does not say which {} it is borrowed from",
2125 "this function's return type contains a borrowed value, \
2126 but the signature does not say whether it is borrowed from {}",
2133 pub(crate) fn is_trait_ref_fn_scope(
2135 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
2137 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2139 self.tcx.lang_items().fn_once_trait(),
2140 self.tcx.lang_items().fn_trait(),
2141 self.tcx.lang_items().fn_mut_trait(),
2143 .contains(&Some(did))
2145 let (span, span_type) = match &trait_ref.bound_generic_params {
2146 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2147 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2149 self.missing_named_lifetime_spots
2150 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2157 pub(crate) fn add_missing_lifetime_specifiers_label(
2159 err: &mut Diagnostic,
2160 mut spans_with_counts: Vec<(Span, usize)>,
2161 lifetime_names: &FxHashSet<Symbol>,
2162 lifetime_spans: Vec<Span>,
2163 params: &[ElisionFailureInfo],
2165 let snippets: Vec<Option<String>> = spans_with_counts
2167 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2170 // Empty generics are marked with a span of "<", but since from now on
2171 // that information is in the snippets it can be removed from the spans.
2172 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2173 if snippet.as_deref() == Some("<") {
2174 *span = span.shrink_to_hi();
2178 for &(span, count) in &spans_with_counts {
2182 "expected {} lifetime parameter{}",
2183 if count == 1 { "named".to_string() } else { count.to_string() },
2189 let suggest_existing =
2190 |err: &mut Diagnostic,
2192 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2193 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2194 self.missing_named_lifetime_spots.iter().rev().next()
2196 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2197 // using `'a`, but also introduce the concept of HRLTs by suggesting
2198 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2199 let mut introduce_suggestion = vec![];
2201 let a_to_z_repeat_n = |n| {
2202 (b'a'..=b'z').map(move |c| {
2203 let mut s = '\''.to_string();
2204 s.extend(std::iter::repeat(char::from(c)).take(n));
2209 // If all single char lifetime names are present, we wrap around and double the chars.
2211 .flat_map(a_to_z_repeat_n)
2212 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2215 "consider making the {} lifetime-generic with a new `{}` lifetime",
2220 "for more information on higher-ranked polymorphism, visit \
2221 https://doc.rust-lang.org/nomicon/hrtb.html",
2223 let for_sugg = span_type.suggestion(<_name);
2224 for param in params {
2225 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2227 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2228 introduce_suggestion
2229 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2230 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2231 introduce_suggestion
2232 .push((param.span, format!("&{} {}", lt_name, stripped)));
2236 introduce_suggestion.push((*for_span, for_sugg));
2237 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2238 if let Some(formatter) = formatter {
2239 introduce_suggestion.push((*span, formatter(<_name)));
2242 err.multipart_suggestion_verbose(
2244 introduce_suggestion,
2245 Applicability::MaybeIncorrect,
2249 let spans_suggs: Vec<_> = formatters
2251 .zip(spans_with_counts.iter())
2252 .filter_map(|(formatter, (span, _))| {
2253 if let Some(formatter) = formatter {
2254 Some((*span, formatter(name)))
2260 if spans_suggs.is_empty() {
2261 // If all the spans come from macros, we cannot extract snippets and then
2262 // `formatters` only contains None and `spans_suggs` is empty.
2265 err.multipart_suggestion_verbose(
2267 "consider using the `{}` lifetime",
2268 lifetime_names.iter().next().unwrap()
2271 Applicability::MaybeIncorrect,
2274 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2275 for missing in self.missing_named_lifetime_spots.iter().rev() {
2276 let mut introduce_suggestion = vec![];
2279 introduce_suggestion.push(match missing {
2280 MissingLifetimeSpot::Generics(generics) => {
2281 if generics.span == DUMMY_SP {
2282 // Account for malformed generics in the HIR. This shouldn't happen,
2283 // but if we make a mistake elsewhere, mainly by keeping something in
2284 // `missing_named_lifetime_spots` that we shouldn't, like associated
2285 // `const`s or making a mistake in the AST lowering we would provide
2286 // nonsensical suggestions. Guard against that by skipping these.
2290 msg = "consider introducing a named lifetime parameter".to_string();
2291 should_break = true;
2292 if let Some(param) = generics.params.iter().find(|p| {
2295 hir::GenericParamKind::Type { synthetic: true, .. }
2296 | hir::GenericParamKind::Lifetime {
2297 kind: hir::LifetimeParamKind::Elided
2301 (param.span.shrink_to_lo(), "'a, ".to_string())
2303 (generics.span, "<'a>".to_string())
2306 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2308 "consider making the {} lifetime-generic with a new `'a` lifetime",
2311 should_break = false;
2313 "for more information on higher-ranked polymorphism, visit \
2314 https://doc.rust-lang.org/nomicon/hrtb.html",
2316 (*span, span_type.suggestion("'a"))
2318 MissingLifetimeSpot::Static => {
2319 let mut spans_suggs = Vec::new();
2320 for ((span, count), snippet) in
2321 spans_with_counts.iter().copied().zip(snippets.iter())
2323 let (span, sugg) = match snippet.as_deref() {
2324 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2325 Some("'_") => (span, "'static".to_owned()),
2326 Some(snippet) if !snippet.ends_with('>') => {
2330 std::iter::repeat("'static")
2332 .collect::<Vec<_>>()
2335 } else if snippet == "<" || snippet == "(" {
2337 span.shrink_to_hi(),
2338 std::iter::repeat("'static")
2340 .collect::<Vec<_>>()
2345 span.shrink_to_hi(),
2348 std::iter::repeat("'static")
2350 .collect::<Vec<_>>()
2358 spans_suggs.push((span, sugg.to_string()));
2360 err.multipart_suggestion_verbose(
2361 "consider using the `'static` lifetime",
2363 Applicability::MaybeIncorrect,
2369 struct Lifetime(Span, String);
2371 fn is_unnamed(&self) -> bool {
2372 self.1.starts_with('&') && !self.1.starts_with("&'")
2374 fn is_underscore(&self) -> bool {
2375 self.1.starts_with("&'_ ")
2377 fn is_named(&self) -> bool {
2378 self.1.starts_with("&'")
2380 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2384 self.is_underscore(),
2386 sugg.starts_with('&'),
2388 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2389 (true, _, _, true) => {
2390 (self.span_unnamed_borrow(), sugg[1..].to_string())
2392 (_, true, _, false) => {
2393 (self.span_underscore_borrow(), sugg.trim().to_string())
2395 (_, true, _, true) => {
2396 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2398 (_, _, true, false) => {
2399 (self.span_named_borrow(), sugg.trim().to_string())
2401 (_, _, true, true) => {
2402 (self.span_named_borrow(), sugg[1..].trim().to_string())
2408 fn span_unnamed_borrow(&self) -> Span {
2409 let lo = self.0.lo() + BytePos(1);
2410 self.0.with_lo(lo).with_hi(lo)
2412 fn span_named_borrow(&self) -> Span {
2413 let lo = self.0.lo() + BytePos(1);
2416 fn span_underscore_borrow(&self) -> Span {
2417 let lo = self.0.lo() + BytePos(1);
2418 let hi = lo + BytePos(2);
2419 self.0.with_lo(lo).with_hi(hi)
2423 for param in params {
2424 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2425 if let Some((span, sugg)) =
2426 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2428 introduce_suggestion.push((span, sugg));
2432 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2433 |((span, _), sugg)| match &sugg {
2434 Some(sugg) => Some((span, sugg.to_string())),
2438 let (span, sugg) = self
2442 .span_to_snippet(span)
2444 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2445 .unwrap_or((span, sugg));
2446 introduce_suggestion.push((span, sugg.to_string()));
2448 err.multipart_suggestion_verbose(
2450 introduce_suggestion,
2451 Applicability::MaybeIncorrect,
2459 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2460 match &lifetime_names[..] {
2462 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2463 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2465 suggs.push(match snippet.as_deref() {
2466 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2467 Some("'_") => Some(Box::new(|n| n.to_string())),
2468 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2469 Some("<") => Some(Box::new(move |n| {
2470 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2472 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2476 std::iter::repeat(name.to_string())
2478 .collect::<Vec<_>>()
2485 suggest_existing(err, name.as_str(), suggs);
2488 let mut suggs = Vec::new();
2489 for (snippet, (_, count)) in
2490 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2492 suggs.push(match snippet.as_deref() {
2493 Some("&") => Some("&'a ".to_string()),
2494 Some("'_") => Some("'a".to_string()),
2496 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2499 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2501 Some(snippet) => Some(format!(
2504 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2509 suggest_new(err, suggs);
2511 lts if lts.len() > 1 => {
2512 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2514 let mut spans_suggs: Vec<_> = Vec::new();
2515 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2516 match snippet.as_deref() {
2517 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2518 Some("&") => spans_suggs
2519 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2524 if spans_suggs.len() > 0 {
2525 // This happens when we have `Foo<T>` where we point at the space before `T`,
2526 // but this can be confusing so we give a suggestion with placeholders.
2527 err.multipart_suggestion_verbose(
2528 "consider using one of the available lifetimes here",
2530 Applicability::HasPlaceholders,
2534 _ => unreachable!(),