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 "if you meant to use `self`, you are also missing a `self` receiver \
208 Applicability::MaybeIncorrect,
214 // Emit special messages for unresolved `Self` and `self`.
215 if is_self_type(path, ns) {
216 err.code(rustc_errors::error_code!(E0411));
219 "`Self` is only available in impls, traits, and type definitions".to_string(),
221 return (err, Vec::new());
223 if is_self_value(path, ns) {
224 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
226 err.code(rustc_errors::error_code!(E0424));
227 err.span_label(span, match source {
228 PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed"
230 _ => "`self` value is a keyword only available in methods with a `self` parameter"
233 if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
234 // The current function has a `self' parameter, but we were unable to resolve
235 // a reference to `self`. This can only happen if the `self` identifier we
236 // are resolving came from a different hygiene context.
237 if fn_kind.decl().inputs.get(0).map(|p| p.is_self()).unwrap_or(false) {
238 err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
240 let doesnt = if is_assoc_fn {
241 let (span, sugg) = fn_kind
245 .map(|p| (p.span.shrink_to_lo(), "&self, "))
251 .span_through_char(*span, '(')
256 err.span_suggestion_verbose(
258 "add a `self` receiver parameter to make the associated `fn` a method",
260 Applicability::MaybeIncorrect,
266 if let Some(ident) = fn_kind.ident() {
269 &format!("this function {} have a `self` parameter", doesnt),
274 return (err, Vec::new());
277 // Try to lookup name in more relaxed fashion for better error reporting.
278 let ident = path.last().unwrap().ident;
279 let candidates = self
281 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
283 .filter(|ImportSuggestion { did, .. }| {
284 match (did, res.and_then(|res| res.opt_def_id())) {
285 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
289 .collect::<Vec<_>>();
290 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
291 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
292 let enum_candidates =
293 self.r.lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant);
295 if !enum_candidates.is_empty() {
296 if let (PathSource::Type, Some(span)) =
297 (source, self.diagnostic_metadata.current_type_ascription.last())
303 .type_ascription_path_suggestions
307 // Already reported this issue on the lhs of the type ascription.
309 return (err, candidates);
313 let mut enum_candidates = enum_candidates
315 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
316 .collect::<Vec<_>>();
317 enum_candidates.sort();
319 // Contextualize for E0412 "cannot find type", but don't belabor the point
320 // (that it's a variant) for E0573 "expected type, found variant".
321 let preamble = if res.is_none() {
322 let others = match enum_candidates.len() {
324 2 => " and 1 other".to_owned(),
325 n => format!(" and {} others", n),
327 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
331 let msg = format!("{}try using the variant's enum", preamble);
333 err.span_suggestions(
338 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
339 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
341 // FIXME: is there a more principled way to do this that
342 // would work for other re-exports?
343 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
344 // Also write `Option` rather than `std::prelude::v1::Option`.
345 .map(|enum_ty_path| {
346 // FIXME #56861: DRY-er prelude filtering.
347 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
349 Applicability::MachineApplicable,
353 if path.len() == 1 && self.self_type_is_available(span) {
354 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
355 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
357 AssocSuggestion::Field => {
358 if self_is_available {
361 "you might have meant to use the available field",
362 format!("self.{}", path_str),
363 Applicability::MachineApplicable,
366 err.span_label(span, "a field by this name exists in `Self`");
369 AssocSuggestion::MethodWithSelf if self_is_available => {
373 format!("self.{}", path_str),
374 Applicability::MachineApplicable,
377 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
381 format!("Self::{}", path_str),
382 Applicability::MachineApplicable,
386 return (err, candidates);
389 // If the first argument in call is `self` suggest calling a method.
390 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
391 let mut args_snippet = String::new();
392 if let Some(args_span) = args_span {
393 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
394 args_snippet = snippet;
400 &format!("try calling `{}` as a method", ident),
401 format!("self.{}({})", path_str, args_snippet),
402 Applicability::MachineApplicable,
404 return (err, candidates);
408 // Try Levenshtein algorithm.
409 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
410 // Try context-dependent help if relaxed lookup didn't work.
411 if let Some(res) = res {
412 if self.smart_resolve_context_dependent_help(
420 // We do this to avoid losing a secondary span when we override the main error span.
421 self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
422 return (err, candidates);
426 if !self.type_ascription_suggestion(&mut err, base_span)
427 && !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span)
430 err.span_label(base_span, fallback_label);
432 match self.diagnostic_metadata.current_let_binding {
433 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
434 err.span_suggestion_short(
435 pat_sp.between(ty_sp),
436 "use `=` if you meant to assign",
438 Applicability::MaybeIncorrect,
447 /// Check if the source is call expression and the first argument is `self`. If true,
448 /// return the span of whole call and the span for all arguments expect the first one (`self`).
449 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
450 let mut has_self_arg = None;
451 if let PathSource::Expr(Some(parent)) = source {
453 ExprKind::Call(_, args) if !args.is_empty() => {
454 let mut expr_kind = &args[0].kind;
457 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
458 if arg_name.segments[0].ident.name == kw::SelfLower {
459 let call_span = parent.span;
460 let tail_args_span = if args.len() > 1 {
463 args.last().unwrap().span.hi(),
469 has_self_arg = Some((call_span, tail_args_span));
473 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
484 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
485 // HACK(estebank): find a better way to figure out that this was a
486 // parser issue where a struct literal is being used on an expression
487 // where a brace being opened means a block is being started. Look
488 // ahead for the next text to see if `span` is followed by a `{`.
489 let sm = self.r.session.source_map();
492 sp = sm.next_point(sp);
493 match sm.span_to_snippet(sp) {
495 if snippet.chars().any(|c| !c.is_whitespace()) {
502 let followed_by_brace = match sm.span_to_snippet(sp) {
503 Ok(ref snippet) if snippet == "{" => true,
506 // In case this could be a struct literal that needs to be surrounded
507 // by parentheses, find the appropriate span.
509 let mut closing_brace = None;
511 sp = sm.next_point(sp);
512 match sm.span_to_snippet(sp) {
515 closing_brace = Some(span.to(sp));
522 // The bigger the span, the more likely we're incorrect --
523 // bound it to 100 chars long.
528 (followed_by_brace, closing_brace)
531 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
533 /// Returns `true` if able to provide context-dependent help.
534 fn smart_resolve_context_dependent_help(
536 err: &mut DiagnosticBuilder<'a>,
538 source: PathSource<'_>,
541 fallback_label: &str,
543 let ns = source.namespace();
544 let is_expected = &|res| source.is_expected(res);
546 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
547 ExprKind::Field(_, ident) => {
550 "use the path separator to refer to an item",
551 format!("{}::{}", path_str, ident),
552 Applicability::MaybeIncorrect,
556 ExprKind::MethodCall(ref segment, ..) => {
557 let span = expr.span.with_hi(segment.ident.span.hi());
560 "use the path separator to refer to an item",
561 format!("{}::{}", path_str, segment.ident),
562 Applicability::MaybeIncorrect,
569 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
570 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
573 PathSource::Expr(Some(
574 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
575 )) if path_sep(err, &parent) => {}
581 | ExprKind::Binary(..)
582 | ExprKind::Unary(..)
584 | ExprKind::While(..)
585 | ExprKind::ForLoop(..)
586 | ExprKind::Match(..),
589 ) if followed_by_brace => {
590 if let Some(sp) = closing_brace {
591 err.span_label(span, fallback_label);
592 err.multipart_suggestion(
593 "surround the struct literal with parentheses",
595 (sp.shrink_to_lo(), "(".to_string()),
596 (sp.shrink_to_hi(), ")".to_string()),
598 Applicability::MaybeIncorrect,
602 span, // Note the parentheses surrounding the suggestion below
604 "you might want to surround a struct literal with parentheses: \
605 `({} {{ /* fields */ }})`?",
611 PathSource::Expr(_) | PathSource::TupleStruct(_) | PathSource::Pat => {
612 let span = match &source {
613 PathSource::Expr(Some(Expr {
614 span, kind: ExprKind::Call(_, _), ..
616 | PathSource::TupleStruct(span) => {
617 // We want the main underline to cover the suggested code as well for
624 if let Some(span) = self.def_span(def_id) {
625 err.span_label(span, &format!("`{}` defined here", path_str));
627 let (tail, descr, applicability) = match source {
628 PathSource::Pat | PathSource::TupleStruct(_) => {
629 ("", "pattern", Applicability::MachineApplicable)
631 _ => (": val", "literal", Applicability::HasPlaceholders),
633 let (fields, applicability) = match self.r.field_names.get(&def_id) {
637 .map(|f| format!("{}{}", f.node, tail))
638 .collect::<Vec<String>>()
642 None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
644 let pad = match self.r.field_names.get(&def_id) {
645 Some(fields) if fields.is_empty() => "",
650 &format!("use struct {} syntax instead", descr),
651 format!("{} {{{pad}{}{pad}}}", path_str, fields, pad = pad),
656 err.span_label(span, fallback_label);
661 match (res, source) {
662 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
663 err.span_label(span, fallback_label);
664 err.span_suggestion_verbose(
666 "use `!` to invoke the macro",
668 Applicability::MaybeIncorrect,
670 if path_str == "try" && span.rust_2015() {
671 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
674 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
675 err.span_label(span, "type aliases cannot be used as traits");
676 if nightly_options::is_nightly_build() {
677 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
679 if let Some(span) = self.def_span(def_id) {
680 err.span_help(span, msg);
686 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
687 if !path_sep(err, &parent) {
692 Res::Def(DefKind::Enum, def_id),
693 PathSource::TupleStruct(_) | PathSource::Expr(..),
697 .current_type_ascription
703 .type_ascription_path_suggestions
710 // We already suggested changing `:` into `::` during parsing.
713 if let Some(variants) = self.collect_enum_variants(def_id) {
714 if !variants.is_empty() {
715 let msg = if variants.len() == 1 {
716 "try using the enum's variant"
718 "try using one of the enum's variants"
721 err.span_suggestions(
724 variants.iter().map(path_names_to_string),
725 Applicability::MaybeIncorrect,
729 err.note("you might have meant to use one of the enum's variants");
732 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
733 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
735 let accessible_ctor =
736 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
737 if is_expected(ctor_def) && !accessible_ctor {
740 "constructor is not visible here due to private fields".to_string(),
744 bad_struct_syntax_suggestion(def_id);
749 DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
753 ) if ns == ValueNS => {
754 bad_struct_syntax_suggestion(def_id);
756 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
757 if let Some(span) = self.def_span(def_id) {
758 err.span_label(span, &format!("`{}` defined here", path_str));
760 err.span_label(span, format!("did you mean `{}( /* fields */ )`?", path_str));
762 (Res::SelfTy(..), _) if ns == ValueNS => {
763 err.span_label(span, fallback_label);
764 err.note("can't use `Self` as a constructor, you must use the implemented struct");
766 (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
767 err.note("can't use a type alias as a constructor");
774 fn lookup_assoc_candidate<FilterFn>(
779 ) -> Option<AssocSuggestion>
781 FilterFn: Fn(Res) -> bool,
783 fn extract_node_id(t: &Ty) -> Option<NodeId> {
785 TyKind::Path(None, _) => Some(t.id),
786 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
787 // This doesn't handle the remaining `Ty` variants as they are not
788 // that commonly the self_type, it might be interesting to provide
789 // support for those in future.
794 // Fields are generally expected in the same contexts as locals.
795 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
796 if let Some(node_id) =
797 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
799 // Look for a field with the same name in the current self_type.
800 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
801 match resolution.base_res() {
802 Res::Def(DefKind::Struct | DefKind::Union, did)
803 if resolution.unresolved_segments() == 0 =>
805 if let Some(field_names) = self.r.field_names.get(&did) {
808 .any(|&field_name| ident.name == field_name.node)
810 return Some(AssocSuggestion::Field);
820 for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
821 if *assoc_type_ident == ident {
822 return Some(AssocSuggestion::AssocItem);
826 // Look for associated items in the current trait.
827 if let Some((module, _)) = self.current_trait_ref {
828 if let Ok(binding) = self.r.resolve_ident_in_module(
829 ModuleOrUniformRoot::Module(module),
836 let res = binding.res();
838 return Some(if self.r.has_self.contains(&res.def_id()) {
839 AssocSuggestion::MethodWithSelf
841 AssocSuggestion::AssocItem
850 fn lookup_typo_candidate(
854 filter_fn: &impl Fn(Res) -> bool,
856 ) -> Option<TypoSuggestion> {
857 let mut names = Vec::new();
859 // Search in lexical scope.
860 // Walk backwards up the ribs in scope and collect candidates.
861 for rib in self.ribs[ns].iter().rev() {
862 // Locals and type parameters
863 for (ident, &res) in &rib.bindings {
865 names.push(TypoSuggestion::from_res(ident.name, res));
869 if let RibKind::ModuleRibKind(module) = rib.kind {
870 // Items from this module
871 self.r.add_module_candidates(module, &mut names, &filter_fn);
873 if let ModuleKind::Block(..) = module.kind {
874 // We can see through blocks
876 // Items from the prelude
877 if !module.no_implicit_prelude {
878 let extern_prelude = self.r.extern_prelude.clone();
879 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
880 self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
882 let crate_mod = Res::Def(
884 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
887 if filter_fn(crate_mod) {
888 Some(TypoSuggestion::from_res(ident.name, crate_mod))
896 if let Some(prelude) = self.r.prelude {
897 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
904 // Add primitive types to the mix
905 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
907 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
908 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
914 let mod_path = &path[..path.len() - 1];
915 if let PathResult::Module(module) =
916 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
918 if let ModuleOrUniformRoot::Module(module) = module {
919 self.r.add_module_candidates(module, &mut names, &filter_fn);
924 let name = path[path.len() - 1].ident.name;
925 // Make sure error reporting is deterministic.
926 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
928 match find_best_match_for_name(
929 names.iter().map(|suggestion| &suggestion.candidate),
933 Some(found) if found != name => {
934 names.into_iter().find(|suggestion| suggestion.candidate == found)
940 /// Only used in a specific case of type ascription suggestions
941 fn get_colon_suggestion_span(&self, start: Span) -> Span {
942 let sm = self.r.session.source_map();
943 start.to(sm.next_point(start))
946 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) -> bool {
947 let sm = self.r.session.source_map();
948 let base_snippet = sm.span_to_snippet(base_span);
949 if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
950 if let Ok(snippet) = sm.span_to_snippet(sp) {
951 let len = snippet.trim_end().len() as u32;
952 if snippet.trim() == ":" {
954 sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
955 let mut show_label = true;
956 if sm.is_multiline(sp) {
957 err.span_suggestion_short(
959 "maybe you meant to write `;` here",
961 Applicability::MaybeIncorrect,
965 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
966 if snippet.len() == 1 {
970 "maybe you meant to write a path separator here",
972 Applicability::MaybeIncorrect,
979 .type_ascription_path_suggestions
986 if let Ok(base_snippet) = base_snippet {
987 let mut sp = after_colon_sp;
989 // Try to find an assignment
990 sp = sm.next_point(sp);
991 let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
993 Ok(ref x) if x.as_str() == "=" => {
996 "maybe you meant to write an assignment here",
997 format!("let {}", base_snippet),
998 Applicability::MaybeIncorrect,
1003 Ok(ref x) if x.as_str() == "\n" => break,
1013 "expecting a type here because of type ascription",
1023 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
1024 let mut result = None;
1025 let mut seen_modules = FxHashSet::default();
1026 let mut worklist = vec![(self.r.graph_root, Vec::new())];
1028 while let Some((in_module, path_segments)) = worklist.pop() {
1029 // abort if the module is already found
1030 if result.is_some() {
1034 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
1035 // abort if the module is already found or if name_binding is private external
1036 if result.is_some() || !name_binding.vis.is_visible_locally() {
1039 if let Some(module) = name_binding.module() {
1041 let mut path_segments = path_segments.clone();
1042 path_segments.push(ast::PathSegment::from_ident(ident));
1043 let module_def_id = module.def_id().unwrap();
1044 if module_def_id == def_id {
1045 let path = Path { span: name_binding.span, segments: path_segments };
1056 // add the module to the lookup
1057 if seen_modules.insert(module_def_id) {
1058 worklist.push((module, path_segments));
1068 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
1069 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
1070 let mut variants = Vec::new();
1071 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
1072 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
1073 let mut segms = enum_import_suggestion.path.segments.clone();
1074 segms.push(ast::PathSegment::from_ident(ident));
1075 variants.push(Path { span: name_binding.span, segments: segms });
1082 crate fn report_missing_type_error(
1085 ) -> Option<(Span, &'static str, String, Applicability)> {
1086 let (ident, span) = match path {
1087 [segment] if !segment.has_generic_args => {
1088 (segment.ident.to_string(), segment.ident.span)
1092 let mut iter = ident.chars().map(|c| c.is_uppercase());
1093 let single_uppercase_char =
1094 matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
1095 if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
1098 match (self.diagnostic_metadata.current_item, single_uppercase_char) {
1099 (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _) if ident.name == sym::main => {
1100 // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
1105 kind @ ItemKind::Fn(..)
1106 | kind @ ItemKind::Enum(..)
1107 | kind @ ItemKind::Struct(..)
1108 | kind @ ItemKind::Union(..),
1113 | (Some(Item { kind, .. }), false) => {
1114 // Likely missing type parameter.
1115 if let Some(generics) = kind.generics() {
1116 if span.overlaps(generics.span) {
1117 // Avoid the following:
1118 // error[E0405]: cannot find trait `A` in this scope
1119 // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
1121 // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
1122 // | ^- help: you might be missing a type parameter: `, A`
1124 // | not found in this scope
1127 let msg = "you might be missing a type parameter";
1128 let (span, sugg) = if let [.., param] = &generics.params[..] {
1129 let span = if let [.., bound] = ¶m.bounds[..] {
1134 (span, format!(", {}", ident))
1136 (generics.span, format!("<{}>", ident))
1138 // Do not suggest if this is coming from macro expansion.
1139 if !span.from_expansion() {
1141 span.shrink_to_hi(),
1144 Applicability::MaybeIncorrect,
1154 /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
1155 /// optionally returning the closest match and whether it is reachable.
1156 crate fn suggestion_for_label_in_rib(
1160 ) -> Option<LabelSuggestion> {
1161 // Are ribs from this `rib_index` within scope?
1162 let within_scope = self.is_label_valid_from_rib(rib_index);
1164 let rib = &self.label_ribs[rib_index];
1168 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
1169 .map(|(id, _)| &id.name);
1171 find_best_match_for_name(names, label.name, None).map(|symbol| {
1172 // Upon finding a similar name, get the ident that it was from - the span
1173 // contained within helps make a useful diagnostic. In addition, determine
1174 // whether this candidate is within scope.
1175 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
1176 (*ident, within_scope)
1181 impl<'tcx> LifetimeContext<'_, 'tcx> {
1182 crate fn report_missing_lifetime_specifiers(
1186 ) -> DiagnosticBuilder<'tcx> {
1191 "missing lifetime specifier{}",
1196 crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
1197 let mut err = struct_span_err!(
1201 "use of undeclared lifetime name `{}`",
1204 err.span_label(lifetime_ref.span, "undeclared lifetime");
1205 let mut suggests_in_band = false;
1206 for missing in &self.missing_named_lifetime_spots {
1208 MissingLifetimeSpot::Generics(generics) => {
1209 let (span, sugg) = if let Some(param) =
1210 generics.params.iter().find(|p| match p.kind {
1211 hir::GenericParamKind::Type {
1212 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1217 (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
1219 suggests_in_band = true;
1220 (generics.span, format!("<{}>", lifetime_ref))
1222 err.span_suggestion(
1224 &format!("consider introducing lifetime `{}` here", lifetime_ref),
1226 Applicability::MaybeIncorrect,
1229 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1230 err.span_suggestion(
1233 "consider making the {} lifetime-generic with a new `{}` lifetime",
1237 span_type.suggestion(&lifetime_ref.to_string()),
1238 Applicability::MaybeIncorrect,
1241 "for more information on higher-ranked polymorphism, visit \
1242 https://doc.rust-lang.org/nomicon/hrtb.html",
1247 if nightly_options::is_nightly_build()
1248 && !self.tcx.features().in_band_lifetimes
1252 "if you want to experiment with in-band lifetime bindings, \
1253 add `#![feature(in_band_lifetimes)]` to the crate attributes",
1259 // FIXME(const_generics): This patches over a ICE caused by non-'static lifetimes in const
1260 // generics. We are disallowing this until we can decide on how we want to handle non-'static
1261 // lifetimes in const generics. See issue #74052 for discussion.
1262 crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
1263 let mut err = struct_span_err!(
1267 "use of non-static lifetime `{}` in const generic",
1271 "for more information, see issue #74052 \
1272 <https://github.com/rust-lang/rust/issues/74052>",
1277 crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
1278 if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
1280 self.tcx.lang_items().fn_once_trait(),
1281 self.tcx.lang_items().fn_trait(),
1282 self.tcx.lang_items().fn_mut_trait(),
1284 .contains(&Some(did))
1286 let (span, span_type) = match &trait_ref.bound_generic_params {
1287 [] => (trait_ref.span.shrink_to_lo(), ForLifetimeSpanType::BoundEmpty),
1288 [.., bound] => (bound.span.shrink_to_hi(), ForLifetimeSpanType::BoundTail),
1290 self.missing_named_lifetime_spots
1291 .push(MissingLifetimeSpot::HigherRanked { span, span_type });
1298 crate fn add_missing_lifetime_specifiers_label(
1300 err: &mut DiagnosticBuilder<'_>,
1303 lifetime_names: &FxHashSet<Ident>,
1304 params: &[ElisionFailureInfo],
1306 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok();
1311 "expected {} lifetime parameter{}",
1312 if count == 1 { "named".to_string() } else { count.to_string() },
1317 let suggest_existing = |err: &mut DiagnosticBuilder<'_>, sugg| {
1318 err.span_suggestion_verbose(
1320 &format!("consider using the `{}` lifetime", lifetime_names.iter().next().unwrap()),
1322 Applicability::MaybeIncorrect,
1325 let suggest_new = |err: &mut DiagnosticBuilder<'_>, sugg: &str| {
1326 for missing in self.missing_named_lifetime_spots.iter().rev() {
1327 let mut introduce_suggestion = vec![];
1330 introduce_suggestion.push(match missing {
1331 MissingLifetimeSpot::Generics(generics) => {
1332 msg = "consider introducing a named lifetime parameter".to_string();
1333 should_break = true;
1334 if let Some(param) = generics.params.iter().find(|p| match p.kind {
1335 hir::GenericParamKind::Type {
1336 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
1341 (param.span.shrink_to_lo(), "'a, ".to_string())
1343 (generics.span, "<'a>".to_string())
1346 MissingLifetimeSpot::HigherRanked { span, span_type } => {
1348 "consider making the {} lifetime-generic with a new `'a` lifetime",
1351 should_break = false;
1353 "for more information on higher-ranked polymorphism, visit \
1354 https://doc.rust-lang.org/nomicon/hrtb.html",
1356 (*span, span_type.suggestion("'a"))
1359 for param in params {
1360 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(param.span) {
1361 if snippet.starts_with('&') && !snippet.starts_with("&'") {
1362 introduce_suggestion
1363 .push((param.span, format!("&'a {}", &snippet[1..])));
1364 } else if snippet.starts_with("&'_ ") {
1365 introduce_suggestion
1366 .push((param.span, format!("&'a {}", &snippet[4..])));
1370 introduce_suggestion.push((span, sugg.to_string()));
1371 err.multipart_suggestion(&msg, introduce_suggestion, Applicability::MaybeIncorrect);
1378 match (lifetime_names.len(), lifetime_names.iter().next(), snippet.as_deref()) {
1379 (1, Some(name), Some("&")) => {
1380 suggest_existing(err, format!("&{} ", name));
1382 (1, Some(name), Some("'_")) => {
1383 suggest_existing(err, name.to_string());
1385 (1, Some(name), Some("")) => {
1386 suggest_existing(err, format!("{}, ", name).repeat(count));
1388 (1, Some(name), Some(snippet)) if !snippet.ends_with('>') => {
1394 std::iter::repeat(name.to_string())
1396 .collect::<Vec<_>>()
1401 (0, _, Some("&")) if count == 1 => {
1402 suggest_new(err, "&'a ");
1404 (0, _, Some("'_")) if count == 1 => {
1405 suggest_new(err, "'a");
1407 (0, _, Some(snippet)) if !snippet.ends_with('>') && count == 1 => {
1408 suggest_new(err, &format!("{}<'a>", snippet));
1410 (n, ..) if n > 1 => {
1411 let spans: Vec<Span> = lifetime_names.iter().map(|lt| lt.span).collect();
1412 err.span_note(spans, "these named lifetimes are available to use");
1413 if Some("") == snippet.as_deref() {
1414 // This happens when we have `Foo<T>` where we point at the space before `T`,
1415 // but this can be confusing so we give a suggestion with placeholders.
1416 err.span_suggestion_verbose(
1418 "consider using one of the available lifetimes here",
1419 "'lifetime, ".repeat(count),
1420 Applicability::HasPlaceholders,