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_session::Session;
29 use rustc_span::edition::Edition;
30 use rustc_span::hygiene::MacroKind;
31 use rustc_span::lev_distance::find_best_match_for_name;
32 use rustc_span::symbol::{kw, sym, Ident, Symbol};
33 use rustc_span::{BytePos, Span, DUMMY_SP};
40 type Res = def::Res<ast::NodeId>;
42 /// A field or associated item from self type suggested in case of resolution failure.
43 enum AssocSuggestion {
51 impl AssocSuggestion {
52 fn action(&self) -> &'static str {
54 AssocSuggestion::Field => "use the available field",
55 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
56 AssocSuggestion::AssocFn => "call the associated function",
57 AssocSuggestion::AssocConst => "use the associated `const`",
58 AssocSuggestion::AssocType => "use the associated type",
63 pub(crate) enum MissingLifetimeSpot<'tcx> {
64 Generics(&'tcx hir::Generics<'tcx>),
65 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
69 pub(crate) enum ForLifetimeSpanType {
76 impl ForLifetimeSpanType {
77 pub(crate) fn descr(&self) -> &'static str {
79 Self::BoundEmpty | Self::BoundTail => "bound",
80 Self::TypeEmpty | Self::TypeTail => "type",
84 pub(crate) fn suggestion(&self, sugg: &str) -> String {
86 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
87 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
92 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &&'tcx hir::Generics<'tcx> {
93 fn into(self) -> MissingLifetimeSpot<'tcx> {
94 MissingLifetimeSpot::Generics(self)
98 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
99 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
102 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
103 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
106 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
107 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
108 let variant_path = &suggestion.path;
109 let variant_path_string = path_names_to_string(variant_path);
111 let path_len = suggestion.path.segments.len();
112 let enum_path = ast::Path {
113 span: suggestion.path.span,
114 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
117 let enum_path_string = path_names_to_string(&enum_path);
119 (variant_path_string, enum_path_string)
122 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
123 fn def_span(&self, def_id: DefId) -> Option<Span> {
125 LOCAL_CRATE => self.r.opt_span(def_id),
130 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
135 /// Handles error reporting for `smart_resolve_path_fragment` function.
136 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
137 pub(crate) fn smart_resolve_report_errors(
141 source: PathSource<'_>,
143 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
144 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
145 let ns = source.namespace();
146 let is_expected = &|res| source.is_expected(res);
147 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
149 // Make the base error.
150 struct BaseError<'a> {
152 fallback_label: String,
155 suggestion: Option<(Span, &'a str, String)>,
157 let mut expected = source.descr_expected();
158 let path_str = Segment::names_to_string(path);
159 let item_str = path.last().unwrap().ident;
160 let base_error = if let Some(res) = res {
162 msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
163 fallback_label: format!("not a {expected}"),
165 could_be_expr: match res {
166 Res::Def(DefKind::Fn, _) => {
167 // Verify whether this is a fn call or an Fn used as a type.
171 .span_to_snippet(span)
172 .map(|snippet| snippet.ends_with(')'))
176 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
181 | Res::Local(_) => true,
187 let item_span = path.last().unwrap().ident.span;
188 let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
189 debug!(?self.diagnostic_metadata.current_impl_items);
190 debug!(?self.diagnostic_metadata.current_function);
191 let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
192 && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
193 && self.current_trait_ref.is_none()
194 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
195 && let Some(item) = items.iter().find(|i| {
196 if let AssocItemKind::Fn(fn_) = &i.kind
197 && !fn_.sig.decl.has_self()
198 && i.ident.name == item_str.name
200 debug!(?item_str.name);
201 debug!(?fn_.sig.decl.inputs);
209 "consider using the associated function",
210 format!("Self::{}", item.ident)
215 (String::new(), "this scope".to_string(), suggestion)
216 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
217 if self.r.session.edition() > Edition::Edition2015 {
218 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
219 // which overrides all other expectations of item type
221 (String::new(), "the list of imported crates".to_string(), None)
223 (String::new(), "the crate root".to_string(), None)
225 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
226 (String::new(), "the crate root".to_string(), None)
228 let mod_path = &path[..path.len() - 1];
229 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
230 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
233 .map_or_else(String::new, |res| format!("{} ", res.descr()));
234 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
237 msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
238 fallback_label: if path_str == "async" && expected.starts_with("struct") {
239 "`async` blocks are only allowed in Rust 2018 or later".to_string()
241 format!("not found in {mod_str}")
244 could_be_expr: false,
249 let code = source.error_code(res.is_some());
251 self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
253 if let Some(sugg) = base_error.suggestion {
254 err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
257 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
258 err.multipart_suggestion(
259 "you might have meant to write a `struct` literal",
261 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
262 (span.shrink_to_hi(), "}".to_string()),
264 Applicability::HasPlaceholders,
267 match (source, self.diagnostic_metadata.in_if_condition) {
268 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
269 err.span_suggestion_verbose(
271 "you might have meant to use pattern matching",
273 Applicability::MaybeIncorrect,
279 let is_assoc_fn = self.self_type_is_available();
280 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
281 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
282 err.span_suggestion_short(
284 "you might have meant to use `self` here instead",
286 Applicability::MaybeIncorrect,
288 if !self.self_value_is_available(path[0].ident.span) {
289 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
290 &self.diagnostic_metadata.current_function
292 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
293 (param.span.shrink_to_lo(), "&self, ")
299 .span_through_char(*fn_span, '(')
304 err.span_suggestion_verbose(
306 "if you meant to use `self`, you are also missing a `self` receiver \
309 Applicability::MaybeIncorrect,
315 self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
317 // Emit special messages for unresolved `Self` and `self`.
318 if is_self_type(path, ns) {
319 err.code(rustc_errors::error_code!(E0411));
322 "`Self` is only available in impls, traits, and type definitions".to_string(),
324 return (err, Vec::new());
326 if is_self_value(path, ns) {
327 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
329 err.code(rustc_errors::error_code!(E0424));
330 err.span_label(span, match source {
331 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
333 _ => "`self` value is a keyword only available in methods with a `self` parameter"
336 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
337 // The current function has a `self' parameter, but we were unable to resolve
338 // a reference to `self`. This can only happen if the `self` identifier we
339 // are resolving came from a different hygiene context.
340 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
341 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
343 let doesnt = if is_assoc_fn {
344 let (span, sugg) = fn_kind
348 .map(|p| (p.span.shrink_to_lo(), "&self, "))
350 // Try to look for the "(" after the function name, if possible.
351 // This avoids placing the suggestion into the visibility specifier.
354 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
359 .span_through_char(span, '(')
364 err.span_suggestion_verbose(
366 "add a `self` receiver parameter to make the associated `fn` a method",
368 Applicability::MaybeIncorrect,
374 if let Some(ident) = fn_kind.ident() {
377 &format!("this function {} have a `self` parameter", doesnt),
382 return (err, Vec::new());
385 // Try to lookup name in more relaxed fashion for better error reporting.
386 let ident = path.last().unwrap().ident;
387 let candidates = self
389 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
391 .filter(|ImportSuggestion { did, .. }| {
392 match (did, res.and_then(|res| res.opt_def_id())) {
393 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
397 .collect::<Vec<_>>();
398 let crate_def_id = CRATE_DEF_ID.to_def_id();
399 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
400 let mut enum_candidates: Vec<_> = self
402 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
404 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
405 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
407 if !enum_candidates.is_empty() {
408 if let (PathSource::Type, Some(span)) =
409 (source, self.diagnostic_metadata.current_type_ascription.last())
415 .type_ascription_path_suggestions
419 // Already reported this issue on the lhs of the type ascription.
421 return (err, candidates);
425 enum_candidates.sort();
427 // Contextualize for E0412 "cannot find type", but don't belabor the point
428 // (that it's a variant) for E0573 "expected type, found variant".
429 let preamble = if res.is_none() {
430 let others = match enum_candidates.len() {
432 2 => " and 1 other".to_owned(),
433 n => format!(" and {} others", n),
435 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
439 let msg = format!("{}try using the variant's enum", preamble);
441 err.span_suggestions(
444 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
445 Applicability::MachineApplicable,
449 // Try Levenshtein algorithm.
450 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
451 if path.len() == 1 && self.self_type_is_available() {
452 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
453 let self_is_available = self.self_value_is_available(path[0].ident.span);
455 AssocSuggestion::Field => {
456 if self_is_available {
459 "you might have meant to use the available field",
460 format!("self.{path_str}"),
461 Applicability::MachineApplicable,
464 err.span_label(span, "a field by this name exists in `Self`");
467 AssocSuggestion::MethodWithSelf if self_is_available => {
470 "you might have meant to call the method",
471 format!("self.{path_str}"),
472 Applicability::MachineApplicable,
475 AssocSuggestion::MethodWithSelf
476 | AssocSuggestion::AssocFn
477 | AssocSuggestion::AssocConst
478 | AssocSuggestion::AssocType => {
481 &format!("you might have meant to {}", candidate.action()),
482 format!("Self::{path_str}"),
483 Applicability::MachineApplicable,
487 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
488 return (err, candidates);
491 // If the first argument in call is `self` suggest calling a method.
492 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
493 let mut args_snippet = String::new();
494 if let Some(args_span) = args_span {
495 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
496 args_snippet = snippet;
502 &format!("try calling `{ident}` as a method"),
503 format!("self.{path_str}({args_snippet})"),
504 Applicability::MachineApplicable,
506 return (err, candidates);
510 // Try context-dependent help if relaxed lookup didn't work.
511 if let Some(res) = res {
512 if self.smart_resolve_context_dependent_help(
518 &base_error.fallback_label,
520 // We do this to avoid losing a secondary span when we override the main error span.
521 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
522 return (err, candidates);
527 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
528 if !self.type_ascription_suggestion(&mut err, base_error.span) {
529 let mut fallback = false;
531 PathSource::Trait(AliasPossibility::Maybe),
532 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
534 ) = (source, res, is_macro)
536 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
538 let spans: Vec<Span> = bounds
540 .map(|bound| bound.span())
541 .filter(|&sp| sp != base_error.span)
544 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
545 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
546 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
547 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
548 let last_bound_span = spans.last().cloned().unwrap();
549 let mut multi_span: MultiSpan = spans.clone().into();
551 let msg = if sp == last_bound_span {
553 "...because of {these} bound{s}",
554 these = pluralize!("this", bounds.len() - 1),
555 s = pluralize!(bounds.len() - 1),
560 multi_span.push_span_label(sp, msg);
562 multi_span.push_span_label(
564 "expected this type to be a trait...".to_string(),
568 "`+` is used to constrain a \"trait object\" type with lifetimes or \
569 auto-traits; structs and enums can't be bound in that way",
571 if bounds.iter().all(|bound| match bound {
572 ast::GenericBound::Outlives(_) => true,
573 ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
575 let mut sugg = vec![];
576 if base_error.span != start_span {
577 sugg.push((start_span.until(base_error.span), String::new()));
579 if base_error.span != end_span {
580 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
583 err.multipart_suggestion(
584 "if you meant to use a type and not a trait here, remove the bounds",
586 Applicability::MaybeIncorrect,
592 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
594 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
596 match self.diagnostic_metadata.current_let_binding {
597 Some((pat_sp, Some(ty_sp), None))
598 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
600 err.span_suggestion_short(
601 pat_sp.between(ty_sp),
602 "use `=` if you meant to assign",
604 Applicability::MaybeIncorrect,
610 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
611 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
612 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
616 err.span_label(base_error.span, base_error.fallback_label);
619 if let Some(err_code) = &err.code {
620 if err_code == &rustc_errors::error_code!(E0425) {
621 for label_rib in &self.label_ribs {
622 for (label_ident, node_id) in &label_rib.bindings {
623 if format!("'{}", ident) == label_ident.to_string() {
624 err.span_label(label_ident.span, "a label with a similar name exists");
625 if let PathSource::Expr(Some(Expr {
626 kind: ExprKind::Break(None, Some(_)),
632 "use the similarly named label",
633 label_ident.name.to_string(),
634 Applicability::MaybeIncorrect,
636 // Do not lint against unused label when we suggest them.
637 self.diagnostic_metadata.unused_labels.remove(node_id);
642 } else if err_code == &rustc_errors::error_code!(E0412) {
643 if let Some(correct) = Self::likely_rust_type(path) {
646 "perhaps you intended to use this type",
648 Applicability::MaybeIncorrect,
657 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
658 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
659 let TyKind::Path(_, path) = &ty.kind else { return; };
660 for segment in &path.segments {
661 let Some(params) = &segment.args else { continue; };
662 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
663 for param in ¶ms.args {
664 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
665 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
668 for bound in bounds {
669 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
674 if base_span == trait_ref.span {
675 err.span_suggestion_verbose(
676 constraint.ident.span.between(trait_ref.span),
677 "you might have meant to write a path instead of an associated type bound",
679 Applicability::MachineApplicable,
687 fn get_single_associated_item(
690 source: &PathSource<'_>,
691 filter_fn: &impl Fn(Res) -> bool,
692 ) -> Option<TypoSuggestion> {
693 if let crate::PathSource::TraitItem(_) = source {
694 let mod_path = &path[..path.len() - 1];
695 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
696 self.resolve_path(mod_path, None, None)
698 let resolutions = self.r.resolutions(module).borrow();
699 let targets: Vec<_> =
702 .filter_map(|(key, resolution)| {
703 resolution.borrow().binding.map(|binding| binding.res()).and_then(
704 |res| if filter_fn(res) { Some((key, res)) } else { None },
708 if targets.len() == 1 {
709 let target = targets[0];
710 return Some(TypoSuggestion::single_item_from_res(
720 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
721 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
722 // Detect that we are actually in a `where` predicate.
723 let (bounded_ty, bounds, where_span) =
724 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
726 bound_generic_params,
729 })) = self.diagnostic_metadata.current_where_predicate
731 if !bound_generic_params.is_empty() {
734 (bounded_ty, bounds, span)
739 // Confirm that the target is an associated type.
740 let (ty, position, path) = if let ast::TyKind::Path(
741 Some(ast::QSelf { ty, position, .. }),
745 // use this to verify that ident is a type param.
746 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
750 partial_res.base_res(),
751 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
752 ) && partial_res.unresolved_segments() == 0)
761 let peeled_ty = ty.peel_refs();
762 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
763 // Confirm that the `SelfTy` is a type parameter.
764 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
768 partial_res.base_res(),
769 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
770 ) && partial_res.unresolved_segments() == 0)
775 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
776 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
777 ) = (&type_param_path.segments[..], &bounds[..])
779 if let [ast::PathSegment { ident, args: None, .. }] =
780 &poly_trait_ref.trait_ref.path.segments[..]
782 if ident.span == span {
783 err.span_suggestion_verbose(
785 &format!("constrain the associated type to `{}`", ident),
791 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
792 .unwrap_or_else(|_| constrain_ident.to_string()),
793 path.segments[..*position]
795 .map(|segment| path_segment_to_string(segment))
798 path.segments[*position..]
800 .map(|segment| path_segment_to_string(segment))
805 Applicability::MaybeIncorrect,
815 /// Check if the source is call expression and the first argument is `self`. If true,
816 /// return the span of whole call and the span for all arguments expect the first one (`self`).
817 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
818 let mut has_self_arg = None;
819 if let PathSource::Expr(Some(parent)) = source {
821 ExprKind::Call(_, args) if !args.is_empty() => {
822 let mut expr_kind = &args[0].kind;
825 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
826 if arg_name.segments[0].ident.name == kw::SelfLower {
827 let call_span = parent.span;
828 let tail_args_span = if args.len() > 1 {
831 args.last().unwrap().span.hi(),
838 has_self_arg = Some((call_span, tail_args_span));
842 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
853 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
854 // HACK(estebank): find a better way to figure out that this was a
855 // parser issue where a struct literal is being used on an expression
856 // where a brace being opened means a block is being started. Look
857 // ahead for the next text to see if `span` is followed by a `{`.
858 let sm = self.r.session.source_map();
861 sp = sm.next_point(sp);
862 match sm.span_to_snippet(sp) {
864 if snippet.chars().any(|c| !c.is_whitespace()) {
871 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
872 // In case this could be a struct literal that needs to be surrounded
873 // by parentheses, find the appropriate span.
875 let mut closing_brace = None;
877 sp = sm.next_point(sp);
878 match sm.span_to_snippet(sp) {
881 closing_brace = Some(span.to(sp));
888 // The bigger the span, the more likely we're incorrect --
889 // bound it to 100 chars long.
894 (followed_by_brace, closing_brace)
897 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
899 /// Returns `true` if able to provide context-dependent help.
900 fn smart_resolve_context_dependent_help(
902 err: &mut Diagnostic,
904 source: PathSource<'_>,
907 fallback_label: &str,
909 let ns = source.namespace();
910 let is_expected = &|res| source.is_expected(res);
912 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
913 ExprKind::Field(_, ident) => {
916 "use the path separator to refer to an item",
917 format!("{}::{}", path_str, ident),
918 Applicability::MaybeIncorrect,
922 ExprKind::MethodCall(ref segment, ..) => {
923 let span = expr.span.with_hi(segment.ident.span.hi());
926 "use the path separator to refer to an item",
927 format!("{}::{}", path_str, segment.ident),
928 Applicability::MaybeIncorrect,
935 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
937 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
938 | PathSource::TupleStruct(span, _) => {
939 // We want the main underline to cover the suggested code as well for
948 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
949 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
952 PathSource::Expr(Some(
953 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
954 )) if path_sep(err, &parent) => {}
960 | ExprKind::Binary(..)
961 | ExprKind::Unary(..)
963 | ExprKind::While(..)
964 | ExprKind::ForLoop(..)
965 | ExprKind::Match(..),
968 ) if followed_by_brace => {
969 if let Some(sp) = closing_brace {
970 err.span_label(span, fallback_label);
971 err.multipart_suggestion(
972 "surround the struct literal with parentheses",
974 (sp.shrink_to_lo(), "(".to_string()),
975 (sp.shrink_to_hi(), ")".to_string()),
977 Applicability::MaybeIncorrect,
981 span, // Note the parentheses surrounding the suggestion below
983 "you might want to surround a struct literal with parentheses: \
984 `({} {{ /* fields */ }})`?",
990 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
991 let span = find_span(&source, err);
992 if let Some(span) = self.def_span(def_id) {
993 err.span_label(span, &format!("`{}` defined here", path_str));
995 let (tail, descr, applicability) = match source {
996 PathSource::Pat | PathSource::TupleStruct(..) => {
997 ("", "pattern", Applicability::MachineApplicable)
999 _ => (": val", "literal", Applicability::HasPlaceholders),
1001 let (fields, applicability) = match self.r.field_names.get(&def_id) {
1005 .map(|f| format!("{}{}", f.node, tail))
1006 .collect::<Vec<String>>()
1010 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
1012 let pad = match self.r.field_names.get(&def_id) {
1013 Some(fields) if fields.is_empty() => "",
1016 err.span_suggestion(
1018 &format!("use struct {} syntax instead", descr),
1019 format!("{path_str} {{{pad}{fields}{pad}}}"),
1024 err.span_label(span, fallback_label);
1029 match (res, source) {
1031 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1032 PathSource::Expr(Some(Expr {
1033 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1035 | PathSource::Struct,
1037 err.span_label(span, fallback_label);
1038 err.span_suggestion_verbose(
1039 span.shrink_to_hi(),
1040 "use `!` to invoke the macro",
1042 Applicability::MaybeIncorrect,
1044 if path_str == "try" && span.rust_2015() {
1045 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1048 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1049 err.span_label(span, fallback_label);
1051 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1052 err.span_label(span, "type aliases cannot be used as traits");
1053 if self.r.session.is_nightly_build() {
1054 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1056 if let Some(span) = self.def_span(def_id) {
1057 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1058 // The span contains a type alias so we should be able to
1059 // replace `type` with `trait`.
1060 let snip = snip.replacen("type", "trait", 1);
1061 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1063 err.span_help(span, msg);
1070 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1071 if !path_sep(err, &parent) {
1076 Res::Def(DefKind::Enum, def_id),
1077 PathSource::TupleStruct(..) | PathSource::Expr(..),
1080 .diagnostic_metadata
1081 .current_type_ascription
1087 .type_ascription_path_suggestions
1093 err.downgrade_to_delayed_bug();
1094 // We already suggested changing `:` into `::` during parsing.
1098 self.suggest_using_enum_variant(err, source, def_id, span);
1100 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1101 let (ctor_def, ctor_vis, fields) =
1102 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1103 if let PathSource::Expr(Some(parent)) = source {
1104 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1105 bad_struct_syntax_suggestion(def_id);
1111 bad_struct_syntax_suggestion(def_id);
1115 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1116 if !is_expected(ctor_def) || is_accessible {
1120 let field_spans = match source {
1121 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1122 PathSource::TupleStruct(_, pattern_spans) => {
1123 err.set_primary_message(
1124 "cannot match against a tuple struct which contains private fields",
1127 // Use spans of the tuple struct pattern.
1128 Some(Vec::from(pattern_spans))
1130 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1131 _ if source.is_call() => {
1132 err.set_primary_message(
1133 "cannot initialize a tuple struct which contains private fields",
1136 // Use spans of the tuple struct definition.
1140 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1145 if let Some(spans) =
1146 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1148 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1149 .filter(|(vis, _)| {
1150 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1152 .map(|(_, span)| *span)
1155 if non_visible_spans.len() > 0 {
1156 let mut m: MultiSpan = non_visible_spans.clone().into();
1159 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1160 err.span_note(m, "constructor is not visible here due to private fields");
1168 "constructor is not visible here due to private fields".to_string(),
1173 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1177 ) if ns == ValueNS => {
1178 bad_struct_syntax_suggestion(def_id);
1180 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1182 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1183 let span = find_span(&source, err);
1184 if let Some(span) = self.def_span(def_id) {
1185 err.span_label(span, &format!("`{}` defined here", path_str));
1187 err.span_suggestion(
1189 "use this syntax instead",
1190 path_str.to_string(),
1191 Applicability::MaybeIncorrect,
1197 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1198 if let Some(span) = self.def_span(def_id) {
1199 err.span_label(span, &format!("`{}` defined here", path_str));
1201 let fields = self.r.field_names.get(&def_id).map_or_else(
1202 || "/* fields */".to_string(),
1203 |fields| vec!["_"; fields.len()].join(", "),
1205 err.span_suggestion(
1207 "use the tuple variant pattern syntax instead",
1208 format!("{}({})", path_str, fields),
1209 Applicability::HasPlaceholders,
1212 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1213 err.span_label(span, fallback_label);
1214 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1216 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1217 err.note("can't use a type alias as a constructor");
1224 /// Given the target `ident` and `kind`, search for the similarly named associated item
1225 /// in `self.current_trait_ref`.
1226 pub(crate) fn find_similarly_named_assoc_item(
1229 kind: &AssocItemKind,
1230 ) -> Option<Symbol> {
1231 let (module, _) = self.current_trait_ref.as_ref()?;
1232 if ident == kw::Underscore {
1233 // We do nothing for `_`.
1237 let resolutions = self.r.resolutions(module);
1238 let targets = resolutions
1241 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1242 .filter(|(_, res)| match (kind, res) {
1243 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1244 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1245 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1248 .map(|(key, _)| key.ident.name)
1249 .collect::<Vec<_>>();
1251 find_best_match_for_name(&targets, ident, None)
1254 fn lookup_assoc_candidate<FilterFn>(
1258 filter_fn: FilterFn,
1259 ) -> Option<AssocSuggestion>
1261 FilterFn: Fn(Res) -> bool,
1263 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1265 TyKind::Path(None, _) => Some(t.id),
1266 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1267 // This doesn't handle the remaining `Ty` variants as they are not
1268 // that commonly the self_type, it might be interesting to provide
1269 // support for those in future.
1274 // Fields are generally expected in the same contexts as locals.
1275 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1276 if let Some(node_id) =
1277 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1279 // Look for a field with the same name in the current self_type.
1280 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1281 match resolution.base_res() {
1282 Res::Def(DefKind::Struct | DefKind::Union, did)
1283 if resolution.unresolved_segments() == 0 =>
1285 if let Some(field_names) = self.r.field_names.get(&did) {
1288 .any(|&field_name| ident.name == field_name.node)
1290 return Some(AssocSuggestion::Field);
1300 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1301 for assoc_item in items {
1302 if assoc_item.ident == ident {
1303 return Some(match &assoc_item.kind {
1304 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1305 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1306 AssocSuggestion::MethodWithSelf
1308 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1309 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1310 ast::AssocItemKind::MacCall(_) => continue,
1316 // Look for associated items in the current trait.
1317 if let Some((module, _)) = self.current_trait_ref {
1318 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1319 ModuleOrUniformRoot::Module(module),
1324 let res = binding.res();
1326 if self.r.has_self.contains(&res.def_id()) {
1327 return Some(AssocSuggestion::MethodWithSelf);
1330 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1331 Res::Def(DefKind::AssocConst, _) => {
1332 return Some(AssocSuggestion::AssocConst);
1334 Res::Def(DefKind::AssocTy, _) => {
1335 return Some(AssocSuggestion::AssocType);
1347 fn lookup_typo_candidate(
1351 filter_fn: &impl Fn(Res) -> bool,
1352 ) -> Option<TypoSuggestion> {
1353 let mut names = Vec::new();
1354 if path.len() == 1 {
1355 // Search in lexical scope.
1356 // Walk backwards up the ribs in scope and collect candidates.
1357 for rib in self.ribs[ns].iter().rev() {
1358 // Locals and type parameters
1359 for (ident, &res) in &rib.bindings {
1361 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1365 if let RibKind::ModuleRibKind(module) = rib.kind {
1366 // Items from this module
1367 self.r.add_module_candidates(module, &mut names, &filter_fn);
1369 if let ModuleKind::Block(..) = module.kind {
1370 // We can see through blocks
1372 // Items from the prelude
1373 if !module.no_implicit_prelude {
1374 let extern_prelude = self.r.extern_prelude.clone();
1375 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1376 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1379 Res::Def(DefKind::Mod, crate_id.as_def_id());
1381 if filter_fn(crate_mod) {
1382 Some(TypoSuggestion::typo_from_res(
1383 ident.name, crate_mod,
1392 if let Some(prelude) = self.r.prelude {
1393 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1400 // Add primitive types to the mix
1401 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1402 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1403 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1407 // Search in module.
1408 let mod_path = &path[..path.len() - 1];
1409 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1410 self.resolve_path(mod_path, Some(TypeNS), None)
1412 self.r.add_module_candidates(module, &mut names, &filter_fn);
1416 let name = path[path.len() - 1].ident.name;
1417 // Make sure error reporting is deterministic.
1418 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1420 match find_best_match_for_name(
1421 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1425 Some(found) if found != name => {
1426 names.into_iter().find(|suggestion| suggestion.candidate == found)
1432 // Returns the name of the Rust type approximately corresponding to
1433 // a type name in another programming language.
1434 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1435 let name = path[path.len() - 1].ident.as_str();
1436 // Common Java types
1438 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1439 "short" => sym::i16,
1440 "boolean" => sym::bool,
1443 "float" => sym::f32,
1444 "double" => sym::f64,
1449 /// Only used in a specific case of type ascription suggestions
1450 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1451 let sm = self.r.session.source_map();
1452 start.to(sm.next_point(start))
1455 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1456 let sm = self.r.session.source_map();
1457 let base_snippet = sm.span_to_snippet(base_span);
1458 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1459 if let Ok(snippet) = sm.span_to_snippet(sp) {
1460 let len = snippet.trim_end().len() as u32;
1461 if snippet.trim() == ":" {
1463 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1464 let mut show_label = true;
1465 if sm.is_multiline(sp) {
1466 err.span_suggestion_short(
1468 "maybe you meant to write `;` here",
1470 Applicability::MaybeIncorrect,
1473 let after_colon_sp =
1474 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1475 if snippet.len() == 1 {
1477 err.span_suggestion(
1479 "maybe you meant to write a path separator here",
1481 Applicability::MaybeIncorrect,
1488 .type_ascription_path_suggestions
1492 err.downgrade_to_delayed_bug();
1495 if let Ok(base_snippet) = base_snippet {
1496 let mut sp = after_colon_sp;
1498 // Try to find an assignment
1499 sp = sm.next_point(sp);
1500 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1502 Ok(ref x) if x.as_str() == "=" => {
1503 err.span_suggestion(
1505 "maybe you meant to write an assignment here",
1506 format!("let {}", base_snippet),
1507 Applicability::MaybeIncorrect,
1512 Ok(ref x) if x.as_str() == "\n" => break,
1522 "expecting a type here because of type ascription",
1532 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1533 let mut result = None;
1534 let mut seen_modules = FxHashSet::default();
1535 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1537 while let Some((in_module, path_segments)) = worklist.pop() {
1538 // abort if the module is already found
1539 if result.is_some() {
1543 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1544 // abort if the module is already found or if name_binding is private external
1545 if result.is_some() || !name_binding.vis.is_visible_locally() {
1548 if let Some(module) = name_binding.module() {
1550 let mut path_segments = path_segments.clone();
1551 path_segments.push(ast::PathSegment::from_ident(ident));
1552 let module_def_id = module.def_id();
1553 if module_def_id == def_id {
1555 Path { span: name_binding.span, segments: path_segments, tokens: None };
1567 // add the module to the lookup
1568 if seen_modules.insert(module_def_id) {
1569 worklist.push((module, path_segments));
1579 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1580 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1581 let mut variants = Vec::new();
1582 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1583 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1584 let mut segms = enum_import_suggestion.path.segments.clone();
1585 segms.push(ast::PathSegment::from_ident(ident));
1586 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1587 variants.push((path, def_id, kind));
1594 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1595 fn suggest_using_enum_variant(
1597 err: &mut Diagnostic,
1598 source: PathSource<'_>,
1602 let Some(variants) = self.collect_enum_ctors(def_id) else {
1603 err.note("you might have meant to use one of the enum's variants");
1607 let suggest_only_tuple_variants =
1608 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1609 if suggest_only_tuple_variants {
1610 // Suggest only tuple variants regardless of whether they have fields and do not
1611 // suggest path with added parentheses.
1612 let suggestable_variants = variants
1614 .filter(|(.., kind)| *kind == CtorKind::Fn)
1615 .map(|(variant, ..)| path_names_to_string(variant))
1616 .collect::<Vec<_>>();
1618 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1620 let source_msg = if source.is_call() {
1622 } else if matches!(source, PathSource::TupleStruct(..)) {
1628 if !suggestable_variants.is_empty() {
1629 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1630 format!("try {} the enum's variant", source_msg)
1632 format!("try {} one of the enum's variants", source_msg)
1635 err.span_suggestions(
1638 suggestable_variants.into_iter(),
1639 Applicability::MaybeIncorrect,
1643 // If the enum has no tuple variants..
1644 if non_suggestable_variant_count == variants.len() {
1645 err.help(&format!("the enum has no tuple variants {}", source_msg));
1648 // If there are also non-tuple variants..
1649 if non_suggestable_variant_count == 1 {
1651 "you might have meant {} the enum's non-tuple variant",
1654 } else if non_suggestable_variant_count >= 1 {
1656 "you might have meant {} one of the enum's non-tuple variants",
1661 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1662 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1664 CtorKind::Const => false,
1665 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1670 let mut suggestable_variants = variants
1672 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1673 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1674 .map(|(variant, kind)| match kind {
1675 CtorKind::Const => variant,
1676 CtorKind::Fn => format!("({}())", variant),
1677 CtorKind::Fictive => format!("({} {{}})", variant),
1679 .collect::<Vec<_>>();
1681 if !suggestable_variants.is_empty() {
1682 let msg = if suggestable_variants.len() == 1 {
1683 "you might have meant to use the following enum variant"
1685 "you might have meant to use one of the following enum variants"
1688 err.span_suggestions(
1691 suggestable_variants.drain(..),
1692 Applicability::MaybeIncorrect,
1696 let suggestable_variants_with_placeholders = variants
1698 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1699 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1700 .filter_map(|(variant, kind)| match kind {
1701 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1702 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1705 .collect::<Vec<_>>();
1707 if !suggestable_variants_with_placeholders.is_empty() {
1709 suggestable_variants.is_empty(),
1710 suggestable_variants_with_placeholders.len(),
1712 (true, 1) => "the following enum variant is available",
1713 (true, _) => "the following enum variants are available",
1714 (false, 1) => "alternatively, the following enum variant is available",
1715 (false, _) => "alternatively, the following enum variants are also available",
1718 err.span_suggestions(
1721 suggestable_variants_with_placeholders.into_iter(),
1722 Applicability::HasPlaceholders,
1727 if def_id.is_local() {
1728 if let Some(span) = self.def_span(def_id) {
1729 err.span_note(span, "the enum is defined here");
1734 pub(crate) fn report_missing_type_error(
1737 ) -> Option<(Span, &'static str, String, Applicability)> {
1738 let (ident, span) = match path {
1739 [segment] if !segment.has_generic_args => {
1740 (segment.ident.to_string(), segment.ident.span)
1744 let mut iter = ident.chars().map(|c| c.is_uppercase());
1745 let single_uppercase_char =
1746 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1747 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1750 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1751 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1752 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1757 kind @ ItemKind::Fn(..)
1758 | kind @ ItemKind::Enum(..)
1759 | kind @ ItemKind::Struct(..)
1760 | kind @ ItemKind::Union(..),
1765 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1766 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1767 | (Some(Item { kind, .. }), false, _) => {
1768 // Likely missing type parameter.
1769 if let Some(generics) = kind.generics() {
1770 if span.overlaps(generics.span) {
1771 // Avoid the following:
1772 // error[E0405]: cannot find trait `A` in this scope
1773 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1775 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1776 // | ^- help: you might be missing a type parameter: `, A`
1778 // | not found in this scope
1781 let msg = "you might be missing a type parameter";
1782 let (span, sugg) = if let [.., param] = &generics.params[..] {
1783 let span = if let [.., bound] = ¶m.bounds[..] {
1785 } else if let GenericParam {
1786 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1788 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1792 (span, format!(", {}", ident))
1794 (generics.span, format!("<{}>", ident))
1796 // Do not suggest if this is coming from macro expansion.
1797 if span.can_be_used_for_suggestions() {
1799 span.shrink_to_hi(),
1802 Applicability::MaybeIncorrect,
1812 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1813 /// optionally returning the closest match and whether it is reachable.
1814 pub(crate) fn suggestion_for_label_in_rib(
1818 ) -> Option<LabelSuggestion> {
1819 // Are ribs from this `rib_index` within scope?
1820 let within_scope = self.is_label_valid_from_rib(rib_index);
1822 let rib = &self.label_ribs[rib_index];
1826 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1827 .map(|(id, _)| id.name)
1828 .collect::<Vec<Symbol>>();
1830 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1831 // Upon finding a similar name, get the ident that it was from - the span
1832 // contained within helps make a useful diagnostic. In addition, determine
1833 // whether this candidate is within scope.
1834 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1835 (*ident, within_scope)
1839 pub(crate) fn maybe_report_lifetime_uses(
1841 generics_span: Span,
1842 params: &[ast::GenericParam],
1844 for (param_index, param) in params.iter().enumerate() {
1845 let GenericParamKind::Lifetime = param.kind else { continue };
1847 let def_id = self.r.local_def_id(param.id);
1849 let use_set = self.lifetime_uses.remove(&def_id);
1851 "Use set for {:?}({:?} at {:?}) is {:?}",
1852 def_id, param.ident, param.ident.span, use_set
1855 let deletion_span = || {
1856 if params.len() == 1 {
1857 // if sole lifetime, remove the entire `<>` brackets
1859 } else if param_index == 0 {
1860 // if removing within `<>` brackets, we also want to
1861 // delete a leading or trailing comma as appropriate
1862 param.span().to(params[param_index + 1].span().shrink_to_lo())
1864 // if removing within `<>` brackets, we also want to
1865 // delete a leading or trailing comma as appropriate
1866 params[param_index - 1].span().shrink_to_hi().to(param.span())
1870 Some(LifetimeUseSet::Many) => {}
1871 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
1872 debug!(?param.ident, ?param.ident.span, ?use_span);
1874 let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
1876 let deletion_span = deletion_span();
1877 self.r.lint_buffer.buffer_lint_with_diagnostic(
1878 lint::builtin::SINGLE_USE_LIFETIMES,
1881 &format!("lifetime parameter `{}` only used once", param.ident),
1882 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1883 param_span: param.ident.span,
1884 use_span: Some((use_span, elidable)),
1890 debug!(?param.ident, ?param.ident.span);
1892 let deletion_span = deletion_span();
1893 self.r.lint_buffer.buffer_lint_with_diagnostic(
1894 lint::builtin::UNUSED_LIFETIMES,
1897 &format!("lifetime parameter `{}` never used", param.ident),
1898 lint::BuiltinLintDiagnostics::SingleUseLifetime {
1899 param_span: param.ident.span,
1909 pub(crate) fn emit_undeclared_lifetime_error(
1911 lifetime_ref: &ast::Lifetime,
1912 outer_lifetime_ref: Option<Ident>,
1914 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1915 let mut err = if let Some(outer) = outer_lifetime_ref {
1916 let mut err = struct_span_err!(
1918 lifetime_ref.ident.span,
1920 "can't use generic parameters from outer item",
1922 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1923 err.span_label(outer.span, "lifetime parameter from outer item");
1926 let mut err = struct_span_err!(
1928 lifetime_ref.ident.span,
1930 "use of undeclared lifetime name `{}`",
1933 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
1936 let mut suggest_note = true;
1938 for rib in self.lifetime_ribs.iter().rev() {
1940 LifetimeRibKind::Generics { binder: _, span, kind } => {
1941 if !span.can_be_used_for_suggestions() && suggest_note {
1942 suggest_note = false; // Avoid displaying the same help multiple times.
1946 "lifetime `{}` is missing in item created through this procedural macro",
1953 let higher_ranked = matches!(
1955 LifetimeBinderKind::BareFnType
1956 | LifetimeBinderKind::PolyTrait
1957 | LifetimeBinderKind::WhereBound
1959 let (span, sugg) = if span.is_empty() {
1962 if higher_ranked { "for" } else { "" },
1964 if higher_ranked { " " } else { "" },
1969 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
1970 let sugg = format!("{}, ", lifetime_ref.ident);
1974 err.span_suggestion(
1977 "consider making the {} lifetime-generic with a new `{}` lifetime",
1982 Applicability::MaybeIncorrect,
1985 "for more information on higher-ranked polymorphism, visit \
1986 https://doc.rust-lang.org/nomicon/hrtb.html",
1989 err.span_suggestion(
1991 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
1993 Applicability::MaybeIncorrect,
1997 LifetimeRibKind::Item => break,
2005 pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
2008 lifetime_ref.ident.span,
2010 "use of non-static lifetime `{}` in const generic",
2014 "for more information, see issue #74052 \
2015 <https://github.com/rust-lang/rust/issues/74052>",
2020 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2021 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2022 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2023 pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
2025 lifetime_ref: &ast::Lifetime,
2027 let feature_active = self.r.session.features_untracked().generic_const_exprs;
2028 if !feature_active {
2030 &self.r.session.parse_sess,
2031 sym::generic_const_exprs,
2032 lifetime_ref.ident.span,
2033 "a non-static lifetime is not allowed in a `const`",
2040 /// Report lifetime/lifetime shadowing as an error.
2041 pub fn signal_lifetime_shadowing(
2045 orig_is_param: bool,
2047 let mut err = if orig_is_param {
2052 "lifetime name `{}` declared twice in the same scope",
2060 "lifetime name `{}` shadows a lifetime name that is already in scope",
2064 err.span_label(orig.span, "first declared here");
2065 err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
2069 /// Shadowing involving a label is only a warning, due to issues with
2070 /// labels and lifetimes not being macro-hygienic.
2071 pub fn signal_label_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
2072 let mut err = sess.struct_span_warn(
2074 &format!("label name `{}` shadows a label name that is already in scope", orig.name),
2076 err.span_label(orig.span, "first declared here");
2077 err.span_label(shadower.span, format!("label `{}` already in scope", orig.name));
2081 impl<'tcx> LifetimeContext<'_, 'tcx> {
2082 pub(crate) fn report_missing_lifetime_specifiers(
2086 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2091 "missing lifetime specifier{}",
2096 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
2097 pub(crate) fn report_elision_failure(
2099 diag: &mut Diagnostic,
2100 params: &[ElisionFailureInfo],
2102 let mut m = String::new();
2103 let len = params.len();
2105 let elided_params: Vec<_> =
2106 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
2108 let elided_len = elided_params.len();
2110 for (i, info) in elided_params.into_iter().enumerate() {
2111 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
2114 diag.span_label(span, "");
2115 let help_name = if let Some(ident) =
2116 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
2118 format!("`{}`", ident)
2120 format!("argument {}", index + 1)
2128 "one of {}'s {} {}lifetimes",
2131 if have_bound_regions { "free " } else { "" }
2136 if elided_len == 2 && i == 0 {
2138 } else if i + 2 == elided_len {
2139 m.push_str(", or ");
2140 } else if i != elided_len - 1 {
2147 "this function's return type contains a borrowed value, \
2148 but there is no value for it to be borrowed from",
2151 } else if elided_len == 0 {
2153 "this function's return type contains a borrowed value with \
2154 an elided lifetime, but the lifetime cannot be derived from \
2158 } else if elided_len == 1 {
2160 "this function's return type contains a borrowed value, \
2161 but the signature does not say which {} it is borrowed from",
2167 "this function's return type contains a borrowed value, \
2168 but the signature does not say whether it is borrowed from {}",
2175 pub(crate) fn is_trait_ref_fn_scope(
2177 trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
2179 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2181 self.tcx.lang_items().fn_once_trait(),
2182 self.tcx.lang_items().fn_trait(),
2183 self.tcx.lang_items().fn_mut_trait(),
2185 .contains(&Some(did))
2187 let (span, span_type) = match &trait_ref.bound_generic_params {
2188 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2189 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2191 self.missing_named_lifetime_spots
2192 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2199 pub(crate) fn add_missing_lifetime_specifiers_label(
2201 err: &mut Diagnostic,
2202 mut spans_with_counts: Vec<(Span, usize)>,
2203 lifetime_names: &FxHashSet<Symbol>,
2204 lifetime_spans: Vec<Span>,
2205 params: &[ElisionFailureInfo],
2207 let snippets: Vec<Option<String>> = spans_with_counts
2209 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2212 // Empty generics are marked with a span of "<", but since from now on
2213 // that information is in the snippets it can be removed from the spans.
2214 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2215 if snippet.as_deref() == Some("<") {
2216 *span = span.shrink_to_hi();
2220 for &(span, count) in &spans_with_counts {
2224 "expected {} lifetime parameter{}",
2225 if count == 1 { "named".to_string() } else { count.to_string() },
2231 let suggest_existing =
2232 |err: &mut Diagnostic,
2234 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2235 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2236 self.missing_named_lifetime_spots.iter().rev().next()
2238 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2239 // using `'a`, but also introduce the concept of HRLTs by suggesting
2240 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2241 let mut introduce_suggestion = vec![];
2243 let a_to_z_repeat_n = |n| {
2244 (b'a'..=b'z').map(move |c| {
2245 let mut s = '\''.to_string();
2246 s.extend(std::iter::repeat(char::from(c)).take(n));
2251 // If all single char lifetime names are present, we wrap around and double the chars.
2253 .flat_map(a_to_z_repeat_n)
2254 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2257 "consider making the {} lifetime-generic with a new `{}` lifetime",
2262 "for more information on higher-ranked polymorphism, visit \
2263 https://doc.rust-lang.org/nomicon/hrtb.html",
2265 let for_sugg = span_type.suggestion(<_name);
2266 for param in params {
2267 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2269 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2270 introduce_suggestion
2271 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2272 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2273 introduce_suggestion
2274 .push((param.span, format!("&{} {}", lt_name, stripped)));
2278 introduce_suggestion.push((*for_span, for_sugg));
2279 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2280 if let Some(formatter) = formatter {
2281 introduce_suggestion.push((*span, formatter(<_name)));
2284 err.multipart_suggestion_verbose(
2286 introduce_suggestion,
2287 Applicability::MaybeIncorrect,
2291 let spans_suggs: Vec<_> = formatters
2293 .zip(spans_with_counts.iter())
2294 .filter_map(|(formatter, (span, _))| {
2295 if let Some(formatter) = formatter {
2296 Some((*span, formatter(name)))
2302 if spans_suggs.is_empty() {
2303 // If all the spans come from macros, we cannot extract snippets and then
2304 // `formatters` only contains None and `spans_suggs` is empty.
2307 err.multipart_suggestion_verbose(
2309 "consider using the `{}` lifetime",
2310 lifetime_names.iter().next().unwrap()
2313 Applicability::MaybeIncorrect,
2316 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2317 for missing in self.missing_named_lifetime_spots.iter().rev() {
2318 let mut introduce_suggestion = vec![];
2321 introduce_suggestion.push(match missing {
2322 MissingLifetimeSpot::Generics(generics) => {
2323 if generics.span == DUMMY_SP {
2324 // Account for malformed generics in the HIR. This shouldn't happen,
2325 // but if we make a mistake elsewhere, mainly by keeping something in
2326 // `missing_named_lifetime_spots` that we shouldn't, like associated
2327 // `const`s or making a mistake in the AST lowering we would provide
2328 // nonsensical suggestions. Guard against that by skipping these.
2332 msg = "consider introducing a named lifetime parameter".to_string();
2333 should_break = true;
2334 if let Some(param) = generics.params.iter().find(|p| {
2337 hir::GenericParamKind::Type { synthetic: true, .. }
2338 | hir::GenericParamKind::Lifetime {
2339 kind: hir::LifetimeParamKind::Elided
2343 (param.span.shrink_to_lo(), "'a, ".to_string())
2345 (generics.span, "<'a>".to_string())
2348 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2350 "consider making the {} lifetime-generic with a new `'a` lifetime",
2353 should_break = false;
2355 "for more information on higher-ranked polymorphism, visit \
2356 https://doc.rust-lang.org/nomicon/hrtb.html",
2358 (*span, span_type.suggestion("'a"))
2360 MissingLifetimeSpot::Static => {
2361 let mut spans_suggs = Vec::new();
2362 for ((span, count), snippet) in
2363 spans_with_counts.iter().copied().zip(snippets.iter())
2365 let (span, sugg) = match snippet.as_deref() {
2366 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2367 Some("'_") => (span, "'static".to_owned()),
2368 Some(snippet) if !snippet.ends_with('>') => {
2372 std::iter::repeat("'static")
2374 .collect::<Vec<_>>()
2377 } else if snippet == "<" || snippet == "(" {
2379 span.shrink_to_hi(),
2380 std::iter::repeat("'static")
2382 .collect::<Vec<_>>()
2387 span.shrink_to_hi(),
2390 std::iter::repeat("'static")
2392 .collect::<Vec<_>>()
2400 spans_suggs.push((span, sugg.to_string()));
2402 err.multipart_suggestion_verbose(
2403 "consider using the `'static` lifetime",
2405 Applicability::MaybeIncorrect,
2411 struct Lifetime(Span, String);
2413 fn is_unnamed(&self) -> bool {
2414 self.1.starts_with('&') && !self.1.starts_with("&'")
2416 fn is_underscore(&self) -> bool {
2417 self.1.starts_with("&'_ ")
2419 fn is_named(&self) -> bool {
2420 self.1.starts_with("&'")
2422 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2426 self.is_underscore(),
2428 sugg.starts_with('&'),
2430 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2431 (true, _, _, true) => {
2432 (self.span_unnamed_borrow(), sugg[1..].to_string())
2434 (_, true, _, false) => {
2435 (self.span_underscore_borrow(), sugg.trim().to_string())
2437 (_, true, _, true) => {
2438 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2440 (_, _, true, false) => {
2441 (self.span_named_borrow(), sugg.trim().to_string())
2443 (_, _, true, true) => {
2444 (self.span_named_borrow(), sugg[1..].trim().to_string())
2450 fn span_unnamed_borrow(&self) -> Span {
2451 let lo = self.0.lo() + BytePos(1);
2452 self.0.with_lo(lo).with_hi(lo)
2454 fn span_named_borrow(&self) -> Span {
2455 let lo = self.0.lo() + BytePos(1);
2458 fn span_underscore_borrow(&self) -> Span {
2459 let lo = self.0.lo() + BytePos(1);
2460 let hi = lo + BytePos(2);
2461 self.0.with_lo(lo).with_hi(hi)
2465 for param in params {
2466 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2467 if let Some((span, sugg)) =
2468 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2470 introduce_suggestion.push((span, sugg));
2474 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2475 |((span, _), sugg)| match &sugg {
2476 Some(sugg) => Some((span, sugg.to_string())),
2480 let (span, sugg) = self
2484 .span_to_snippet(span)
2486 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2487 .unwrap_or((span, sugg));
2488 introduce_suggestion.push((span, sugg.to_string()));
2490 err.multipart_suggestion_verbose(
2492 introduce_suggestion,
2493 Applicability::MaybeIncorrect,
2501 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2502 match &lifetime_names[..] {
2504 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2505 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2507 suggs.push(match snippet.as_deref() {
2508 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2509 Some("'_") => Some(Box::new(|n| n.to_string())),
2510 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2511 Some("<") => Some(Box::new(move |n| {
2512 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2514 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2518 std::iter::repeat(name.to_string())
2520 .collect::<Vec<_>>()
2527 suggest_existing(err, name.as_str(), suggs);
2530 let mut suggs = Vec::new();
2531 for (snippet, (_, count)) in
2532 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2534 suggs.push(match snippet.as_deref() {
2535 Some("&") => Some("&'a ".to_string()),
2536 Some("'_") => Some("'a".to_string()),
2538 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2541 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2543 Some(snippet) => Some(format!(
2546 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2551 suggest_new(err, suggs);
2553 lts if lts.len() > 1 => {
2554 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2556 let mut spans_suggs: Vec<_> = Vec::new();
2557 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2558 match snippet.as_deref() {
2559 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2560 Some("&") => spans_suggs
2561 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2566 if spans_suggs.len() > 0 {
2567 // This happens when we have `Foo<T>` where we point at the space before `T`,
2568 // but this can be confusing so we give a suggestion with placeholders.
2569 err.multipart_suggestion_verbose(
2570 "consider using one of the available lifetimes here",
2572 Applicability::HasPlaceholders,
2576 _ => unreachable!(),