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_ID, 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 = CRATE_DEF_ID.to_def_id();
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 (module, _) = self.current_trait_ref.as_ref()?;
1187 if ident == kw::Underscore {
1188 // We do nothing for `_`.
1192 let resolutions = self.r.resolutions(module);
1193 let targets = resolutions
1196 .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
1197 .filter(|(_, res)| match (kind, res) {
1198 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
1199 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
1200 (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
1203 .map(|(key, _)| key.ident.name)
1204 .collect::<Vec<_>>();
1206 find_best_match_for_name(&targets, ident, None)
1209 fn lookup_assoc_candidate<FilterFn>(
1213 filter_fn: FilterFn,
1214 ) -> Option<AssocSuggestion>
1216 FilterFn: Fn(Res) -> bool,
1218 fn extract_node_id(t: &Ty) -> Option<NodeId> {
1220 TyKind::Path(None, _) => Some(t.id),
1221 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
1222 // This doesn't handle the remaining `Ty` variants as they are not
1223 // that commonly the self_type, it might be interesting to provide
1224 // support for those in future.
1229 // Fields are generally expected in the same contexts as locals.
1230 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
1231 if let Some(node_id) =
1232 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
1234 // Look for a field with the same name in the current self_type.
1235 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
1236 match resolution.base_res() {
1237 Res::Def(DefKind::Struct | DefKind::Union, did)
1238 if resolution.unresolved_segments() == 0 =>
1240 if let Some(field_names) = self.r.field_names.get(&did) {
1243 .any(|&field_name| ident.name == field_name.node)
1245 return Some(AssocSuggestion::Field);
1255 if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
1256 for assoc_item in items {
1257 if assoc_item.ident == ident {
1258 return Some(match &assoc_item.kind {
1259 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
1260 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
1261 AssocSuggestion::MethodWithSelf
1263 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
1264 ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
1265 ast::AssocItemKind::MacCall(_) => continue,
1271 // Look for associated items in the current trait.
1272 if let Some((module, _)) = self.current_trait_ref {
1273 if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
1274 ModuleOrUniformRoot::Module(module),
1279 let res = binding.res();
1281 if self.r.has_self.contains(&res.def_id()) {
1282 return Some(AssocSuggestion::MethodWithSelf);
1285 Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
1286 Res::Def(DefKind::AssocConst, _) => {
1287 return Some(AssocSuggestion::AssocConst);
1289 Res::Def(DefKind::AssocTy, _) => {
1290 return Some(AssocSuggestion::AssocType);
1302 fn lookup_typo_candidate(
1306 filter_fn: &impl Fn(Res) -> bool,
1307 ) -> Option<TypoSuggestion> {
1308 let mut names = Vec::new();
1309 if path.len() == 1 {
1310 // Search in lexical scope.
1311 // Walk backwards up the ribs in scope and collect candidates.
1312 for rib in self.ribs[ns].iter().rev() {
1313 // Locals and type parameters
1314 for (ident, &res) in &rib.bindings {
1316 names.push(TypoSuggestion::typo_from_res(ident.name, res));
1320 if let RibKind::ModuleRibKind(module) = rib.kind {
1321 // Items from this module
1322 self.r.add_module_candidates(module, &mut names, &filter_fn);
1324 if let ModuleKind::Block(..) = module.kind {
1325 // We can see through blocks
1327 // Items from the prelude
1328 if !module.no_implicit_prelude {
1329 let extern_prelude = self.r.extern_prelude.clone();
1330 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
1331 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
1334 Res::Def(DefKind::Mod, crate_id.as_def_id());
1336 if filter_fn(crate_mod) {
1337 Some(TypoSuggestion::typo_from_res(
1338 ident.name, crate_mod,
1347 if let Some(prelude) = self.r.prelude {
1348 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
1355 // Add primitive types to the mix
1356 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
1357 names.extend(PrimTy::ALL.iter().map(|prim_ty| {
1358 TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
1362 // Search in module.
1363 let mod_path = &path[..path.len() - 1];
1364 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1365 self.resolve_path(mod_path, Some(TypeNS), Finalize::No)
1367 self.r.add_module_candidates(module, &mut names, &filter_fn);
1371 let name = path[path.len() - 1].ident.name;
1372 // Make sure error reporting is deterministic.
1373 names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1375 match find_best_match_for_name(
1376 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1380 Some(found) if found != name => {
1381 names.into_iter().find(|suggestion| suggestion.candidate == found)
1387 // Returns the name of the Rust type approximately corresponding to
1388 // a type name in another programming language.
1389 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
1390 let name = path[path.len() - 1].ident.as_str();
1391 // Common Java types
1393 "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
1394 "short" => sym::i16,
1395 "boolean" => sym::bool,
1398 "float" => sym::f32,
1399 "double" => sym::f64,
1404 /// Only used in a specific case of type ascription suggestions
1405 fn get_colon_suggestion_span(&self, start: Span) -> Span {
1406 let sm = self.r.session.source_map();
1407 start.to(sm.next_point(start))
1410 fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
1411 let sm = self.r.session.source_map();
1412 let base_snippet = sm.span_to_snippet(base_span);
1413 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
1414 if let Ok(snippet) = sm.span_to_snippet(sp) {
1415 let len = snippet.trim_end().len() as u32;
1416 if snippet.trim() == ":" {
1418 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
1419 let mut show_label = true;
1420 if sm.is_multiline(sp) {
1421 err.span_suggestion_short(
1423 "maybe you meant to write `;` here",
1425 Applicability::MaybeIncorrect,
1428 let after_colon_sp =
1429 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
1430 if snippet.len() == 1 {
1432 err.span_suggestion(
1434 "maybe you meant to write a path separator here",
1436 Applicability::MaybeIncorrect,
1443 .type_ascription_path_suggestions
1447 err.downgrade_to_delayed_bug();
1450 if let Ok(base_snippet) = base_snippet {
1451 let mut sp = after_colon_sp;
1453 // Try to find an assignment
1454 sp = sm.next_point(sp);
1455 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
1457 Ok(ref x) if x.as_str() == "=" => {
1458 err.span_suggestion(
1460 "maybe you meant to write an assignment here",
1461 format!("let {}", base_snippet),
1462 Applicability::MaybeIncorrect,
1467 Ok(ref x) if x.as_str() == "\n" => break,
1477 "expecting a type here because of type ascription",
1487 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1488 let mut result = None;
1489 let mut seen_modules = FxHashSet::default();
1490 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1492 while let Some((in_module, path_segments)) = worklist.pop() {
1493 // abort if the module is already found
1494 if result.is_some() {
1498 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1499 // abort if the module is already found or if name_binding is private external
1500 if result.is_some() || !name_binding.vis.is_visible_locally() {
1503 if let Some(module) = name_binding.module() {
1505 let mut path_segments = path_segments.clone();
1506 path_segments.push(ast::PathSegment::from_ident(ident));
1507 let module_def_id = module.def_id();
1508 if module_def_id == def_id {
1510 Path { span: name_binding.span, segments: path_segments, tokens: None };
1522 // add the module to the lookup
1523 if seen_modules.insert(module_def_id) {
1524 worklist.push((module, path_segments));
1534 fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
1535 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1536 let mut variants = Vec::new();
1537 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1538 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
1539 let mut segms = enum_import_suggestion.path.segments.clone();
1540 segms.push(ast::PathSegment::from_ident(ident));
1541 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1542 variants.push((path, def_id, kind));
1549 /// Adds a suggestion for using an enum's variant when an enum is used instead.
1550 fn suggest_using_enum_variant(
1552 err: &mut Diagnostic,
1553 source: PathSource<'_>,
1557 let Some(variants) = self.collect_enum_ctors(def_id) else {
1558 err.note("you might have meant to use one of the enum's variants");
1562 let suggest_only_tuple_variants =
1563 matches!(source, PathSource::TupleStruct(..)) || source.is_call();
1564 if suggest_only_tuple_variants {
1565 // Suggest only tuple variants regardless of whether they have fields and do not
1566 // suggest path with added parentheses.
1567 let suggestable_variants = variants
1569 .filter(|(.., kind)| *kind == CtorKind::Fn)
1570 .map(|(variant, ..)| path_names_to_string(variant))
1571 .collect::<Vec<_>>();
1573 let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
1575 let source_msg = if source.is_call() {
1577 } else if matches!(source, PathSource::TupleStruct(..)) {
1583 if !suggestable_variants.is_empty() {
1584 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
1585 format!("try {} the enum's variant", source_msg)
1587 format!("try {} one of the enum's variants", source_msg)
1590 err.span_suggestions(
1593 suggestable_variants.into_iter(),
1594 Applicability::MaybeIncorrect,
1598 // If the enum has no tuple variants..
1599 if non_suggestable_variant_count == variants.len() {
1600 err.help(&format!("the enum has no tuple variants {}", source_msg));
1603 // If there are also non-tuple variants..
1604 if non_suggestable_variant_count == 1 {
1606 "you might have meant {} the enum's non-tuple variant",
1609 } else if non_suggestable_variant_count >= 1 {
1611 "you might have meant {} one of the enum's non-tuple variants",
1616 let needs_placeholder = |def_id: DefId, kind: CtorKind| {
1617 let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
1619 CtorKind::Const => false,
1620 CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
1625 let mut suggestable_variants = variants
1627 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
1628 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1629 .map(|(variant, kind)| match kind {
1630 CtorKind::Const => variant,
1631 CtorKind::Fn => format!("({}())", variant),
1632 CtorKind::Fictive => format!("({} {{}})", variant),
1634 .collect::<Vec<_>>();
1636 if !suggestable_variants.is_empty() {
1637 let msg = if suggestable_variants.len() == 1 {
1638 "you might have meant to use the following enum variant"
1640 "you might have meant to use one of the following enum variants"
1643 err.span_suggestions(
1646 suggestable_variants.drain(..),
1647 Applicability::MaybeIncorrect,
1651 let suggestable_variants_with_placeholders = variants
1653 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
1654 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
1655 .filter_map(|(variant, kind)| match kind {
1656 CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
1657 CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
1660 .collect::<Vec<_>>();
1662 if !suggestable_variants_with_placeholders.is_empty() {
1664 suggestable_variants.is_empty(),
1665 suggestable_variants_with_placeholders.len(),
1667 (true, 1) => "the following enum variant is available",
1668 (true, _) => "the following enum variants are available",
1669 (false, 1) => "alternatively, the following enum variant is available",
1670 (false, _) => "alternatively, the following enum variants are also available",
1673 err.span_suggestions(
1676 suggestable_variants_with_placeholders.into_iter(),
1677 Applicability::HasPlaceholders,
1682 if def_id.is_local() {
1683 if let Some(span) = self.def_span(def_id) {
1684 err.span_note(span, "the enum is defined here");
1689 crate fn report_missing_type_error(
1692 ) -> Option<(Span, &'static str, String, Applicability)> {
1693 let (ident, span) = match path {
1694 [segment] if !segment.has_generic_args => {
1695 (segment.ident.to_string(), segment.ident.span)
1699 let mut iter = ident.chars().map(|c| c.is_uppercase());
1700 let single_uppercase_char =
1701 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1702 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1705 match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
1706 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
1707 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1712 kind @ ItemKind::Fn(..)
1713 | kind @ ItemKind::Enum(..)
1714 | kind @ ItemKind::Struct(..)
1715 | kind @ ItemKind::Union(..),
1720 // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
1721 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
1722 | (Some(Item { kind, .. }), false, _) => {
1723 // Likely missing type parameter.
1724 if let Some(generics) = kind.generics() {
1725 if span.overlaps(generics.span) {
1726 // Avoid the following:
1727 // error[E0405]: cannot find trait `A` in this scope
1728 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1730 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1731 // | ^- help: you might be missing a type parameter: `, A`
1733 // | not found in this scope
1736 let msg = "you might be missing a type parameter";
1737 let (span, sugg) = if let [.., param] = &generics.params[..] {
1738 let span = if let [.., bound] = ¶m.bounds[..] {
1740 } else if let GenericParam {
1741 kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
1743 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
1747 (span, format!(", {}", ident))
1749 (generics.span, format!("<{}>", ident))
1751 // Do not suggest if this is coming from macro expansion.
1752 if span.can_be_used_for_suggestions() {
1754 span.shrink_to_hi(),
1757 Applicability::MaybeIncorrect,
1767 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1768 /// optionally returning the closest match and whether it is reachable.
1769 crate fn suggestion_for_label_in_rib(
1773 ) -> Option<LabelSuggestion> {
1774 // Are ribs from this `rib_index` within scope?
1775 let within_scope = self.is_label_valid_from_rib(rib_index);
1777 let rib = &self.label_ribs[rib_index];
1781 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1782 .map(|(id, _)| id.name)
1783 .collect::<Vec<Symbol>>();
1785 find_best_match_for_name(&names, label.name, None).map(|symbol| {
1786 // Upon finding a similar name, get the ident that it was from - the span
1787 // contained within helps make a useful diagnostic. In addition, determine
1788 // whether this candidate is within scope.
1789 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1790 (*ident, within_scope)
1794 crate fn emit_undeclared_lifetime_error(
1796 lifetime_ref: &ast::Lifetime,
1797 outer_lifetime_ref: Option<Ident>,
1799 debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
1800 let mut err = if let Some(outer) = outer_lifetime_ref {
1801 let mut err = struct_span_err!(
1803 lifetime_ref.ident.span,
1805 "can't use generic parameters from outer item",
1807 err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
1808 err.span_label(outer.span, "lifetime parameter from outer item");
1811 let mut err = struct_span_err!(
1813 lifetime_ref.ident.span,
1815 "use of undeclared lifetime name `{}`",
1818 err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
1821 let mut suggest_note = true;
1823 for rib in self.lifetime_ribs.iter().rev() {
1825 LifetimeRibKind::Generics { span, kind } => {
1826 if !span.can_be_used_for_suggestions() && suggest_note {
1827 suggest_note = false; // Avoid displaying the same help multiple times.
1831 "lifetime `{}` is missing in item created through this procedural macro",
1838 let higher_ranked = matches!(
1840 LifetimeBinderKind::BareFnType
1841 | LifetimeBinderKind::PolyTrait
1842 | LifetimeBinderKind::WhereBound
1844 let (span, sugg) = if span.is_empty() {
1847 if higher_ranked { "for" } else { "" },
1849 if higher_ranked { " " } else { "" },
1854 self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
1855 let sugg = format!("{}, ", lifetime_ref.ident);
1859 err.span_suggestion(
1862 "consider making the {} lifetime-generic with a new `{}` lifetime",
1867 Applicability::MaybeIncorrect,
1870 "for more information on higher-ranked polymorphism, visit \
1871 https://doc.rust-lang.org/nomicon/hrtb.html",
1874 err.span_suggestion(
1876 &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
1878 Applicability::MaybeIncorrect,
1882 LifetimeRibKind::Item => break,
1891 impl<'tcx> LifetimeContext<'_, 'tcx> {
1892 crate fn report_missing_lifetime_specifiers(
1896 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1901 "missing lifetime specifier{}",
1906 /// Returns whether to add `'static` lifetime to the suggested lifetime list.
1907 crate fn report_elision_failure(
1909 diag: &mut Diagnostic,
1910 params: &[ElisionFailureInfo],
1912 let mut m = String::new();
1913 let len = params.len();
1915 let elided_params: Vec<_> =
1916 params.iter().cloned().filter(|info| info.lifetime_count > 0).collect();
1918 let elided_len = elided_params.len();
1920 for (i, info) in elided_params.into_iter().enumerate() {
1921 let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions, span } =
1924 diag.span_label(span, "");
1925 let help_name = if let Some(ident) =
1926 parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident())
1928 format!("`{}`", ident)
1930 format!("argument {}", index + 1)
1938 "one of {}'s {} {}lifetimes",
1941 if have_bound_regions { "free " } else { "" }
1946 if elided_len == 2 && i == 0 {
1948 } else if i + 2 == elided_len {
1949 m.push_str(", or ");
1950 } else if i != elided_len - 1 {
1957 "this function's return type contains a borrowed value, \
1958 but there is no value for it to be borrowed from",
1961 } else if elided_len == 0 {
1963 "this function's return type contains a borrowed value with \
1964 an elided lifetime, but the lifetime cannot be derived from \
1968 } else if elided_len == 1 {
1970 "this function's return type contains a borrowed value, \
1971 but the signature does not say which {} it is borrowed from",
1977 "this function's return type contains a borrowed value, \
1978 but the signature does not say whether it is borrowed from {}",
1985 // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
1986 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1987 // lifetimes in const generics. See issue #74052 for discussion.
1988 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1989 let mut err = struct_span_err!(
1993 "use of non-static lifetime `{}` in const generic",
1997 "for more information, see issue #74052 \
1998 <https://github.com/rust-lang/rust/issues/74052>",
2003 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
2004 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
2006 self.tcx.lang_items().fn_once_trait(),
2007 self.tcx.lang_items().fn_trait(),
2008 self.tcx.lang_items().fn_mut_trait(),
2010 .contains(&Some(did))
2012 let (span, span_type) = match &trait_ref.bound_generic_params {
2013 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
2014 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
2016 self.missing_named_lifetime_spots
2017 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
2024 crate fn add_missing_lifetime_specifiers_label(
2026 err: &mut Diagnostic,
2027 mut spans_with_counts: Vec<(Span, usize)>,
2028 lifetime_names: &FxHashSet<Symbol>,
2029 lifetime_spans: Vec<Span>,
2030 params: &[ElisionFailureInfo],
2032 let snippets: Vec<Option<String>> = spans_with_counts
2034 .map(|(span, _)| self.tcx.sess.source_map().span_to_snippet(*span).ok())
2037 // Empty generics are marked with a span of "<", but since from now on
2038 // that information is in the snippets it can be removed from the spans.
2039 for ((span, _), snippet) in spans_with_counts.iter_mut().zip(&snippets) {
2040 if snippet.as_deref() == Some("<") {
2041 *span = span.shrink_to_hi();
2045 for &(span, count) in &spans_with_counts {
2049 "expected {} lifetime parameter{}",
2050 if count == 1 { "named".to_string() } else { count.to_string() },
2056 let suggest_existing =
2057 |err: &mut Diagnostic,
2059 formatters: Vec<Option<Box<dyn Fn(&str) -> String>>>| {
2060 if let Some(MissingLifetimeSpot::HigherRanked { span: for_span, span_type }) =
2061 self.missing_named_lifetime_spots.iter().rev().next()
2063 // When we have `struct S<'a>(&'a dyn Fn(&X) -> &X);` we want to not only suggest
2064 // using `'a`, but also introduce the concept of HRLTs by suggesting
2065 // `struct S<'a>(&'a dyn for<'b> Fn(&X) -> &'b X);`. (#72404)
2066 let mut introduce_suggestion = vec![];
2068 let a_to_z_repeat_n = |n| {
2069 (b'a'..=b'z').map(move |c| {
2070 let mut s = '\''.to_string();
2071 s.extend(std::iter::repeat(char::from(c)).take(n));
2076 // If all single char lifetime names are present, we wrap around and double the chars.
2078 .flat_map(a_to_z_repeat_n)
2079 .find(|lt| !lifetime_names.contains(&Symbol::intern(<)))
2082 "consider making the {} lifetime-generic with a new `{}` lifetime",
2087 "for more information on higher-ranked polymorphism, visit \
2088 https://doc.rust-lang.org/nomicon/hrtb.html",
2090 let for_sugg = span_type.suggestion(<_name);
2091 for param in params {
2092 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span)
2094 if snippet.starts_with('&') && !snippet.starts_with("&'") {
2095 introduce_suggestion
2096 .push((param.span, format!("&{} {}", lt_name, &snippet[1..])));
2097 } else if let Some(stripped) = snippet.strip_prefix("&'_ ") {
2098 introduce_suggestion
2099 .push((param.span, format!("&{} {}", lt_name, stripped)));
2103 introduce_suggestion.push((*for_span, for_sugg));
2104 for ((span, _), formatter) in spans_with_counts.iter().zip(formatters.iter()) {
2105 if let Some(formatter) = formatter {
2106 introduce_suggestion.push((*span, formatter(<_name)));
2109 err.multipart_suggestion_verbose(
2111 introduce_suggestion,
2112 Applicability::MaybeIncorrect,
2116 let spans_suggs: Vec<_> = formatters
2118 .zip(spans_with_counts.iter())
2119 .filter_map(|(formatter, (span, _))| {
2120 if let Some(formatter) = formatter {
2121 Some((*span, formatter(name)))
2127 if spans_suggs.is_empty() {
2128 // If all the spans come from macros, we cannot extract snippets and then
2129 // `formatters` only contains None and `spans_suggs` is empty.
2132 err.multipart_suggestion_verbose(
2134 "consider using the `{}` lifetime",
2135 lifetime_names.iter().next().unwrap()
2138 Applicability::MaybeIncorrect,
2141 let suggest_new = |err: &mut Diagnostic, suggs: Vec<Option<String>>| {
2142 for missing in self.missing_named_lifetime_spots.iter().rev() {
2143 let mut introduce_suggestion = vec![];
2146 introduce_suggestion.push(match missing {
2147 MissingLifetimeSpot::Generics(generics) => {
2148 if generics.span == DUMMY_SP {
2149 // Account for malformed generics in the HIR. This shouldn't happen,
2150 // but if we make a mistake elsewhere, mainly by keeping something in
2151 // `missing_named_lifetime_spots` that we shouldn't, like associated
2152 // `const`s or making a mistake in the AST lowering we would provide
2153 // nonsensical suggestions. Guard against that by skipping these.
2157 msg = "consider introducing a named lifetime parameter".to_string();
2158 should_break = true;
2159 if let Some(param) = generics.params.iter().find(|p| {
2162 hir::GenericParamKind::Type { synthetic: true, .. }
2163 | hir::GenericParamKind::Lifetime {
2164 kind: hir::LifetimeParamKind::Elided
2168 (param.span.shrink_to_lo(), "'a, ".to_string())
2170 (generics.span, "<'a>".to_string())
2173 MissingLifetimeSpot::HigherRanked { span, span_type } => {
2175 "consider making the {} lifetime-generic with a new `'a` lifetime",
2178 should_break = false;
2180 "for more information on higher-ranked polymorphism, visit \
2181 https://doc.rust-lang.org/nomicon/hrtb.html",
2183 (*span, span_type.suggestion("'a"))
2185 MissingLifetimeSpot::Static => {
2186 let mut spans_suggs = Vec::new();
2187 for ((span, count), snippet) in
2188 spans_with_counts.iter().copied().zip(snippets.iter())
2190 let (span, sugg) = match snippet.as_deref() {
2191 Some("&") => (span.shrink_to_hi(), "'static ".to_owned()),
2192 Some("'_") => (span, "'static".to_owned()),
2193 Some(snippet) if !snippet.ends_with('>') => {
2197 std::iter::repeat("'static")
2199 .collect::<Vec<_>>()
2202 } else if snippet == "<" || snippet == "(" {
2204 span.shrink_to_hi(),
2205 std::iter::repeat("'static")
2207 .collect::<Vec<_>>()
2212 span.shrink_to_hi(),
2215 std::iter::repeat("'static")
2217 .collect::<Vec<_>>()
2225 spans_suggs.push((span, sugg.to_string()));
2227 err.multipart_suggestion_verbose(
2228 "consider using the `'static` lifetime",
2230 Applicability::MaybeIncorrect,
2236 struct Lifetime(Span, String);
2238 fn is_unnamed(&self) -> bool {
2239 self.1.starts_with('&') && !self.1.starts_with("&'")
2241 fn is_underscore(&self) -> bool {
2242 self.1.starts_with("&'_ ")
2244 fn is_named(&self) -> bool {
2245 self.1.starts_with("&'")
2247 fn suggestion(&self, sugg: String) -> Option<(Span, String)> {
2251 self.is_underscore(),
2253 sugg.starts_with('&'),
2255 (true, _, _, false) => (self.span_unnamed_borrow(), sugg),
2256 (true, _, _, true) => {
2257 (self.span_unnamed_borrow(), sugg[1..].to_string())
2259 (_, true, _, false) => {
2260 (self.span_underscore_borrow(), sugg.trim().to_string())
2262 (_, true, _, true) => {
2263 (self.span_underscore_borrow(), sugg[1..].trim().to_string())
2265 (_, _, true, false) => {
2266 (self.span_named_borrow(), sugg.trim().to_string())
2268 (_, _, true, true) => {
2269 (self.span_named_borrow(), sugg[1..].trim().to_string())
2275 fn span_unnamed_borrow(&self) -> Span {
2276 let lo = self.0.lo() + BytePos(1);
2277 self.0.with_lo(lo).with_hi(lo)
2279 fn span_named_borrow(&self) -> Span {
2280 let lo = self.0.lo() + BytePos(1);
2283 fn span_underscore_borrow(&self) -> Span {
2284 let lo = self.0.lo() + BytePos(1);
2285 let hi = lo + BytePos(2);
2286 self.0.with_lo(lo).with_hi(hi)
2290 for param in params {
2291 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
2292 if let Some((span, sugg)) =
2293 Lifetime(param.span, snippet).suggestion("'a ".to_string())
2295 introduce_suggestion.push((span, sugg));
2299 for (span, sugg) in spans_with_counts.iter().copied().zip(suggs.iter()).filter_map(
2300 |((span, _), sugg)| match &sugg {
2301 Some(sugg) => Some((span, sugg.to_string())),
2305 let (span, sugg) = self
2309 .span_to_snippet(span)
2311 .and_then(|snippet| Lifetime(span, snippet).suggestion(sugg.clone()))
2312 .unwrap_or((span, sugg));
2313 introduce_suggestion.push((span, sugg.to_string()));
2315 err.multipart_suggestion_verbose(
2317 introduce_suggestion,
2318 Applicability::MaybeIncorrect,
2326 let lifetime_names: Vec<_> = lifetime_names.iter().collect();
2327 match &lifetime_names[..] {
2329 let mut suggs: Vec<Option<Box<dyn Fn(&str) -> String>>> = Vec::new();
2330 for (snippet, (_, count)) in snippets.iter().zip(spans_with_counts.iter().copied())
2332 suggs.push(match snippet.as_deref() {
2333 Some("&") => Some(Box::new(|name| format!("&{} ", name))),
2334 Some("'_") => Some(Box::new(|n| n.to_string())),
2335 Some("") => Some(Box::new(move |n| format!("{}, ", n).repeat(count))),
2336 Some("<") => Some(Box::new(move |n| {
2337 std::iter::repeat(n).take(count).collect::<Vec<_>>().join(", ")
2339 Some(snippet) if !snippet.ends_with('>') => Some(Box::new(move |name| {
2343 std::iter::repeat(name.to_string())
2345 .collect::<Vec<_>>()
2352 suggest_existing(err, name.as_str(), suggs);
2355 let mut suggs = Vec::new();
2356 for (snippet, (_, count)) in
2357 snippets.iter().cloned().zip(spans_with_counts.iter().copied())
2359 suggs.push(match snippet.as_deref() {
2360 Some("&") => Some("&'a ".to_string()),
2361 Some("'_") => Some("'a".to_string()),
2363 Some(std::iter::repeat("'a, ").take(count).collect::<Vec<_>>().join(""))
2366 Some(std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "))
2368 Some(snippet) => Some(format!(
2371 std::iter::repeat("'a").take(count).collect::<Vec<_>>().join(", "),
2376 suggest_new(err, suggs);
2378 lts if lts.len() > 1 => {
2379 err.span_note(lifetime_spans, "these named lifetimes are available to use");
2381 let mut spans_suggs: Vec<_> = Vec::new();
2382 for ((span, _), snippet) in spans_with_counts.iter().copied().zip(snippets.iter()) {
2383 match snippet.as_deref() {
2384 Some("") => spans_suggs.push((span, "'lifetime, ".to_string())),
2385 Some("&") => spans_suggs
2386 .push((span.with_lo(span.lo() + BytePos(1)), "'lifetime ".to_string())),
2391 if spans_suggs.len() > 0 {
2392 // This happens when we have `Foo<T>` where we point at the space before `T`,
2393 // but this can be confusing so we give a suggestion with placeholders.
2394 err.multipart_suggestion_verbose(
2395 "consider using one of the available lifetimes here",
2397 Applicability::HasPlaceholders,
2401 _ => unreachable!(),
2405 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
2406 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
2407 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
2408 crate fn maybe_emit_forbidden_non_static_lifetime_error(
2410 body_id: hir::BodyId,
2411 lifetime_ref: &'tcx hir::Lifetime,
2413 let is_anon_const = matches!(
2414 self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
2415 hir::def::DefKind::AnonConst
2417 let is_allowed_lifetime = matches!(
2419 hir::LifetimeName::Implicit | hir::LifetimeName::Static | hir::LifetimeName::Underscore
2422 if !self.tcx.lazy_normalization() && is_anon_const && !is_allowed_lifetime {
2424 &self.tcx.sess.parse_sess,
2425 sym::generic_const_exprs,
2427 "a non-static lifetime is not allowed in a `const`",