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_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::def::Namespace::{self, *};
11 use rustc_hir::def::{self, CtorKind, DefKind};
12 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
13 use rustc_hir::PrimTy;
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::kw;
17 use syntax::ast::{self, Expr, ExprKind, Ident, NodeId, Path, Ty, TyKind};
18 use syntax::util::lev_distance::find_best_match_for_name;
22 type Res = def::Res<ast::NodeId>;
24 /// A field or associated item from self type suggested in case of resolution failure.
25 enum AssocSuggestion {
31 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
32 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
35 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
36 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
39 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
40 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
41 let variant_path = &suggestion.path;
42 let variant_path_string = path_names_to_string(variant_path);
44 let path_len = suggestion.path.segments.len();
45 let enum_path = ast::Path {
46 span: suggestion.path.span,
47 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
49 let enum_path_string = path_names_to_string(&enum_path);
51 (variant_path_string, enum_path_string)
54 impl<'a> LateResolutionVisitor<'a, '_> {
55 /// Handles error reporting for `smart_resolve_path_fragment` function.
56 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
57 pub(crate) fn smart_resolve_report_errors(
61 source: PathSource<'_>,
63 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
64 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
65 let ns = source.namespace();
66 let is_expected = &|res| source.is_expected(res);
67 let is_enum_variant = &|res| {
68 if let Res::Def(DefKind::Variant, _) = res { true } else { false }
71 // Make the base error.
72 let expected = source.descr_expected();
73 let path_str = Segment::names_to_string(path);
74 let item_str = path.last().unwrap().ident;
75 let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
77 format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
78 format!("not a {}", expected),
81 Res::Def(DefKind::Fn, _) => {
82 // Verify whether this is a fn call or an Fn used as a type.
86 .span_to_snippet(span)
87 .map(|snippet| snippet.ends_with(')'))
90 Res::Def(DefKind::Ctor(..), _)
91 | Res::Def(DefKind::Method, _)
92 | Res::Def(DefKind::Const, _)
93 | Res::Def(DefKind::AssocConst, _)
96 | Res::Local(_) => true,
101 let item_span = path.last().unwrap().ident.span;
102 let (mod_prefix, mod_str) = if path.len() == 1 {
103 (String::new(), "this scope".to_string())
104 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
105 (String::new(), "the crate root".to_string())
107 let mod_path = &path[..path.len() - 1];
109 match self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No) {
110 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
113 .map_or(String::new(), |res| format!("{} ", res.descr()));
114 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
117 format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
118 format!("not found in {}", mod_str),
124 let code = source.error_code(res.is_some());
125 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
127 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
128 if ["this", "my"].contains(&&*item_str.as_str())
129 && self.self_value_is_available(path[0].ident.span, span)
135 Applicability::MaybeIncorrect,
139 // Emit special messages for unresolved `Self` and `self`.
140 if is_self_type(path, ns) {
141 err.code(rustc_errors::error_code!(E0411));
144 format!("`Self` is only available in impls, traits, and type definitions"),
146 return (err, Vec::new());
148 if is_self_value(path, ns) {
149 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
151 err.code(rustc_errors::error_code!(E0424));
152 err.span_label(span, match source {
153 PathSource::Pat => format!(
154 "`self` value is a keyword and may not be bound to variables or shadowed",
157 "`self` value is a keyword only available in methods with a `self` parameter",
160 if let Some(span) = &self.diagnostic_metadata.current_function {
161 err.span_label(*span, "this function doesn't have a `self` parameter");
163 return (err, Vec::new());
166 // Try to lookup name in more relaxed fashion for better error reporting.
167 let ident = path.last().unwrap().ident;
168 let candidates = self
170 .lookup_import_candidates(ident, ns, is_expected)
172 .filter(|ImportSuggestion { did, .. }| {
173 match (did, res.and_then(|res| res.opt_def_id())) {
174 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
178 .collect::<Vec<_>>();
179 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
180 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
181 let enum_candidates = self.r.lookup_import_candidates(ident, ns, is_enum_variant);
182 let mut enum_candidates = enum_candidates
184 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
185 .collect::<Vec<_>>();
186 enum_candidates.sort();
188 if !enum_candidates.is_empty() {
189 // Contextualize for E0412 "cannot find type", but don't belabor the point
190 // (that it's a variant) for E0573 "expected type, found variant".
191 let preamble = if res.is_none() {
192 let others = match enum_candidates.len() {
194 2 => " and 1 other".to_owned(),
195 n => format!(" and {} others", n),
197 format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
201 let msg = format!("{}try using the variant's enum", preamble);
203 err.span_suggestions(
208 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
209 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
211 // FIXME: is there a more principled way to do this that
212 // would work for other re-exports?
213 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
214 // Also write `Option` rather than `std::prelude::v1::Option`.
215 .map(|enum_ty_path| {
216 // FIXME #56861: DRY-er prelude filtering.
217 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
219 Applicability::MachineApplicable,
223 if path.len() == 1 && self.self_type_is_available(span) {
224 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
225 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
227 AssocSuggestion::Field => {
228 if self_is_available {
231 "you might have meant to use the available field",
232 format!("self.{}", path_str),
233 Applicability::MachineApplicable,
236 err.span_label(span, "a field by this name exists in `Self`");
239 AssocSuggestion::MethodWithSelf if self_is_available => {
243 format!("self.{}", path_str),
244 Applicability::MachineApplicable,
247 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
251 format!("Self::{}", path_str),
252 Applicability::MachineApplicable,
256 return (err, candidates);
259 // If the first argument in call is `self` suggest calling a method.
260 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
261 let mut args_snippet = String::new();
262 if let Some(args_span) = args_span {
263 if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
264 args_snippet = snippet;
270 &format!("try calling `{}` as a method", ident),
271 format!("self.{}({})", path_str, args_snippet),
272 Applicability::MachineApplicable,
274 return (err, candidates);
278 // Try Levenshtein algorithm.
279 let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected, span);
280 let levenshtein_worked = self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
282 // Try context-dependent help if relaxed lookup didn't work.
283 if let Some(res) = res {
284 if self.smart_resolve_context_dependent_help(
292 return (err, candidates);
297 if !levenshtein_worked {
298 err.span_label(base_span, fallback_label);
299 self.type_ascription_suggestion(&mut err, base_span);
300 match self.diagnostic_metadata.current_let_binding {
301 Some((pat_sp, Some(ty_sp), None)) if ty_sp.contains(base_span) && could_be_expr => {
302 err.span_suggestion_short(
303 pat_sp.between(ty_sp),
304 "use `=` if you meant to assign",
306 Applicability::MaybeIncorrect,
315 /// Check if the source is call expression and the first argument is `self`. If true,
316 /// return the span of whole call and the span for all arguments expect the first one (`self`).
317 fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
318 let mut has_self_arg = None;
319 if let PathSource::Expr(parent) = source {
320 match &parent?.kind {
321 ExprKind::Call(_, args) if args.len() > 0 => {
322 let mut expr_kind = &args[0].kind;
325 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
326 if arg_name.segments[0].ident.name == kw::SelfLower {
327 let call_span = parent.unwrap().span;
328 let tail_args_span = if args.len() > 1 {
331 args.last().unwrap().span.hi(),
337 has_self_arg = Some((call_span, tail_args_span));
341 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
352 fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
353 // HACK(estebank): find a better way to figure out that this was a
354 // parser issue where a struct literal is being used on an expression
355 // where a brace being opened means a block is being started. Look
356 // ahead for the next text to see if `span` is followed by a `{`.
357 let sm = self.r.session.source_map();
360 sp = sm.next_point(sp);
361 match sm.span_to_snippet(sp) {
363 if snippet.chars().any(|c| !c.is_whitespace()) {
370 let followed_by_brace = match sm.span_to_snippet(sp) {
371 Ok(ref snippet) if snippet == "{" => true,
374 // In case this could be a struct literal that needs to be surrounded
375 // by parenthesis, find the appropriate span.
377 let mut closing_brace = None;
379 sp = sm.next_point(sp);
380 match sm.span_to_snippet(sp) {
383 let sp = span.to(sp);
384 if let Ok(snippet) = sm.span_to_snippet(sp) {
385 closing_brace = Some((sp, snippet));
393 // The bigger the span, the more likely we're incorrect --
394 // bound it to 100 chars long.
399 return (followed_by_brace, closing_brace);
402 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
404 /// Returns `true` if able to provide context-dependent help.
405 fn smart_resolve_context_dependent_help(
407 err: &mut DiagnosticBuilder<'a>,
409 source: PathSource<'_>,
412 fallback_label: &str,
414 let ns = source.namespace();
415 let is_expected = &|res| source.is_expected(res);
417 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
418 ExprKind::Field(_, ident) => {
421 "use the path separator to refer to an item",
422 format!("{}::{}", path_str, ident),
423 Applicability::MaybeIncorrect,
427 ExprKind::MethodCall(ref segment, ..) => {
428 let span = expr.span.with_hi(segment.ident.span.hi());
431 "use the path separator to refer to an item",
432 format!("{}::{}", path_str, segment.ident),
433 Applicability::MaybeIncorrect,
440 let mut bad_struct_syntax_suggestion = |def_id: DefId| {
441 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
442 let mut suggested = false;
444 PathSource::Expr(Some(parent)) => {
445 suggested = path_sep(err, &parent);
447 PathSource::Expr(None) if followed_by_brace == true => {
448 if let Some((sp, snippet)) = closing_brace {
451 "surround the struct literal with parenthesis",
452 format!("({})", snippet),
453 Applicability::MaybeIncorrect,
457 span, // Note the parenthesis surrounding the suggestion below
458 format!("did you mean `({} {{ /* fields */ }})`?", path_str),
466 if let Some(span) = self.r.definitions.opt_span(def_id) {
467 err.span_label(span, &format!("`{}` defined here", path_str));
469 err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?", path_str));
473 match (res, source) {
474 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
477 "use `!` to invoke the macro",
478 format!("{}!", path_str),
479 Applicability::MaybeIncorrect,
481 if path_str == "try" && span.rust_2015() {
482 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
485 (Res::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
486 err.span_label(span, "type aliases cannot be used as traits");
487 if nightly_options::is_nightly_build() {
488 err.note("did you mean to use a trait alias?");
491 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
492 if !path_sep(err, &parent) {
496 (Res::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
497 | (Res::Def(DefKind::Enum, def_id), PathSource::Expr(..)) => {
498 if let Some(variants) = self.collect_enum_variants(def_id) {
499 if !variants.is_empty() {
500 let msg = if variants.len() == 1 {
501 "try using the enum's variant"
503 "try using one of the enum's variants"
506 err.span_suggestions(
509 variants.iter().map(path_names_to_string),
510 Applicability::MaybeIncorrect,
514 err.note("did you mean to use one of the enum's variants?");
517 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
518 if let Some((ctor_def, ctor_vis)) = self.r.struct_constructors.get(&def_id).cloned()
520 let accessible_ctor =
521 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
522 if is_expected(ctor_def) && !accessible_ctor {
525 format!("constructor is not visible here due to private fields"),
529 bad_struct_syntax_suggestion(def_id);
532 (Res::Def(DefKind::Union, def_id), _)
533 | (Res::Def(DefKind::Variant, def_id), _)
534 | (Res::Def(DefKind::Ctor(_, CtorKind::Fictive), def_id), _)
537 bad_struct_syntax_suggestion(def_id);
539 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
540 if let Some(span) = self.r.definitions.opt_span(def_id) {
541 err.span_label(span, &format!("`{}` defined here", path_str));
543 err.span_label(span, format!("did you mean `{}( /* fields */ )`?", path_str));
545 (Res::SelfTy(..), _) if ns == ValueNS => {
546 err.span_label(span, fallback_label);
547 err.note("can't use `Self` as a constructor, you must use the implemented struct");
549 (Res::Def(DefKind::TyAlias, _), _) | (Res::Def(DefKind::AssocTy, _), _)
552 err.note("can't use a type alias as a constructor");
559 fn lookup_assoc_candidate<FilterFn>(
564 ) -> Option<AssocSuggestion>
566 FilterFn: Fn(Res) -> bool,
568 fn extract_node_id(t: &Ty) -> Option<NodeId> {
570 TyKind::Path(None, _) => Some(t.id),
571 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
572 // This doesn't handle the remaining `Ty` variants as they are not
573 // that commonly the self_type, it might be interesting to provide
574 // support for those in future.
579 // Fields are generally expected in the same contexts as locals.
580 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
581 if let Some(node_id) =
582 self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
584 // Look for a field with the same name in the current self_type.
585 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
586 match resolution.base_res() {
587 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did)
588 if resolution.unresolved_segments() == 0 =>
590 if let Some(field_names) = self.r.field_names.get(&did) {
593 .any(|&field_name| ident.name == field_name.node)
595 return Some(AssocSuggestion::Field);
605 for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
606 if *assoc_type_ident == ident {
607 return Some(AssocSuggestion::AssocItem);
611 // Look for associated items in the current trait.
612 if let Some((module, _)) = self.current_trait_ref {
613 if let Ok(binding) = self.r.resolve_ident_in_module(
614 ModuleOrUniformRoot::Module(module),
621 let res = binding.res();
623 return Some(if self.r.has_self.contains(&res.def_id()) {
624 AssocSuggestion::MethodWithSelf
626 AssocSuggestion::AssocItem
635 fn lookup_typo_candidate(
639 filter_fn: &impl Fn(Res) -> bool,
641 ) -> Option<TypoSuggestion> {
642 let mut names = Vec::new();
644 // Search in lexical scope.
645 // Walk backwards up the ribs in scope and collect candidates.
646 for rib in self.ribs[ns].iter().rev() {
647 // Locals and type parameters
648 for (ident, &res) in &rib.bindings {
650 names.push(TypoSuggestion::from_res(ident.name, res));
654 if let RibKind::ModuleRibKind(module) = rib.kind {
655 // Items from this module
656 self.r.add_module_candidates(module, &mut names, &filter_fn);
658 if let ModuleKind::Block(..) = module.kind {
659 // We can see through blocks
661 // Items from the prelude
662 if !module.no_implicit_prelude {
663 let extern_prelude = self.r.extern_prelude.clone();
664 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
667 .maybe_process_path_extern(ident.name, ident.span)
668 .and_then(|crate_id| {
669 let crate_mod = Res::Def(
671 DefId { krate: crate_id, index: CRATE_DEF_INDEX },
674 if filter_fn(crate_mod) {
675 Some(TypoSuggestion::from_res(ident.name, crate_mod))
682 if let Some(prelude) = self.r.prelude {
683 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
690 // Add primitive types to the mix
691 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
693 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
694 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
700 let mod_path = &path[..path.len() - 1];
701 if let PathResult::Module(module) =
702 self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
704 if let ModuleOrUniformRoot::Module(module) = module {
705 self.r.add_module_candidates(module, &mut names, &filter_fn);
710 let name = path[path.len() - 1].ident.name;
711 // Make sure error reporting is deterministic.
712 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
714 match find_best_match_for_name(
715 names.iter().map(|suggestion| &suggestion.candidate),
719 Some(found) if found != name => {
720 names.into_iter().find(|suggestion| suggestion.candidate == found)
726 /// Only used in a specific case of type ascription suggestions
727 fn get_colon_suggestion_span(&self, start: Span) -> Span {
728 let cm = self.r.session.source_map();
729 start.to(cm.next_point(start))
732 fn type_ascription_suggestion(&self, err: &mut DiagnosticBuilder<'_>, base_span: Span) {
733 let cm = self.r.session.source_map();
734 let base_snippet = cm.span_to_snippet(base_span);
735 if let Some(sp) = self.diagnostic_metadata.current_type_ascription.last() {
738 // Try to find the `:`; bail on first non-':' / non-whitespace.
739 sp = cm.next_point(sp);
740 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
741 let line_sp = cm.lookup_char_pos(sp.hi()).line;
742 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
744 let mut show_label = true;
745 if line_sp != line_base_sp {
746 err.span_suggestion_short(
748 "did you mean to use `;` here instead?",
750 Applicability::MaybeIncorrect,
753 let colon_sp = self.get_colon_suggestion_span(sp);
755 self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
757 .span_to_snippet(after_colon_sp)
763 "maybe you meant to write a path separator here",
765 Applicability::MaybeIncorrect,
769 if let Ok(base_snippet) = base_snippet {
770 let mut sp = after_colon_sp;
772 // Try to find an assignment
773 sp = cm.next_point(sp);
774 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
776 Ok(ref x) if x.as_str() == "=" => {
779 "maybe you meant to write an assignment here",
780 format!("let {}", base_snippet),
781 Applicability::MaybeIncorrect,
786 Ok(ref x) if x.as_str() == "\n" => break,
796 "expecting a type here because of type ascription",
800 } else if !snippet.trim().is_empty() {
801 debug!("tried to find type ascription `:` token, couldn't find it");
811 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
812 let mut result = None;
813 let mut seen_modules = FxHashSet::default();
814 let mut worklist = vec![(self.r.graph_root, Vec::new())];
816 while let Some((in_module, path_segments)) = worklist.pop() {
817 // abort if the module is already found
818 if result.is_some() {
822 in_module.for_each_child(self.r, |_, ident, _, name_binding| {
823 // abort if the module is already found or if name_binding is private external
824 if result.is_some() || !name_binding.vis.is_visible_locally() {
827 if let Some(module) = name_binding.module() {
829 let mut path_segments = path_segments.clone();
830 path_segments.push(ast::PathSegment::from_ident(ident));
831 let module_def_id = module.def_id().unwrap();
832 if module_def_id == def_id {
833 let path = Path { span: name_binding.span, segments: path_segments };
834 result = Some((module, ImportSuggestion { did: Some(def_id), path }));
836 // add the module to the lookup
837 if seen_modules.insert(module_def_id) {
838 worklist.push((module, path_segments));
848 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
849 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
850 let mut variants = Vec::new();
851 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
852 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
853 let mut segms = enum_import_suggestion.path.segments.clone();
854 segms.push(ast::PathSegment::from_ident(ident));
855 variants.push(Path { span: name_binding.span, segments: segms });