3 use errors::{Applicability, DiagnosticBuilder};
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::feature_gate::BUILTIN_ATTRIBUTES;
14 use syntax::source_map::SourceMap;
15 use syntax::struct_span_err;
16 use syntax::symbol::{Symbol, kw};
17 use syntax::util::lev_distance::find_best_match_for_name;
18 use syntax_pos::hygiene::MacroKind;
19 use syntax_pos::{BytePos, Span, MultiSpan};
21 use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver};
22 use crate::path_names_to_string;
23 use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot};
24 use crate::{PathResult, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Segment};
26 use rustc_error_codes::*;
28 type Res = def::Res<ast::NodeId>;
30 /// A vector of spans and replacements, a message and applicability.
31 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
33 crate struct TypoSuggestion {
34 pub candidate: Symbol,
39 crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
40 TypoSuggestion { candidate, res }
44 /// A free importable items suggested in case of resolution failure.
45 crate struct ImportSuggestion {
46 pub did: Option<DefId>,
50 /// Adjust the impl span so that just the `impl` keyword is taken by removing
51 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
52 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
54 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
55 /// parser. If you need to use this function or something similar, please consider updating the
56 /// `source_map` functions and this function to something more robust.
57 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
58 let impl_span = cm.span_until_char(impl_span, '<');
59 let impl_span = cm.span_until_whitespace(impl_span);
63 impl<'a> Resolver<'a> {
64 crate fn add_module_candidates(
67 names: &mut Vec<TypoSuggestion>,
68 filter_fn: &impl Fn(Res) -> bool,
70 for (key, resolution) in self.resolutions(module).borrow().iter() {
71 if let Some(binding) = resolution.borrow().binding {
72 let res = binding.res();
74 names.push(TypoSuggestion::from_res(key.ident.name, res));
80 /// Combines an error with provided span and emits it.
82 /// This takes the error provided, combines it with the span and any additional spans inside the
83 /// error and emits it.
84 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
85 self.into_struct_error(span, resolution_error).emit();
88 crate fn into_struct_error(
89 &self, span: Span, resolution_error: ResolutionError<'_>
90 ) -> DiagnosticBuilder<'_> {
91 match resolution_error {
92 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
93 let mut err = struct_span_err!(self.session,
96 "can't use generic parameters from outer function",
98 err.span_label(span, format!("use of generic parameter from outer function"));
100 let cm = self.session.source_map();
102 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
103 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
104 self.definitions.opt_span(def_id)
107 reduce_impl_span_to_impl_keyword(cm, impl_span),
108 "`Self` type implicitly declared here, by this `impl`",
111 match (maybe_trait_defid, maybe_impl_defid) {
113 err.span_label(span, "can't use `Self` here");
116 err.span_label(span, "use a type here instead");
118 (None, None) => bug!("`impl` without trait nor type?"),
122 Res::Def(DefKind::TyParam, def_id) => {
123 if let Some(span) = self.definitions.opt_span(def_id) {
124 err.span_label(span, "type parameter from outer function");
127 Res::Def(DefKind::ConstParam, def_id) => {
128 if let Some(span) = self.definitions.opt_span(def_id) {
129 err.span_label(span, "const parameter from outer function");
133 bug!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
138 if has_generic_params == HasGenericParams::Yes {
139 // Try to retrieve the span of the function signature and generate a new
140 // message with a local type or const parameter.
141 let sugg_msg = &format!("try using a local generic parameter instead");
142 if let Some((sugg_span, snippet)) = cm.generate_local_type_param_snippet(span) {
143 // Suggest the modification to the user
148 Applicability::MachineApplicable,
150 } else if let Some(sp) = cm.generate_fn_name_span(span) {
152 format!("try adding a local generic parameter in this method instead"));
154 err.help(&format!("try using a local generic parameter instead"));
160 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
161 let mut err = struct_span_err!(
165 "the name `{}` is already used for a generic \
166 parameter in this item's generic parameters",
169 err.span_label(span, "already used");
170 err.span_label(first_use_span, format!("first use of `{}`", name));
173 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
174 let mut err = struct_span_err!(self.session,
177 "method `{}` is not a member of trait `{}`",
180 err.span_label(span, format!("not a member of trait `{}`", trait_));
183 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
184 let mut err = struct_span_err!(self.session,
187 "type `{}` is not a member of trait `{}`",
190 err.span_label(span, format!("not a member of trait `{}`", trait_));
193 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
194 let mut err = struct_span_err!(self.session,
197 "const `{}` is not a member of trait `{}`",
200 err.span_label(span, format!("not a member of trait `{}`", trait_));
203 ResolutionError::VariableNotBoundInPattern(binding_error) => {
204 let BindingError { name, target, origin, could_be_path } = binding_error;
206 let target_sp = target.iter().copied().collect::<Vec<_>>();
207 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
209 let msp = MultiSpan::from_spans(target_sp.clone());
210 let mut err = struct_span_err!(
214 "variable `{}` is not bound in all patterns", name,
216 for sp in target_sp {
217 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
219 for sp in origin_sp {
220 err.span_label(sp, "variable not in all patterns");
223 let help_msg = format!(
224 "if you meant to match on a variant or a `const` item, consider \
225 making the path in the pattern qualified: `?::{}`",
228 err.span_help(span, &help_msg);
232 ResolutionError::VariableBoundWithDifferentMode(variable_name,
233 first_binding_span) => {
234 let mut err = struct_span_err!(self.session,
237 "variable `{}` is bound in inconsistent \
238 ways within the same match arm",
240 err.span_label(span, "bound in different ways");
241 err.span_label(first_binding_span, "first binding");
244 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
245 let mut err = struct_span_err!(self.session,
248 "identifier `{}` is bound more than once in this parameter list",
250 err.span_label(span, "used as parameter more than once");
253 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
254 let mut err = struct_span_err!(self.session,
257 "identifier `{}` is bound more than once in the same pattern",
259 err.span_label(span, "used in a pattern more than once");
262 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
263 let mut err = struct_span_err!(self.session,
266 "use of undeclared label `{}`",
268 if let Some(lev_candidate) = lev_candidate {
271 "a label with a similar name exists in this scope",
272 lev_candidate.to_string(),
273 Applicability::MaybeIncorrect,
276 err.span_label(span, format!("undeclared label `{}`", name));
280 ResolutionError::SelfImportsOnlyAllowedWithin => {
281 struct_span_err!(self.session,
285 "`self` imports are only allowed within a { } list")
287 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
288 let mut err = struct_span_err!(self.session, span, E0430,
289 "`self` import can only appear once in an import list");
290 err.span_label(span, "can only appear once in an import list");
293 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
294 let mut err = struct_span_err!(self.session, span, E0431,
295 "`self` import can only appear in an import list with \
296 a non-empty prefix");
297 err.span_label(span, "can only appear in an import list with a non-empty prefix");
300 ResolutionError::FailedToResolve { label, suggestion } => {
301 let mut err = struct_span_err!(self.session, span, E0433,
302 "failed to resolve: {}", &label);
303 err.span_label(span, label);
305 if let Some((suggestions, msg, applicability)) = suggestion {
306 err.multipart_suggestion(&msg, suggestions, applicability);
311 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
312 let mut err = struct_span_err!(self.session,
316 "can't capture dynamic environment in a fn item");
317 err.help("use the `|| { ... }` closure form instead");
320 ResolutionError::AttemptToUseNonConstantValueInConstant => {
321 let mut err = struct_span_err!(self.session, span, E0435,
322 "attempt to use a non-constant value in a constant");
323 err.span_label(span, "non-constant value");
326 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
327 let res = binding.res();
328 let shadows_what = res.descr();
329 let mut err = struct_span_err!(self.session, span, E0530, "{}s cannot shadow {}s",
330 what_binding, shadows_what);
331 err.span_label(span, format!("cannot be named the same as {} {}",
332 res.article(), shadows_what));
333 let participle = if binding.is_import() { "imported" } else { "defined" };
334 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
335 err.span_label(binding.span, msg);
338 ResolutionError::ForwardDeclaredTyParam => {
339 let mut err = struct_span_err!(self.session, span, E0128,
340 "type parameters with a default cannot use \
341 forward declared identifiers");
343 span, "defaulted type parameters cannot be forward declared".to_string());
346 ResolutionError::SelfInTyParamDefault => {
347 let mut err = struct_span_err!(
351 "type parameters cannot use `Self` in their defaults"
354 span, "`Self` in type parameter default".to_string());
360 /// Lookup typo candidate in scope for a macro or import.
361 fn early_lookup_typo_candidate(
364 parent_scope: &ParentScope<'a>,
366 filter_fn: &impl Fn(Res) -> bool,
367 ) -> Option<TypoSuggestion> {
368 let mut suggestions = Vec::new();
369 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
371 Scope::DeriveHelpers(expn_id) => {
372 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
374 suggestions.extend(this.helper_attrs.get(&expn_id)
375 .into_iter().flatten().map(|ident| {
376 TypoSuggestion::from_res(ident.name, res)
380 Scope::DeriveHelpersCompat => {
381 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
383 for derive in parent_scope.derives {
385 &ParentScope { derives: &[], ..*parent_scope };
386 if let Ok((Some(ext), _)) = this.resolve_macro_path(
387 derive, Some(MacroKind::Derive), parent_scope, false, false
389 suggestions.extend(ext.helper_attrs.iter().map(|name| {
390 TypoSuggestion::from_res(*name, res)
396 Scope::MacroRules(legacy_scope) => {
397 if let LegacyScope::Binding(legacy_binding) = legacy_scope {
398 let res = legacy_binding.binding.res();
401 TypoSuggestion::from_res(legacy_binding.ident.name, res)
406 Scope::CrateRoot => {
407 let root_ident = Ident::new(kw::PathRoot, ident.span);
408 let root_module = this.resolve_crate_root(root_ident);
409 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
411 Scope::Module(module) => {
412 this.add_module_candidates(module, &mut suggestions, filter_fn);
414 Scope::RegisteredAttrs => {
415 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
417 suggestions.extend(this.registered_attrs.iter().map(|ident| {
418 TypoSuggestion::from_res(ident.name, res)
422 Scope::MacroUsePrelude => {
423 suggestions.extend(this.macro_use_prelude.iter().filter_map(|(name, binding)| {
424 let res = binding.res();
426 Some(TypoSuggestion::from_res(*name, res))
432 Scope::BuiltinAttrs => {
433 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
435 suggestions.extend(BUILTIN_ATTRIBUTES.iter().map(|(name, ..)| {
436 TypoSuggestion::from_res(*name, res)
440 Scope::ExternPrelude => {
441 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
442 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
444 Some(TypoSuggestion::from_res(ident.name, res))
450 Scope::ToolPrelude => {
451 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
452 suggestions.extend(this.registered_tools.iter().map(|ident| {
453 TypoSuggestion::from_res(ident.name, res)
456 Scope::StdLibPrelude => {
457 if let Some(prelude) = this.prelude {
458 let mut tmp_suggestions = Vec::new();
459 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
460 suggestions.extend(tmp_suggestions.into_iter().filter(|s| {
461 use_prelude || this.is_builtin_macro(s.res)
465 Scope::BuiltinTypes => {
466 let primitive_types = &this.primitive_type_table.primitive_types;
468 primitive_types.iter().flat_map(|(name, prim_ty)| {
469 let res = Res::PrimTy(*prim_ty);
471 Some(TypoSuggestion::from_res(*name, res))
483 // Make sure error reporting is deterministic.
484 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
486 match find_best_match_for_name(
487 suggestions.iter().map(|suggestion| &suggestion.candidate),
491 Some(found) if found != ident.name => suggestions
493 .find(|suggestion| suggestion.candidate == found),
498 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
500 namespace: Namespace,
501 start_module: Module<'a>,
504 -> Vec<ImportSuggestion>
505 where FilterFn: Fn(Res) -> bool
507 let mut candidates = Vec::new();
508 let mut seen_modules = FxHashSet::default();
509 let not_local_module = crate_name.name != kw::Crate;
510 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
512 while let Some((in_module,
514 in_module_is_extern)) = worklist.pop() {
515 // We have to visit module children in deterministic order to avoid
516 // instabilities in reported imports (#43552).
517 in_module.for_each_child(self, |this, ident, ns, name_binding| {
518 // avoid imports entirely
519 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
520 // avoid non-importable candidates as well
521 if !name_binding.is_importable() { return; }
523 // collect results based on the filter function
524 if ident.name == lookup_ident.name && ns == namespace {
525 let res = name_binding.res();
528 let mut segms = path_segments.clone();
529 if lookup_ident.span.rust_2018() {
530 // crate-local absolute paths start with `crate::` in edition 2018
531 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
533 0, ast::PathSegment::from_ident(crate_name)
537 segms.push(ast::PathSegment::from_ident(ident));
539 span: name_binding.span,
542 // the entity is accessible in the following cases:
543 // 1. if it's defined in the same crate, it's always
544 // accessible (since private entities can be made public)
545 // 2. if it's defined in another crate, it's accessible
546 // only if both the module is public and the entity is
547 // declared as public (due to pruning, we don't explore
548 // outside crate private modules => no need to check this)
549 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
550 let did = match res {
551 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
552 _ => res.opt_def_id(),
554 candidates.push(ImportSuggestion { did, path });
559 // collect submodules to explore
560 if let Some(module) = name_binding.module() {
562 let mut path_segments = path_segments.clone();
563 path_segments.push(ast::PathSegment::from_ident(ident));
565 let is_extern_crate_that_also_appears_in_prelude =
566 name_binding.is_extern_crate() &&
567 lookup_ident.span.rust_2018();
569 let is_visible_to_user =
570 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
572 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
573 // add the module to the lookup
574 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
575 if seen_modules.insert(module.def_id().unwrap()) {
576 worklist.push((module, path_segments, is_extern));
586 /// When name resolution fails, this method can be used to look up candidate
587 /// entities with the expected name. It allows filtering them using the
588 /// supplied predicate (which should be used to only accept the types of
589 /// definitions expected, e.g., traits). The lookup spans across all crates.
591 /// N.B., the method does not look into imports, but this is not a problem,
592 /// since we report the definitions (thus, the de-aliased imports).
593 crate fn lookup_import_candidates<FilterFn>(
594 &mut self, lookup_ident: Ident, namespace: Namespace, filter_fn: FilterFn
595 ) -> Vec<ImportSuggestion>
596 where FilterFn: Fn(Res) -> bool
598 let mut suggestions = self.lookup_import_candidates_from_module(
599 lookup_ident, namespace, self.graph_root, Ident::with_dummy_span(kw::Crate), &filter_fn
602 if lookup_ident.span.rust_2018() {
603 let extern_prelude_names = self.extern_prelude.clone();
604 for (ident, _) in extern_prelude_names.into_iter() {
605 if ident.span.from_expansion() {
606 // Idents are adjusted to the root context before being
607 // resolved in the extern prelude, so reporting this to the
608 // user is no help. This skips the injected
609 // `extern crate std` in the 2018 edition, which would
610 // otherwise cause duplicate suggestions.
613 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
615 let crate_root = self.get_module(DefId {
617 index: CRATE_DEF_INDEX,
619 suggestions.extend(self.lookup_import_candidates_from_module(
620 lookup_ident, namespace, crate_root, ident, &filter_fn));
628 crate fn unresolved_macro_suggestions(
630 err: &mut DiagnosticBuilder<'a>,
631 macro_kind: MacroKind,
632 parent_scope: &ParentScope<'a>,
635 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
636 let suggestion = self.early_lookup_typo_candidate(
637 ScopeSet::Macro(macro_kind), parent_scope, ident, is_expected
639 self.add_typo_suggestion(err, suggestion, ident.span);
641 if macro_kind == MacroKind::Derive &&
642 (ident.as_str() == "Send" || ident.as_str() == "Sync") {
643 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
644 err.span_note(ident.span, &msg);
646 if self.macro_names.contains(&ident.modern()) {
647 err.help("have you added the `#[macro_use]` on the module/import?");
651 crate fn add_typo_suggestion(
653 err: &mut DiagnosticBuilder<'_>,
654 suggestion: Option<TypoSuggestion>,
657 if let Some(suggestion) = suggestion {
659 "{} {} with a similar name exists", suggestion.res.article(), suggestion.res.descr()
662 span, &msg, suggestion.candidate.to_string(), Applicability::MaybeIncorrect
664 let def_span = suggestion.res.opt_def_id()
665 .and_then(|def_id| self.definitions.opt_span(def_id));
666 if let Some(span) = def_span {
667 err.span_label(span, &format!(
668 "similarly named {} `{}` defined here",
669 suggestion.res.descr(),
670 suggestion.candidate.as_str(),
679 impl<'a, 'b> ImportResolver<'a, 'b> {
680 /// Adds suggestions for a path that cannot be resolved.
681 pub(crate) fn make_path_suggestion(
684 mut path: Vec<Segment>,
685 parent_scope: &ParentScope<'b>,
686 ) -> Option<(Vec<Segment>, Vec<String>)> {
687 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
689 match (path.get(0), path.get(1)) {
690 // `{{root}}::ident::...` on both editions.
691 // On 2015 `{{root}}` is usually added implicitly.
692 (Some(fst), Some(snd)) if fst.ident.name == kw::PathRoot &&
693 !snd.ident.is_path_segment_keyword() => {}
694 // `ident::...` on 2018.
695 (Some(fst), _) if fst.ident.span.rust_2018() &&
696 !fst.ident.is_path_segment_keyword() => {
697 // Insert a placeholder that's later replaced by `self`/`super`/etc.
698 path.insert(0, Segment::from_ident(Ident::invalid()));
703 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
704 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
705 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
706 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
709 /// Suggest a missing `self::` if that resolves to an correct module.
713 /// LL | use foo::Bar;
714 /// | ^^^ did you mean `self::foo`?
716 fn make_missing_self_suggestion(
719 mut path: Vec<Segment>,
720 parent_scope: &ParentScope<'b>,
721 ) -> Option<(Vec<Segment>, Vec<String>)> {
722 // Replace first ident with `self` and check if that is valid.
723 path[0].ident.name = kw::SelfLower;
724 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
725 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
726 if let PathResult::Module(..) = result {
727 Some((path, Vec::new()))
733 /// Suggests a missing `crate::` if that resolves to an correct module.
737 /// LL | use foo::Bar;
738 /// | ^^^ did you mean `crate::foo`?
740 fn make_missing_crate_suggestion(
743 mut path: Vec<Segment>,
744 parent_scope: &ParentScope<'b>,
745 ) -> Option<(Vec<Segment>, Vec<String>)> {
746 // Replace first ident with `crate` and check if that is valid.
747 path[0].ident.name = kw::Crate;
748 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
749 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
750 if let PathResult::Module(..) = result {
754 "`use` statements changed in Rust 2018; read more at \
755 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
756 clarity.html>".to_string()
764 /// Suggests a missing `super::` if that resolves to an correct module.
768 /// LL | use foo::Bar;
769 /// | ^^^ did you mean `super::foo`?
771 fn make_missing_super_suggestion(
774 mut path: Vec<Segment>,
775 parent_scope: &ParentScope<'b>,
776 ) -> Option<(Vec<Segment>, Vec<String>)> {
777 // Replace first ident with `crate` and check if that is valid.
778 path[0].ident.name = kw::Super;
779 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
780 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
781 if let PathResult::Module(..) = result {
782 Some((path, Vec::new()))
788 /// Suggests a missing external crate name if that resolves to an correct module.
792 /// LL | use foobar::Baz;
793 /// | ^^^^^^ did you mean `baz::foobar`?
796 /// Used when importing a submodule of an external crate but missing that crate's
797 /// name as the first part of path.
798 fn make_external_crate_suggestion(
801 mut path: Vec<Segment>,
802 parent_scope: &ParentScope<'b>,
803 ) -> Option<(Vec<Segment>, Vec<String>)> {
804 if path[1].ident.span.rust_2015() {
808 // Sort extern crate names in reverse order to get
809 // 1) some consistent ordering for emitted dignostics, and
810 // 2) `std` suggestions before `core` suggestions.
811 let mut extern_crate_names =
812 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
813 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
815 for name in extern_crate_names.into_iter() {
816 // Replace first ident with a crate name and check if that is valid.
817 path[0].ident.name = name;
818 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
819 debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
821 if let PathResult::Module(..) = result {
822 return Some((path, Vec::new()));
829 /// Suggests importing a macro from the root of the crate rather than a module within
833 /// help: a macro with this name exists at the root of the crate
835 /// LL | use issue_59764::makro;
836 /// | ^^^^^^^^^^^^^^^^^^
838 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
839 /// at the root of the crate instead of the module where it is defined
841 pub(crate) fn check_for_module_export_macro(
843 directive: &'b ImportDirective<'b>,
844 module: ModuleOrUniformRoot<'b>,
846 ) -> Option<(Option<Suggestion>, Vec<String>)> {
847 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
853 while let Some(parent) = crate_module.parent {
854 crate_module = parent;
857 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
858 // Don't make a suggestion if the import was already from the root of the
863 let resolutions = self.r.resolutions(crate_module).borrow();
864 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
865 let binding = resolution.borrow().binding()?;
866 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
867 let module_name = crate_module.kind.name().unwrap();
868 let import = match directive.subclass {
869 ImportDirectiveSubclass::SingleImport { source, target, .. } if source != target =>
870 format!("{} as {}", source, target),
871 _ => format!("{}", ident),
874 let mut corrections: Vec<(Span, String)> = Vec::new();
875 if !directive.is_nested() {
876 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
877 // intermediate segments.
878 corrections.push((directive.span, format!("{}::{}", module_name, import)));
880 // Find the binding span (and any trailing commas and spaces).
881 // ie. `use a::b::{c, d, e};`
883 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
884 self.r.session, directive.span, directive.use_span,
886 debug!("check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
887 found_closing_brace, binding_span);
889 let mut removal_span = binding_span;
890 if found_closing_brace {
891 // If the binding span ended with a closing brace, as in the below example:
892 // ie. `use a::b::{c, d};`
894 // Then expand the span of characters to remove to include the previous
895 // binding's trailing comma.
896 // ie. `use a::b::{c, d};`
898 if let Some(previous_span) = extend_span_to_previous_binding(
899 self.r.session, binding_span,
901 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
902 removal_span = removal_span.with_lo(previous_span.lo());
905 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
907 // Remove the `removal_span`.
908 corrections.push((removal_span, "".to_string()));
910 // Find the span after the crate name and if it has nested imports immediatately
911 // after the crate name already.
912 // ie. `use a::b::{c, d};`
914 // or `use a::{b, c, d}};`
916 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
917 self.r.session, module_name, directive.use_span,
919 debug!("check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
920 has_nested, after_crate_name);
922 let source_map = self.r.session.source_map();
924 // Add the import to the start, with a `{` if required.
925 let start_point = source_map.start_point(after_crate_name);
926 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
930 // In this case, `start_snippet` must equal '{'.
931 format!("{}{}, ", start_snippet, import)
933 // In this case, add a `{`, then the moved import, then whatever
935 format!("{{{}, {}", import, start_snippet)
940 // Add a `};` to the end if nested, matching the `{` added at the start.
942 corrections.push((source_map.end_point(after_crate_name),
947 let suggestion = Some((
949 String::from("a macro with this name exists at the root of the crate"),
950 Applicability::MaybeIncorrect,
953 "this could be because a macro annotated with `#[macro_export]` will be exported \
954 at the root of the crate instead of the module where it is defined".to_string(),
956 Some((suggestion, note))
963 /// Given a `binding_span` of a binding within a use statement:
966 /// use foo::{a, b, c};
970 /// then return the span until the next binding or the end of the statement:
973 /// use foo::{a, b, c};
976 pub(crate) fn find_span_of_binding_until_next_binding(
981 let source_map = sess.source_map();
983 // Find the span of everything after the binding.
984 // ie. `a, e};` or `a};`
985 let binding_until_end = binding_span.with_hi(use_span.hi());
987 // Find everything after the binding but not including the binding.
988 // ie. `, e};` or `};`
989 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
991 // Keep characters in the span until we encounter something that isn't a comma or
995 // Also note whether a closing brace character was encountered. If there
996 // was, then later go backwards to remove any trailing commas that are left.
997 let mut found_closing_brace = false;
998 let after_binding_until_next_binding = source_map.span_take_while(
999 after_binding_until_end,
1001 if ch == '}' { found_closing_brace = true; }
1002 ch == ' ' || ch == ','
1006 // Combine the two spans.
1007 // ie. `a, ` or `a`.
1009 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1010 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1012 (found_closing_brace, span)
1015 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1019 /// use foo::a::{a, b, c};
1020 /// ^^--- binding span
1024 /// use foo::{a, b, c};
1025 /// --- binding span
1027 pub(crate) fn extend_span_to_previous_binding(
1031 let source_map = sess.source_map();
1033 // `prev_source` will contain all of the source that came before the span.
1034 // Then split based on a command and take the first (ie. closest to our span)
1035 // snippet. In the example, this is a space.
1036 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1038 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1039 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1040 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1044 let prev_comma = prev_comma.first().unwrap();
1045 let prev_starting_brace = prev_starting_brace.first().unwrap();
1047 // If the amount of source code before the comma is greater than
1048 // the amount of source code before the starting brace then we've only
1049 // got one item in the nested item (eg. `issue_52891::{self}`).
1050 if prev_comma.len() > prev_starting_brace.len() {
1054 Some(binding_span.with_lo(BytePos(
1055 // Take away the number of bytes for the characters we've found and an
1056 // extra for the comma.
1057 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
1061 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1062 /// it is a nested use tree.
1065 /// use foo::a::{b, c};
1066 /// ^^^^^^^^^^ // false
1068 /// use foo::{a, b, c};
1069 /// ^^^^^^^^^^ // true
1071 /// use foo::{a, b::{c, d}};
1072 /// ^^^^^^^^^^^^^^^ // true
1074 fn find_span_immediately_after_crate_name(
1076 module_name: Symbol,
1079 debug!("find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1080 module_name, use_span);
1081 let source_map = sess.source_map();
1083 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1084 let mut num_colons = 0;
1085 // Find second colon.. `use issue_59764:`
1086 let until_second_colon = source_map.span_take_while(use_span, |c| {
1087 if *c == ':' { num_colons += 1; }
1089 ':' if num_colons == 2 => false,
1093 // Find everything after the second colon.. `foo::{baz, makro};`
1094 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1096 let mut found_a_non_whitespace_character = false;
1097 // Find the first non-whitespace character in `from_second_colon`.. `f`
1098 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1099 if found_a_non_whitespace_character { return false; }
1100 if !c.is_whitespace() { found_a_non_whitespace_character = true; }
1104 // Find the first `{` in from_second_colon.. `foo::{`
1105 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1107 (next_left_bracket == after_second_colon, from_second_colon)
1110 /// When an entity with a given name is not available in scope, we search for
1111 /// entities with that name in all crates. This method allows outputting the
1112 /// results of this search in a programmer-friendly way
1113 crate fn show_candidates(
1114 err: &mut DiagnosticBuilder<'_>,
1115 // This is `None` if all placement locations are inside expansions
1117 candidates: &[ImportSuggestion],
1121 // we want consistent results across executions, but candidates are produced
1122 // by iterating through a hash map, so make sure they are ordered:
1123 let mut path_strings: Vec<_> =
1124 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
1125 path_strings.sort();
1127 let better = if better { "better " } else { "" };
1128 let msg_diff = match path_strings.len() {
1129 1 => " is found in another module, you can import it",
1130 _ => "s are found in other modules, you can import them",
1132 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1134 if let Some(span) = span {
1135 for candidate in &mut path_strings {
1136 // produce an additional newline to separate the new use statement
1137 // from the directly following item.
1138 let additional_newline = if found_use {
1143 *candidate = format!("use {};\n{}", candidate, additional_newline);
1146 err.span_suggestions(
1149 path_strings.into_iter(),
1150 Applicability::Unspecified,
1155 for candidate in path_strings {
1157 msg.push_str(&candidate);