3 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
6 use rustc::hir::def::{self, DefKind, NonMacroAttrKind};
7 use rustc::hir::def::Namespace::{self, *};
8 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
9 use rustc::session::Session;
10 use rustc::ty::{self, DefIdTree};
11 use rustc::util::nodemap::FxHashSet;
12 use syntax::ast::{self, Ident, Path};
13 use syntax_expand::base::MacroKind;
14 use syntax::feature_gate::BUILTIN_ATTRIBUTES;
15 use syntax::source_map::SourceMap;
16 use syntax::struct_span_err;
17 use syntax::symbol::{Symbol, kw};
18 use syntax::util::lev_distance::find_best_match_for_name;
19 use syntax_pos::{BytePos, Span, MultiSpan};
21 use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver};
22 use crate::{path_names_to_string, KNOWN_TOOLS};
23 use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot};
24 use crate::{PathResult, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Segment};
26 type Res = def::Res<ast::NodeId>;
28 /// A vector of spans and replacements, a message and applicability.
29 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
31 crate struct TypoSuggestion {
32 pub candidate: Symbol,
37 crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
38 TypoSuggestion { candidate, res }
42 /// A free importable items suggested in case of resolution failure.
43 crate struct ImportSuggestion {
44 pub did: Option<DefId>,
48 /// Adjust the impl span so that just the `impl` keyword is taken by removing
49 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
50 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
52 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
53 /// parser. If you need to use this function or something similar, please consider updating the
54 /// `source_map` functions and this function to something more robust.
55 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
56 let impl_span = cm.span_until_char(impl_span, '<');
57 let impl_span = cm.span_until_whitespace(impl_span);
61 crate fn add_typo_suggestion(
62 err: &mut DiagnosticBuilder<'_>, suggestion: Option<TypoSuggestion>, span: Span
64 if let Some(suggestion) = suggestion {
66 "{} {} with a similar name exists", suggestion.res.article(), suggestion.res.descr()
69 span, &msg, suggestion.candidate.to_string(), Applicability::MaybeIncorrect
76 impl<'a> Resolver<'a> {
77 crate fn add_module_candidates(
80 names: &mut Vec<TypoSuggestion>,
81 filter_fn: &impl Fn(Res) -> bool,
83 for (key, resolution) in self.resolutions(module).borrow().iter() {
84 if let Some(binding) = resolution.borrow().binding {
85 let res = binding.res();
87 names.push(TypoSuggestion::from_res(key.ident.name, res));
93 /// Combines an error with provided span and emits it.
95 /// This takes the error provided, combines it with the span and any additional spans inside the
96 /// error and emits it.
97 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
98 self.into_struct_error(span, resolution_error).emit();
101 crate fn into_struct_error(
102 &self, span: Span, resolution_error: ResolutionError<'_>
103 ) -> DiagnosticBuilder<'_> {
104 match resolution_error {
105 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
106 let mut err = struct_span_err!(self.session,
109 "can't use generic parameters from outer function",
111 err.span_label(span, format!("use of generic parameter from outer function"));
113 let cm = self.session.source_map();
115 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
116 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
117 self.definitions.opt_span(def_id)
120 reduce_impl_span_to_impl_keyword(cm, impl_span),
121 "`Self` type implicitly declared here, by this `impl`",
124 match (maybe_trait_defid, maybe_impl_defid) {
126 err.span_label(span, "can't use `Self` here");
129 err.span_label(span, "use a type here instead");
131 (None, None) => bug!("`impl` without trait nor type?"),
135 Res::Def(DefKind::TyParam, def_id) => {
136 if let Some(span) = self.definitions.opt_span(def_id) {
137 err.span_label(span, "type parameter from outer function");
140 Res::Def(DefKind::ConstParam, def_id) => {
141 if let Some(span) = self.definitions.opt_span(def_id) {
142 err.span_label(span, "const parameter from outer function");
146 bug!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
151 if has_generic_params == HasGenericParams::Yes {
152 // Try to retrieve the span of the function signature and generate a new
153 // message with a local type or const parameter.
154 let sugg_msg = &format!("try using a local generic parameter instead");
155 if let Some((sugg_span, snippet)) = cm.generate_local_type_param_snippet(span) {
156 // Suggest the modification to the user
161 Applicability::MachineApplicable,
163 } else if let Some(sp) = cm.generate_fn_name_span(span) {
165 format!("try adding a local generic parameter in this method instead"));
167 err.help(&format!("try using a local generic parameter instead"));
173 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
174 let mut err = struct_span_err!(
178 "the name `{}` is already used for a generic \
179 parameter in this item's generic parameters",
182 err.span_label(span, "already used");
183 err.span_label(first_use_span, format!("first use of `{}`", name));
186 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
187 let mut err = struct_span_err!(self.session,
190 "method `{}` is not a member of trait `{}`",
193 err.span_label(span, format!("not a member of trait `{}`", trait_));
196 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
197 let mut err = struct_span_err!(self.session,
200 "type `{}` is not a member of trait `{}`",
203 err.span_label(span, format!("not a member of trait `{}`", trait_));
206 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
207 let mut err = struct_span_err!(self.session,
210 "const `{}` is not a member of trait `{}`",
213 err.span_label(span, format!("not a member of trait `{}`", trait_));
216 ResolutionError::VariableNotBoundInPattern(binding_error) => {
217 let BindingError { name, target, origin, could_be_path } = binding_error;
219 let target_sp = target.iter().copied().collect::<Vec<_>>();
220 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
222 let msp = MultiSpan::from_spans(target_sp.clone());
223 let msg = format!("variable `{}` is not bound in all patterns", name);
224 let mut err = self.session.struct_span_err_with_code(
227 DiagnosticId::Error("E0408".into()),
229 for sp in target_sp {
230 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
232 for sp in origin_sp {
233 err.span_label(sp, "variable not in all patterns");
236 let help_msg = format!(
237 "if you meant to match on a variant or a `const` item, consider \
238 making the path in the pattern qualified: `?::{}`",
241 err.span_help(span, &help_msg);
245 ResolutionError::VariableBoundWithDifferentMode(variable_name,
246 first_binding_span) => {
247 let mut err = struct_span_err!(self.session,
250 "variable `{}` is bound in inconsistent \
251 ways within the same match arm",
253 err.span_label(span, "bound in different ways");
254 err.span_label(first_binding_span, "first binding");
257 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
258 let mut err = struct_span_err!(self.session,
261 "identifier `{}` is bound more than once in this parameter list",
263 err.span_label(span, "used as parameter more than once");
266 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
267 let mut err = struct_span_err!(self.session,
270 "identifier `{}` is bound more than once in the same pattern",
272 err.span_label(span, "used in a pattern more than once");
275 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
276 let mut err = struct_span_err!(self.session,
279 "use of undeclared label `{}`",
281 if let Some(lev_candidate) = lev_candidate {
284 "a label with a similar name exists in this scope",
285 lev_candidate.to_string(),
286 Applicability::MaybeIncorrect,
289 err.span_label(span, format!("undeclared label `{}`", name));
293 ResolutionError::SelfImportsOnlyAllowedWithin => {
294 struct_span_err!(self.session,
298 "`self` imports are only allowed within a { } list")
300 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
301 let mut err = struct_span_err!(self.session, span, E0430,
302 "`self` import can only appear once in an import list");
303 err.span_label(span, "can only appear once in an import list");
306 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
307 let mut err = struct_span_err!(self.session, span, E0431,
308 "`self` import can only appear in an import list with \
309 a non-empty prefix");
310 err.span_label(span, "can only appear in an import list with a non-empty prefix");
313 ResolutionError::FailedToResolve { label, suggestion } => {
314 let mut err = struct_span_err!(self.session, span, E0433,
315 "failed to resolve: {}", &label);
316 err.span_label(span, label);
318 if let Some((suggestions, msg, applicability)) = suggestion {
319 err.multipart_suggestion(&msg, suggestions, applicability);
324 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
325 let mut err = struct_span_err!(self.session,
329 "can't capture dynamic environment in a fn item");
330 err.help("use the `|| { ... }` closure form instead");
333 ResolutionError::AttemptToUseNonConstantValueInConstant => {
334 let mut err = struct_span_err!(self.session, span, E0435,
335 "attempt to use a non-constant value in a constant");
336 err.span_label(span, "non-constant value");
339 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
340 let res = binding.res();
341 let shadows_what = res.descr();
342 let mut err = struct_span_err!(self.session, span, E0530, "{}s cannot shadow {}s",
343 what_binding, shadows_what);
344 err.span_label(span, format!("cannot be named the same as {} {}",
345 res.article(), shadows_what));
346 let participle = if binding.is_import() { "imported" } else { "defined" };
347 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
348 err.span_label(binding.span, msg);
351 ResolutionError::ForwardDeclaredTyParam => {
352 let mut err = struct_span_err!(self.session, span, E0128,
353 "type parameters with a default cannot use \
354 forward declared identifiers");
356 span, "defaulted type parameters cannot be forward declared".to_string());
359 ResolutionError::SelfInTyParamDefault => {
360 let mut err = struct_span_err!(
364 "type parameters cannot use `Self` in their defaults"
367 span, "`Self` in type parameter default".to_string());
370 ResolutionError::ConstParamDependentOnTypeParam => {
371 let mut err = struct_span_err!(
375 "const parameters cannot depend on type parameters"
377 err.span_label(span, format!("const parameter depends on type parameter"));
383 /// Lookup typo candidate in scope for a macro or import.
384 fn early_lookup_typo_candidate(
387 parent_scope: &ParentScope<'a>,
389 filter_fn: &impl Fn(Res) -> bool,
390 ) -> Option<TypoSuggestion> {
391 let mut suggestions = Vec::new();
392 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
394 Scope::DeriveHelpers => {
395 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
397 for derive in parent_scope.derives {
399 &ParentScope { derives: &[], ..*parent_scope };
400 if let Ok((Some(ext), _)) = this.resolve_macro_path(
401 derive, Some(MacroKind::Derive), parent_scope, false, false
403 suggestions.extend(ext.helper_attrs.iter().map(|name| {
404 TypoSuggestion::from_res(*name, res)
410 Scope::MacroRules(legacy_scope) => {
411 if let LegacyScope::Binding(legacy_binding) = legacy_scope {
412 let res = legacy_binding.binding.res();
415 TypoSuggestion::from_res(legacy_binding.ident.name, res)
420 Scope::CrateRoot => {
421 let root_ident = Ident::new(kw::PathRoot, ident.span);
422 let root_module = this.resolve_crate_root(root_ident);
423 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
425 Scope::Module(module) => {
426 this.add_module_candidates(module, &mut suggestions, filter_fn);
428 Scope::MacroUsePrelude => {
429 suggestions.extend(this.macro_use_prelude.iter().filter_map(|(name, binding)| {
430 let res = binding.res();
432 Some(TypoSuggestion::from_res(*name, res))
438 Scope::BuiltinAttrs => {
439 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
441 suggestions.extend(BUILTIN_ATTRIBUTES.iter().map(|(name, ..)| {
442 TypoSuggestion::from_res(*name, res)
446 Scope::LegacyPluginHelpers => {
447 let res = Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
449 let plugin_attributes = this.session.plugin_attributes.borrow();
450 suggestions.extend(plugin_attributes.iter().map(|(name, _)| {
451 TypoSuggestion::from_res(*name, res)
455 Scope::ExternPrelude => {
456 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
457 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
459 Some(TypoSuggestion::from_res(ident.name, res))
465 Scope::ToolPrelude => {
466 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
467 suggestions.extend(KNOWN_TOOLS.iter().map(|name| {
468 TypoSuggestion::from_res(*name, res)
471 Scope::StdLibPrelude => {
472 if let Some(prelude) = this.prelude {
473 let mut tmp_suggestions = Vec::new();
474 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
475 suggestions.extend(tmp_suggestions.into_iter().filter(|s| {
476 use_prelude || this.is_builtin_macro(s.res)
480 Scope::BuiltinTypes => {
481 let primitive_types = &this.primitive_type_table.primitive_types;
483 primitive_types.iter().flat_map(|(name, prim_ty)| {
484 let res = Res::PrimTy(*prim_ty);
486 Some(TypoSuggestion::from_res(*name, res))
498 // Make sure error reporting is deterministic.
499 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
501 match find_best_match_for_name(
502 suggestions.iter().map(|suggestion| &suggestion.candidate),
506 Some(found) if found != ident.name => suggestions
508 .find(|suggestion| suggestion.candidate == found),
513 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
515 namespace: Namespace,
516 start_module: Module<'a>,
519 -> Vec<ImportSuggestion>
520 where FilterFn: Fn(Res) -> bool
522 let mut candidates = Vec::new();
523 let mut seen_modules = FxHashSet::default();
524 let not_local_module = crate_name.name != kw::Crate;
525 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
527 while let Some((in_module,
529 in_module_is_extern)) = worklist.pop() {
530 // We have to visit module children in deterministic order to avoid
531 // instabilities in reported imports (#43552).
532 in_module.for_each_child(self, |this, ident, ns, name_binding| {
533 // avoid imports entirely
534 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
535 // avoid non-importable candidates as well
536 if !name_binding.is_importable() { return; }
538 // collect results based on the filter function
539 if ident.name == lookup_ident.name && ns == namespace {
540 let res = name_binding.res();
543 let mut segms = path_segments.clone();
544 if lookup_ident.span.rust_2018() {
545 // crate-local absolute paths start with `crate::` in edition 2018
546 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
548 0, ast::PathSegment::from_ident(crate_name)
552 segms.push(ast::PathSegment::from_ident(ident));
554 span: name_binding.span,
557 // the entity is accessible in the following cases:
558 // 1. if it's defined in the same crate, it's always
559 // accessible (since private entities can be made public)
560 // 2. if it's defined in another crate, it's accessible
561 // only if both the module is public and the entity is
562 // declared as public (due to pruning, we don't explore
563 // outside crate private modules => no need to check this)
564 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
565 let did = match res {
566 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
567 _ => res.opt_def_id(),
569 candidates.push(ImportSuggestion { did, path });
574 // collect submodules to explore
575 if let Some(module) = name_binding.module() {
577 let mut path_segments = path_segments.clone();
578 path_segments.push(ast::PathSegment::from_ident(ident));
580 let is_extern_crate_that_also_appears_in_prelude =
581 name_binding.is_extern_crate() &&
582 lookup_ident.span.rust_2018();
584 let is_visible_to_user =
585 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
587 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
588 // add the module to the lookup
589 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
590 if seen_modules.insert(module.def_id().unwrap()) {
591 worklist.push((module, path_segments, is_extern));
601 /// When name resolution fails, this method can be used to look up candidate
602 /// entities with the expected name. It allows filtering them using the
603 /// supplied predicate (which should be used to only accept the types of
604 /// definitions expected, e.g., traits). The lookup spans across all crates.
606 /// N.B., the method does not look into imports, but this is not a problem,
607 /// since we report the definitions (thus, the de-aliased imports).
608 crate fn lookup_import_candidates<FilterFn>(
609 &mut self, lookup_ident: Ident, namespace: Namespace, filter_fn: FilterFn
610 ) -> Vec<ImportSuggestion>
611 where FilterFn: Fn(Res) -> bool
613 let mut suggestions = self.lookup_import_candidates_from_module(
614 lookup_ident, namespace, self.graph_root, Ident::with_dummy_span(kw::Crate), &filter_fn
617 if lookup_ident.span.rust_2018() {
618 let extern_prelude_names = self.extern_prelude.clone();
619 for (ident, _) in extern_prelude_names.into_iter() {
620 if ident.span.from_expansion() {
621 // Idents are adjusted to the root context before being
622 // resolved in the extern prelude, so reporting this to the
623 // user is no help. This skips the injected
624 // `extern crate std` in the 2018 edition, which would
625 // otherwise cause duplicate suggestions.
628 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
630 let crate_root = self.get_module(DefId {
632 index: CRATE_DEF_INDEX,
634 suggestions.extend(self.lookup_import_candidates_from_module(
635 lookup_ident, namespace, crate_root, ident, &filter_fn));
643 crate fn unresolved_macro_suggestions(
645 err: &mut DiagnosticBuilder<'a>,
646 macro_kind: MacroKind,
647 parent_scope: &ParentScope<'a>,
650 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
651 let suggestion = self.early_lookup_typo_candidate(
652 ScopeSet::Macro(macro_kind), parent_scope, ident, is_expected
654 add_typo_suggestion(err, suggestion, ident.span);
656 if macro_kind == MacroKind::Derive &&
657 (ident.as_str() == "Send" || ident.as_str() == "Sync") {
658 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
659 err.span_note(ident.span, &msg);
661 if self.macro_names.contains(&ident.modern()) {
662 err.help("have you added the `#[macro_use]` on the module/import?");
667 impl<'a, 'b> ImportResolver<'a, 'b> {
668 /// Adds suggestions for a path that cannot be resolved.
669 pub(crate) fn make_path_suggestion(
672 mut path: Vec<Segment>,
673 parent_scope: &ParentScope<'b>,
674 ) -> Option<(Vec<Segment>, Vec<String>)> {
675 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
677 match (path.get(0), path.get(1)) {
678 // `{{root}}::ident::...` on both editions.
679 // On 2015 `{{root}}` is usually added implicitly.
680 (Some(fst), Some(snd)) if fst.ident.name == kw::PathRoot &&
681 !snd.ident.is_path_segment_keyword() => {}
682 // `ident::...` on 2018.
683 (Some(fst), _) if fst.ident.span.rust_2018() &&
684 !fst.ident.is_path_segment_keyword() => {
685 // Insert a placeholder that's later replaced by `self`/`super`/etc.
686 path.insert(0, Segment::from_ident(Ident::invalid()));
691 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
692 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
693 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
694 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
697 /// Suggest a missing `self::` if that resolves to an correct module.
701 /// LL | use foo::Bar;
702 /// | ^^^ did you mean `self::foo`?
704 fn make_missing_self_suggestion(
707 mut path: Vec<Segment>,
708 parent_scope: &ParentScope<'b>,
709 ) -> Option<(Vec<Segment>, Vec<String>)> {
710 // Replace first ident with `self` and check if that is valid.
711 path[0].ident.name = kw::SelfLower;
712 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
713 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
714 if let PathResult::Module(..) = result {
715 Some((path, Vec::new()))
721 /// Suggests a missing `crate::` if that resolves to an correct module.
725 /// LL | use foo::Bar;
726 /// | ^^^ did you mean `crate::foo`?
728 fn make_missing_crate_suggestion(
731 mut path: Vec<Segment>,
732 parent_scope: &ParentScope<'b>,
733 ) -> Option<(Vec<Segment>, Vec<String>)> {
734 // Replace first ident with `crate` and check if that is valid.
735 path[0].ident.name = kw::Crate;
736 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
737 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
738 if let PathResult::Module(..) = result {
742 "`use` statements changed in Rust 2018; read more at \
743 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
744 clarity.html>".to_string()
752 /// Suggests a missing `super::` if that resolves to an correct module.
756 /// LL | use foo::Bar;
757 /// | ^^^ did you mean `super::foo`?
759 fn make_missing_super_suggestion(
762 mut path: Vec<Segment>,
763 parent_scope: &ParentScope<'b>,
764 ) -> Option<(Vec<Segment>, Vec<String>)> {
765 // Replace first ident with `crate` and check if that is valid.
766 path[0].ident.name = kw::Super;
767 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
768 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
769 if let PathResult::Module(..) = result {
770 Some((path, Vec::new()))
776 /// Suggests a missing external crate name if that resolves to an correct module.
780 /// LL | use foobar::Baz;
781 /// | ^^^^^^ did you mean `baz::foobar`?
784 /// Used when importing a submodule of an external crate but missing that crate's
785 /// name as the first part of path.
786 fn make_external_crate_suggestion(
789 mut path: Vec<Segment>,
790 parent_scope: &ParentScope<'b>,
791 ) -> Option<(Vec<Segment>, Vec<String>)> {
792 if path[1].ident.span.rust_2015() {
796 // Sort extern crate names in reverse order to get
797 // 1) some consistent ordering for emitted dignostics, and
798 // 2) `std` suggestions before `core` suggestions.
799 let mut extern_crate_names =
800 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
801 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
803 for name in extern_crate_names.into_iter() {
804 // Replace first ident with a crate name and check if that is valid.
805 path[0].ident.name = name;
806 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
807 debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
809 if let PathResult::Module(..) = result {
810 return Some((path, Vec::new()));
817 /// Suggests importing a macro from the root of the crate rather than a module within
821 /// help: a macro with this name exists at the root of the crate
823 /// LL | use issue_59764::makro;
824 /// | ^^^^^^^^^^^^^^^^^^
826 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
827 /// at the root of the crate instead of the module where it is defined
829 pub(crate) fn check_for_module_export_macro(
831 directive: &'b ImportDirective<'b>,
832 module: ModuleOrUniformRoot<'b>,
834 ) -> Option<(Option<Suggestion>, Vec<String>)> {
835 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
841 while let Some(parent) = crate_module.parent {
842 crate_module = parent;
845 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
846 // Don't make a suggestion if the import was already from the root of the
851 let resolutions = self.r.resolutions(crate_module).borrow();
852 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
853 let binding = resolution.borrow().binding()?;
854 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
855 let module_name = crate_module.kind.name().unwrap();
856 let import = match directive.subclass {
857 ImportDirectiveSubclass::SingleImport { source, target, .. } if source != target =>
858 format!("{} as {}", source, target),
859 _ => format!("{}", ident),
862 let mut corrections: Vec<(Span, String)> = Vec::new();
863 if !directive.is_nested() {
864 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
865 // intermediate segments.
866 corrections.push((directive.span, format!("{}::{}", module_name, import)));
868 // Find the binding span (and any trailing commas and spaces).
869 // ie. `use a::b::{c, d, e};`
871 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
872 self.r.session, directive.span, directive.use_span,
874 debug!("check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
875 found_closing_brace, binding_span);
877 let mut removal_span = binding_span;
878 if found_closing_brace {
879 // If the binding span ended with a closing brace, as in the below example:
880 // ie. `use a::b::{c, d};`
882 // Then expand the span of characters to remove to include the previous
883 // binding's trailing comma.
884 // ie. `use a::b::{c, d};`
886 if let Some(previous_span) = extend_span_to_previous_binding(
887 self.r.session, binding_span,
889 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
890 removal_span = removal_span.with_lo(previous_span.lo());
893 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
895 // Remove the `removal_span`.
896 corrections.push((removal_span, "".to_string()));
898 // Find the span after the crate name and if it has nested imports immediatately
899 // after the crate name already.
900 // ie. `use a::b::{c, d};`
902 // or `use a::{b, c, d}};`
904 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
905 self.r.session, module_name, directive.use_span,
907 debug!("check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
908 has_nested, after_crate_name);
910 let source_map = self.r.session.source_map();
912 // Add the import to the start, with a `{` if required.
913 let start_point = source_map.start_point(after_crate_name);
914 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
918 // In this case, `start_snippet` must equal '{'.
919 format!("{}{}, ", start_snippet, import)
921 // In this case, add a `{`, then the moved import, then whatever
923 format!("{{{}, {}", import, start_snippet)
928 // Add a `};` to the end if nested, matching the `{` added at the start.
930 corrections.push((source_map.end_point(after_crate_name),
935 let suggestion = Some((
937 String::from("a macro with this name exists at the root of the crate"),
938 Applicability::MaybeIncorrect,
941 "this could be because a macro annotated with `#[macro_export]` will be exported \
942 at the root of the crate instead of the module where it is defined".to_string(),
944 Some((suggestion, note))
951 /// Given a `binding_span` of a binding within a use statement:
954 /// use foo::{a, b, c};
958 /// then return the span until the next binding or the end of the statement:
961 /// use foo::{a, b, c};
964 pub(crate) fn find_span_of_binding_until_next_binding(
969 let source_map = sess.source_map();
971 // Find the span of everything after the binding.
972 // ie. `a, e};` or `a};`
973 let binding_until_end = binding_span.with_hi(use_span.hi());
975 // Find everything after the binding but not including the binding.
976 // ie. `, e};` or `};`
977 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
979 // Keep characters in the span until we encounter something that isn't a comma or
983 // Also note whether a closing brace character was encountered. If there
984 // was, then later go backwards to remove any trailing commas that are left.
985 let mut found_closing_brace = false;
986 let after_binding_until_next_binding = source_map.span_take_while(
987 after_binding_until_end,
989 if ch == '}' { found_closing_brace = true; }
990 ch == ' ' || ch == ','
994 // Combine the two spans.
997 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
998 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1000 (found_closing_brace, span)
1003 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1007 /// use foo::a::{a, b, c};
1008 /// ^^--- binding span
1012 /// use foo::{a, b, c};
1013 /// --- binding span
1015 pub(crate) fn extend_span_to_previous_binding(
1019 let source_map = sess.source_map();
1021 // `prev_source` will contain all of the source that came before the span.
1022 // Then split based on a command and take the first (ie. closest to our span)
1023 // snippet. In the example, this is a space.
1024 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1026 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1027 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1028 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1032 let prev_comma = prev_comma.first().unwrap();
1033 let prev_starting_brace = prev_starting_brace.first().unwrap();
1035 // If the amount of source code before the comma is greater than
1036 // the amount of source code before the starting brace then we've only
1037 // got one item in the nested item (eg. `issue_52891::{self}`).
1038 if prev_comma.len() > prev_starting_brace.len() {
1042 Some(binding_span.with_lo(BytePos(
1043 // Take away the number of bytes for the characters we've found and an
1044 // extra for the comma.
1045 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
1049 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1050 /// it is a nested use tree.
1053 /// use foo::a::{b, c};
1054 /// ^^^^^^^^^^ // false
1056 /// use foo::{a, b, c};
1057 /// ^^^^^^^^^^ // true
1059 /// use foo::{a, b::{c, d}};
1060 /// ^^^^^^^^^^^^^^^ // true
1062 fn find_span_immediately_after_crate_name(
1064 module_name: Symbol,
1067 debug!("find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1068 module_name, use_span);
1069 let source_map = sess.source_map();
1071 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1072 let mut num_colons = 0;
1073 // Find second colon.. `use issue_59764:`
1074 let until_second_colon = source_map.span_take_while(use_span, |c| {
1075 if *c == ':' { num_colons += 1; }
1077 ':' if num_colons == 2 => false,
1081 // Find everything after the second colon.. `foo::{baz, makro};`
1082 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1084 let mut found_a_non_whitespace_character = false;
1085 // Find the first non-whitespace character in `from_second_colon`.. `f`
1086 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1087 if found_a_non_whitespace_character { return false; }
1088 if !c.is_whitespace() { found_a_non_whitespace_character = true; }
1092 // Find the first `{` in from_second_colon.. `foo::{`
1093 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1095 (next_left_bracket == after_second_colon, from_second_colon)
1098 /// When an entity with a given name is not available in scope, we search for
1099 /// entities with that name in all crates. This method allows outputting the
1100 /// results of this search in a programmer-friendly way
1101 crate fn show_candidates(
1102 err: &mut DiagnosticBuilder<'_>,
1103 // This is `None` if all placement locations are inside expansions
1105 candidates: &[ImportSuggestion],
1109 // we want consistent results across executions, but candidates are produced
1110 // by iterating through a hash map, so make sure they are ordered:
1111 let mut path_strings: Vec<_> =
1112 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
1113 path_strings.sort();
1115 let better = if better { "better " } else { "" };
1116 let msg_diff = match path_strings.len() {
1117 1 => " is found in another module, you can import it",
1118 _ => "s are found in other modules, you can import them",
1120 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1122 if let Some(span) = span {
1123 for candidate in &mut path_strings {
1124 // produce an additional newline to separate the new use statement
1125 // from the directly following item.
1126 let additional_newline = if found_use {
1131 *candidate = format!("use {};\n{}", candidate, additional_newline);
1134 err.span_suggestions(
1137 path_strings.into_iter(),
1138 Applicability::Unspecified,
1143 for candidate in path_strings {
1145 msg.push_str(&candidate);