1 use crate::diagnostics::{ImportSuggestion, TypoSuggestion};
2 use crate::late::{LateResolutionVisitor, RibKind};
3 use crate::path_names_to_string;
4 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
5 use crate::{PathResult, PathSource, Segment};
7 use rustc::session::config::nightly_options;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_error_codes::*;
10 use rustc_errors::{Applicability, DiagnosticBuilder};
11 use rustc_hir::def::Namespace::{self, *};
12 use rustc_hir::def::{self, CtorKind, DefKind};
13 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
14 use rustc_hir::PrimTy;
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::kw;
18 use syntax::ast::{self, Expr, ExprKind, Ident, NodeId, Path, Ty, TyKind};
19 use syntax::util::lev_distance::find_best_match_for_name;
23 type Res = def::Res<ast::NodeId>;
25 /// A field or associated item from self type suggested in case of resolution failure.
26 enum AssocSuggestion {
32 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
33 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
36 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
37 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
40 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
41 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
42 let variant_path = &suggestion.path;
43 let variant_path_string = path_names_to_string(variant_path);
45 let path_len = suggestion.path.segments.len();
46 let enum_path = ast::Path {
47 span: suggestion.path.span,
48 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
50 let enum_path_string = path_names_to_string(&enum_path);
52 (variant_path_string, enum_path_string)
55 impl<'a> LateResolutionVisitor<'a, '_> {
56 /// Handles error reporting for `smart_resolve_path_fragment` function.
57 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
58 pub(crate) fn smart_resolve_report_errors(
62 source: PathSource<'_>,
64 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
65 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
66 let ns = source.namespace();
67 let is_expected = &|res| source.is_expected(res);
68 let is_enum_variant = &|res| {
69 if let Res::Def(DefKind::Variant, _) = res { true } else { false }
72 // Make the base error.
73 let expected = source.descr_expected();
74 let path_str = Segment::names_to_string(path);
75 let item_str = path.last().unwrap().ident;
76 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
78 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
79 format!("not a {}", expected),
82 Res::Def(DefKind::Fn, _) => {
83 // Verify whether this is a fn call or an Fn used as a type.
87 .span_to_snippet(span)
88 .map(|snippet| snippet.ends_with(')'))
91 Res::Def(DefKind::Ctor(..), _)
92 | Res::Def(DefKind::Method, _)
93 | Res::Def(DefKind::Const, _)
94 | Res::Def(DefKind::AssocConst, _)
97 | Res::Local(_) => true,
102 let item_span = path.last().unwrap().ident.span;
103 let (mod_prefix, mod_str) = if path.len() == 1 {
104 (String::new(), "this scope".to_string())
105 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
106 (String::new(), "the crate root".to_string())
108 let mod_path = &path[..path.len() - 1];
110 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
111 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
114 .map_or(String::new(), |res| format!("{} ", res.descr()));
115 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
118 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
119 format!("not found in {}", mod_str),
125 let code = source.error_code(res.is_some());
126 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
128 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
129 if ["this", "my"].contains(&&*item_str.as_str())
130 && self.self_value_is_available(path[0].ident.span, span)
136 Applicability::MaybeIncorrect,
140 // Emit special messages for unresolved `Self` and `self`.
141 if is_self_type(path, ns) {
142 err.code(rustc_errors::error_code!(E0411));
145 format!("`Self` is only available in impls, traits, and type definitions"),
147 return (err, Vec::new());
149 if is_self_value(path, ns) {
150 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
152 err.code(rustc_errors::error_code!(E0424));
153 err.span_label(span, match source {
154 PathSource::Pat => format!(
155 "`self` value is a keyword and may not be bound to variables or shadowed",
158 "`self` value is a keyword only available in methods with a `self` parameter",
161 if let Some(span) = &self.diagnostic_metadata.current_function {
162 err.span_label(*span, "this function doesn't have a `self` parameter");
164 return (err, Vec::new());
167 // Try to lookup name in more relaxed fashion for better error reporting.
168 let ident = path.last().unwrap().ident;
169 let candidates = self
171 .lookup_import_candidates(ident, ns, is_expected)
173 .filter(|ImportSuggestion { did, .. }| {
174 match (did, res.and_then(|res| res.opt_def_id())) {
175 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
179 .collect::<Vec<_>>();
180 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
181 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
182 let enum_candidates = self.r.lookup_import_candidates(ident, ns, is_enum_variant);
183 let mut enum_candidates = enum_candidates
185 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
186 .collect::<Vec<_>>();
187 enum_candidates.sort();
189 if !enum_candidates.is_empty() {
190 // Contextualize for E0412 "cannot find type", but don't belabor the point
191 // (that it's a variant) for E0573 "expected type, found variant".
192 let preamble = if res.is_none() {
193 let others = match enum_candidates.len() {
195 2 => " and 1 other".to_owned(),
196 n => format!(" and {} others", n),
198 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
202 let msg = format!("{}try using the variant's enum", preamble);
204 err.span_suggestions(
209 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
210 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
212 // FIXME: is there a more principled way to do this that
213 // would work for other re-exports?
214 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
215 // Also write `Option` rather than `std::prelude::v1::Option`.
216 .map(|enum_ty_path| {
217 // FIXME #56861: DRY-er prelude filtering.
218 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
220 Applicability::MachineApplicable,
224 if path.len() == 1 && self.self_type_is_available(span) {
225 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
226 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
228 AssocSuggestion::Field => {
229 if self_is_available {
232 "you might have meant to use the available field",
233 format!("self.{}", path_str),
234 Applicability::MachineApplicable,
237 err.span_label(span, "a field by this name exists in `Self`");
240 AssocSuggestion::MethodWithSelf if self_is_available => {
244 format!("self.{}", path_str),
245 Applicability::MachineApplicable,
248 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
252 format!("Self::{}", path_str),
253 Applicability::MachineApplicable,
257 return (err, candidates);
260 // If the first argument in call is `self` suggest calling a method.
261 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
262 let mut args_snippet = String::new();
263 if let Some(args_span) = args_span {
264 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
265 args_snippet = snippet;
271 &format!("try calling `{}` as a method", ident),
272 format!("self.{}({})", path_str, args_snippet),
273 Applicability::MachineApplicable,
275 return (err, candidates);
279 // Try Levenshtein algorithm.
280 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
281 let levenshtein_worked = self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
283 // Try context-dependent help if relaxed lookup didn't work.
284 if let Some(res) = res {
285 if self.smart_resolve_context_dependent_help(
293 return (err, candidates);
298 if !levenshtein_worked {
299 err.span_label(base_span, fallback_label);
300 self.type_ascription_suggestion(&mut err, base_span);
301 match self.diagnostic_metadata.current_let_binding {
302 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
303 err.span_suggestion_short(
304 pat_sp.between(ty_sp),
305 "use `=` if you meant to assign",
307 Applicability::MaybeIncorrect,
316 /// Check if the source is call expression and the first argument is `self`. If true,
317 /// return the span of whole call and the span for all arguments expect the first one (`self`).
318 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
319 let mut has_self_arg = None;
320 if let PathSource::Expr(parent) = source {
321 match &parent?.kind {
322 ExprKind::Call(_, args) if args.len() > 0 => {
323 let mut expr_kind = &args[0].kind;
326 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
327 if arg_name.segments[0].ident.name == kw::SelfLower {
328 let call_span = parent.unwrap().span;
329 let tail_args_span = if args.len() > 1 {
332 args.last().unwrap().span.hi(),
338 has_self_arg = Some((call_span, tail_args_span));
342 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
353 fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
354 // HACK(estebank): find a better way to figure out that this was a
355 // parser issue where a struct literal is being used on an expression
356 // where a brace being opened means a block is being started. Look
357 // ahead for the next text to see if `span` is followed by a `{`.
358 let sm = self.r.session.source_map();
361 sp = sm.next_point(sp);
362 match sm.span_to_snippet(sp) {
364 if snippet.chars().any(|c| !c.is_whitespace()) {
371 let followed_by_brace = match sm.span_to_snippet(sp) {
372 Ok(ref snippet) if snippet == "{" => true,
375 // In case this could be a struct literal that needs to be surrounded
376 // by parenthesis, find the appropriate span.
378 let mut closing_brace = None;
380 sp = sm.next_point(sp);
381 match sm.span_to_snippet(sp) {
384 let sp = span.to(sp);
385 if let Ok(snippet) = sm.span_to_snippet(sp) {
386 closing_brace = Some((sp, snippet));
394 // The bigger the span, the more likely we're incorrect --
395 // bound it to 100 chars long.
400 return (followed_by_brace, closing_brace);
403 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
405 /// Returns `true` if able to provide context-dependent help.
406 fn smart_resolve_context_dependent_help(
408 err: &mut DiagnosticBuilder<'a>,
410 source: PathSource<'_>,
413 fallback_label: &str,
415 let ns = source.namespace();
416 let is_expected = &|res| source.is_expected(res);
418 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
419 ExprKind::Field(_, ident) => {
422 "use the path separator to refer to an item",
423 format!("{}::{}", path_str, ident),
424 Applicability::MaybeIncorrect,
428 ExprKind::MethodCall(ref segment, ..) => {
429 let span = expr.span.with_hi(segment.ident.span.hi());
432 "use the path separator to refer to an item",
433 format!("{}::{}", path_str, segment.ident),
434 Applicability::MaybeIncorrect,
441 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
442 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
443 let mut suggested = false;
445 PathSource::Expr(Some(parent)) => {
446 suggested = path_sep(err, &parent);
448 PathSource::Expr(None) if followed_by_brace == true => {
449 if let Some((sp, snippet)) = closing_brace {
452 "surround the struct literal with parenthesis",
453 format!("({})", snippet),
454 Applicability::MaybeIncorrect,
458 span, // Note the parenthesis surrounding the suggestion below
459 format!("did you mean `({} {{ /* fields */ }})`?", path_str),
467 if let Some(span) = self.r.definitions.opt_span(def_id) {
468 err.span_label(span, &format!("`{}` defined here", path_str));
470 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?", path_str));
474 match (res, source) {
475 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
478 "use `!` to invoke the macro",
479 format!("{}!", path_str),
480 Applicability::MaybeIncorrect,
482 if path_str == "try" && span.rust_2015() {
483 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
486 (Res::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
487 err.span_label(span, "type aliases cannot be used as traits");
488 if nightly_options::is_nightly_build() {
489 err.note("did you mean to use a trait alias?");
492 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
493 if !path_sep(err, &parent) {
497 (Res::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
498 | (Res::Def(DefKind::Enum, def_id), PathSource::Expr(..)) => {
499 if let Some(variants) = self.collect_enum_variants(def_id) {
500 if !variants.is_empty() {
501 let msg = if variants.len() == 1 {
502 "try using the enum's variant"
504 "try using one of the enum's variants"
507 err.span_suggestions(
510 variants.iter().map(path_names_to_string),
511 Applicability::MaybeIncorrect,
515 err.note("did you mean to use one of the enum's variants?");
518 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
519 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
521 let accessible_ctor =
522 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
523 if is_expected(ctor_def) && !accessible_ctor {
526 format!("constructor is not visible here due to private fields"),
530 bad_struct_syntax_suggestion(def_id);
533 (Res::Def(DefKind::Union, def_id), _)
534 | (Res::Def(DefKind::Variant, def_id), _)
535 | (Res::Def(DefKind::Ctor(_, CtorKind::Fictive), def_id), _)
538 bad_struct_syntax_suggestion(def_id);
540 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
541 if let Some(span) = self.r.definitions.opt_span(def_id) {
542 err.span_label(span, &format!("`{}` defined here", path_str));
544 err.span_label(span, format!("did you mean `{}( /* fields */ )`?", path_str));
546 (Res::SelfTy(..), _) if ns == ValueNS => {
547 err.span_label(span, fallback_label);
548 err.note("can't use `Self` as a constructor, you must use the implemented struct");
550 (Res::Def(DefKind::TyAlias, _), _) | (Res::Def(DefKind::AssocTy, _), _)
553 err.note("can't use a type alias as a constructor");
560 fn lookup_assoc_candidate<FilterFn>(
565 ) -> Option<AssocSuggestion>
567 FilterFn: Fn(Res) -> bool,
569 fn extract_node_id(t: &Ty) -> Option<NodeId> {
571 TyKind::Path(None, _) => Some(t.id),
572 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
573 // This doesn't handle the remaining `Ty` variants as they are not
574 // that commonly the self_type, it might be interesting to provide
575 // support for those in future.
580 // Fields are generally expected in the same contexts as locals.
581 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
582 if let Some(node_id) =
583 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
585 // Look for a field with the same name in the current self_type.
586 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
587 match resolution.base_res() {
588 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did)
589 if resolution.unresolved_segments() == 0 =>
591 if let Some(field_names) = self.r.field_names.get(&did) {
594 .any(|&field_name| ident.name == field_name.node)
596 return Some(AssocSuggestion::Field);
606 for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
607 if *assoc_type_ident == ident {
608 return Some(AssocSuggestion::AssocItem);
612 // Look for associated items in the current trait.
613 if let Some((module, _)) = self.current_trait_ref {
614 if let Ok(binding) = self.r.resolve_ident_in_module(
615 ModuleOrUniformRoot::Module(module),
622 let res = binding.res();
624 return Some(if self.r.has_self.contains(&res.def_id()) {
625 AssocSuggestion::MethodWithSelf
627 AssocSuggestion::AssocItem
636 fn lookup_typo_candidate(
640 filter_fn: &impl Fn(Res) -> bool,
642 ) -> Option<TypoSuggestion> {
643 let mut names = Vec::new();
645 // Search in lexical scope.
646 // Walk backwards up the ribs in scope and collect candidates.
647 for rib in self.ribs[ns].iter().rev() {
648 // Locals and type parameters
649 for (ident, &res) in &rib.bindings {
651 names.push(TypoSuggestion::from_res(ident.name, res));
655 if let RibKind::ModuleRibKind(module) = rib.kind {
656 // Items from this module
657 self.r.add_module_candidates(module, &mut names, &filter_fn);
659 if let ModuleKind::Block(..) = module.kind {
660 // We can see through blocks
662 // Items from the prelude
663 if !module.no_implicit_prelude {
664 let extern_prelude = self.r.extern_prelude.clone();
665 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
668 .maybe_process_path_extern(ident.name, ident.span)
669 .and_then(|crate_id| {
670 let crate_mod = Res::Def(
672 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
675 if filter_fn(crate_mod) {
676 Some(TypoSuggestion::from_res(ident.name, crate_mod))
683 if let Some(prelude) = self.r.prelude {
684 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
691 // Add primitive types to the mix
692 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
694 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
695 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
701 let mod_path = &path[..path.len() - 1];
702 if let PathResult::Module(module) =
703 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
705 if let ModuleOrUniformRoot::Module(module) = module {
706 self.r.add_module_candidates(module, &mut names, &filter_fn);
711 let name = path[path.len() - 1].ident.name;
712 // Make sure error reporting is deterministic.
713 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
715 match find_best_match_for_name(
716 names.iter().map(|suggestion| &suggestion.candidate),
720 Some(found) if found != name => {
721 names.into_iter().find(|suggestion| suggestion.candidate == found)
727 /// Only used in a specific case of type ascription suggestions
728 fn get_colon_suggestion_span(&self, start: Span) -> Span {
729 let cm = self.r.session.source_map();
730 start.to(cm.next_point(start))
733 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) {
734 let cm = self.r.session.source_map();
735 let base_snippet = cm.span_to_snippet(base_span);
736 if let Some(sp) = self.diagnostic_metadata.current_type_ascription.last() {
739 // Try to find the `:`; bail on first non-':' / non-whitespace.
740 sp = cm.next_point(sp);
741 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
742 let line_sp = cm.lookup_char_pos(sp.hi()).line;
743 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
745 let mut show_label = true;
746 if line_sp != line_base_sp {
747 err.span_suggestion_short(
749 "did you mean to use `;` here instead?",
751 Applicability::MaybeIncorrect,
754 let colon_sp = self.get_colon_suggestion_span(sp);
756 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
758 .span_to_snippet(after_colon_sp)
764 "maybe you meant to write a path separator here",
766 Applicability::MaybeIncorrect,
770 if let Ok(base_snippet) = base_snippet {
771 let mut sp = after_colon_sp;
773 // Try to find an assignment
774 sp = cm.next_point(sp);
775 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
777 Ok(ref x) if x.as_str() == "=" => {
780 "maybe you meant to write an assignment here",
781 format!("let {}", base_snippet),
782 Applicability::MaybeIncorrect,
787 Ok(ref x) if x.as_str() == "\n" => break,
797 "expecting a type here because of type ascription",
801 } else if !snippet.trim().is_empty() {
802 debug!("tried to find type ascription `:` token, couldn't find it");
812 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
813 let mut result = None;
814 let mut seen_modules = FxHashSet::default();
815 let mut worklist = vec![(self.r.graph_root, Vec::new())];
817 while let Some((in_module, path_segments)) = worklist.pop() {
818 // abort if the module is already found
819 if result.is_some() {
823 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
824 // abort if the module is already found or if name_binding is private external
825 if result.is_some() || !name_binding.vis.is_visible_locally() {
828 if let Some(module) = name_binding.module() {
830 let mut path_segments = path_segments.clone();
831 path_segments.push(ast::PathSegment::from_ident(ident));
832 let module_def_id = module.def_id().unwrap();
833 if module_def_id == def_id {
834 let path = Path { span: name_binding.span, segments: path_segments };
835 result = Some((module, ImportSuggestion { did: Some(def_id), path }));
837 // add the module to the lookup
838 if seen_modules.insert(module_def_id) {
839 worklist.push((module, path_segments));
849 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
850 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
851 let mut variants = Vec::new();
852 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
853 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
854 let mut segms = enum_import_suggestion.path.segments.clone();
855 segms.push(ast::PathSegment::from_ident(ident));
856 variants.push(Path { span: name_binding.span, segments: segms });