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};
5 use crate::path_names_to_string;
6 use crate::{Finalize, Module, ModuleKind, ModuleOrUniformRoot};
7 use crate::{PathResult, PathSource, Segment};
9 use rustc_ast::visit::FnKind;
11 self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
12 NodeId, Path, Ty, TyKind,
14 use rustc_ast_pretty::pprust::path_segment_to_string;
15 use rustc_data_structures::fx::FxHashSet;
17 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
21 use rustc_hir::def::Namespace::{self, *};
22 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
23 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
24 use rustc_hir::PrimTy;
25 use rustc_session::parse::feature_err;
26 use rustc_span::edition::Edition;
27 use rustc_span::hygiene::MacroKind;
28 use rustc_span::lev_distance::find_best_match_for_name;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::{BytePos, Span, DUMMY_SP};
37 type Res = def::Res<ast::NodeId>;
39 /// A field or associated item from self type suggested in case of resolution failure.
40 enum AssocSuggestion {
48 impl AssocSuggestion {
49 fn action(&self) -> &'static str {
51 AssocSuggestion::Field => "use the available field",
52 AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
53 AssocSuggestion::AssocFn => "call the associated function",
54 AssocSuggestion::AssocConst => "use the associated `const`",
55 AssocSuggestion::AssocType => "use the associated type",
60 crate enum MissingLifetimeSpot<'tcx> {
61 Generics(&'tcx hir::Generics<'tcx>),
62 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
66 crate enum ForLifetimeSpanType {
73 impl ForLifetimeSpanType {
74 crate fn descr(&self) -> &'static str {
76 Self::BoundEmpty | Self::BoundTail => "bound",
77 Self::TypeEmpty | Self::TypeTail => "type",
81 crate fn suggestion(&self, sugg: &str) -> String {
83 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
84 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
89 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
90 fn into(self) -> MissingLifetimeSpot<'tcx> {
91 MissingLifetimeSpot::Generics(self)
95 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
96 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
99 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
100 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
103 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
104 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
105 let variant_path = &suggestion.path;
106 let variant_path_string = path_names_to_string(variant_path);
108 let path_len = suggestion.path.segments.len();
109 let enum_path = ast::Path {
110 span: suggestion.path.span,
111 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
114 let enum_path_string = path_names_to_string(&enum_path);
116 (variant_path_string, enum_path_string)
119 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
120 fn def_span(&self, def_id: DefId) -> Option<Span> {
122 LOCAL_CRATE => self.r.opt_span(def_id),
127 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
132 /// Handles error reporting for `smart_resolve_path_fragment` function.
133 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
134 pub(crate) fn smart_resolve_report_errors(
138 source: PathSource<'_>,
140 ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
141 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
142 let ns = source.namespace();
143 let is_expected = &|res| source.is_expected(res);
144 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
146 // Make the base error.
147 let mut expected = source.descr_expected();
148 let path_str = Segment::names_to_string(path);
149 let item_str = path.last().unwrap().ident;
150 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
152 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
153 format!("not a {}", expected),
156 Res::Def(DefKind::Fn, _) => {
157 // Verify whether this is a fn call or an Fn used as a type.
161 .span_to_snippet(span)
162 .map(|snippet| snippet.ends_with(')'))
166 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
171 | Res::Local(_) => true,
176 let item_span = path.last().unwrap().ident.span;
177 let (mod_prefix, mod_str) = if path.len() == 1 {
178 (String::new(), "this scope".to_string())
179 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
180 if self.r.session.edition() > Edition::Edition2015 {
181 // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
182 // which overrides all other expectations of item type
184 (String::new(), "the list of imported crates".to_string())
186 (String::new(), "the crate root".to_string())
188 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
189 (String::new(), "the crate root".to_string())
191 let mod_path = &path[..path.len() - 1];
192 let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), Finalize::No) {
193 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
196 .map_or_else(String::new, |res| format!("{} ", res.descr()));
197 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
200 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
201 if path_str == "async" && expected.starts_with("struct") {
202 "`async` blocks are only allowed in Rust 2018 or later".to_string()
204 format!("not found in {}", mod_str)
211 let code = source.error_code(res.is_some());
212 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
214 if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
215 err.multipart_suggestion(
216 "you might have meant to write a `struct` literal",
218 (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
219 (span.shrink_to_hi(), "}".to_string()),
221 Applicability::HasPlaceholders,
224 match (source, self.diagnostic_metadata.in_if_condition) {
225 (PathSource::Expr(_), Some(Expr { span, kind: ExprKind::Assign(..), .. })) => {
226 err.span_suggestion_verbose(
228 "you might have meant to use pattern matching",
230 Applicability::MaybeIncorrect,
236 let is_assoc_fn = self.self_type_is_available();
237 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
238 if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
239 err.span_suggestion_short(
241 "you might have meant to use `self` here instead",
243 Applicability::MaybeIncorrect,
245 if !self.self_value_is_available(path[0].ident.span) {
246 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
247 &self.diagnostic_metadata.current_function
249 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
250 (param.span.shrink_to_lo(), "&self, ")
256 .span_through_char(*fn_span, '(')
261 err.span_suggestion_verbose(
263 "if you meant to use `self`, you are also missing a `self` receiver \
266 Applicability::MaybeIncorrect,
272 self.detect_assoct_type_constraint_meant_as_path(base_span, &mut err);
274 // Emit special messages for unresolved `Self` and `self`.
275 if is_self_type(path, ns) {
276 err.code(rustc_errors::error_code!(E0411));
279 "`Self` is only available in impls, traits, and type definitions".to_string(),
281 return (err, Vec::new());
283 if is_self_value(path, ns) {
284 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
286 err.code(rustc_errors::error_code!(E0424));
287 err.span_label(span, match source {
288 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
290 _ => "`self` value is a keyword only available in methods with a `self` parameter"
293 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
294 // The current function has a `self' parameter, but we were unable to resolve
295 // a reference to `self`. This can only happen if the `self` identifier we
296 // are resolving came from a different hygiene context.
297 if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
298 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
300 let doesnt = if is_assoc_fn {
301 let (span, sugg) = fn_kind
305 .map(|p| (p.span.shrink_to_lo(), "&self, "))
307 // Try to look for the "(" after the function name, if possible.
308 // This avoids placing the suggestion into the visibility specifier.
311 .map_or(*span, |ident| span.with_lo(ident.span.hi()));
316 .span_through_char(span, '(')
321 err.span_suggestion_verbose(
323 "add a `self` receiver parameter to make the associated `fn` a method",
325 Applicability::MaybeIncorrect,
331 if let Some(ident) = fn_kind.ident() {
334 &format!("this function {} have a `self` parameter", doesnt),
339 return (err, Vec::new());
342 // Try to lookup name in more relaxed fashion for better error reporting.
343 let ident = path.last().unwrap().ident;
344 let candidates = self
346 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
348 .filter(|ImportSuggestion { did, .. }| {
349 match (did, res.and_then(|res| res.opt_def_id())) {
350 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
354 .collect::<Vec<_>>();
355 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
356 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
357 let mut enum_candidates: Vec<_> = self
359 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
361 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
362 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
364 if !enum_candidates.is_empty() {
365 if let (PathSource::Type, Some(span)) =
366 (source, self.diagnostic_metadata.current_type_ascription.last())
372 .type_ascription_path_suggestions
376 // Already reported this issue on the lhs of the type ascription.
378 return (err, candidates);
382 enum_candidates.sort();
384 // Contextualize for E0412 "cannot find type", but don't belabor the point
385 // (that it's a variant) for E0573 "expected type, found variant".
386 let preamble = if res.is_none() {
387 let others = match enum_candidates.len() {
389 2 => " and 1 other".to_owned(),
390 n => format!(" and {} others", n),
392 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
396 let msg = format!("{}try using the variant's enum", preamble);
398 err.span_suggestions(
401 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
402 Applicability::MachineApplicable,
406 if path.len() == 1 && self.self_type_is_available() {
407 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
408 let self_is_available = self.self_value_is_available(path[0].ident.span);
410 AssocSuggestion::Field => {
411 if self_is_available {
414 "you might have meant to use the available field",
415 format!("self.{}", path_str),
416 Applicability::MachineApplicable,
419 err.span_label(span, "a field by this name exists in `Self`");
422 AssocSuggestion::MethodWithSelf if self_is_available => {
425 "you might have meant to call the method",
426 format!("self.{}", path_str),
427 Applicability::MachineApplicable,
430 AssocSuggestion::MethodWithSelf
431 | AssocSuggestion::AssocFn
432 | AssocSuggestion::AssocConst
433 | AssocSuggestion::AssocType => {
436 &format!("you might have meant to {}", candidate.action()),
437 format!("Self::{}", path_str),
438 Applicability::MachineApplicable,
442 return (err, candidates);
445 // If the first argument in call is `self` suggest calling a method.
446 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
447 let mut args_snippet = String::new();
448 if let Some(args_span) = args_span {
449 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
450 args_snippet = snippet;
456 &format!("try calling `{}` as a method", ident),
457 format!("self.{}({})", path_str, args_snippet),
458 Applicability::MachineApplicable,
460 return (err, candidates);
464 // Try Levenshtein algorithm.
465 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
466 // Try context-dependent help if relaxed lookup didn't work.
467 if let Some(res) = res {
468 if self.smart_resolve_context_dependent_help(
476 // We do this to avoid losing a secondary span when we override the main error span.
477 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
478 return (err, candidates);
482 let is_macro = base_span.from_expansion() && base_span.desugaring_kind().is_none();
483 if !self.type_ascription_suggestion(&mut err, base_span) {
484 let mut fallback = false;
486 PathSource::Trait(AliasPossibility::Maybe),
487 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
489 ) = (source, res, is_macro)
491 if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
493 let spans: Vec<Span> = bounds
495 .map(|bound| bound.span())
496 .filter(|&sp| sp != base_span)
499 let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
500 // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
501 let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
502 // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
503 let last_bound_span = spans.last().cloned().unwrap();
504 let mut multi_span: MultiSpan = spans.clone().into();
506 let msg = if sp == last_bound_span {
508 "...because of {these} bound{s}",
509 these = pluralize!("this", bounds.len() - 1),
510 s = pluralize!(bounds.len() - 1),
515 multi_span.push_span_label(sp, msg);
517 multi_span.push_span_label(
519 "expected this type to be a trait...".to_string(),
523 "`+` is used to constrain a \"trait object\" type with lifetimes or \
524 auto-traits; structs and enums can't be bound in that way",
526 if bounds.iter().all(|bound| match bound {
527 ast::GenericBound::Outlives(_) => true,
528 ast::GenericBound::Trait(tr, _) => tr.span == base_span,
530 let mut sugg = vec![];
531 if base_span != start_span {
532 sugg.push((start_span.until(base_span), String::new()));
534 if base_span != end_span {
535 sugg.push((base_span.shrink_to_hi().to(end_span), String::new()));
538 err.multipart_suggestion(
539 "if you meant to use a type and not a trait here, remove the bounds",
541 Applicability::MaybeIncorrect,
547 fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
549 if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
551 match self.diagnostic_metadata.current_let_binding {
552 Some((pat_sp, Some(ty_sp), None))
553 if ty_sp.contains(base_span) && could_be_expr =>
555 err.span_suggestion_short(
556 pat_sp.between(ty_sp),
557 "use `=` if you meant to assign",
559 Applicability::MaybeIncorrect,
565 // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
566 let suggestion = self.get_single_associated_item(&path, &source, is_expected);
567 self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
571 err.span_label(base_span, fallback_label);
574 if let Some(err_code) = &err.code {
575 if err_code == &rustc_errors::error_code!(E0425) {
576 for label_rib in &self.label_ribs {
577 for (label_ident, node_id) in &label_rib.bindings {
578 if format!("'{}", ident) == label_ident.to_string() {
579 err.span_label(label_ident.span, "a label with a similar name exists");
580 if let PathSource::Expr(Some(Expr {
581 kind: ExprKind::Break(None, Some(_)),
587 "use the similarly named label",
588 label_ident.name.to_string(),
589 Applicability::MaybeIncorrect,
591 // Do not lint against unused label when we suggest them.
592 self.diagnostic_metadata.unused_labels.remove(node_id);
597 } else if err_code == &rustc_errors::error_code!(E0412) {
598 if let Some(correct) = Self::likely_rust_type(path) {
601 "perhaps you intended to use this type",
603 Applicability::MaybeIncorrect,
612 fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
613 let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
614 let TyKind::Path(_, path) = &ty.kind else { return; };
615 for segment in &path.segments {
616 let Some(params) = &segment.args else { continue; };
617 let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
618 for param in ¶ms.args {
619 let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
620 let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
623 for bound in bounds {
624 let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
629 if base_span == trait_ref.span {
630 err.span_suggestion_verbose(
631 constraint.ident.span.between(trait_ref.span),
632 "you might have meant to write a path instead of an associated type bound",
634 Applicability::MachineApplicable,
642 fn get_single_associated_item(
645 source: &PathSource<'_>,
646 filter_fn: &impl Fn(Res) -> bool,
647 ) -> Option<TypoSuggestion> {
648 if let crate::PathSource::TraitItem(_) = source {
649 let mod_path = &path[..path.len() - 1];
650 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
651 self.resolve_path(mod_path, None, Finalize::No)
653 let resolutions = self.r.resolutions(module).borrow();
654 let targets: Vec<_> =
657 .filter_map(|(key, resolution)| {
658 resolution.borrow().binding.map(|binding| binding.res()).and_then(
659 |res| if filter_fn(res) { Some((key, res)) } else { None },
663 if targets.len() == 1 {
664 let target = targets[0];
665 return Some(TypoSuggestion::single_item_from_res(
675 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
676 fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
677 // Detect that we are actually in a `where` predicate.
678 let (bounded_ty, bounds, where_span) =
679 if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
681 bound_generic_params,
684 })) = self.diagnostic_metadata.current_where_predicate
686 if !bound_generic_params.is_empty() {
689 (bounded_ty, bounds, span)
694 // Confirm that the target is an associated type.
695 let (ty, position, path) = if let ast::TyKind::Path(
696 Some(ast::QSelf { ty, position, .. }),
700 // use this to verify that ident is a type param.
701 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
705 partial_res.base_res(),
706 hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
707 ) && partial_res.unresolved_segments() == 0)
716 let peeled_ty = ty.peel_refs();
717 if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
718 // Confirm that the `SelfTy` is a type parameter.
719 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
723 partial_res.base_res(),
724 hir::def::Res::Def(hir::def::DefKind::TyParam, _)
725 ) && partial_res.unresolved_segments() == 0)
730 [ast::PathSegment { ident: constrain_ident, args: None, .. }],
731 [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
732 ) = (&type_param_path.segments[..], &bounds[..])
734 if let [ast::PathSegment { ident, args: None, .. }] =
735 &poly_trait_ref.trait_ref.path.segments[..]
737 if ident.span == span {
738 err.span_suggestion_verbose(
740 &format!("constrain the associated type to `{}`", ident),
746 .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
747 .unwrap_or_else(|_| constrain_ident.to_string()),
748 path.segments[..*position]
750 .map(|segment| path_segment_to_string(segment))
753 path.segments[*position..]
755 .map(|segment| path_segment_to_string(segment))
760 Applicability::MaybeIncorrect,
770 /// Check if the source is call expression and the first argument is `self`. If true,
771 /// return the span of whole call and the span for all arguments expect the first one (`self`).
772 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
773 let mut has_self_arg = None;
774 if let PathSource::Expr(Some(parent)) = source {
776 ExprKind::Call(_, args) if !args.is_empty() => {
777 let mut expr_kind = &args[0].kind;
780 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
781 if arg_name.segments[0].ident.name == kw::SelfLower {
782 let call_span = parent.span;
783 let tail_args_span = if args.len() > 1 {
786 args.last().unwrap().span.hi(),
793 has_self_arg = Some((call_span, tail_args_span));
797 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
808 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
809 // HACK(estebank): find a better way to figure out that this was a
810 // parser issue where a struct literal is being used on an expression
811 // where a brace being opened means a block is being started. Look
812 // ahead for the next text to see if `span` is followed by a `{`.
813 let sm = self.r.session.source_map();
816 sp = sm.next_point(sp);
817 match sm.span_to_snippet(sp) {
819 if snippet.chars().any(|c| !c.is_whitespace()) {
826 let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
827 // In case this could be a struct literal that needs to be surrounded
828 // by parentheses, find the appropriate span.
830 let mut closing_brace = None;
832 sp = sm.next_point(sp);
833 match sm.span_to_snippet(sp) {
836 closing_brace = Some(span.to(sp));
843 // The bigger the span, the more likely we're incorrect --
844 // bound it to 100 chars long.
849 (followed_by_brace, closing_brace)
852 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
854 /// Returns `true` if able to provide context-dependent help.
855 fn smart_resolve_context_dependent_help(
857 err: &mut Diagnostic,
859 source: PathSource<'_>,
862 fallback_label: &str,
864 let ns = source.namespace();
865 let is_expected = &|res| source.is_expected(res);
867 let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
868 ExprKind::Field(_, ident) => {
871 "use the path separator to refer to an item",
872 format!("{}::{}", path_str, ident),
873 Applicability::MaybeIncorrect,
877 ExprKind::MethodCall(ref segment, ..) => {
878 let span = expr.span.with_hi(segment.ident.span.hi());
881 "use the path separator to refer to an item",
882 format!("{}::{}", path_str, segment.ident),
883 Applicability::MaybeIncorrect,
890 let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
892 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
893 | PathSource::TupleStruct(span, _) => {
894 // We want the main underline to cover the suggested code as well for
903 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
904 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
907 PathSource::Expr(Some(
908 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
909 )) if path_sep(err, &parent) => {}
915 | ExprKind::Binary(..)
916 | ExprKind::Unary(..)
918 | ExprKind::While(..)
919 | ExprKind::ForLoop(..)
920 | ExprKind::Match(..),
923 ) if followed_by_brace => {
924 if let Some(sp) = closing_brace {
925 err.span_label(span, fallback_label);
926 err.multipart_suggestion(
927 "surround the struct literal with parentheses",
929 (sp.shrink_to_lo(), "(".to_string()),
930 (sp.shrink_to_hi(), ")".to_string()),
932 Applicability::MaybeIncorrect,
936 span, // Note the parentheses surrounding the suggestion below
938 "you might want to surround a struct literal with parentheses: \
939 `({} {{ /* fields */ }})`?",
945 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
946 let span = find_span(&source, err);
947 if let Some(span) = self.def_span(def_id) {
948 err.span_label(span, &format!("`{}` defined here", path_str));
950 let (tail, descr, applicability) = match source {
951 PathSource::Pat | PathSource::TupleStruct(..) => {
952 ("", "pattern", Applicability::MachineApplicable)
954 _ => (": val", "literal", Applicability::HasPlaceholders),
956 let (fields, applicability) = match self.r.field_names.get(&def_id) {
960 .map(|f| format!("{}{}", f.node, tail))
961 .collect::<Vec<String>>()
965 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
967 let pad = match self.r.field_names.get(&def_id) {
968 Some(fields) if fields.is_empty() => "",
973 &format!("use struct {} syntax instead", descr),
974 format!("{path_str} {{{pad}{fields}{pad}}}"),
979 err.span_label(span, fallback_label);
984 match (res, source) {
986 Res::Def(DefKind::Macro(MacroKind::Bang), _),
987 PathSource::Expr(Some(Expr {
988 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
990 | PathSource::Struct,
992 err.span_label(span, fallback_label);
993 err.span_suggestion_verbose(
995 "use `!` to invoke the macro",
997 Applicability::MaybeIncorrect,
999 if path_str == "try" && span.rust_2015() {
1000 err.note("if you want the `try` keyword, you need Rust 2018 or later");
1003 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
1004 err.span_label(span, fallback_label);
1006 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1007 err.span_label(span, "type aliases cannot be used as traits");
1008 if self.r.session.is_nightly_build() {
1009 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1011 if let Some(span) = self.def_span(def_id) {
1012 if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
1013 // The span contains a type alias so we should be able to
1014 // replace `type` with `trait`.
1015 let snip = snip.replacen("type", "trait", 1);
1016 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1018 err.span_help(span, msg);
1025 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
1026 if !path_sep(err, &parent) {
1031 Res::Def(DefKind::Enum, def_id),
1032 PathSource::TupleStruct(..) | PathSource::Expr(..),
1035 .diagnostic_metadata
1036 .current_type_ascription
1042 .type_ascription_path_suggestions
1048 err.downgrade_to_delayed_bug();
1049 // We already suggested changing `:` into `::` during parsing.
1053 self.suggest_using_enum_variant(err, source, def_id, span);
1055 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1056 let (ctor_def, ctor_vis, fields) =
1057 if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
1058 if let PathSource::Expr(Some(parent)) = source {
1059 if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
1060 bad_struct_syntax_suggestion(def_id);
1066 bad_struct_syntax_suggestion(def_id);
1070 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1071 if !is_expected(ctor_def) || is_accessible {
1075 let field_spans = match source {
1076 // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1077 PathSource::TupleStruct(_, pattern_spans) => {
1078 err.set_primary_message(
1079 "cannot match against a tuple struct which contains private fields",
1082 // Use spans of the tuple struct pattern.
1083 Some(Vec::from(pattern_spans))
1085 // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1086 _ if source.is_call() => {
1087 err.set_primary_message(
1088 "cannot initialize a tuple struct which contains private fields",
1091 // Use spans of the tuple struct definition.
1095 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1100 if let Some(spans) =
1101 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1103 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1104 .filter(|(vis, _)| {
1105 !self.r.is_accessible_from(**vis, self.parent_scope.module)
1107 .map(|(_, span)| *span)
1110 if non_visible_spans.len() > 0 {
1111 let mut m: MultiSpan = non_visible_spans.clone().into();
1114 .for_each(|s| m.push_span_label(s, "private field".to_string()));
1115 err.span_note(m, "constructor is not visible here due to private fields");
1123 "constructor is not visible here due to private fields".to_string(),
1128 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
1132 ) if ns == ValueNS => {
1133 bad_struct_syntax_suggestion(def_id);
1135 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
1137 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1138 let span = find_span(&source, err);
1139 if let Some(span) = self.def_span(def_id) {
1140 err.span_label(span, &format!("`{}` defined here", path_str));
1142 err.span_suggestion(
1144 "use this syntax instead",
1145 path_str.to_string(),
1146 Applicability::MaybeIncorrect,
1152 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
1153 if let Some(span) = self.def_span(def_id) {
1154 err.span_label(span, &format!("`{}` defined here", path_str));
1156 let fields = self.r.field_names.get(&def_id).map_or_else(
1157 || "/* fields */".to_string(),
1158 |fields| vec!["_"; fields.len()].join(", "),
1160 err.span_suggestion(
1162 "use the tuple variant pattern syntax instead",
1163 format!("{}({})", path_str, fields),
1164 Applicability::HasPlaceholders,
1167 (Res::SelfTy { .. }, _) if ns == ValueNS => {
1168 err.span_label(span, fallback_label);
1169 err.note("can't use `Self` as a constructor, you must use the implemented struct");
1171 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
1172 err.note("can't use a type alias as a constructor");
1179 /// Given the target `ident` and `kind`, search for the similarly named associated item
1180 /// in `self.current_trait_ref`.
1181 crate fn find_similarly_named_assoc_item(
1184 kind: &AssocItemKind,
1185 ) -> Option<Symbol> {
1186 let Some((module, _)) = &self.current_trait_ref else {
1189 if ident == kw::Underscore {
1190 // We do nothing for `_`.
1194 let resolutions = self.r.resolutions(module);
1195 let targets = resolutions
1198 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1199 .filter(|(_, res)| match (kind, res) {
1200 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1201 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1202 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1205 .map(|(key, _)| key.ident.name)
1206 .collect::<Vec<_>>();
1208 find_best_match_for_name(&targets, ident, None)
1211 fn lookup_assoc_candidate<FilterFn>(
1215 filter_fn: FilterFn,
1216 ) -> Option<AssocSuggestion>
1218 FilterFn: Fn(Res) -> bool,
1220 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1222 TyKind::Path(None, _) => Some(t.id),
1223 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1224 // This doesn't handle the remaining `Ty` variants as they are not
1225 // that commonly the self_type, it might be interesting to provide
1226 // support for those in future.
1231 // Fields are generally expected in the same contexts as locals.
1232 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1233 if let Some(node_id) =
1234 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1236 // Look for a field with the same name in the current self_type.
1237 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1238 match resolution.base_res() {
1239 Res::Def(DefKind::Struct | DefKind::Union, did)
1240 if resolution.unresolved_segments() == 0 =>
1242 if let Some(field_names) = self.r.field_names.get(&did) {
1245 .any(|&field_name| ident.name == field_name.node)
1247 return Some(AssocSuggestion::Field);
1257 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1258 for assoc_item in items {
1259 if assoc_item.ident == ident {
1260 return Some(match &assoc_item.kind {
1261 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1262 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1263 AssocSuggestion::MethodWithSelf
1265 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1266 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1267 ast::AssocItemKind::MacCall(_) => continue,
1273 // Look for associated items in the current trait.
1274 if let Some((module, _)) = self.current_trait_ref {
1275 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1276 ModuleOrUniformRoot::Module(module),
1281 let res = binding.res();
1283 if self.r.has_self.contains(&res.def_id()) {
1284 return Some(AssocSuggestion::MethodWithSelf);
1287 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1288 Res::Def(DefKind::AssocConst, _) => {
1289 return Some(AssocSuggestion::AssocConst);
1291 Res::Def(DefKind::AssocTy, _) => {
1292 return Some(AssocSuggestion::AssocType);
1304 fn lookup_typo_candidate(
1308 filter_fn: &impl Fn(Res) -> bool,
1309 ) -> Option<TypoSuggestion> {
1310 let mut names = Vec::new();
1311 if path.len() == 1 {
1312 // Search in lexical scope.
1313 // Walk backwards up the ribs in scope and collect candidates.
1314 for rib in self.ribs[ns].iter().rev() {
1315 // Locals and type parameters
1316 for (ident, &res) in &rib.bindings {
1318 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1322 if let RibKind::ModuleRibKind(module) = rib.kind {
1323 // Items from this module
1324 self.r.add_module_candidates(module, &mut names, &filter_fn);
1326 if let ModuleKind::Block(..) = module.kind {
1327 // We can see through blocks
1329 // Items from the prelude
1330 if !module.no_implicit_prelude {
1331 let extern_prelude = self.r.extern_prelude.clone();
1332 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1333 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1335 let crate_mod = Res::Def(
1337 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
1340 if filter_fn(crate_mod) {
1341 Some(TypoSuggestion::typo_from_res(
1342 ident.name, crate_mod,
1351 if let Some(prelude) = self.r.prelude {
1352 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1359 // Add primitive types to the mix
1360 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1361 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1362 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1366 // Search in module.
1367 let mod_path = &path[..path.len() - 1];
1368 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1369 self.resolve_path(mod_path, Some(TypeNS), Finalize::No)
1371 self.r.add_module_candidates(module, &mut names, &filter_fn);
1375 let name = path[path.len() - 1].ident.name;
1376 // Make sure error reporting is deterministic.
1377 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1379 match find_best_match_for_name(
1380 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1384 Some(found) if found != name => {
1385 names.into_iter().find(|suggestion| suggestion.candidate == found)
1391 // Returns the name of the Rust type approximately corresponding to
1392 // a type name in another programming language.
1393 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1394 let name = path[path.len() - 1].ident.as_str();
1395 // Common Java types
1397 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1398 "short" => sym::i16,
1399 "boolean" => sym::bool,
1402 "float" => sym::f32,
1403 "double" => sym::f64,
1408 /// Only used in a specific case of type ascription suggestions
1409 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1410 let sm = self.r.session.source_map();
1411 start.to(sm.next_point(start))
1414 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1415 let sm = self.r.session.source_map();
1416 let base_snippet = sm.span_to_snippet(base_span);
1417 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1418 if let Ok(snippet) = sm.span_to_snippet(sp) {
1419 let len = snippet.trim_end().len() as u32;
1420 if snippet.trim() == ":" {
1422 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1423 let mut show_label = true;
1424 if sm.is_multiline(sp) {
1425 err.span_suggestion_short(
1427 "maybe you meant to write `;` here",
1429 Applicability::MaybeIncorrect,
1432 let after_colon_sp =
1433 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1434 if snippet.len() == 1 {
1436 err.span_suggestion(
1438 "maybe you meant to write a path separator here",
1440 Applicability::MaybeIncorrect,
1447 .type_ascription_path_suggestions
1451 err.downgrade_to_delayed_bug();
1454 if let Ok(base_snippet) = base_snippet {
1455 let mut sp = after_colon_sp;
1457 // Try to find an assignment
1458 sp = sm.next_point(sp);
1459 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1461 Ok(ref x) if x.as_str() == "=" => {
1462 err.span_suggestion(
1464 "maybe you meant to write an assignment here",
1465 format!("let {}", base_snippet),
1466 Applicability::MaybeIncorrect,
1471 Ok(ref x) if x.as_str() == "\n" => break,
1481 "expecting a type here because of type ascription",
1491 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1492 let mut result = None;
1493 let mut seen_modules = FxHashSet::default();
1494 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1496 while let Some((in_module, path_segments)) = worklist.pop() {
1497 // abort if the module is already found
1498 if result.is_some() {
1502 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1503 // abort if the module is already found or if name_binding is private external
1504 if result.is_some() || !name_binding.vis.is_visible_locally() {
1507 if let Some(module) = name_binding.module() {
1509 let mut path_segments = path_segments.clone();
1510 path_segments.push(ast::PathSegment::from_ident(ident));
1511 let module_def_id = module.def_id();
1512 if module_def_id == def_id {
1514 Path { span: name_binding.span, segments: path_segments, tokens: None };
1526 // add the module to the lookup
1527 if seen_modules.insert(module_def_id) {
1528 worklist.push((module, path_segments));
1538 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1539 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1540 let mut variants = Vec::new();
1541 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1542 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1543 let mut segms = enum_import_suggestion.path.segments.clone();
1544 segms.push(ast::PathSegment::from_ident(ident));
1545 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1546 variants.push((path, def_id, kind));
1553 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1554 fn suggest_using_enum_variant(
1556 err: &mut Diagnostic,
1557 source: PathSource<'_>,
1561 let Some(variants) = self.collect_enum_ctors(def_id) else {
1562 err.note("you might have meant to use one of the enum's variants");
1566 let suggest_only_tuple_variants =
1567 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1568 if suggest_only_tuple_variants {
1569 // Suggest only tuple variants regardless of whether they have fields and do not
1570 // suggest path with added parentheses.
1571 let suggestable_variants = variants
1573 .filter(|(.., kind)| *kind == CtorKind::Fn)
1574 .map(|(variant, ..)| path_names_to_string(variant))
1575 .collect::<Vec<_>>();
1577 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1579 let source_msg = if source.is_call() {
1581 } else if matches!(source, PathSource::TupleStruct(..)) {
1587 if !suggestable_variants.is_empty() {
1588 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1589 format!("try {} the enum's variant", source_msg)
1591 format!("try {} one of the enum's variants", source_msg)
1594 err.span_suggestions(
1597 suggestable_variants.into_iter(),
1598 Applicability::MaybeIncorrect,
1602 // If the enum has no tuple variants..
1603 if non_suggestable_variant_count == variants.len() {
1604 err.help(&format!("the enum has no tuple variants {}", source_msg));
1607 // If there are also non-tuple variants..
1608 if non_suggestable_variant_count == 1 {
1610 "you might have meant {} the enum's non-tuple variant",
1613 } else if non_suggestable_variant_count >= 1 {
1615 "you might have meant {} one of the enum's non-tuple variants",
1620 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1621 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1623 CtorKind::Const => false,
1624 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1629 let mut suggestable_variants = variants
1631 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1632 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1633 .map(|(variant, kind)| match kind {
1634 CtorKind::Const => variant,
1635 CtorKind::Fn => format!("({}())", variant),
1636 CtorKind::Fictive => format!("({} {{}})", variant),
1638 .collect::<Vec<_>>();
1640 if !suggestable_variants.is_empty() {
1641 let msg = if suggestable_variants.len() == 1 {
1642 "you might have meant to use the following enum variant"
1644 "you might have meant to use one of the following enum variants"
1647 err.span_suggestions(
1650 suggestable_variants.drain(..),
1651 Applicability::MaybeIncorrect,
1655 let suggestable_variants_with_placeholders = variants
1657 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1658 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1659 .filter_map(|(variant, kind)| match kind {
1660 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1661 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1664 .collect::<Vec<_>>();
1666 if !suggestable_variants_with_placeholders.is_empty() {
1668 suggestable_variants.is_empty(),
1669 suggestable_variants_with_placeholders.len(),
1671 (true, 1) => "the following enum variant is available",
1672 (true, _) => "the following enum variants are available",
1673 (false, 1) => "alternatively, the following enum variant is available",
1674 (false, _) => "alternatively, the following enum variants are also available",
1677 err.span_suggestions(
1680 suggestable_variants_with_placeholders.into_iter(),
1681 Applicability::HasPlaceholders,
1686 if def_id.is_local() {
1687 if let Some(span) = self.def_span(def_id) {
1688 err.span_note(span, "the enum is defined here");
1693 crate fn report_missing_type_error(
1696 ) -> Option<(Span, &'static str, String, Applicability)> {
1697 let (ident, span) = match path {
1698 [segment] if !segment.has_generic_args => {
1699 (segment.ident.to_string(), segment.ident.span)
1703 let mut iter = ident.chars().map(|c| c.is_uppercase());
1704 let single_uppercase_char =
1705 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1706 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1709 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1710 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1711 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1716 kind @ ItemKind::Fn(..)
1717 | kind @ ItemKind::Enum(..)
1718 | kind @ ItemKind::Struct(..)
1719 | kind @ ItemKind::Union(..),
1724 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1725 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1726 | (Some(Item { kind, .. }), false, _) => {
1727 // Likely missing type parameter.
1728 if let Some(generics) = kind.generics() {
1729 if span.overlaps(generics.span) {
1730 // Avoid the following:
1731 // error[E0405]: cannot find trait `A` in this scope
1732 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1734 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1735 // | ^- help: you might be missing a type parameter: `, A`
1737 // | not found in this scope
1740 let msg = "you might be missing a type parameter";
1741 let (span, sugg) = if let [.., param] = &generics.params[..] {
1742 let span = if let [.., bound] = ¶m.bounds[..] {
1744 } else if let GenericParam {
1745 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1747 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1751 (span, format!(", {}", ident))
1753 (generics.span, format!("<{}>", ident))
1755 // Do not suggest if this is coming from macro expansion.
1756 if span.can_be_used_for_suggestions() {
1758 span.shrink_to_hi(),
1761 Applicability::MaybeIncorrect,
1771 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1772 /// optionally returning the closest match and whether it is reachable.
1773 crate fn suggestion_for_label_in_rib(
1777 ) -> Option<LabelSuggestion> {
1778 // Are ribs from this `rib_index` within scope?
1779 let within_scope = self.is_label_valid_from_rib(rib_index);
1781 let rib = &self.label_ribs[rib_index];
1785 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1786 .map(|(id, _)| id.name)
1787 .collect::<Vec<Symbol>>();
1789 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1790 // Upon finding a similar name, get the ident that it was from - the span
1791 // contained within helps make a useful diagnostic. In addition, determine
1792 // whether this candidate is within scope.
1793 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1794 (*ident, within_scope)
1798 crate fn emit_undeclared_lifetime_error(
1800 lifetime_ref: &ast::Lifetime,
1801 outer_lifetime_ref: Option<Ident>,
1803 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1804 let mut err = if let Some(outer) = outer_lifetime_ref {
1805 let mut err = struct_span_err!(
1807 lifetime_ref.ident.span,
1809 "can't use generic parameters from outer item",
1811 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1812 err.span_label(outer.span, "lifetime parameter from outer item");
1815 let mut err = struct_span_err!(
1817 lifetime_ref.ident.span,
1819 "use of undeclared lifetime name `{}`",
1822 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
1825 let mut suggest_note = true;
1827 for rib in self.lifetime_ribs.iter().rev() {
1829 LifetimeRibKind::Generics { span, kind } => {
1830 if !span.can_be_used_for_suggestions() && suggest_note {
1831 suggest_note = false; // Avoid displaying the same help multiple times.
1835 "lifetime `{}` is missing in item created through this procedural macro",
1842 let higher_ranked = matches!(
1844 LifetimeBinderKind::BareFnType
1845 | LifetimeBinderKind::PolyTrait
1846 | LifetimeBinderKind::WhereBound
1848 let (span, sugg) = if span.is_empty() {
1851 if higher_ranked { "for" } else { "" },
1853 if higher_ranked { " " } else { "" },
1858 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
1859 let sugg = format!("{}, ", lifetime_ref.ident);
1863 err.span_suggestion(
1866 "consider making the {} lifetime-generic with a new `{}` lifetime",
1871 Applicability::MaybeIncorrect,
1874 "for more information on higher-ranked polymorphism, visit \
1875 https://doc.rust-lang.org/nomicon/hrtb.html",
1878 err.span_suggestion(
1880 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
1882 Applicability::MaybeIncorrect,
1886 LifetimeRibKind::Item => break,
1895 impl<'tcx> LifetimeContext<'_, 'tcx> {
1896 crate fn report_missing_lifetime_specifiers(
1900 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1905 "missing lifetime specifier{}",
1910 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
1911 crate fn report_elision_failure(
1913 diag: &mut Diagnostic,
1914 params: &[ElisionFailureInfo],
1916 let mut m = String::new();
1917 let len = params.len();
1919 let elided_params: Vec<_> =
1920 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
1922 let elided_len = elided_params.len();
1924 for (i, info) in elided_params.into_iter().enumerate() {
1925 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
1928 diag.span_label(span, "");
1929 let help_name = if let Some(ident) =
1930 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
1932 format!("`{}`", ident)
1934 format!("argument {}", index + 1)
1942 "one of {}'s {} {}lifetimes",
1945 if have_bound_regions { "free " } else { "" }
1950 if elided_len == 2 && i == 0 {
1952 } else if i + 2 == elided_len {
1953 m.push_str(", or ");
1954 } else if i != elided_len - 1 {
1961 "this function's return type contains a borrowed value, \
1962 but there is no value for it to be borrowed from",
1965 } else if elided_len == 0 {
1967 "this function's return type contains a borrowed value with \
1968 an elided lifetime, but the lifetime cannot be derived from \
1972 } else if elided_len == 1 {
1974 "this function's return type contains a borrowed value, \
1975 but the signature does not say which {} it is borrowed from",
1981 "this function's return type contains a borrowed value, \
1982 but the signature does not say whether it is borrowed from {}",
1989 // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
1990 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1991 // lifetimes in const generics. See issue #74052 for discussion.
1992 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1993 let mut err = struct_span_err!(
1997 "use of non-static lifetime `{}` in const generic",
2001 "for more information, see issue #74052 \
2002 <https://github.com/rust-lang/rust/issues/74052>",
2007 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
2008 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2010 self.tcx.lang_items().fn_once_trait(),
2011 self.tcx.lang_items().fn_trait(),
2012 self.tcx.lang_items().fn_mut_trait(),
2014 .contains(&Some(did))
2016 let (span, span_type) = match &trait_ref.bound_generic_params {
2017 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2018 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2020 self.missing_named_lifetime_spots
2021 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2028 crate fn add_missing_lifetime_specifiers_label(
2030 err: &mut Diagnostic,
2031 mut spans_with_counts: Vec<(Span, usize)>,
2032 lifetime_names: &FxHashSet<Symbol>,
2033 lifetime_spans: Vec<Span>,
2034 params: &[ElisionFailureInfo],
2036 let snippets: Vec<Option<String>> = spans_with_counts
2038 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2041 // Empty generics are marked with a span of "<", but since from now on
2042 // that information is in the snippets it can be removed from the spans.
2043 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2044 if snippet.as_deref() == Some("<") {
2045 *span = span.shrink_to_hi();
2049 for &(span, count) in &spans_with_counts {
2053 "expected {} lifetime parameter{}",
2054 if count == 1 { "named".to_string() } else { count.to_string() },
2060 let suggest_existing =
2061 |err: &mut Diagnostic,
2063 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2064 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2065 self.missing_named_lifetime_spots.iter().rev().next()
2067 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2068 // using `'a`, but also introduce the concept of HRLTs by suggesting
2069 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2070 let mut introduce_suggestion = vec![];
2072 let a_to_z_repeat_n = |n| {
2073 (b'a'..=b'z').map(move |c| {
2074 let mut s = '\''.to_string();
2075 s.extend(std::iter::repeat(char::from(c)).take(n));
2080 // If all single char lifetime names are present, we wrap around and double the chars.
2082 .flat_map(a_to_z_repeat_n)
2083 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2086 "consider making the {} lifetime-generic with a new `{}` lifetime",
2091 "for more information on higher-ranked polymorphism, visit \
2092 https://doc.rust-lang.org/nomicon/hrtb.html",
2094 let for_sugg = span_type.suggestion(<_name);
2095 for param in params {
2096 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2098 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2099 introduce_suggestion
2100 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2101 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2102 introduce_suggestion
2103 .push((param.span, format!("&{} {}", lt_name, stripped)));
2107 introduce_suggestion.push((*for_span, for_sugg));
2108 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2109 if let Some(formatter) = formatter {
2110 introduce_suggestion.push((*span, formatter(<_name)));
2113 err.multipart_suggestion_verbose(
2115 introduce_suggestion,
2116 Applicability::MaybeIncorrect,
2120 let spans_suggs: Vec<_> = formatters
2122 .zip(spans_with_counts.iter())
2123 .filter_map(|(formatter, (span, _))| {
2124 if let Some(formatter) = formatter {
2125 Some((*span, formatter(name)))
2131 if spans_suggs.is_empty() {
2132 // If all the spans come from macros, we cannot extract snippets and then
2133 // `formatters` only contains None and `spans_suggs` is empty.
2136 err.multipart_suggestion_verbose(
2138 "consider using the `{}` lifetime",
2139 lifetime_names.iter().next().unwrap()
2142 Applicability::MaybeIncorrect,
2145 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2146 for missing in self.missing_named_lifetime_spots.iter().rev() {
2147 let mut introduce_suggestion = vec![];
2150 introduce_suggestion.push(match missing {
2151 MissingLifetimeSpot::Generics(generics) => {
2152 if generics.span == DUMMY_SP {
2153 // Account for malformed generics in the HIR. This shouldn't happen,
2154 // but if we make a mistake elsewhere, mainly by keeping something in
2155 // `missing_named_lifetime_spots` that we shouldn't, like associated
2156 // `const`s or making a mistake in the AST lowering we would provide
2157 // nonsensical suggestions. Guard against that by skipping these.
2161 msg = "consider introducing a named lifetime parameter".to_string();
2162 should_break = true;
2163 if let Some(param) = generics.params.iter().find(|p| {
2166 hir::GenericParamKind::Type { synthetic: true, .. }
2167 | hir::GenericParamKind::Lifetime {
2168 kind: hir::LifetimeParamKind::Elided
2172 (param.span.shrink_to_lo(), "'a, ".to_string())
2174 (generics.span, "<'a>".to_string())
2177 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2179 "consider making the {} lifetime-generic with a new `'a` lifetime",
2182 should_break = false;
2184 "for more information on higher-ranked polymorphism, visit \
2185 https://doc.rust-lang.org/nomicon/hrtb.html",
2187 (*span, span_type.suggestion("'a"))
2189 MissingLifetimeSpot::Static => {
2190 let mut spans_suggs = Vec::new();
2191 for ((span, count), snippet) in
2192 spans_with_counts.iter().copied().zip(snippets.iter())
2194 let (span, sugg) = match snippet.as_deref() {
2195 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2196 Some("'_") => (span, "'static".to_owned()),
2197 Some(snippet) if !snippet.ends_with('>') => {
2201 std::iter::repeat("'static")
2203 .collect::<Vec<_>>()
2206 } else if snippet == "<" || snippet == "(" {
2208 span.shrink_to_hi(),
2209 std::iter::repeat("'static")
2211 .collect::<Vec<_>>()
2216 span.shrink_to_hi(),
2219 std::iter::repeat("'static")
2221 .collect::<Vec<_>>()
2229 spans_suggs.push((span, sugg.to_string()));
2231 err.multipart_suggestion_verbose(
2232 "consider using the `'static` lifetime",
2234 Applicability::MaybeIncorrect,
2240 struct Lifetime(Span, String);
2242 fn is_unnamed(&self) -> bool {
2243 self.1.starts_with('&') && !self.1.starts_with("&'")
2245 fn is_underscore(&self) -> bool {
2246 self.1.starts_with("&'_ ")
2248 fn is_named(&self) -> bool {
2249 self.1.starts_with("&'")
2251 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2255 self.is_underscore(),
2257 sugg.starts_with('&'),
2259 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2260 (true, _, _, true) => {
2261 (self.span_unnamed_borrow(), sugg[1..].to_string())
2263 (_, true, _, false) => {
2264 (self.span_underscore_borrow(), sugg.trim().to_string())
2266 (_, true, _, true) => {
2267 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2269 (_, _, true, false) => {
2270 (self.span_named_borrow(), sugg.trim().to_string())
2272 (_, _, true, true) => {
2273 (self.span_named_borrow(), sugg[1..].trim().to_string())
2279 fn span_unnamed_borrow(&self) -> Span {
2280 let lo = self.0.lo() + BytePos(1);
2281 self.0.with_lo(lo).with_hi(lo)
2283 fn span_named_borrow(&self) -> Span {
2284 let lo = self.0.lo() + BytePos(1);
2287 fn span_underscore_borrow(&self) -> Span {
2288 let lo = self.0.lo() + BytePos(1);
2289 let hi = lo + BytePos(2);
2290 self.0.with_lo(lo).with_hi(hi)
2294 for param in params {
2295 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2296 if let Some((span, sugg)) =
2297 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2299 introduce_suggestion.push((span, sugg));
2303 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2304 |((span, _), sugg)| match &sugg {
2305 Some(sugg) => Some((span, sugg.to_string())),
2309 let (span, sugg) = self
2313 .span_to_snippet(span)
2315 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2316 .unwrap_or((span, sugg));
2317 introduce_suggestion.push((span, sugg.to_string()));
2319 err.multipart_suggestion_verbose(
2321 introduce_suggestion,
2322 Applicability::MaybeIncorrect,
2330 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2331 match &lifetime_names[..] {
2333 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2334 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2336 suggs.push(match snippet.as_deref() {
2337 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2338 Some("'_") => Some(Box::new(|n| n.to_string())),
2339 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2340 Some("<") => Some(Box::new(move |n| {
2341 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2343 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2347 std::iter::repeat(name.to_string())
2349 .collect::<Vec<_>>()
2356 suggest_existing(err, name.as_str(), suggs);
2359 let mut suggs = Vec::new();
2360 for (snippet, (_, count)) in
2361 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2363 suggs.push(match snippet.as_deref() {
2364 Some("&") => Some("&'a ".to_string()),
2365 Some("'_") => Some("'a".to_string()),
2367 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2370 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2372 Some(snippet) => Some(format!(
2375 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2380 suggest_new(err, suggs);
2382 lts if lts.len() > 1 => {
2383 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2385 let mut spans_suggs: Vec<_> = Vec::new();
2386 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2387 match snippet.as_deref() {
2388 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2389 Some("&") => spans_suggs
2390 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2395 if spans_suggs.len() > 0 {
2396 // This happens when we have `Foo<T>` where we point at the space before `T`,
2397 // but this can be confusing so we give a suggestion with placeholders.
2398 err.multipart_suggestion_verbose(
2399 "consider using one of the available lifetimes here",
2401 Applicability::HasPlaceholders,
2405 _ => unreachable!(),
2409 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2410 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2411 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2412 crate fn maybe_emit_forbidden_non_static_lifetime_error(
2414 body_id: hir::BodyId,
2415 lifetime_ref: &'tcx hir::Lifetime,
2417 let is_anon_const = matches!(
2418 self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
2419 hir::def::DefKind::AnonConst
2421 let is_allowed_lifetime = matches!(
2423 hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore
2426 if !self.tcx.lazy_normalization() && is_anon_const && !is_allowed_lifetime {
2428 &self.tcx.sess.parse_sess,
2429 sym::generic_const_exprs,
2431 "a non-static lifetime is not allowed in a `const`",