1 use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
2 use crate::{PathResult, PathSource, Segment};
3 use crate::path_names_to_string;
4 use crate::diagnostics::{add_typo_suggestion, ImportSuggestion, TypoSuggestion};
5 use crate::late::{LateResolutionVisitor, RibKind};
7 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
9 use rustc::hir::def::{self, DefKind, CtorKind};
10 use rustc::hir::def::Namespace::{self, *};
11 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
12 use rustc::hir::PrimTy;
13 use rustc::session::config::nightly_options;
14 use rustc::util::nodemap::FxHashSet;
15 use syntax::ast::{self, Expr, ExprKind, Ident, NodeId, Path, Ty, TyKind};
16 use syntax::ext::base::MacroKind;
17 use syntax::symbol::kw;
18 use syntax::util::lev_distance::find_best_match_for_name;
21 type Res = def::Res<ast::NodeId>;
23 /// A field or associated item from self type suggested in case of resolution failure.
24 enum AssocSuggestion {
30 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
31 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
34 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
35 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
38 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
39 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
40 let variant_path = &suggestion.path;
41 let variant_path_string = path_names_to_string(variant_path);
43 let path_len = suggestion.path.segments.len();
44 let enum_path = ast::Path {
45 span: suggestion.path.span,
46 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
48 let enum_path_string = path_names_to_string(&enum_path);
50 (variant_path_string, enum_path_string)
53 impl<'a> LateResolutionVisitor<'a, '_> {
54 /// Handles error reporting for `smart_resolve_path_fragment` function.
55 /// Creates base error and amends it with one short label and possibly some longer helps/notes.
56 pub(crate) fn smart_resolve_report_errors(
60 source: PathSource<'_>,
62 ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
63 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
64 let ns = source.namespace();
65 let is_expected = &|res| source.is_expected(res);
66 let is_enum_variant = &|res| {
67 if let Res::Def(DefKind::Variant, _) = res { true } else { false }
70 // Make the base error.
71 let expected = source.descr_expected();
72 let path_str = Segment::names_to_string(path);
73 let item_str = path.last().unwrap().ident;
74 let code = source.error_code(res.is_some());
75 let (base_msg, fallback_label, base_span) = if let Some(res) = res {
76 (format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
77 format!("not a {}", expected),
80 let item_span = path.last().unwrap().ident.span;
81 let (mod_prefix, mod_str) = if path.len() == 1 {
82 (String::new(), "this scope".to_string())
83 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
84 (String::new(), "the crate root".to_string())
86 let mod_path = &path[..path.len() - 1];
87 let mod_prefix = match self.resolve_path(
88 mod_path, Some(TypeNS), false, span, CrateLint::No
90 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
92 }.map_or(String::new(), |res| format!("{} ", res.descr()));
93 (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
95 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
96 format!("not found in {}", mod_str),
100 let code = DiagnosticId::Error(code.into());
101 let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
103 // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
104 if ["this", "my"].contains(&&*item_str.as_str())
105 && self.self_value_is_available(path[0].ident.span, span) {
110 Applicability::MaybeIncorrect,
114 // Emit special messages for unresolved `Self` and `self`.
115 if is_self_type(path, ns) {
116 syntax::diagnostic_used!(E0411);
117 err.code(DiagnosticId::Error("E0411".into()));
118 err.span_label(span, format!("`Self` is only available in impls, traits, \
119 and type definitions"));
120 return (err, Vec::new());
122 if is_self_value(path, ns) {
123 debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
125 syntax::diagnostic_used!(E0424);
126 err.code(DiagnosticId::Error("E0424".into()));
127 err.span_label(span, match source {
129 format!("`self` value is a keyword \
130 and may not be bound to \
131 variables or shadowed")
134 format!("`self` value is a keyword \
135 only available in methods \
136 with `self` parameter")
139 return (err, Vec::new());
142 // Try to lookup name in more relaxed fashion for better error reporting.
143 let ident = path.last().unwrap().ident;
144 let candidates = self.r.lookup_import_candidates(ident, ns, is_expected)
146 .filter(|ImportSuggestion { did, .. }| {
147 match (did, res.and_then(|res| res.opt_def_id())) {
148 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
152 .collect::<Vec<_>>();
153 let crate_def_id = DefId::local(CRATE_DEF_INDEX);
154 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
155 let enum_candidates =
156 self.r.lookup_import_candidates(ident, ns, is_enum_variant);
157 let mut enum_candidates = enum_candidates.iter()
159 import_candidate_to_enum_paths(&suggestion)
160 }).collect::<Vec<_>>();
161 enum_candidates.sort();
163 if !enum_candidates.is_empty() {
164 // Contextualize for E0412 "cannot find type", but don't belabor the point
165 // (that it's a variant) for E0573 "expected type, found variant".
166 let preamble = if res.is_none() {
167 let others = match enum_candidates.len() {
169 2 => " and 1 other".to_owned(),
170 n => format!(" and {} others", n)
172 format!("there is an enum variant `{}`{}; ",
173 enum_candidates[0].0, others)
177 let msg = format!("{}try using the variant's enum", preamble);
179 err.span_suggestions(
182 enum_candidates.into_iter()
183 .map(|(_variant_path, enum_ty_path)| enum_ty_path)
184 // Variants re-exported in prelude doesn't mean `prelude::v1` is the
186 // FIXME: is there a more principled way to do this that
187 // would work for other re-exports?
188 .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
189 // Also write `Option` rather than `std::prelude::v1::Option`.
190 .map(|enum_ty_path| {
191 // FIXME #56861: DRY-er prelude filtering.
192 enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
194 Applicability::MachineApplicable,
198 if path.len() == 1 && self.self_type_is_available(span) {
199 if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
200 let self_is_available = self.self_value_is_available(path[0].ident.span, span);
202 AssocSuggestion::Field => {
203 if self_is_available {
206 "you might have meant to use the available field",
207 format!("self.{}", path_str),
208 Applicability::MachineApplicable,
213 "a field by this name exists in `Self`",
217 AssocSuggestion::MethodWithSelf if self_is_available => {
221 format!("self.{}", path_str),
222 Applicability::MachineApplicable,
225 AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
229 format!("Self::{}", path_str),
230 Applicability::MachineApplicable,
234 return (err, candidates);
238 // Try Levenshtein algorithm.
239 let levenshtein_worked = add_typo_suggestion(
240 &mut err, self.lookup_typo_candidate(path, ns, is_expected, span), ident_span
243 // Try context-dependent help if relaxed lookup didn't work.
244 if let Some(res) = res {
245 if self.smart_resolve_context_dependent_help(&mut err,
251 return (err, candidates);
256 if !levenshtein_worked {
257 err.span_label(base_span, fallback_label);
258 self.type_ascription_suggestion(&mut err, base_span);
263 fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
264 // HACK(estebank): find a better way to figure out that this was a
265 // parser issue where a struct literal is being used on an expression
266 // where a brace being opened means a block is being started. Look
267 // ahead for the next text to see if `span` is followed by a `{`.
268 let sm = self.r.session.source_map();
271 sp = sm.next_point(sp);
272 match sm.span_to_snippet(sp) {
274 if snippet.chars().any(|c| { !c.is_whitespace() }) {
281 let followed_by_brace = match sm.span_to_snippet(sp) {
282 Ok(ref snippet) if snippet == "{" => true,
285 // In case this could be a struct literal that needs to be surrounded
286 // by parenthesis, find the appropriate span.
288 let mut closing_brace = None;
290 sp = sm.next_point(sp);
291 match sm.span_to_snippet(sp) {
294 let sp = span.to(sp);
295 if let Ok(snippet) = sm.span_to_snippet(sp) {
296 closing_brace = Some((sp, snippet));
304 // The bigger the span, the more likely we're incorrect --
305 // bound it to 100 chars long.
310 return (followed_by_brace, closing_brace)
313 /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
315 /// Returns `true` if able to provide context-dependent help.
316 fn smart_resolve_context_dependent_help(
318 err: &mut DiagnosticBuilder<'a>,
320 source: PathSource<'_>,
323 fallback_label: &str,
325 let ns = source.namespace();
326 let is_expected = &|res| source.is_expected(res);
328 let path_sep = |err: &mut DiagnosticBuilder<'_>, expr: &Expr| match expr.kind {
329 ExprKind::Field(_, ident) => {
332 "use the path separator to refer to an item",
333 format!("{}::{}", path_str, ident),
334 Applicability::MaybeIncorrect,
338 ExprKind::MethodCall(ref segment, ..) => {
339 let span = expr.span.with_hi(segment.ident.span.hi());
342 "use the path separator to refer to an item",
343 format!("{}::{}", path_str, segment.ident),
344 Applicability::MaybeIncorrect,
351 let mut bad_struct_syntax_suggestion = || {
352 let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
353 let mut suggested = false;
355 PathSource::Expr(Some(parent)) => {
356 suggested = path_sep(err, &parent);
358 PathSource::Expr(None) if followed_by_brace == true => {
359 if let Some((sp, snippet)) = closing_brace {
362 "surround the struct literal with parenthesis",
363 format!("({})", snippet),
364 Applicability::MaybeIncorrect,
368 span, // Note the parenthesis surrounding the suggestion below
369 format!("did you mean `({} {{ /* fields */ }})`?", path_str),
379 format!("did you mean `{} {{ /* fields */ }}`?", path_str),
384 match (res, source) {
385 (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
388 "use `!` to invoke the macro",
389 format!("{}!", path_str),
390 Applicability::MaybeIncorrect,
392 if path_str == "try" && span.rust_2015() {
393 err.note("if you want the `try` keyword, you need to be in the 2018 edition");
396 (Res::Def(DefKind::TyAlias, _), PathSource::Trait(_)) => {
397 err.span_label(span, "type aliases cannot be used as traits");
398 if nightly_options::is_nightly_build() {
399 err.note("did you mean to use a trait alias?");
402 (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
403 if !path_sep(err, &parent) {
407 (Res::Def(DefKind::Enum, def_id), PathSource::TupleStruct)
408 | (Res::Def(DefKind::Enum, def_id), PathSource::Expr(..)) => {
409 if let Some(variants) = self.collect_enum_variants(def_id) {
410 if !variants.is_empty() {
411 let msg = if variants.len() == 1 {
412 "try using the enum's variant"
414 "try using one of the enum's variants"
417 err.span_suggestions(
420 variants.iter().map(path_names_to_string),
421 Applicability::MaybeIncorrect,
425 err.note("did you mean to use one of the enum's variants?");
428 (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {
429 if let Some((ctor_def, ctor_vis))
430 = self.r.struct_constructors.get(&def_id).cloned() {
431 let accessible_ctor =
432 self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
433 if is_expected(ctor_def) && !accessible_ctor {
436 format!("constructor is not visible here due to private fields"),
440 bad_struct_syntax_suggestion();
443 (Res::Def(DefKind::Union, _), _) |
444 (Res::Def(DefKind::Variant, _), _) |
445 (Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _), _) if ns == ValueNS => {
446 bad_struct_syntax_suggestion();
448 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), _) if ns == ValueNS => {
451 format!("did you mean `{} ( /* fields */ )`?", path_str),
454 (Res::SelfTy(..), _) if ns == ValueNS => {
455 err.span_label(span, fallback_label);
456 err.note("can't use `Self` as a constructor, you must use the implemented struct");
458 (Res::Def(DefKind::TyAlias, _), _)
459 | (Res::Def(DefKind::AssocTy, _), _) if ns == ValueNS => {
460 err.note("can't use a type alias as a constructor");
467 fn lookup_assoc_candidate<FilterFn>(&mut self,
471 -> Option<AssocSuggestion>
472 where FilterFn: Fn(Res) -> bool
474 fn extract_node_id(t: &Ty) -> Option<NodeId> {
476 TyKind::Path(None, _) => Some(t.id),
477 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
478 // This doesn't handle the remaining `Ty` variants as they are not
479 // that commonly the self_type, it might be interesting to provide
480 // support for those in future.
485 // Fields are generally expected in the same contexts as locals.
486 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
487 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
488 // Look for a field with the same name in the current self_type.
489 if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
490 match resolution.base_res() {
491 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did)
492 if resolution.unresolved_segments() == 0 => {
493 if let Some(field_names) = self.r.field_names.get(&did) {
494 if field_names.iter().any(|&field_name| ident.name == field_name) {
495 return Some(AssocSuggestion::Field);
505 for assoc_type_ident in &self.current_trait_assoc_types {
506 if *assoc_type_ident == ident {
507 return Some(AssocSuggestion::AssocItem);
511 // Look for associated items in the current trait.
512 if let Some((module, _)) = self.current_trait_ref {
513 if let Ok(binding) = self.r.resolve_ident_in_module(
514 ModuleOrUniformRoot::Module(module),
521 let res = binding.res();
523 return Some(if self.r.has_self.contains(&res.def_id()) {
524 AssocSuggestion::MethodWithSelf
526 AssocSuggestion::AssocItem
535 fn lookup_typo_candidate(
539 filter_fn: &impl Fn(Res) -> bool,
541 ) -> Option<TypoSuggestion> {
542 let mut names = Vec::new();
544 // Search in lexical scope.
545 // Walk backwards up the ribs in scope and collect candidates.
546 for rib in self.ribs[ns].iter().rev() {
547 // Locals and type parameters
548 for (ident, &res) in &rib.bindings {
550 names.push(TypoSuggestion::from_res(ident.name, res));
554 if let RibKind::ModuleRibKind(module) = rib.kind {
555 // Items from this module
556 self.r.add_module_candidates(module, &mut names, &filter_fn);
558 if let ModuleKind::Block(..) = module.kind {
559 // We can see through blocks
561 // Items from the prelude
562 if !module.no_implicit_prelude {
563 let extern_prelude = self.r.extern_prelude.clone();
564 names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
566 .maybe_process_path_extern(ident.name, ident.span)
567 .and_then(|crate_id| {
568 let crate_mod = Res::Def(
572 index: CRATE_DEF_INDEX,
576 if filter_fn(crate_mod) {
577 Some(TypoSuggestion::from_res(ident.name, crate_mod))
584 if let Some(prelude) = self.r.prelude {
585 self.r.add_module_candidates(prelude, &mut names, &filter_fn);
592 // Add primitive types to the mix
593 if filter_fn(Res::PrimTy(PrimTy::Bool)) {
595 self.r.primitive_type_table.primitive_types.iter().map(|(name, prim_ty)| {
596 TypoSuggestion::from_res(*name, Res::PrimTy(*prim_ty))
602 let mod_path = &path[..path.len() - 1];
603 if let PathResult::Module(module) = self.resolve_path(
604 mod_path, Some(TypeNS), false, span, CrateLint::No
606 if let ModuleOrUniformRoot::Module(module) = module {
607 self.r.add_module_candidates(module, &mut names, &filter_fn);
612 let name = path[path.len() - 1].ident.name;
613 // Make sure error reporting is deterministic.
614 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
616 match find_best_match_for_name(
617 names.iter().map(|suggestion| &suggestion.candidate),
621 Some(found) if found != name => names
623 .find(|suggestion| suggestion.candidate == found),
628 /// Only used in a specific case of type ascription suggestions
629 fn get_colon_suggestion_span(&self, start: Span) -> Span {
630 let cm = self.r.session.source_map();
631 start.to(cm.next_point(start))
634 fn type_ascription_suggestion(
636 err: &mut DiagnosticBuilder<'_>,
639 debug!("type_ascription_suggetion {:?}", base_span);
640 let cm = self.r.session.source_map();
641 let base_snippet = cm.span_to_snippet(base_span);
642 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
643 if let Some(sp) = self.current_type_ascription.last() {
646 // Try to find the `:`; bail on first non-':' / non-whitespace.
647 sp = cm.next_point(sp);
648 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
649 let line_sp = cm.lookup_char_pos(sp.hi()).line;
650 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
652 let mut show_label = true;
653 if line_sp != line_base_sp {
654 err.span_suggestion_short(
656 "did you mean to use `;` here instead?",
658 Applicability::MaybeIncorrect,
661 let colon_sp = self.get_colon_suggestion_span(sp);
662 let after_colon_sp = self.get_colon_suggestion_span(
663 colon_sp.shrink_to_hi(),
665 if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
670 "maybe you meant to write a path separator here",
672 Applicability::MaybeIncorrect,
676 if let Ok(base_snippet) = base_snippet {
677 let mut sp = after_colon_sp;
679 // Try to find an assignment
680 sp = cm.next_point(sp);
681 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
683 Ok(ref x) if x.as_str() == "=" => {
686 "maybe you meant to write an assignment here",
687 format!("let {}", base_snippet),
688 Applicability::MaybeIncorrect,
693 Ok(ref x) if x.as_str() == "\n" => break,
701 err.span_label(base_span,
702 "expecting a type here because of type ascription");
705 } else if !snippet.trim().is_empty() {
706 debug!("tried to find type ascription `:` token, couldn't find it");
716 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
717 let mut result = None;
718 let mut seen_modules = FxHashSet::default();
719 let mut worklist = vec![(self.r.graph_root, Vec::new())];
721 while let Some((in_module, path_segments)) = worklist.pop() {
722 // abort if the module is already found
723 if result.is_some() { break; }
725 in_module.for_each_child_stable(self.r, |_, ident, _, name_binding| {
726 // abort if the module is already found or if name_binding is private external
727 if result.is_some() || !name_binding.vis.is_visible_locally() {
730 if let Some(module) = name_binding.module() {
732 let mut path_segments = path_segments.clone();
733 path_segments.push(ast::PathSegment::from_ident(ident));
734 let module_def_id = module.def_id().unwrap();
735 if module_def_id == def_id {
737 span: name_binding.span,
738 segments: path_segments,
740 result = Some((module, ImportSuggestion { did: Some(def_id), path }));
742 // add the module to the lookup
743 if seen_modules.insert(module_def_id) {
744 worklist.push((module, path_segments));
754 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
755 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
756 let mut variants = Vec::new();
757 enum_module.for_each_child_stable(self.r, |_, ident, _, name_binding| {
758 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
759 let mut segms = enum_import_suggestion.path.segments.clone();
760 segms.push(ast::PathSegment::from_ident(ident));
762 span: name_binding.span,