1 use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
2 use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
3 use crate::late::{LateResolutionVisitor, RibKind};
4 use crate::path_names_to_string;
5 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
6 use crate::{PathResult, PathSource, Segment};
8 use rustc_ast::ast::{self, Expr, ExprKind, Item, ItemKind, NodeId, Path, Ty, TyKind};
9 use rustc_ast::util::lev_distance::find_best_match_for_name;
10 use rustc_ast::visit::FnKind;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
14 use rustc_hir::def::Namespace::{self, *};
15 use rustc_hir::def::{self, CtorKind, DefKind};
16 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
17 use rustc_hir::PrimTy;
18 use rustc_session::config::nightly_options;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::symbol::{kw, sym, Ident};
21 use rustc_span::{BytePos, Span};
25 type Res = def::Res<ast::NodeId>;
27 /// A field or associated item from self type suggested in case of resolution failure.
28 enum AssocSuggestion {
34 crate enum MissingLifetimeSpot<'tcx> {
35 Generics(&'tcx hir::Generics<'tcx>),
36 HigherRanked { span: Span, span_type: ForLifetimeSpanType },
39 crate enum ForLifetimeSpanType {
46 impl ForLifetimeSpanType {
47 crate fn descr(&self) -> &'static str {
49 Self::BoundEmpty | Self::BoundTail => "bound",
50 Self::TypeEmpty | Self::TypeTail => "type",
54 crate fn suggestion(&self, sugg: &str) -> String {
56 Self::BoundEmpty | Self::TypeEmpty => format!("for<{}> ", sugg),
57 Self::BoundTail | Self::TypeTail => format!(", {}", sugg),
62 impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
63 fn into(self) -> MissingLifetimeSpot<'tcx> {
64 MissingLifetimeSpot::Generics(self)
68 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
69 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
72 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
73 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
76 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
77 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
78 let variant_path = &suggestion.path;
79 let variant_path_string = path_names_to_string(variant_path);
81 let path_len = suggestion.path.segments.len();
82 let enum_path = ast::Path {
83 span: suggestion.path.span,
84 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
86 let enum_path_string = path_names_to_string(&enum_path);
88 (variant_path_string, enum_path_string)
91 impl<'a> LateResolutionVisitor<'a, '_, '_> {
92 fn def_span(&self, def_id: DefId) -> Option<Span> {
94 LOCAL_CRATE => self.r.opt_span(def_id),
99 .guess_head_span(self.r.cstore().get_span_untracked(def_id, self.r.session)),
104 /// Handles error reporting for `smart_resolve_path_fragment` function.
105 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
106 pub(crate) fn smart_resolve_report_errors(
110 source: PathSource<'_>,
112 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
113 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
114 let ns = source.namespace();
115 let is_expected = &|res| source.is_expected(res);
116 let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
118 // Make the base error.
119 let expected = source.descr_expected();
120 let path_str = Segment::names_to_string(path);
121 let item_str = path.last().unwrap().ident;
122 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
124 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
125 format!("not a {}", expected),
128 Res::Def(DefKind::Fn, _) => {
129 // Verify whether this is a fn call or an Fn used as a type.
133 .span_to_snippet(span)
134 .map(|snippet| snippet.ends_with(')'))
138 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
143 | Res::Local(_) => true,
148 let item_span = path.last().unwrap().ident.span;
149 let (mod_prefix, mod_str) = if path.len() == 1 {
150 (String::new(), "this scope".to_string())
151 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
152 (String::new(), "the crate root".to_string())
154 let mod_path = &path[..path.len() - 1];
156 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
157 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
160 .map_or(String::new(), |res| format!("{} ", res.descr()));
161 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
164 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
165 if path_str == "async" && expected.starts_with("struct") {
166 "`async` blocks are only allowed in the 2018 edition".to_string()
168 format!("not found in {}", mod_str)
175 let code = source.error_code(res.is_some());
176 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
178 let is_assoc_fn = self.self_type_is_available(span);
179 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
180 if ["this", "my"].contains(&&*item_str.as_str()) && is_assoc_fn {
181 err.span_suggestion_short(
183 "you might have meant to use `self` here instead",
185 Applicability::MaybeIncorrect,
187 if !self.self_value_is_available(path[0].ident.span, span) {
188 if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
189 &self.diagnostic_metadata.current_function
191 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
192 (param.span.shrink_to_lo(), "&self, ")
198 .span_through_char(*fn_span, '(')
203 err.span_suggestion_verbose(
205 "you are also missing a `self` receiver argument",
207 Applicability::MaybeIncorrect,
213 // Emit special messages for unresolved `Self` and `self`.
214 if is_self_type(path, ns) {
215 err.code(rustc_errors::error_code!(E0411));
218 "`Self` is only available in impls, traits, and type definitions".to_string(),
220 return (err, Vec::new());
222 if is_self_value(path, ns) {
223 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
225 err.code(rustc_errors::error_code!(E0424));
226 err.span_label(span, match source {
227 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
229 _ => "`self` value is a keyword only available in methods with a `self` parameter"
232 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
233 // The current function has a `self' parameter, but we were unable to resolve
234 // a reference to `self`. This can only happen if the `self` identifier we
235 // are resolving came from a different hygiene context.
236 if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
237 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
239 let doesnt = if is_assoc_fn {
240 let (span, sugg) = fn_kind
244 .map(|p| (p.span.shrink_to_lo(), "&self, "))
250 .span_through_char(*span, '(')
255 err.span_suggestion_verbose(
257 "add a `self` receiver parameter to make the associated `fn` a method",
259 Applicability::MaybeIncorrect,
265 if let Some(ident) = fn_kind.ident() {
268 &format!("this function {} have a `self` parameter", doesnt),
273 return (err, Vec::new());
276 // Try to lookup name in more relaxed fashion for better error reporting.
277 let ident = path.last().unwrap().ident;
278 let candidates = self
280 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
282 .filter(|ImportSuggestion { did, .. }| {
283 match (did, res.and_then(|res| res.opt_def_id())) {
284 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
288 .collect::<Vec<_>>();
289 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
290 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
291 let enum_candidates =
292 self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
294 if !enum_candidates.is_empty() {
295 if let (PathSource::Type, Some(span)) =
296 (source, self.diagnostic_metadata.current_type_ascription.last())
302 .type_ascription_path_suggestions
306 // Already reported this issue on the lhs of the type ascription.
308 return (err, candidates);
312 let mut enum_candidates = enum_candidates
314 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
315 .collect::<Vec<_>>();
316 enum_candidates.sort();
318 // Contextualize for E0412 "cannot find type", but don't belabor the point
319 // (that it's a variant) for E0573 "expected type, found variant".
320 let preamble = if res.is_none() {
321 let others = match enum_candidates.len() {
323 2 => " and 1 other".to_owned(),
324 n => format!(" and {} others", n),
326 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
330 let msg = format!("{}try using the variant's enum", preamble);
332 err.span_suggestions(
337 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
338 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
340 // FIXME: is there a more principled way to do this that
341 // would work for other re-exports?
342 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
343 // Also write `Option` rather than `std::prelude::v1::Option`.
344 .map(|enum_ty_path| {
345 // FIXME #56861: DRY-er prelude filtering.
346 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
348 Applicability::MachineApplicable,
352 if path.len() == 1 && self.self_type_is_available(span) {
353 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
354 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
356 AssocSuggestion::Field => {
357 if self_is_available {
360 "you might have meant to use the available field",
361 format!("self.{}", path_str),
362 Applicability::MachineApplicable,
365 err.span_label(span, "a field by this name exists in `Self`");
368 AssocSuggestion::MethodWithSelf if self_is_available => {
372 format!("self.{}", path_str),
373 Applicability::MachineApplicable,
376 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
380 format!("Self::{}", path_str),
381 Applicability::MachineApplicable,
385 return (err, candidates);
388 // If the first argument in call is `self` suggest calling a method.
389 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
390 let mut args_snippet = String::new();
391 if let Some(args_span) = args_span {
392 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
393 args_snippet = snippet;
399 &format!("try calling `{}` as a method", ident),
400 format!("self.{}({})", path_str, args_snippet),
401 Applicability::MachineApplicable,
403 return (err, candidates);
407 // Try Levenshtein algorithm.
408 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
409 // Try context-dependent help if relaxed lookup didn't work.
410 if let Some(res) = res {
411 if self.smart_resolve_context_dependent_help(
419 // We do this to avoid losing a secondary span when we override the main error span.
420 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
421 return (err, candidates);
425 if !self.type_ascription_suggestion(&mut err, base_span)
426 && !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span)
429 err.span_label(base_span, fallback_label);
431 match self.diagnostic_metadata.current_let_binding {
432 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
433 err.span_suggestion_short(
434 pat_sp.between(ty_sp),
435 "use `=` if you meant to assign",
437 Applicability::MaybeIncorrect,
446 /// Check if the source is call expression and the first argument is `self`. If true,
447 /// return the span of whole call and the span for all arguments expect the first one (`self`).
448 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
449 let mut has_self_arg = None;
450 if let PathSource::Expr(Some(parent)) = source {
452 ExprKind::Call(_, args) if !args.is_empty() => {
453 let mut expr_kind = &args[0].kind;
456 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
457 if arg_name.segments[0].ident.name == kw::SelfLower {
458 let call_span = parent.span;
459 let tail_args_span = if args.len() > 1 {
462 args.last().unwrap().span.hi(),
468 has_self_arg = Some((call_span, tail_args_span));
472 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
483 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
484 // HACK(estebank): find a better way to figure out that this was a
485 // parser issue where a struct literal is being used on an expression
486 // where a brace being opened means a block is being started. Look
487 // ahead for the next text to see if `span` is followed by a `{`.
488 let sm = self.r.session.source_map();
491 sp = sm.next_point(sp);
492 match sm.span_to_snippet(sp) {
494 if snippet.chars().any(|c| !c.is_whitespace()) {
501 let followed_by_brace = match sm.span_to_snippet(sp) {
502 Ok(ref snippet) if snippet == "{" => true,
505 // In case this could be a struct literal that needs to be surrounded
506 // by parentheses, find the appropriate span.
508 let mut closing_brace = None;
510 sp = sm.next_point(sp);
511 match sm.span_to_snippet(sp) {
514 closing_brace = Some(span.to(sp));
521 // The bigger the span, the more likely we're incorrect --
522 // bound it to 100 chars long.
527 (followed_by_brace, closing_brace)
530 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
532 /// Returns `true` if able to provide context-dependent help.
533 fn smart_resolve_context_dependent_help(
535 err: &mut DiagnosticBuilder<'a>,
537 source: PathSource<'_>,
540 fallback_label: &str,
542 let ns = source.namespace();
543 let is_expected = &|res| source.is_expected(res);
545 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
546 ExprKind::Field(_, ident) => {
549 "use the path separator to refer to an item",
550 format!("{}::{}", path_str, ident),
551 Applicability::MaybeIncorrect,
555 ExprKind::MethodCall(ref segment, ..) => {
556 let span = expr.span.with_hi(segment.ident.span.hi());
559 "use the path separator to refer to an item",
560 format!("{}::{}", path_str, segment.ident),
561 Applicability::MaybeIncorrect,
568 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
569 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
572 PathSource::Expr(Some(
573 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
574 )) if path_sep(err, &parent) => {}
580 | ExprKind::Binary(..)
581 | ExprKind::Unary(..)
583 | ExprKind::While(..)
584 | ExprKind::ForLoop(..)
585 | ExprKind::Match(..),
588 ) if followed_by_brace => {
589 if let Some(sp) = closing_brace {
590 err.span_label(span, fallback_label);
591 err.multipart_suggestion(
592 "surround the struct literal with parentheses",
594 (sp.shrink_to_lo(), "(".to_string()),
595 (sp.shrink_to_hi(), ")".to_string()),
597 Applicability::MaybeIncorrect,
601 span, // Note the parentheses surrounding the suggestion below
603 "you might want to surround a struct literal with parentheses: \
604 `({} {{ /* fields */ }})`?",
610 PathSource::Expr(_) | PathSource::TupleStruct(_) | PathSource::Pat => {
611 let span = match &source {
612 PathSource::Expr(Some(Expr {
613 span, kind: ExprKind::Call(_, _), ..
615 | PathSource::TupleStruct(span) => {
616 // We want the main underline to cover the suggested code as well for
623 if let Some(span) = self.def_span(def_id) {
624 err.span_label(span, &format!("`{}` defined here", path_str));
626 let (tail, descr, applicability) = match source {
627 PathSource::Pat | PathSource::TupleStruct(_) => {
628 ("", "pattern", Applicability::MachineApplicable)
630 _ => (": val", "literal", Applicability::HasPlaceholders),
632 let (fields, applicability) = match self.r.field_names.get(&def_id) {
636 .map(|f| format!("{}{}", f.node, tail))
637 .collect::<Vec<String>>()
641 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
643 let pad = match self.r.field_names.get(&def_id) {
644 Some(fields) if fields.is_empty() => "",
649 &format!("use struct {} syntax instead", descr),
650 format!("{} {{{pad}{}{pad}}}", path_str, fields, pad = pad),
655 err.span_label(span, fallback_label);
660 match (res, source) {
661 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
662 err.span_label(span, fallback_label);
663 err.span_suggestion_verbose(
665 "use `!` to invoke the macro",
667 Applicability::MaybeIncorrect,
669 if path_str == "try" && span.rust_2015() {
670 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
673 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
674 err.span_label(span, "type aliases cannot be used as traits");
675 if nightly_options::is_nightly_build() {
676 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
678 if let Some(span) = self.def_span(def_id) {
679 err.span_help(span, msg);
685 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
686 if !path_sep(err, &parent) {
691 Res::Def(DefKind::Enum, def_id),
692 PathSource::TupleStruct(_) | PathSource::Expr(..),
696 .current_type_ascription
702 .type_ascription_path_suggestions
709 // We already suggested changing `:` into `::` during parsing.
712 if let Some(variants) = self.collect_enum_variants(def_id) {
713 if !variants.is_empty() {
714 let msg = if variants.len() == 1 {
715 "try using the enum's variant"
717 "try using one of the enum's variants"
720 err.span_suggestions(
723 variants.iter().map(path_names_to_string),
724 Applicability::MaybeIncorrect,
728 err.note("you might have meant to use one of the enum's variants");
731 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
732 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
734 let accessible_ctor =
735 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
736 if is_expected(ctor_def) && !accessible_ctor {
739 "constructor is not visible here due to private fields".to_string(),
743 bad_struct_syntax_suggestion(def_id);
748 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
752 ) if ns == ValueNS => {
753 bad_struct_syntax_suggestion(def_id);
755 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
756 if let Some(span) = self.def_span(def_id) {
757 err.span_label(span, &format!("`{}` defined here", path_str));
759 err.span_label(span, format!("did you mean `{}( /* fields */ )`?", path_str));
761 (Res::SelfTy(..), _) if ns == ValueNS => {
762 err.span_label(span, fallback_label);
763 err.note("can't use `Self` as a constructor, you must use the implemented struct");
765 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
766 err.note("can't use a type alias as a constructor");
773 fn lookup_assoc_candidate<FilterFn>(
778 ) -> Option<AssocSuggestion>
780 FilterFn: Fn(Res) -> bool,
782 fn extract_node_id(t: &Ty) -> Option<NodeId> {
784 TyKind::Path(None, _) => Some(t.id),
785 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
786 // This doesn't handle the remaining `Ty` variants as they are not
787 // that commonly the self_type, it might be interesting to provide
788 // support for those in future.
793 // Fields are generally expected in the same contexts as locals.
794 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
795 if let Some(node_id) =
796 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
798 // Look for a field with the same name in the current self_type.
799 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
800 match resolution.base_res() {
801 Res::Def(DefKind::Struct | DefKind::Union, did)
802 if resolution.unresolved_segments() == 0 =>
804 if let Some(field_names) = self.r.field_names.get(&did) {
807 .any(|&field_name| ident.name == field_name.node)
809 return Some(AssocSuggestion::Field);
819 for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
820 if *assoc_type_ident == ident {
821 return Some(AssocSuggestion::AssocItem);
825 // Look for associated items in the current trait.
826 if let Some((module, _)) = self.current_trait_ref {
827 if let Ok(binding) = self.r.resolve_ident_in_module(
828 ModuleOrUniformRoot::Module(module),
835 let res = binding.res();
837 return Some(if self.r.has_self.contains(&res.def_id()) {
838 AssocSuggestion::MethodWithSelf
840 AssocSuggestion::AssocItem
849 fn lookup_typo_candidate(
853 filter_fn: &impl Fn(Res) -> bool,
855 ) -> Option<TypoSuggestion> {
856 let mut names = Vec::new();
858 // Search in lexical scope.
859 // Walk backwards up the ribs in scope and collect candidates.
860 for rib in self.ribs[ns].iter().rev() {
861 // Locals and type parameters
862 for (ident, &res) in &rib.bindings {
864 names.push(TypoSuggestion::from_res(ident.name, res));
868 if let RibKind::ModuleRibKind(module) = rib.kind {
869 // Items from this module
870 self.r.add_module_candidates(module, &mut names, &filter_fn);
872 if let ModuleKind::Block(..) = module.kind {
873 // We can see through blocks
875 // Items from the prelude
876 if !module.no_implicit_prelude {
877 let extern_prelude = self.r.extern_prelude.clone();
878 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
879 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
881 let crate_mod = Res::Def(
883 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
886 if filter_fn(crate_mod) {
887 Some(TypoSuggestion::from_res(ident.name, crate_mod))
895 if let Some(prelude) = self.r.prelude {
896 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
903 // Add primitive types to the mix
904 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
906 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
907 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
913 let mod_path = &path[..path.len() - 1];
914 if let PathResult::Module(module) =
915 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
917 if let ModuleOrUniformRoot::Module(module) = module {
918 self.r.add_module_candidates(module, &mut names, &filter_fn);
923 let name = path[path.len() - 1].ident.name;
924 // Make sure error reporting is deterministic.
925 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
927 match find_best_match_for_name(
928 names.iter().map(|suggestion| &suggestion.candidate),
932 Some(found) if found != name => {
933 names.into_iter().find(|suggestion| suggestion.candidate == found)
939 /// Only used in a specific case of type ascription suggestions
940 fn get_colon_suggestion_span(&self, start: Span) -> Span {
941 let sm = self.r.session.source_map();
942 start.to(sm.next_point(start))
945 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
946 let sm = self.r.session.source_map();
947 let base_snippet = sm.span_to_snippet(base_span);
948 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
949 if let Ok(snippet) = sm.span_to_snippet(sp) {
950 let len = snippet.trim_end().len() as u32;
951 if snippet.trim() == ":" {
953 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
954 let mut show_label = true;
955 if sm.is_multiline(sp) {
956 err.span_suggestion_short(
958 "maybe you meant to write `;` here",
960 Applicability::MaybeIncorrect,
964 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
965 if snippet.len() == 1 {
969 "maybe you meant to write a path separator here",
971 Applicability::MaybeIncorrect,
978 .type_ascription_path_suggestions
985 if let Ok(base_snippet) = base_snippet {
986 let mut sp = after_colon_sp;
988 // Try to find an assignment
989 sp = sm.next_point(sp);
990 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
992 Ok(ref x) if x.as_str() == "=" => {
995 "maybe you meant to write an assignment here",
996 format!("let {}", base_snippet),
997 Applicability::MaybeIncorrect,
1002 Ok(ref x) if x.as_str() == "\n" => break,
1012 "expecting a type here because of type ascription",
1022 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1023 let mut result = None;
1024 let mut seen_modules = FxHashSet::default();
1025 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1027 while let Some((in_module, path_segments)) = worklist.pop() {
1028 // abort if the module is already found
1029 if result.is_some() {
1033 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1034 // abort if the module is already found or if name_binding is private external
1035 if result.is_some() || !name_binding.vis.is_visible_locally() {
1038 if let Some(module) = name_binding.module() {
1040 let mut path_segments = path_segments.clone();
1041 path_segments.push(ast::PathSegment::from_ident(ident));
1042 let module_def_id = module.def_id().unwrap();
1043 if module_def_id == def_id {
1044 let path = Path { span: name_binding.span, segments: path_segments };
1055 // add the module to the lookup
1056 if seen_modules.insert(module_def_id) {
1057 worklist.push((module, path_segments));
1067 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
1068 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1069 let mut variants = Vec::new();
1070 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1071 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
1072 let mut segms = enum_import_suggestion.path.segments.clone();
1073 segms.push(ast::PathSegment::from_ident(ident));
1074 variants.push(Path { span: name_binding.span, segments: segms });
1081 crate fn report_missing_type_error(
1084 ) -> Option<(Span, &'static str, String, Applicability)> {
1085 let (ident, span) = match path {
1086 [segment] if !segment.has_generic_args => {
1087 (segment.ident.to_string(), segment.ident.span)
1091 let mut iter = ident.chars().map(|c| c.is_uppercase());
1092 let single_uppercase_char =
1093 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1094 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1097 match (self.diagnostic_metadata.current_item, single_uppercase_char) {
1098 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
1099 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1104 kind @ ItemKind::Fn(..)
1105 | kind @ ItemKind::Enum(..)
1106 | kind @ ItemKind::Struct(..)
1107 | kind @ ItemKind::Union(..),
1112 | (Some(Item { kind, .. }), false) => {
1113 // Likely missing type parameter.
1114 if let Some(generics) = kind.generics() {
1115 if span.overlaps(generics.span) {
1116 // Avoid the following:
1117 // error[E0405]: cannot find trait `A` in this scope
1118 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1120 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1121 // | ^- help: you might be missing a type parameter: `, A`
1123 // | not found in this scope
1126 let msg = "you might be missing a type parameter";
1127 let (span, sugg) = if let [.., param] = &generics.params[..] {
1128 let span = if let [.., bound] = ¶m.bounds[..] {
1133 (span, format!(", {}", ident))
1135 (generics.span, format!("<{}>", ident))
1137 // Do not suggest if this is coming from macro expansion.
1138 if !span.from_expansion() {
1140 span.shrink_to_hi(),
1143 Applicability::MaybeIncorrect,
1153 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1154 /// optionally returning the closest match and whether it is reachable.
1155 crate fn suggestion_for_label_in_rib(
1159 ) -> Option<LabelSuggestion> {
1160 // Are ribs from this `rib_index` within scope?
1161 let within_scope = self.is_label_valid_from_rib(rib_index);
1163 let rib = &self.label_ribs[rib_index];
1167 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1168 .map(|(id, _)| &id.name);
1170 find_best_match_for_name(names, label.name, None).map(|symbol| {
1171 // Upon finding a similar name, get the ident that it was from - the span
1172 // contained within helps make a useful diagnostic. In addition, determine
1173 // whether this candidate is within scope.
1174 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1175 (*ident, within_scope)
1180 impl<'tcx> LifetimeContext<'_, 'tcx> {
1181 crate fn report_missing_lifetime_specifiers(
1185 ) -> DiagnosticBuilder<'tcx> {
1190 "missing lifetime specifier{}",
1195 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1196 let mut err = struct_span_err!(
1200 "use of undeclared lifetime name `{}`",
1203 err.span_label(lifetime_ref.span, "undeclared lifetime");
1204 let mut suggests_in_band = false;
1205 for missing in &self.missing_named_lifetime_spots {
1207 MissingLifetimeSpot::Generics(generics) => {
1208 let (span, sugg) = if let Some(param) =
1209 generics.params.iter().find(|p| match p.kind {
1210 hir::GenericParamKind::Type {
1211 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1216 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1218 suggests_in_band = true;
1219 (generics.span, format!("<{}>", lifetime_ref))
1221 err.span_suggestion(
1223 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1225 Applicability::MaybeIncorrect,
1228 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1229 err.span_suggestion(
1232 "consider making the {} lifetime-generic with a new `{}` lifetime",
1236 span_type.suggestion(&lifetime_ref.to_string()),
1237 Applicability::MaybeIncorrect,
1240 "for more information on higher-ranked polymorphism, visit \
1241 https://doc.rust-lang.org/nomicon/hrtb.html",
1246 if nightly_options::is_nightly_build()
1247 && !self.tcx.features().in_band_lifetimes
1251 "if you want to experiment with in-band lifetime bindings, \
1252 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1258 // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
1259 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1260 // lifetimes in const generics. See issue #74052 for discussion.
1261 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1262 let mut err = struct_span_err!(
1266 "use of non-static lifetime `{}` in const generic",
1270 "for more information, see issue #74052 \
1271 <https://github.com/rust-lang/rust/issues/74052>",
1276 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1277 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1279 self.tcx.lang_items().fn_once_trait(),
1280 self.tcx.lang_items().fn_trait(),
1281 self.tcx.lang_items().fn_mut_trait(),
1283 .contains(&Some(did))
1285 let (span, span_type) = match &trait_ref.bound_generic_params {
1286 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1287 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1289 self.missing_named_lifetime_spots
1290 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1297 crate fn add_missing_lifetime_specifiers_label(
1299 err: &mut DiagnosticBuilder<'_>,
1302 lifetime_names: &FxHashSet<Ident>,
1303 params: &[ElisionFailureInfo],
1305 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1310 "expected {} lifetime parameter{}",
1311 if count == 1 { "named".to_string() } else { count.to_string() },
1316 let suggest_existing = |err: &mut DiagnosticBuilder<'_>, sugg| {
1317 err.span_suggestion_verbose(
1319 &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
1321 Applicability::MaybeIncorrect,
1324 let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1325 for missing in self.missing_named_lifetime_spots.iter().rev() {
1326 let mut introduce_suggestion = vec![];
1329 introduce_suggestion.push(match missing {
1330 MissingLifetimeSpot::Generics(generics) => {
1331 msg = "consider introducing a named lifetime parameter".to_string();
1332 should_break = true;
1333 if let Some(param) = generics.params.iter().find(|p| match p.kind {
1334 hir::GenericParamKind::Type {
1335 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1340 (param.span.shrink_to_lo(), "'a, ".to_string())
1342 (generics.span, "<'a>".to_string())
1345 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1347 "consider making the {} lifetime-generic with a new `'a` lifetime",
1350 should_break = false;
1352 "for more information on higher-ranked polymorphism, visit \
1353 https://doc.rust-lang.org/nomicon/hrtb.html",
1355 (*span, span_type.suggestion("'a"))
1358 for param in params {
1359 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1360 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1361 introduce_suggestion
1362 .push((param.span, format!("&'a {}", &snippet[1..])));
1363 } else if snippet.starts_with("&'_ ") {
1364 introduce_suggestion
1365 .push((param.span, format!("&'a {}", &snippet[4..])));
1369 introduce_suggestion.push((span, sugg.to_string()));
1370 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1377 match (lifetime_names.len(), lifetime_names.iter().next(), snippet.as_deref()) {
1378 (1, Some(name), Some("&")) => {
1379 suggest_existing(err, format!("&{} ", name));
1381 (1, Some(name), Some("'_")) => {
1382 suggest_existing(err, name.to_string());
1384 (1, Some(name), Some("")) => {
1385 suggest_existing(err, format!("{}, ", name).repeat(count));
1387 (1, Some(name), Some(snippet)) if !snippet.ends_with('>') => {
1393 std::iter::repeat(name.to_string())
1395 .collect::<Vec<_>>()
1400 (0, _, Some("&")) if count == 1 => {
1401 suggest_new(err, "&'a ");
1403 (0, _, Some("'_")) if count == 1 => {
1404 suggest_new(err, "'a");
1406 (0, _, Some(snippet)) if !snippet.ends_with('>') && count == 1 => {
1407 suggest_new(err, &format!("{}<'a>", snippet));
1409 (n, ..) if n > 1 => {
1410 let spans: Vec<Span> = lifetime_names.iter().map(|lt| lt.span).collect();
1411 err.span_note(spans, "these named lifetimes are available to use");
1412 if Some("") == snippet.as_deref() {
1413 // This happens when we have `Foo<T>` where we point at the space before `T`,
1414 // but this can be confusing so we give a suggestion with placeholders.
1415 err.span_suggestion_verbose(
1417 "consider using one of the available lifetimes here",
1418 "'lifetime, ".repeat(count),
1419 Applicability::HasPlaceholders,