1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
4 use crate::path_names_to_string;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
6 use crate::{PathResult, PathSource, Segment};
8 use rustc_ast::visit::FnKind;
10 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
11 NodeId, Path, Ty, TyKind,
13 use rustc_ast_pretty::pprust::path_segment_to_string;
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder};
17 use rustc_hir::def::Namespace::{self, *};
18 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
19 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
20 use rustc_hir::PrimTy;
21 use rustc_session::parse::feature_err;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::MacroKind;
24 use rustc_span::lev_distance::find_best_match_for_name;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
33 type Res = def::Res<ast::NodeId>;
35 /// A field or associated item from self type suggested in case of resolution failure.
36 enum AssocSuggestion {
44 impl AssocSuggestion {
45 fn action(&self) -> &'static str {
47 AssocSuggestion::Field => "use the available field",
48 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
49 AssocSuggestion::AssocFn => "call the associated function",
50 AssocSuggestion::AssocConst => "use the associated `const`",
51 AssocSuggestion::AssocType => "use the associated type",
56 crate enum MissingLifetimeSpot<'tcx> {
57 Generics(&'tcx hir::Generics<'tcx>),
58 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
62 crate enum ForLifetimeSpanType {
69 impl ForLifetimeSpanType {
70 crate fn descr(&self) -> &'static str {
72 Self::BoundEmpty | Self::BoundTail => "bound",
73 Self::TypeEmpty | Self::TypeTail => "type",
77 crate fn suggestion(&self, sugg: &str) -> String {
79 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
80 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
85 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
86 fn into(self) -> MissingLifetimeSpot<'tcx> {
87 MissingLifetimeSpot::Generics(self)
91 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
92 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
95 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
96 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
99 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
100 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
101 let variant_path = &suggestion.path;
102 let variant_path_string = path_names_to_string(variant_path);
104 let path_len = suggestion.path.segments.len();
105 let enum_path = ast::Path {
106 span: suggestion.path.span,
107 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
110 let enum_path_string = path_names_to_string(&enum_path);
112 (variant_path_string, enum_path_string)
115 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
116 fn def_span(&self, def_id: DefId) -> Option<Span> {
118 LOCAL_CRATE => self.r.opt_span(def_id),
123 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
128 /// Handles error reporting for `smart_resolve_path_fragment` function.
129 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
130 pub(crate) fn smart_resolve_report_errors(
134 source: PathSource<'_>,
136 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
137 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
138 let ns = source.namespace();
139 let is_expected = &|res| source.is_expected(res);
140 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
142 // Make the base error.
143 let mut expected = source.descr_expected();
144 let path_str = Segment::names_to_string(path);
145 let item_str = path.last().unwrap().ident;
146 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
148 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
149 format!("not a {}", expected),
152 Res::Def(DefKind::Fn, _) => {
153 // Verify whether this is a fn call or an Fn used as a type.
157 .span_to_snippet(span)
158 .map(|snippet| snippet.ends_with(')'))
162 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
167 | Res::Local(_) => true,
172 let item_span = path.last().unwrap().ident.span;
173 let (mod_prefix, mod_str) = if path.len() == 1 {
174 (String::new(), "this scope".to_string())
175 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
176 if self.r.session.edition() > Edition::Edition2015 {
177 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
178 // which overrides all other expectations of item type
180 (String::new(), "the list of imported crates".to_string())
182 (String::new(), "the crate root".to_string())
184 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
185 (String::new(), "the crate root".to_string())
187 let mod_path = &path[..path.len() - 1];
189 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
190 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
193 .map_or_else(String::new, |res| format!("{} ", res.descr()));
194 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
197 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
198 if path_str == "async" && expected.starts_with("struct") {
199 "`async` blocks are only allowed in Rust 2018 or later".to_string()
201 format!("not found in {}", mod_str)
208 let code = source.error_code(res.is_some());
209 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
211 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
212 err.multipart_suggestion(
213 "you might have meant to write a `struct` literal",
215 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
216 (span.shrink_to_hi(), "}".to_string()),
218 Applicability::HasPlaceholders,
221 match (source, self.diagnostic_metadata.in_if_condition) {
222 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
223 err.span_suggestion_verbose(
225 "you might have meant to use pattern matching",
227 Applicability::MaybeIncorrect,
233 let is_assoc_fn = self.self_type_is_available(span);
234 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
235 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
236 err.span_suggestion_short(
238 "you might have meant to use `self` here instead",
240 Applicability::MaybeIncorrect,
242 if !self.self_value_is_available(path[0].ident.span, span) {
243 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
244 &self.diagnostic_metadata.current_function
246 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
247 (param.span.shrink_to_lo(), "&self, ")
253 .span_through_char(*fn_span, '(')
258 err.span_suggestion_verbose(
260 "if you meant to use `self`, you are also missing a `self` receiver \
263 Applicability::MaybeIncorrect,
269 self.detect_assoct_type_constraint_meant_as_path(base_span, &mut err);
271 // Emit special messages for unresolved `Self` and `self`.
272 if is_self_type(path, ns) {
273 err.code(rustc_errors::error_code!(E0411));
276 "`Self` is only available in impls, traits, and type definitions".to_string(),
278 return (err, Vec::new());
280 if is_self_value(path, ns) {
281 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
283 err.code(rustc_errors::error_code!(E0424));
284 err.span_label(span, match source {
285 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
287 _ => "`self` value is a keyword only available in methods with a `self` parameter"
290 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
291 // The current function has a `self' parameter, but we were unable to resolve
292 // a reference to `self`. This can only happen if the `self` identifier we
293 // are resolving came from a different hygiene context.
294 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
295 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
297 let doesnt = if is_assoc_fn {
298 let (span, sugg) = fn_kind
302 .map(|p| (p.span.shrink_to_lo(), "&self, "))
304 // Try to look for the "(" after the function name, if possible.
305 // This avoids placing the suggestion into the visibility specifier.
308 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
313 .span_through_char(span, '(')
318 err.span_suggestion_verbose(
320 "add a `self` receiver parameter to make the associated `fn` a method",
322 Applicability::MaybeIncorrect,
328 if let Some(ident) = fn_kind.ident() {
331 &format!("this function {} have a `self` parameter", doesnt),
336 return (err, Vec::new());
339 // Try to lookup name in more relaxed fashion for better error reporting.
340 let ident = path.last().unwrap().ident;
341 let candidates = self
343 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
345 .filter(|ImportSuggestion { did, .. }| {
346 match (did, res.and_then(|res| res.opt_def_id())) {
347 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
351 .collect::<Vec<_>>();
352 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
353 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
354 let mut enum_candidates: Vec<_> = self
356 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
358 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
359 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
361 if !enum_candidates.is_empty() {
362 if let (PathSource::Type, Some(span)) =
363 (source, self.diagnostic_metadata.current_type_ascription.last())
369 .type_ascription_path_suggestions
373 // Already reported this issue on the lhs of the type ascription.
375 return (err, candidates);
379 enum_candidates.sort();
381 // Contextualize for E0412 "cannot find type", but don't belabor the point
382 // (that it's a variant) for E0573 "expected type, found variant".
383 let preamble = if res.is_none() {
384 let others = match enum_candidates.len() {
386 2 => " and 1 other".to_owned(),
387 n => format!(" and {} others", n),
389 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
393 let msg = format!("{}try using the variant's enum", preamble);
395 err.span_suggestions(
398 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
399 Applicability::MachineApplicable,
403 if path.len() == 1 && self.self_type_is_available(span) {
404 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
405 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
407 AssocSuggestion::Field => {
408 if self_is_available {
411 "you might have meant to use the available field",
412 format!("self.{}", path_str),
413 Applicability::MachineApplicable,
416 err.span_label(span, "a field by this name exists in `Self`");
419 AssocSuggestion::MethodWithSelf if self_is_available => {
422 "you might have meant to call the method",
423 format!("self.{}", path_str),
424 Applicability::MachineApplicable,
427 AssocSuggestion::MethodWithSelf
428 | AssocSuggestion::AssocFn
429 | AssocSuggestion::AssocConst
430 | AssocSuggestion::AssocType => {
433 &format!("you might have meant to {}", candidate.action()),
434 format!("Self::{}", path_str),
435 Applicability::MachineApplicable,
439 return (err, candidates);
442 // If the first argument in call is `self` suggest calling a method.
443 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
444 let mut args_snippet = String::new();
445 if let Some(args_span) = args_span {
446 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
447 args_snippet = snippet;
453 &format!("try calling `{}` as a method", ident),
454 format!("self.{}({})", path_str, args_snippet),
455 Applicability::MachineApplicable,
457 return (err, candidates);
461 // Try Levenshtein algorithm.
462 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
463 // Try context-dependent help if relaxed lookup didn't work.
464 if let Some(res) = res {
465 if self.smart_resolve_context_dependent_help(
473 // We do this to avoid losing a secondary span when we override the main error span.
474 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
475 return (err, candidates);
479 let is_macro = base_span.from_expansion() && base_span.desugaring_kind().is_none();
480 if !self.type_ascription_suggestion(&mut err, base_span) {
481 let mut fallback = false;
483 PathSource::Trait(AliasPossibility::Maybe),
484 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
486 ) = (source, res, is_macro)
488 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
490 let spans: Vec<Span> = bounds
492 .map(|bound| bound.span())
493 .filter(|&sp| sp != base_span)
496 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
497 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
498 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
499 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
500 let last_bound_span = spans.last().cloned().unwrap();
501 let mut multi_span: MultiSpan = spans.clone().into();
503 let msg = if sp == last_bound_span {
505 "...because of {} bound{}",
506 if bounds.len() <= 2 { "this" } else { "these" },
507 if bounds.len() <= 2 { "" } else { "s" },
512 multi_span.push_span_label(sp, msg);
514 multi_span.push_span_label(
516 "expected this type to be a trait...".to_string(),
520 "`+` is used to constrain a \"trait object\" type with lifetimes or \
521 auto-traits; structs and enums can't be bound in that way",
523 if bounds.iter().all(|bound| match bound {
524 ast::GenericBound::Outlives(_) => true,
525 ast::GenericBound::Trait(tr, _) => tr.span == base_span,
527 let mut sugg = vec![];
528 if base_span != start_span {
529 sugg.push((start_span.until(base_span), String::new()));
531 if base_span != end_span {
532 sugg.push((base_span.shrink_to_hi().to(end_span), String::new()));
535 err.multipart_suggestion(
536 "if you meant to use a type and not a trait here, remove the bounds",
538 Applicability::MaybeIncorrect,
544 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
546 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
548 match self.diagnostic_metadata.current_let_binding {
549 Some((pat_sp, Some(ty_sp), None))
550 if ty_sp.contains(base_span) && could_be_expr =>
552 err.span_suggestion_short(
553 pat_sp.between(ty_sp),
554 "use `=` if you meant to assign",
556 Applicability::MaybeIncorrect,
562 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
563 let suggestion = self.get_single_associated_item(&path, span, &source, is_expected);
564 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
568 err.span_label(base_span, fallback_label);
571 if let Some(err_code) = &err.code {
572 if err_code == &rustc_errors::error_code!(E0425) {
573 for label_rib in &self.label_ribs {
574 for (label_ident, node_id) in &label_rib.bindings {
575 if format!("'{}", ident) == label_ident.to_string() {
576 err.span_label(label_ident.span, "a label with a similar name exists");
577 if let PathSource::Expr(Some(Expr {
578 kind: ExprKind::Break(None, Some(_)),
584 "use the similarly named label",
585 label_ident.name.to_string(),
586 Applicability::MaybeIncorrect,
588 // Do not lint against unused label when we suggest them.
589 self.diagnostic_metadata.unused_labels.remove(node_id);
594 } else if err_code == &rustc_errors::error_code!(E0412) {
595 if let Some(correct) = Self::likely_rust_type(path) {
598 "perhaps you intended to use this type",
600 Applicability::MaybeIncorrect,
609 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
610 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
611 let TyKind::Path(_, path) = &ty.kind else { return; };
612 for segment in &path.segments {
613 let Some(params) = &segment.args else { continue; };
614 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
615 for param in ¶ms.args {
616 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
617 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
620 for bound in bounds {
621 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
626 if base_span == trait_ref.span {
627 err.span_suggestion_verbose(
628 constraint.ident.span.between(trait_ref.span),
629 "you might have meant to write a path instead of an associated type bound",
631 Applicability::MachineApplicable,
639 fn get_single_associated_item(
643 source: &PathSource<'_>,
644 filter_fn: &impl Fn(Res) -> bool,
645 ) -> Option<TypoSuggestion> {
646 if let crate::PathSource::TraitItem(_) = source {
647 let mod_path = &path[..path.len() - 1];
648 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
649 self.resolve_path(mod_path, None, false, span, CrateLint::No)
651 let resolutions = self.r.resolutions(module).borrow();
652 let targets: Vec<_> =
655 .filter_map(|(key, resolution)| {
656 resolution.borrow().binding.map(|binding| binding.res()).and_then(
657 |res| if filter_fn(res) { Some((key, res)) } else { None },
661 if targets.len() == 1 {
662 let target = targets[0];
663 return Some(TypoSuggestion::single_item_from_res(
673 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
674 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
675 // Detect that we are actually in a `where` predicate.
676 let (bounded_ty, bounds, where_span) =
677 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
679 bound_generic_params,
682 })) = self.diagnostic_metadata.current_where_predicate
684 if !bound_generic_params.is_empty() {
687 (bounded_ty, bounds, span)
692 // Confirm that the target is an associated type.
693 let (ty, position, path) = if let ast::TyKind::Path(
694 Some(ast::QSelf { ty, position, .. }),
698 // use this to verify that ident is a type param.
699 let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
702 &Segment::from_path(path),
711 partial_res.base_res(),
712 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
713 ) && partial_res.unresolved_segments() == 0)
722 if let ast::TyKind::Path(None, type_param_path) = &ty.peel_refs().kind {
723 // Confirm that the `SelfTy` is a type parameter.
724 let Ok(Some(partial_res)) = self.resolve_qpath_anywhere(
727 &Segment::from_path(type_param_path),
736 partial_res.base_res(),
737 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
738 ) && partial_res.unresolved_segments() == 0)
743 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
744 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
745 ) = (&type_param_path.segments[..], &bounds[..])
747 if let [ast::PathSegment { ident, args: None, .. }] =
748 &poly_trait_ref.trait_ref.path.segments[..]
750 if ident.span == span {
751 err.span_suggestion_verbose(
753 &format!("constrain the associated type to `{}`", ident),
759 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
760 .unwrap_or_else(|_| constrain_ident.to_string()),
761 path.segments[..*position]
763 .map(|segment| path_segment_to_string(segment))
766 path.segments[*position..]
768 .map(|segment| path_segment_to_string(segment))
773 Applicability::MaybeIncorrect,
783 /// Check if the source is call expression and the first argument is `self`. If true,
784 /// return the span of whole call and the span for all arguments expect the first one (`self`).
785 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
786 let mut has_self_arg = None;
787 if let PathSource::Expr(Some(parent)) = source {
789 ExprKind::Call(_, args) if !args.is_empty() => {
790 let mut expr_kind = &args[0].kind;
793 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
794 if arg_name.segments[0].ident.name == kw::SelfLower {
795 let call_span = parent.span;
796 let tail_args_span = if args.len() > 1 {
799 args.last().unwrap().span.hi(),
806 has_self_arg = Some((call_span, tail_args_span));
810 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
821 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
822 // HACK(estebank): find a better way to figure out that this was a
823 // parser issue where a struct literal is being used on an expression
824 // where a brace being opened means a block is being started. Look
825 // ahead for the next text to see if `span` is followed by a `{`.
826 let sm = self.r.session.source_map();
829 sp = sm.next_point(sp);
830 match sm.span_to_snippet(sp) {
832 if snippet.chars().any(|c| !c.is_whitespace()) {
839 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
840 // In case this could be a struct literal that needs to be surrounded
841 // by parentheses, find the appropriate span.
843 let mut closing_brace = None;
845 sp = sm.next_point(sp);
846 match sm.span_to_snippet(sp) {
849 closing_brace = Some(span.to(sp));
856 // The bigger the span, the more likely we're incorrect --
857 // bound it to 100 chars long.
862 (followed_by_brace, closing_brace)
865 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
867 /// Returns `true` if able to provide context-dependent help.
868 fn smart_resolve_context_dependent_help(
870 err: &mut Diagnostic,
872 source: PathSource<'_>,
875 fallback_label: &str,
877 let ns = source.namespace();
878 let is_expected = &|res| source.is_expected(res);
880 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
881 ExprKind::Field(_, ident) => {
884 "use the path separator to refer to an item",
885 format!("{}::{}", path_str, ident),
886 Applicability::MaybeIncorrect,
890 ExprKind::MethodCall(ref segment, ..) => {
891 let span = expr.span.with_hi(segment.ident.span.hi());
894 "use the path separator to refer to an item",
895 format!("{}::{}", path_str, segment.ident),
896 Applicability::MaybeIncorrect,
903 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
905 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
906 | PathSource::TupleStruct(span, _) => {
907 // We want the main underline to cover the suggested code as well for
916 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
917 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
920 PathSource::Expr(Some(
921 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
922 )) if path_sep(err, &parent) => {}
928 | ExprKind::Binary(..)
929 | ExprKind::Unary(..)
931 | ExprKind::While(..)
932 | ExprKind::ForLoop(..)
933 | ExprKind::Match(..),
936 ) if followed_by_brace => {
937 if let Some(sp) = closing_brace {
938 err.span_label(span, fallback_label);
939 err.multipart_suggestion(
940 "surround the struct literal with parentheses",
942 (sp.shrink_to_lo(), "(".to_string()),
943 (sp.shrink_to_hi(), ")".to_string()),
945 Applicability::MaybeIncorrect,
949 span, // Note the parentheses surrounding the suggestion below
951 "you might want to surround a struct literal with parentheses: \
952 `({} {{ /* fields */ }})`?",
958 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
959 let span = find_span(&source, err);
960 if let Some(span) = self.def_span(def_id) {
961 err.span_label(span, &format!("`{}` defined here", path_str));
963 let (tail, descr, applicability) = match source {
964 PathSource::Pat | PathSource::TupleStruct(..) => {
965 ("", "pattern", Applicability::MachineApplicable)
967 _ => (": val", "literal", Applicability::HasPlaceholders),
969 let (fields, applicability) = match self.r.field_names.get(&def_id) {
973 .map(|f| format!("{}{}", f.node, tail))
974 .collect::<Vec<String>>()
978 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
980 let pad = match self.r.field_names.get(&def_id) {
981 Some(fields) if fields.is_empty() => "",
986 &format!("use struct {} syntax instead", descr),
987 format!("{path_str} {{{pad}{fields}{pad}}}"),
992 err.span_label(span, fallback_label);
997 match (res, source) {
999 Res::Def(DefKind::Macro(MacroKind::Bang), _),
1000 PathSource::Expr(Some(Expr {
1001 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1003 | PathSource::Struct,
1005 err.span_label(span, fallback_label);
1006 err.span_suggestion_verbose(
1007 span.shrink_to_hi(),
1008 "use `!` to invoke the macro",
1010 Applicability::MaybeIncorrect,
1012 if path_str == "try" && span.rust_2015() {
1013 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1016 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1017 err.span_label(span, fallback_label);
1019 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1020 err.span_label(span, "type aliases cannot be used as traits");
1021 if self.r.session.is_nightly_build() {
1022 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1024 if let Some(span) = self.def_span(def_id) {
1025 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1026 // The span contains a type alias so we should be able to
1027 // replace `type` with `trait`.
1028 let snip = snip.replacen("type", "trait", 1);
1029 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1031 err.span_help(span, msg);
1038 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1039 if !path_sep(err, &parent) {
1044 Res::Def(DefKind::Enum, def_id),
1045 PathSource::TupleStruct(..) | PathSource::Expr(..),
1048 .diagnostic_metadata
1049 .current_type_ascription
1055 .type_ascription_path_suggestions
1061 err.downgrade_to_delayed_bug();
1062 // We already suggested changing `:` into `::` during parsing.
1066 self.suggest_using_enum_variant(err, source, def_id, span);
1068 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1069 let (ctor_def, ctor_vis, fields) =
1070 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1071 if let PathSource::Expr(Some(parent)) = source {
1072 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1073 bad_struct_syntax_suggestion(def_id);
1079 bad_struct_syntax_suggestion(def_id);
1083 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1084 if !is_expected(ctor_def) || is_accessible {
1088 let field_spans = match source {
1089 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1090 PathSource::TupleStruct(_, pattern_spans) => {
1091 err.set_primary_message(
1092 "cannot match against a tuple struct which contains private fields",
1095 // Use spans of the tuple struct pattern.
1096 Some(Vec::from(pattern_spans))
1098 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1099 _ if source.is_call() => {
1100 err.set_primary_message(
1101 "cannot initialize a tuple struct which contains private fields",
1104 // Use spans of the tuple struct definition.
1108 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1113 if let Some(spans) =
1114 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1116 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1117 .filter(|(vis, _)| {
1118 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1120 .map(|(_, span)| *span)
1123 if non_visible_spans.len() > 0 {
1124 let mut m: rustc_span::MultiSpan = non_visible_spans.clone().into();
1127 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1128 err.span_note(m, "constructor is not visible here due to private fields");
1136 "constructor is not visible here due to private fields".to_string(),
1141 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1145 ) if ns == ValueNS => {
1146 bad_struct_syntax_suggestion(def_id);
1148 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1150 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1151 let span = find_span(&source, err);
1152 if let Some(span) = self.def_span(def_id) {
1153 err.span_label(span, &format!("`{}` defined here", path_str));
1155 err.span_suggestion(
1157 &"use this syntax instead",
1158 path_str.to_string(),
1159 Applicability::MaybeIncorrect,
1165 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1166 if let Some(span) = self.def_span(def_id) {
1167 err.span_label(span, &format!("`{}` defined here", path_str));
1169 let fields = self.r.field_names.get(&def_id).map_or_else(
1170 || "/* fields */".to_string(),
1171 |fields| vec!["_"; fields.len()].join(", "),
1173 err.span_suggestion(
1175 "use the tuple variant pattern syntax instead",
1176 format!("{}({})", path_str, fields),
1177 Applicability::HasPlaceholders,
1180 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1181 err.span_label(span, fallback_label);
1182 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1184 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1185 err.note("can't use a type alias as a constructor");
1192 /// Given the target `ident` and `kind`, search for the similarly named associated item
1193 /// in `self.current_trait_ref`.
1194 crate fn find_similarly_named_assoc_item(
1197 kind: &AssocItemKind,
1198 ) -> Option<Symbol> {
1199 let Some((module, _)) = &self.current_trait_ref else {
1202 if ident == kw::Underscore {
1203 // We do nothing for `_`.
1207 let resolutions = self.r.resolutions(module);
1208 let targets = resolutions
1211 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1212 .filter(|(_, res)| match (kind, res) {
1213 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1214 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1215 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1218 .map(|(key, _)| key.ident.name)
1219 .collect::<Vec<_>>();
1221 find_best_match_for_name(&targets, ident, None)
1224 fn lookup_assoc_candidate<FilterFn>(
1228 filter_fn: FilterFn,
1229 ) -> Option<AssocSuggestion>
1231 FilterFn: Fn(Res) -> bool,
1233 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1235 TyKind::Path(None, _) => Some(t.id),
1236 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1237 // This doesn't handle the remaining `Ty` variants as they are not
1238 // that commonly the self_type, it might be interesting to provide
1239 // support for those in future.
1244 // Fields are generally expected in the same contexts as locals.
1245 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1246 if let Some(node_id) =
1247 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1249 // Look for a field with the same name in the current self_type.
1250 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1251 match resolution.base_res() {
1252 Res::Def(DefKind::Struct | DefKind::Union, did)
1253 if resolution.unresolved_segments() == 0 =>
1255 if let Some(field_names) = self.r.field_names.get(&did) {
1258 .any(|&field_name| ident.name == field_name.node)
1260 return Some(AssocSuggestion::Field);
1270 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1271 for assoc_item in items {
1272 if assoc_item.ident == ident {
1273 return Some(match &assoc_item.kind {
1274 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1275 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1276 AssocSuggestion::MethodWithSelf
1278 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1279 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1280 ast::AssocItemKind::MacCall(_) => continue,
1286 // Look for associated items in the current trait.
1287 if let Some((module, _)) = self.current_trait_ref {
1288 if let Ok(binding) = self.r.resolve_ident_in_module(
1289 ModuleOrUniformRoot::Module(module),
1296 let res = binding.res();
1298 if self.r.has_self.contains(&res.def_id()) {
1299 return Some(AssocSuggestion::MethodWithSelf);
1302 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1303 Res::Def(DefKind::AssocConst, _) => {
1304 return Some(AssocSuggestion::AssocConst);
1306 Res::Def(DefKind::AssocTy, _) => {
1307 return Some(AssocSuggestion::AssocType);
1319 fn lookup_typo_candidate(
1323 filter_fn: &impl Fn(Res) -> bool,
1325 ) -> Option<TypoSuggestion> {
1326 let mut names = Vec::new();
1327 if path.len() == 1 {
1328 // Search in lexical scope.
1329 // Walk backwards up the ribs in scope and collect candidates.
1330 for rib in self.ribs[ns].iter().rev() {
1331 // Locals and type parameters
1332 for (ident, &res) in &rib.bindings {
1334 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1338 if let RibKind::ModuleRibKind(module) = rib.kind {
1339 // Items from this module
1340 self.r.add_module_candidates(module, &mut names, &filter_fn);
1342 if let ModuleKind::Block(..) = module.kind {
1343 // We can see through blocks
1345 // Items from the prelude
1346 if !module.no_implicit_prelude {
1347 let extern_prelude = self.r.extern_prelude.clone();
1348 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1349 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1351 let crate_mod = Res::Def(
1353 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
1356 if filter_fn(crate_mod) {
1357 Some(TypoSuggestion::typo_from_res(
1358 ident.name, crate_mod,
1367 if let Some(prelude) = self.r.prelude {
1368 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1375 // Add primitive types to the mix
1376 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1377 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1378 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1382 // Search in module.
1383 let mod_path = &path[..path.len() - 1];
1384 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1385 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
1387 self.r.add_module_candidates(module, &mut names, &filter_fn);
1391 let name = path[path.len() - 1].ident.name;
1392 // Make sure error reporting is deterministic.
1393 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1395 match find_best_match_for_name(
1396 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1400 Some(found) if found != name => {
1401 names.into_iter().find(|suggestion| suggestion.candidate == found)
1407 // Returns the name of the Rust type approximately corresponding to
1408 // a type name in another programming language.
1409 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1410 let name = path[path.len() - 1].ident.as_str();
1411 // Common Java types
1413 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1414 "short" => sym::i16,
1415 "boolean" => sym::bool,
1418 "float" => sym::f32,
1419 "double" => sym::f64,
1424 /// Only used in a specific case of type ascription suggestions
1425 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1426 let sm = self.r.session.source_map();
1427 start.to(sm.next_point(start))
1430 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1431 let sm = self.r.session.source_map();
1432 let base_snippet = sm.span_to_snippet(base_span);
1433 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1434 if let Ok(snippet) = sm.span_to_snippet(sp) {
1435 let len = snippet.trim_end().len() as u32;
1436 if snippet.trim() == ":" {
1438 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1439 let mut show_label = true;
1440 if sm.is_multiline(sp) {
1441 err.span_suggestion_short(
1443 "maybe you meant to write `;` here",
1445 Applicability::MaybeIncorrect,
1448 let after_colon_sp =
1449 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1450 if snippet.len() == 1 {
1452 err.span_suggestion(
1454 "maybe you meant to write a path separator here",
1456 Applicability::MaybeIncorrect,
1463 .type_ascription_path_suggestions
1467 err.downgrade_to_delayed_bug();
1470 if let Ok(base_snippet) = base_snippet {
1471 let mut sp = after_colon_sp;
1473 // Try to find an assignment
1474 sp = sm.next_point(sp);
1475 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1477 Ok(ref x) if x.as_str() == "=" => {
1478 err.span_suggestion(
1480 "maybe you meant to write an assignment here",
1481 format!("let {}", base_snippet),
1482 Applicability::MaybeIncorrect,
1487 Ok(ref x) if x.as_str() == "\n" => break,
1497 "expecting a type here because of type ascription",
1507 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1508 let mut result = None;
1509 let mut seen_modules = FxHashSet::default();
1510 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1512 while let Some((in_module, path_segments)) = worklist.pop() {
1513 // abort if the module is already found
1514 if result.is_some() {
1518 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1519 // abort if the module is already found or if name_binding is private external
1520 if result.is_some() || !name_binding.vis.is_visible_locally() {
1523 if let Some(module) = name_binding.module() {
1525 let mut path_segments = path_segments.clone();
1526 path_segments.push(ast::PathSegment::from_ident(ident));
1527 let module_def_id = module.def_id();
1528 if module_def_id == def_id {
1530 Path { span: name_binding.span, segments: path_segments, tokens: None };
1542 // add the module to the lookup
1543 if seen_modules.insert(module_def_id) {
1544 worklist.push((module, path_segments));
1554 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1555 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1556 let mut variants = Vec::new();
1557 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1558 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1559 let mut segms = enum_import_suggestion.path.segments.clone();
1560 segms.push(ast::PathSegment::from_ident(ident));
1561 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1562 variants.push((path, def_id, kind));
1569 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1570 fn suggest_using_enum_variant(
1572 err: &mut Diagnostic,
1573 source: PathSource<'_>,
1577 let Some(variants) = self.collect_enum_ctors(def_id) else {
1578 err.note("you might have meant to use one of the enum's variants");
1582 let suggest_only_tuple_variants =
1583 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1584 if suggest_only_tuple_variants {
1585 // Suggest only tuple variants regardless of whether they have fields and do not
1586 // suggest path with added parentheses.
1587 let suggestable_variants = variants
1589 .filter(|(.., kind)| *kind == CtorKind::Fn)
1590 .map(|(variant, ..)| path_names_to_string(variant))
1591 .collect::<Vec<_>>();
1593 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1595 let source_msg = if source.is_call() {
1597 } else if matches!(source, PathSource::TupleStruct(..)) {
1603 if !suggestable_variants.is_empty() {
1604 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1605 format!("try {} the enum's variant", source_msg)
1607 format!("try {} one of the enum's variants", source_msg)
1610 err.span_suggestions(
1613 suggestable_variants.into_iter(),
1614 Applicability::MaybeIncorrect,
1618 // If the enum has no tuple variants..
1619 if non_suggestable_variant_count == variants.len() {
1620 err.help(&format!("the enum has no tuple variants {}", source_msg));
1623 // If there are also non-tuple variants..
1624 if non_suggestable_variant_count == 1 {
1626 "you might have meant {} the enum's non-tuple variant",
1629 } else if non_suggestable_variant_count >= 1 {
1631 "you might have meant {} one of the enum's non-tuple variants",
1636 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1637 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1639 CtorKind::Const => false,
1640 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1645 let mut suggestable_variants = variants
1647 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1648 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1649 .map(|(variant, kind)| match kind {
1650 CtorKind::Const => variant,
1651 CtorKind::Fn => format!("({}())", variant),
1652 CtorKind::Fictive => format!("({} {{}})", variant),
1654 .collect::<Vec<_>>();
1656 if !suggestable_variants.is_empty() {
1657 let msg = if suggestable_variants.len() == 1 {
1658 "you might have meant to use the following enum variant"
1660 "you might have meant to use one of the following enum variants"
1663 err.span_suggestions(
1666 suggestable_variants.drain(..),
1667 Applicability::MaybeIncorrect,
1671 let suggestable_variants_with_placeholders = variants
1673 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1674 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1675 .filter_map(|(variant, kind)| match kind {
1676 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1677 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1680 .collect::<Vec<_>>();
1682 if !suggestable_variants_with_placeholders.is_empty() {
1684 suggestable_variants.is_empty(),
1685 suggestable_variants_with_placeholders.len(),
1687 (true, 1) => "the following enum variant is available",
1688 (true, _) => "the following enum variants are available",
1689 (false, 1) => "alternatively, the following enum variant is available",
1690 (false, _) => "alternatively, the following enum variants are also available",
1693 err.span_suggestions(
1696 suggestable_variants_with_placeholders.into_iter(),
1697 Applicability::HasPlaceholders,
1702 if def_id.is_local() {
1703 if let Some(span) = self.def_span(def_id) {
1704 err.span_note(span, "the enum is defined here");
1709 crate fn report_missing_type_error(
1712 ) -> Option<(Span, &'static str, String, Applicability)> {
1713 let (ident, span) = match path {
1714 [segment] if !segment.has_generic_args => {
1715 (segment.ident.to_string(), segment.ident.span)
1719 let mut iter = ident.chars().map(|c| c.is_uppercase());
1720 let single_uppercase_char =
1721 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1722 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1725 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1726 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1727 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1732 kind @ ItemKind::Fn(..)
1733 | kind @ ItemKind::Enum(..)
1734 | kind @ ItemKind::Struct(..)
1735 | kind @ ItemKind::Union(..),
1740 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1741 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1742 | (Some(Item { kind, .. }), false, _) => {
1743 // Likely missing type parameter.
1744 if let Some(generics) = kind.generics() {
1745 if span.overlaps(generics.span) {
1746 // Avoid the following:
1747 // error[E0405]: cannot find trait `A` in this scope
1748 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1750 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1751 // | ^- help: you might be missing a type parameter: `, A`
1753 // | not found in this scope
1756 let msg = "you might be missing a type parameter";
1757 let (span, sugg) = if let [.., param] = &generics.params[..] {
1758 let span = if let [.., bound] = ¶m.bounds[..] {
1760 } else if let GenericParam {
1761 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1763 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1767 (span, format!(", {}", ident))
1769 (generics.span, format!("<{}>", ident))
1771 // Do not suggest if this is coming from macro expansion.
1772 if span.can_be_used_for_suggestions() {
1774 span.shrink_to_hi(),
1777 Applicability::MaybeIncorrect,
1787 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1788 /// optionally returning the closest match and whether it is reachable.
1789 crate fn suggestion_for_label_in_rib(
1793 ) -> Option<LabelSuggestion> {
1794 // Are ribs from this `rib_index` within scope?
1795 let within_scope = self.is_label_valid_from_rib(rib_index);
1797 let rib = &self.label_ribs[rib_index];
1801 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1802 .map(|(id, _)| id.name)
1803 .collect::<Vec<Symbol>>();
1805 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1806 // Upon finding a similar name, get the ident that it was from - the span
1807 // contained within helps make a useful diagnostic. In addition, determine
1808 // whether this candidate is within scope.
1809 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1810 (*ident, within_scope)
1815 impl<'tcx> LifetimeContext<'_, 'tcx> {
1816 crate fn report_missing_lifetime_specifiers(
1820 ) -> DiagnosticBuilder<'tcx> {
1825 "missing lifetime specifier{}",
1830 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1831 let mut err = struct_span_err!(
1835 "use of undeclared lifetime name `{}`",
1838 err.span_label(lifetime_ref.span, "undeclared lifetime");
1839 let mut suggests_in_band = false;
1840 let mut suggested_spans = vec![];
1841 for missing in &self.missing_named_lifetime_spots {
1843 MissingLifetimeSpot::Generics(generics) => {
1844 let (span, sugg) = if let Some(param) = generics.params.iter().find(|p| {
1847 hir::GenericParamKind::Type { synthetic: true, .. }
1848 | hir::GenericParamKind::Lifetime {
1849 kind: hir::LifetimeParamKind::Elided,
1853 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1855 suggests_in_band = true;
1856 (generics.span, format!("<{}>", lifetime_ref))
1858 if suggested_spans.contains(&span) {
1861 suggested_spans.push(span);
1862 if span.can_be_used_for_suggestions() {
1863 err.span_suggestion(
1865 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1867 Applicability::MaybeIncorrect,
1871 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1872 err.span_suggestion(
1875 "consider making the {} lifetime-generic with a new `{}` lifetime",
1879 span_type.suggestion(&lifetime_ref.to_string()),
1880 Applicability::MaybeIncorrect,
1883 "for more information on higher-ranked polymorphism, visit \
1884 https://doc.rust-lang.org/nomicon/hrtb.html",
1890 if self.tcx.sess.is_nightly_build()
1891 && !self.tcx.features().in_band_lifetimes
1895 "if you want to experiment with in-band lifetime bindings, \
1896 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1902 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
1903 crate fn report_elision_failure(
1905 // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
1906 db: &mut Diagnostic,
1907 params: &[ElisionFailureInfo],
1909 let mut m = String::new();
1910 let len = params.len();
1912 let elided_params: Vec<_> =
1913 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
1915 let elided_len = elided_params.len();
1917 for (i, info) in elided_params.into_iter().enumerate() {
1918 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
1921 db.span_label(span, "");
1922 let help_name = if let Some(ident) =
1923 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
1925 format!("`{}`", ident)
1927 format!("argument {}", index + 1)
1935 "one of {}'s {} {}lifetimes",
1938 if have_bound_regions { "free " } else { "" }
1943 if elided_len == 2 && i == 0 {
1945 } else if i + 2 == elided_len {
1946 m.push_str(", or ");
1947 } else if i != elided_len - 1 {
1954 "this function's return type contains a borrowed value, \
1955 but there is no value for it to be borrowed from",
1958 } else if elided_len == 0 {
1960 "this function's return type contains a borrowed value with \
1961 an elided lifetime, but the lifetime cannot be derived from \
1965 } else if elided_len == 1 {
1967 "this function's return type contains a borrowed value, \
1968 but the signature does not say which {} it is borrowed from",
1974 "this function's return type contains a borrowed value, \
1975 but the signature does not say whether it is borrowed from {}",
1982 crate fn report_elided_lifetime_in_ty(&self, lifetime_refs: &[&hir::Lifetime]) {
1983 let Some(missing_lifetime) = lifetime_refs.iter().find(|lt| {
1984 lt.name == hir::LifetimeName::Implicit(true)
1987 let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
1989 let mut spans_dedup = spans.clone();
1990 spans_dedup.dedup();
1991 let spans_with_counts: Vec<_> = spans_dedup
1993 .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
1996 self.tcx.struct_span_lint_hir(
1997 rustc_session::lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1998 missing_lifetime.hir_id,
2001 let mut db = lint.build("hidden lifetime parameters in types are deprecated");
2002 self.add_missing_lifetime_specifiers_label(
2005 &FxHashSet::from_iter([kw::UnderscoreLifetime]),
2014 // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
2015 // generics. We are disallowing this until we can decide on how we want to handle non-'static
2016 // lifetimes in const generics. See issue #74052 for discussion.
2017 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
2018 let mut err = struct_span_err!(
2022 "use of non-static lifetime `{}` in const generic",
2026 "for more information, see issue #74052 \
2027 <https://github.com/rust-lang/rust/issues/74052>",
2032 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
2033 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2035 self.tcx.lang_items().fn_once_trait(),
2036 self.tcx.lang_items().fn_trait(),
2037 self.tcx.lang_items().fn_mut_trait(),
2039 .contains(&Some(did))
2041 let (span, span_type) = match &trait_ref.bound_generic_params {
2042 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2043 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2045 self.missing_named_lifetime_spots
2046 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2053 crate fn add_missing_lifetime_specifiers_label(
2055 err: &mut Diagnostic,
2056 mut spans_with_counts: Vec<(Span, usize)>,
2057 lifetime_names: &FxHashSet<Symbol>,
2058 lifetime_spans: Vec<Span>,
2059 params: &[ElisionFailureInfo],
2061 let snippets: Vec<Option<String>> = spans_with_counts
2063 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2066 // Empty generics are marked with a span of "<", but since from now on
2067 // that information is in the snippets it can be removed from the spans.
2068 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2069 if snippet.as_deref() == Some("<") {
2070 *span = span.shrink_to_hi();
2074 for &(span, count) in &spans_with_counts {
2078 "expected {} lifetime parameter{}",
2079 if count == 1 { "named".to_string() } else { count.to_string() },
2085 let suggest_existing =
2086 |err: &mut Diagnostic,
2088 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2089 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2090 self.missing_named_lifetime_spots.iter().rev().next()
2092 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2093 // using `'a`, but also introduce the concept of HRLTs by suggesting
2094 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2095 let mut introduce_suggestion = vec![];
2097 let a_to_z_repeat_n = |n| {
2098 (b'a'..=b'z').map(move |c| {
2099 let mut s = '\''.to_string();
2100 s.extend(std::iter::repeat(char::from(c)).take(n));
2105 // If all single char lifetime names are present, we wrap around and double the chars.
2107 .flat_map(a_to_z_repeat_n)
2108 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2111 "consider making the {} lifetime-generic with a new `{}` lifetime",
2116 "for more information on higher-ranked polymorphism, visit \
2117 https://doc.rust-lang.org/nomicon/hrtb.html",
2119 let for_sugg = span_type.suggestion(<_name);
2120 for param in params {
2121 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2123 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2124 introduce_suggestion
2125 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2126 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2127 introduce_suggestion
2128 .push((param.span, format!("&{} {}", lt_name, stripped)));
2132 introduce_suggestion.push((*for_span, for_sugg));
2133 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2134 if let Some(formatter) = formatter {
2135 introduce_suggestion.push((*span, formatter(<_name)));
2138 err.multipart_suggestion_verbose(
2140 introduce_suggestion,
2141 Applicability::MaybeIncorrect,
2145 let spans_suggs: Vec<_> = formatters
2147 .zip(spans_with_counts.iter())
2148 .filter_map(|(formatter, (span, _))| {
2149 if let Some(formatter) = formatter {
2150 Some((*span, formatter(name)))
2156 if spans_suggs.is_empty() {
2157 // If all the spans come from macros, we cannot extract snippets and then
2158 // `formatters` only contains None and `spans_suggs` is empty.
2161 err.multipart_suggestion_verbose(
2163 "consider using the `{}` lifetime",
2164 lifetime_names.iter().next().unwrap()
2167 Applicability::MaybeIncorrect,
2170 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2171 for missing in self.missing_named_lifetime_spots.iter().rev() {
2172 let mut introduce_suggestion = vec![];
2175 introduce_suggestion.push(match missing {
2176 MissingLifetimeSpot::Generics(generics) => {
2177 if generics.span == DUMMY_SP {
2178 // Account for malformed generics in the HIR. This shouldn't happen,
2179 // but if we make a mistake elsewhere, mainly by keeping something in
2180 // `missing_named_lifetime_spots` that we shouldn't, like associated
2181 // `const`s or making a mistake in the AST lowering we would provide
2182 // non-sensical suggestions. Guard against that by skipping these.
2186 msg = "consider introducing a named lifetime parameter".to_string();
2187 should_break = true;
2188 if let Some(param) = generics.params.iter().find(|p| {
2191 hir::GenericParamKind::Type { synthetic: true, .. }
2192 | hir::GenericParamKind::Lifetime {
2193 kind: hir::LifetimeParamKind::Elided
2197 (param.span.shrink_to_lo(), "'a, ".to_string())
2199 (generics.span, "<'a>".to_string())
2202 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2204 "consider making the {} lifetime-generic with a new `'a` lifetime",
2207 should_break = false;
2209 "for more information on higher-ranked polymorphism, visit \
2210 https://doc.rust-lang.org/nomicon/hrtb.html",
2212 (*span, span_type.suggestion("'a"))
2214 MissingLifetimeSpot::Static => {
2215 let mut spans_suggs = Vec::new();
2216 for ((span, count), snippet) in
2217 spans_with_counts.iter().copied().zip(snippets.iter())
2219 let (span, sugg) = match snippet.as_deref() {
2220 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2221 Some("'_") => (span, "'static".to_owned()),
2222 Some(snippet) if !snippet.ends_with('>') => {
2226 std::iter::repeat("'static")
2228 .collect::<Vec<_>>()
2231 } else if snippet == "<" || snippet == "(" {
2233 span.shrink_to_hi(),
2234 std::iter::repeat("'static")
2236 .collect::<Vec<_>>()
2241 span.shrink_to_hi(),
2244 std::iter::repeat("'static")
2246 .collect::<Vec<_>>()
2254 spans_suggs.push((span, sugg.to_string()));
2256 err.multipart_suggestion_verbose(
2257 "consider using the `'static` lifetime",
2259 Applicability::MaybeIncorrect,
2265 struct Lifetime(Span, String);
2267 fn is_unnamed(&self) -> bool {
2268 self.1.starts_with('&') && !self.1.starts_with("&'")
2270 fn is_underscore(&self) -> bool {
2271 self.1.starts_with("&'_ ")
2273 fn is_named(&self) -> bool {
2274 self.1.starts_with("&'")
2276 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2280 self.is_underscore(),
2282 sugg.starts_with('&'),
2284 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2285 (true, _, _, true) => {
2286 (self.span_unnamed_borrow(), sugg[1..].to_string())
2288 (_, true, _, false) => {
2289 (self.span_underscore_borrow(), sugg.trim().to_string())
2291 (_, true, _, true) => {
2292 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2294 (_, _, true, false) => {
2295 (self.span_named_borrow(), sugg.trim().to_string())
2297 (_, _, true, true) => {
2298 (self.span_named_borrow(), sugg[1..].trim().to_string())
2304 fn span_unnamed_borrow(&self) -> Span {
2305 let lo = self.0.lo() + BytePos(1);
2306 self.0.with_lo(lo).with_hi(lo)
2308 fn span_named_borrow(&self) -> Span {
2309 let lo = self.0.lo() + BytePos(1);
2312 fn span_underscore_borrow(&self) -> Span {
2313 let lo = self.0.lo() + BytePos(1);
2314 let hi = lo + BytePos(2);
2315 self.0.with_lo(lo).with_hi(hi)
2319 for param in params {
2320 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2321 if let Some((span, sugg)) =
2322 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2324 introduce_suggestion.push((span, sugg));
2328 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2329 |((span, _), sugg)| match &sugg {
2330 Some(sugg) => Some((span, sugg.to_string())),
2334 let (span, sugg) = self
2338 .span_to_snippet(span)
2340 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2341 .unwrap_or((span, sugg));
2342 introduce_suggestion.push((span, sugg.to_string()));
2344 err.multipart_suggestion_verbose(
2346 introduce_suggestion,
2347 Applicability::MaybeIncorrect,
2355 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2356 match &lifetime_names[..] {
2358 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2359 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2361 suggs.push(match snippet.as_deref() {
2362 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2363 Some("'_") => Some(Box::new(|n| n.to_string())),
2364 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2365 Some("<") => Some(Box::new(move |n| {
2366 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2368 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2372 std::iter::repeat(name.to_string())
2374 .collect::<Vec<_>>()
2381 suggest_existing(err, name.as_str(), suggs);
2384 let mut suggs = Vec::new();
2385 for (snippet, (_, count)) in
2386 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2388 suggs.push(match snippet.as_deref() {
2389 Some("&") => Some("&'a ".to_string()),
2390 Some("'_") => Some("'a".to_string()),
2392 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2395 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2397 Some(snippet) => Some(format!(
2400 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2405 suggest_new(err, suggs);
2407 lts if lts.len() > 1 => {
2408 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2410 let mut spans_suggs: Vec<_> = Vec::new();
2411 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2412 match snippet.as_deref() {
2413 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2414 Some("&") => spans_suggs
2415 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2420 if spans_suggs.len() > 0 {
2421 // This happens when we have `Foo<T>` where we point at the space before `T`,
2422 // but this can be confusing so we give a suggestion with placeholders.
2423 err.multipart_suggestion_verbose(
2424 "consider using one of the available lifetimes here",
2426 Applicability::HasPlaceholders,
2430 _ => unreachable!(),
2434 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2435 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2436 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2437 crate fn maybe_emit_forbidden_non_static_lifetime_error(
2439 body_id: hir::BodyId,
2440 lifetime_ref: &'tcx hir::Lifetime,
2442 let is_anon_const = matches!(
2443 self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
2444 hir::def::DefKind::AnonConst
2446 let is_allowed_lifetime = matches!(
2448 hir::LifetimeName::Implicit(_)
2449 | hir::LifetimeName::Static
2450 | hir::LifetimeName::Underscore
2453 if !self.tcx.lazy_normalization() && is_anon_const && !is_allowed_lifetime {
2455 &self.tcx.sess.parse_sess,
2456 sym::generic_const_exprs,
2458 "a non-static lifetime is not allowed in a `const`",