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::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 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 impl<'a> Resolver<'a> {
62 crate fn add_module_candidates(
65 names: &mut Vec<TypoSuggestion>,
66 filter_fn: &impl Fn(Res) -> bool,
68 for (key, resolution) in self.resolutions(module).borrow().iter() {
69 if let Some(binding) = resolution.borrow().binding {
70 let res = binding.res();
72 names.push(TypoSuggestion::from_res(key.ident.name, res));
78 /// Combines an error with provided span and emits it.
80 /// This takes the error provided, combines it with the span and any additional spans inside the
81 /// error and emits it.
82 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
83 self.into_struct_error(span, resolution_error).emit();
86 crate fn into_struct_error(
87 &self, span: Span, resolution_error: ResolutionError<'_>
88 ) -> DiagnosticBuilder<'_> {
89 match resolution_error {
90 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
91 let mut err = struct_span_err!(self.session,
94 "can't use generic parameters from outer function",
96 err.span_label(span, format!("use of generic parameter from outer function"));
98 let cm = self.session.source_map();
100 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
101 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
102 self.definitions.opt_span(def_id)
105 reduce_impl_span_to_impl_keyword(cm, impl_span),
106 "`Self` type implicitly declared here, by this `impl`",
109 match (maybe_trait_defid, maybe_impl_defid) {
111 err.span_label(span, "can't use `Self` here");
114 err.span_label(span, "use a type here instead");
116 (None, None) => bug!("`impl` without trait nor type?"),
120 Res::Def(DefKind::TyParam, def_id) => {
121 if let Some(span) = self.definitions.opt_span(def_id) {
122 err.span_label(span, "type parameter from outer function");
125 Res::Def(DefKind::ConstParam, def_id) => {
126 if let Some(span) = self.definitions.opt_span(def_id) {
127 err.span_label(span, "const parameter from outer function");
131 bug!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
136 if has_generic_params == HasGenericParams::Yes {
137 // Try to retrieve the span of the function signature and generate a new
138 // message with a local type or const parameter.
139 let sugg_msg = &format!("try using a local generic parameter instead");
140 if let Some((sugg_span, snippet)) = cm.generate_local_type_param_snippet(span) {
141 // Suggest the modification to the user
146 Applicability::MachineApplicable,
148 } else if let Some(sp) = cm.generate_fn_name_span(span) {
150 format!("try adding a local generic parameter in this method instead"));
152 err.help(&format!("try using a local generic parameter instead"));
158 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
159 let mut err = struct_span_err!(
163 "the name `{}` is already used for a generic \
164 parameter in this item's generic parameters",
167 err.span_label(span, "already used");
168 err.span_label(first_use_span, format!("first use of `{}`", name));
171 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
172 let mut err = struct_span_err!(self.session,
175 "method `{}` is not a member of trait `{}`",
178 err.span_label(span, format!("not a member of trait `{}`", trait_));
181 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
182 let mut err = struct_span_err!(self.session,
185 "type `{}` is not a member of trait `{}`",
188 err.span_label(span, format!("not a member of trait `{}`", trait_));
191 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
192 let mut err = struct_span_err!(self.session,
195 "const `{}` is not a member of trait `{}`",
198 err.span_label(span, format!("not a member of trait `{}`", trait_));
201 ResolutionError::VariableNotBoundInPattern(binding_error) => {
202 let BindingError { name, target, origin, could_be_path } = binding_error;
204 let target_sp = target.iter().copied().collect::<Vec<_>>();
205 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
207 let msp = MultiSpan::from_spans(target_sp.clone());
208 let msg = format!("variable `{}` is not bound in all patterns", name);
209 let mut err = self.session.struct_span_err_with_code(
212 DiagnosticId::Error("E0408".into()),
214 for sp in target_sp {
215 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
217 for sp in origin_sp {
218 err.span_label(sp, "variable not in all patterns");
221 let help_msg = format!(
222 "if you meant to match on a variant or a `const` item, consider \
223 making the path in the pattern qualified: `?::{}`",
226 err.span_help(span, &help_msg);
230 ResolutionError::VariableBoundWithDifferentMode(variable_name,
231 first_binding_span) => {
232 let mut err = struct_span_err!(self.session,
235 "variable `{}` is bound in inconsistent \
236 ways within the same match arm",
238 err.span_label(span, "bound in different ways");
239 err.span_label(first_binding_span, "first binding");
242 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
243 let mut err = struct_span_err!(self.session,
246 "identifier `{}` is bound more than once in this parameter list",
248 err.span_label(span, "used as parameter more than once");
251 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
252 let mut err = struct_span_err!(self.session,
255 "identifier `{}` is bound more than once in the same pattern",
257 err.span_label(span, "used in a pattern more than once");
260 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
261 let mut err = struct_span_err!(self.session,
264 "use of undeclared label `{}`",
266 if let Some(lev_candidate) = lev_candidate {
269 "a label with a similar name exists in this scope",
270 lev_candidate.to_string(),
271 Applicability::MaybeIncorrect,
274 err.span_label(span, format!("undeclared label `{}`", name));
278 ResolutionError::SelfImportsOnlyAllowedWithin => {
279 struct_span_err!(self.session,
283 "`self` imports are only allowed within a { } list")
285 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
286 let mut err = struct_span_err!(self.session, span, E0430,
287 "`self` import can only appear once in an import list");
288 err.span_label(span, "can only appear once in an import list");
291 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
292 let mut err = struct_span_err!(self.session, span, E0431,
293 "`self` import can only appear in an import list with \
294 a non-empty prefix");
295 err.span_label(span, "can only appear in an import list with a non-empty prefix");
298 ResolutionError::FailedToResolve { label, suggestion } => {
299 let mut err = struct_span_err!(self.session, span, E0433,
300 "failed to resolve: {}", &label);
301 err.span_label(span, label);
303 if let Some((suggestions, msg, applicability)) = suggestion {
304 err.multipart_suggestion(&msg, suggestions, applicability);
309 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
310 let mut err = struct_span_err!(self.session,
314 "can't capture dynamic environment in a fn item");
315 err.help("use the `|| { ... }` closure form instead");
318 ResolutionError::AttemptToUseNonConstantValueInConstant => {
319 let mut err = struct_span_err!(self.session, span, E0435,
320 "attempt to use a non-constant value in a constant");
321 err.span_label(span, "non-constant value");
324 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
325 let res = binding.res();
326 let shadows_what = res.descr();
327 let mut err = struct_span_err!(self.session, span, E0530, "{}s cannot shadow {}s",
328 what_binding, shadows_what);
329 err.span_label(span, format!("cannot be named the same as {} {}",
330 res.article(), shadows_what));
331 let participle = if binding.is_import() { "imported" } else { "defined" };
332 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
333 err.span_label(binding.span, msg);
336 ResolutionError::ForwardDeclaredTyParam => {
337 let mut err = struct_span_err!(self.session, span, E0128,
338 "type parameters with a default cannot use \
339 forward declared identifiers");
341 span, "defaulted type parameters cannot be forward declared".to_string());
344 ResolutionError::SelfInTyParamDefault => {
345 let mut err = struct_span_err!(
349 "type parameters cannot use `Self` in their defaults"
352 span, "`Self` in type parameter default".to_string());
358 /// Lookup typo candidate in scope for a macro or import.
359 fn early_lookup_typo_candidate(
362 parent_scope: &ParentScope<'a>,
364 filter_fn: &impl Fn(Res) -> bool,
365 ) -> Option<TypoSuggestion> {
366 let mut suggestions = Vec::new();
367 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
369 Scope::DeriveHelpers => {
370 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
372 for derive in parent_scope.derives {
374 &ParentScope { derives: &[], ..*parent_scope };
375 if let Ok((Some(ext), _)) = this.resolve_macro_path(
376 derive, Some(MacroKind::Derive), parent_scope, false, false
378 suggestions.extend(ext.helper_attrs.iter().map(|name| {
379 TypoSuggestion::from_res(*name, res)
385 Scope::MacroRules(legacy_scope) => {
386 if let LegacyScope::Binding(legacy_binding) = legacy_scope {
387 let res = legacy_binding.binding.res();
390 TypoSuggestion::from_res(legacy_binding.ident.name, res)
395 Scope::CrateRoot => {
396 let root_ident = Ident::new(kw::PathRoot, ident.span);
397 let root_module = this.resolve_crate_root(root_ident);
398 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
400 Scope::Module(module) => {
401 this.add_module_candidates(module, &mut suggestions, filter_fn);
403 Scope::RegisteredAttrs => {
404 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
406 suggestions.extend(this.registered_attrs.iter().map(|ident| {
407 TypoSuggestion::from_res(ident.name, res)
411 Scope::MacroUsePrelude => {
412 suggestions.extend(this.macro_use_prelude.iter().filter_map(|(name, binding)| {
413 let res = binding.res();
415 Some(TypoSuggestion::from_res(*name, res))
421 Scope::BuiltinAttrs => {
422 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
424 suggestions.extend(BUILTIN_ATTRIBUTES.iter().map(|(name, ..)| {
425 TypoSuggestion::from_res(*name, res)
429 Scope::LegacyPluginHelpers => {
430 let res = Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
432 let plugin_attributes = this.session.plugin_attributes.borrow();
433 suggestions.extend(plugin_attributes.iter().map(|(name, _)| {
434 TypoSuggestion::from_res(*name, res)
438 Scope::ExternPrelude => {
439 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
440 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
442 Some(TypoSuggestion::from_res(ident.name, res))
448 Scope::ToolPrelude => {
449 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
450 suggestions.extend(this.registered_tools.iter().map(|ident| {
451 TypoSuggestion::from_res(ident.name, res)
454 Scope::StdLibPrelude => {
455 if let Some(prelude) = this.prelude {
456 let mut tmp_suggestions = Vec::new();
457 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
458 suggestions.extend(tmp_suggestions.into_iter().filter(|s| {
459 use_prelude || this.is_builtin_macro(s.res)
463 Scope::BuiltinTypes => {
464 let primitive_types = &this.primitive_type_table.primitive_types;
466 primitive_types.iter().flat_map(|(name, prim_ty)| {
467 let res = Res::PrimTy(*prim_ty);
469 Some(TypoSuggestion::from_res(*name, res))
481 // Make sure error reporting is deterministic.
482 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
484 match find_best_match_for_name(
485 suggestions.iter().map(|suggestion| &suggestion.candidate),
489 Some(found) if found != ident.name => suggestions
491 .find(|suggestion| suggestion.candidate == found),
496 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
498 namespace: Namespace,
499 start_module: Module<'a>,
502 -> Vec<ImportSuggestion>
503 where FilterFn: Fn(Res) -> bool
505 let mut candidates = Vec::new();
506 let mut seen_modules = FxHashSet::default();
507 let not_local_module = crate_name.name != kw::Crate;
508 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
510 while let Some((in_module,
512 in_module_is_extern)) = worklist.pop() {
513 // We have to visit module children in deterministic order to avoid
514 // instabilities in reported imports (#43552).
515 in_module.for_each_child(self, |this, ident, ns, name_binding| {
516 // avoid imports entirely
517 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
518 // avoid non-importable candidates as well
519 if !name_binding.is_importable() { return; }
521 // collect results based on the filter function
522 if ident.name == lookup_ident.name && ns == namespace {
523 let res = name_binding.res();
526 let mut segms = path_segments.clone();
527 if lookup_ident.span.rust_2018() {
528 // crate-local absolute paths start with `crate::` in edition 2018
529 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
531 0, ast::PathSegment::from_ident(crate_name)
535 segms.push(ast::PathSegment::from_ident(ident));
537 span: name_binding.span,
540 // the entity is accessible in the following cases:
541 // 1. if it's defined in the same crate, it's always
542 // accessible (since private entities can be made public)
543 // 2. if it's defined in another crate, it's accessible
544 // only if both the module is public and the entity is
545 // declared as public (due to pruning, we don't explore
546 // outside crate private modules => no need to check this)
547 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
548 let did = match res {
549 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
550 _ => res.opt_def_id(),
552 candidates.push(ImportSuggestion { did, path });
557 // collect submodules to explore
558 if let Some(module) = name_binding.module() {
560 let mut path_segments = path_segments.clone();
561 path_segments.push(ast::PathSegment::from_ident(ident));
563 let is_extern_crate_that_also_appears_in_prelude =
564 name_binding.is_extern_crate() &&
565 lookup_ident.span.rust_2018();
567 let is_visible_to_user =
568 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
570 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
571 // add the module to the lookup
572 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
573 if seen_modules.insert(module.def_id().unwrap()) {
574 worklist.push((module, path_segments, is_extern));
584 /// When name resolution fails, this method can be used to look up candidate
585 /// entities with the expected name. It allows filtering them using the
586 /// supplied predicate (which should be used to only accept the types of
587 /// definitions expected, e.g., traits). The lookup spans across all crates.
589 /// N.B., the method does not look into imports, but this is not a problem,
590 /// since we report the definitions (thus, the de-aliased imports).
591 crate fn lookup_import_candidates<FilterFn>(
592 &mut self, lookup_ident: Ident, namespace: Namespace, filter_fn: FilterFn
593 ) -> Vec<ImportSuggestion>
594 where FilterFn: Fn(Res) -> bool
596 let mut suggestions = self.lookup_import_candidates_from_module(
597 lookup_ident, namespace, self.graph_root, Ident::with_dummy_span(kw::Crate), &filter_fn
600 if lookup_ident.span.rust_2018() {
601 let extern_prelude_names = self.extern_prelude.clone();
602 for (ident, _) in extern_prelude_names.into_iter() {
603 if ident.span.from_expansion() {
604 // Idents are adjusted to the root context before being
605 // resolved in the extern prelude, so reporting this to the
606 // user is no help. This skips the injected
607 // `extern crate std` in the 2018 edition, which would
608 // otherwise cause duplicate suggestions.
611 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
613 let crate_root = self.get_module(DefId {
615 index: CRATE_DEF_INDEX,
617 suggestions.extend(self.lookup_import_candidates_from_module(
618 lookup_ident, namespace, crate_root, ident, &filter_fn));
626 crate fn unresolved_macro_suggestions(
628 err: &mut DiagnosticBuilder<'a>,
629 macro_kind: MacroKind,
630 parent_scope: &ParentScope<'a>,
633 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
634 let suggestion = self.early_lookup_typo_candidate(
635 ScopeSet::Macro(macro_kind), parent_scope, ident, is_expected
637 self.add_typo_suggestion(err, suggestion, ident.span);
639 if macro_kind == MacroKind::Derive &&
640 (ident.as_str() == "Send" || ident.as_str() == "Sync") {
641 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
642 err.span_note(ident.span, &msg);
644 if self.macro_names.contains(&ident.modern()) {
645 err.help("have you added the `#[macro_use]` on the module/import?");
649 crate fn add_typo_suggestion(
651 err: &mut DiagnosticBuilder<'_>,
652 suggestion: Option<TypoSuggestion>,
655 if let Some(suggestion) = suggestion {
657 "{} {} with a similar name exists", suggestion.res.article(), suggestion.res.descr()
660 span, &msg, suggestion.candidate.to_string(), Applicability::MaybeIncorrect
662 let def_span = suggestion.res.opt_def_id()
663 .and_then(|def_id| self.definitions.opt_span(def_id));
664 if let Some(span) = def_span {
665 err.span_label(span, &format!(
666 "similarly named {} `{}` defined here",
667 suggestion.res.descr(),
668 suggestion.candidate.as_str(),
677 impl<'a, 'b> ImportResolver<'a, 'b> {
678 /// Adds suggestions for a path that cannot be resolved.
679 pub(crate) fn make_path_suggestion(
682 mut path: Vec<Segment>,
683 parent_scope: &ParentScope<'b>,
684 ) -> Option<(Vec<Segment>, Vec<String>)> {
685 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
687 match (path.get(0), path.get(1)) {
688 // `{{root}}::ident::...` on both editions.
689 // On 2015 `{{root}}` is usually added implicitly.
690 (Some(fst), Some(snd)) if fst.ident.name == kw::PathRoot &&
691 !snd.ident.is_path_segment_keyword() => {}
692 // `ident::...` on 2018.
693 (Some(fst), _) if fst.ident.span.rust_2018() &&
694 !fst.ident.is_path_segment_keyword() => {
695 // Insert a placeholder that's later replaced by `self`/`super`/etc.
696 path.insert(0, Segment::from_ident(Ident::invalid()));
701 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
702 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
703 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
704 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
707 /// Suggest a missing `self::` if that resolves to an correct module.
711 /// LL | use foo::Bar;
712 /// | ^^^ did you mean `self::foo`?
714 fn make_missing_self_suggestion(
717 mut path: Vec<Segment>,
718 parent_scope: &ParentScope<'b>,
719 ) -> Option<(Vec<Segment>, Vec<String>)> {
720 // Replace first ident with `self` and check if that is valid.
721 path[0].ident.name = kw::SelfLower;
722 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
723 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
724 if let PathResult::Module(..) = result {
725 Some((path, Vec::new()))
731 /// Suggests a missing `crate::` if that resolves to an correct module.
735 /// LL | use foo::Bar;
736 /// | ^^^ did you mean `crate::foo`?
738 fn make_missing_crate_suggestion(
741 mut path: Vec<Segment>,
742 parent_scope: &ParentScope<'b>,
743 ) -> Option<(Vec<Segment>, Vec<String>)> {
744 // Replace first ident with `crate` and check if that is valid.
745 path[0].ident.name = kw::Crate;
746 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
747 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
748 if let PathResult::Module(..) = result {
752 "`use` statements changed in Rust 2018; read more at \
753 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
754 clarity.html>".to_string()
762 /// Suggests a missing `super::` if that resolves to an correct module.
766 /// LL | use foo::Bar;
767 /// | ^^^ did you mean `super::foo`?
769 fn make_missing_super_suggestion(
772 mut path: Vec<Segment>,
773 parent_scope: &ParentScope<'b>,
774 ) -> Option<(Vec<Segment>, Vec<String>)> {
775 // Replace first ident with `crate` and check if that is valid.
776 path[0].ident.name = kw::Super;
777 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
778 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
779 if let PathResult::Module(..) = result {
780 Some((path, Vec::new()))
786 /// Suggests a missing external crate name if that resolves to an correct module.
790 /// LL | use foobar::Baz;
791 /// | ^^^^^^ did you mean `baz::foobar`?
794 /// Used when importing a submodule of an external crate but missing that crate's
795 /// name as the first part of path.
796 fn make_external_crate_suggestion(
799 mut path: Vec<Segment>,
800 parent_scope: &ParentScope<'b>,
801 ) -> Option<(Vec<Segment>, Vec<String>)> {
802 if path[1].ident.span.rust_2015() {
806 // Sort extern crate names in reverse order to get
807 // 1) some consistent ordering for emitted dignostics, and
808 // 2) `std` suggestions before `core` suggestions.
809 let mut extern_crate_names =
810 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
811 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
813 for name in extern_crate_names.into_iter() {
814 // Replace first ident with a crate name and check if that is valid.
815 path[0].ident.name = name;
816 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
817 debug!("make_external_crate_suggestion: name={:?} path={:?} result={:?}",
819 if let PathResult::Module(..) = result {
820 return Some((path, Vec::new()));
827 /// Suggests importing a macro from the root of the crate rather than a module within
831 /// help: a macro with this name exists at the root of the crate
833 /// LL | use issue_59764::makro;
834 /// | ^^^^^^^^^^^^^^^^^^
836 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
837 /// at the root of the crate instead of the module where it is defined
839 pub(crate) fn check_for_module_export_macro(
841 directive: &'b ImportDirective<'b>,
842 module: ModuleOrUniformRoot<'b>,
844 ) -> Option<(Option<Suggestion>, Vec<String>)> {
845 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
851 while let Some(parent) = crate_module.parent {
852 crate_module = parent;
855 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
856 // Don't make a suggestion if the import was already from the root of the
861 let resolutions = self.r.resolutions(crate_module).borrow();
862 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
863 let binding = resolution.borrow().binding()?;
864 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
865 let module_name = crate_module.kind.name().unwrap();
866 let import = match directive.subclass {
867 ImportDirectiveSubclass::SingleImport { source, target, .. } if source != target =>
868 format!("{} as {}", source, target),
869 _ => format!("{}", ident),
872 let mut corrections: Vec<(Span, String)> = Vec::new();
873 if !directive.is_nested() {
874 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
875 // intermediate segments.
876 corrections.push((directive.span, format!("{}::{}", module_name, import)));
878 // Find the binding span (and any trailing commas and spaces).
879 // ie. `use a::b::{c, d, e};`
881 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
882 self.r.session, directive.span, directive.use_span,
884 debug!("check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
885 found_closing_brace, binding_span);
887 let mut removal_span = binding_span;
888 if found_closing_brace {
889 // If the binding span ended with a closing brace, as in the below example:
890 // ie. `use a::b::{c, d};`
892 // Then expand the span of characters to remove to include the previous
893 // binding's trailing comma.
894 // ie. `use a::b::{c, d};`
896 if let Some(previous_span) = extend_span_to_previous_binding(
897 self.r.session, binding_span,
899 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
900 removal_span = removal_span.with_lo(previous_span.lo());
903 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
905 // Remove the `removal_span`.
906 corrections.push((removal_span, "".to_string()));
908 // Find the span after the crate name and if it has nested imports immediatately
909 // after the crate name already.
910 // ie. `use a::b::{c, d};`
912 // or `use a::{b, c, d}};`
914 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
915 self.r.session, module_name, directive.use_span,
917 debug!("check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
918 has_nested, after_crate_name);
920 let source_map = self.r.session.source_map();
922 // Add the import to the start, with a `{` if required.
923 let start_point = source_map.start_point(after_crate_name);
924 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
928 // In this case, `start_snippet` must equal '{'.
929 format!("{}{}, ", start_snippet, import)
931 // In this case, add a `{`, then the moved import, then whatever
933 format!("{{{}, {}", import, start_snippet)
938 // Add a `};` to the end if nested, matching the `{` added at the start.
940 corrections.push((source_map.end_point(after_crate_name),
945 let suggestion = Some((
947 String::from("a macro with this name exists at the root of the crate"),
948 Applicability::MaybeIncorrect,
951 "this could be because a macro annotated with `#[macro_export]` will be exported \
952 at the root of the crate instead of the module where it is defined".to_string(),
954 Some((suggestion, note))
961 /// Given a `binding_span` of a binding within a use statement:
964 /// use foo::{a, b, c};
968 /// then return the span until the next binding or the end of the statement:
971 /// use foo::{a, b, c};
974 pub(crate) fn find_span_of_binding_until_next_binding(
979 let source_map = sess.source_map();
981 // Find the span of everything after the binding.
982 // ie. `a, e};` or `a};`
983 let binding_until_end = binding_span.with_hi(use_span.hi());
985 // Find everything after the binding but not including the binding.
986 // ie. `, e};` or `};`
987 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
989 // Keep characters in the span until we encounter something that isn't a comma or
993 // Also note whether a closing brace character was encountered. If there
994 // was, then later go backwards to remove any trailing commas that are left.
995 let mut found_closing_brace = false;
996 let after_binding_until_next_binding = source_map.span_take_while(
997 after_binding_until_end,
999 if ch == '}' { found_closing_brace = true; }
1000 ch == ' ' || ch == ','
1004 // Combine the two spans.
1005 // ie. `a, ` or `a`.
1007 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1008 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1010 (found_closing_brace, span)
1013 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1017 /// use foo::a::{a, b, c};
1018 /// ^^--- binding span
1022 /// use foo::{a, b, c};
1023 /// --- binding span
1025 pub(crate) fn extend_span_to_previous_binding(
1029 let source_map = sess.source_map();
1031 // `prev_source` will contain all of the source that came before the span.
1032 // Then split based on a command and take the first (ie. closest to our span)
1033 // snippet. In the example, this is a space.
1034 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1036 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1037 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1038 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1042 let prev_comma = prev_comma.first().unwrap();
1043 let prev_starting_brace = prev_starting_brace.first().unwrap();
1045 // If the amount of source code before the comma is greater than
1046 // the amount of source code before the starting brace then we've only
1047 // got one item in the nested item (eg. `issue_52891::{self}`).
1048 if prev_comma.len() > prev_starting_brace.len() {
1052 Some(binding_span.with_lo(BytePos(
1053 // Take away the number of bytes for the characters we've found and an
1054 // extra for the comma.
1055 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
1059 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1060 /// it is a nested use tree.
1063 /// use foo::a::{b, c};
1064 /// ^^^^^^^^^^ // false
1066 /// use foo::{a, b, c};
1067 /// ^^^^^^^^^^ // true
1069 /// use foo::{a, b::{c, d}};
1070 /// ^^^^^^^^^^^^^^^ // true
1072 fn find_span_immediately_after_crate_name(
1074 module_name: Symbol,
1077 debug!("find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1078 module_name, use_span);
1079 let source_map = sess.source_map();
1081 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1082 let mut num_colons = 0;
1083 // Find second colon.. `use issue_59764:`
1084 let until_second_colon = source_map.span_take_while(use_span, |c| {
1085 if *c == ':' { num_colons += 1; }
1087 ':' if num_colons == 2 => false,
1091 // Find everything after the second colon.. `foo::{baz, makro};`
1092 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1094 let mut found_a_non_whitespace_character = false;
1095 // Find the first non-whitespace character in `from_second_colon`.. `f`
1096 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1097 if found_a_non_whitespace_character { return false; }
1098 if !c.is_whitespace() { found_a_non_whitespace_character = true; }
1102 // Find the first `{` in from_second_colon.. `foo::{`
1103 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1105 (next_left_bracket == after_second_colon, from_second_colon)
1108 /// When an entity with a given name is not available in scope, we search for
1109 /// entities with that name in all crates. This method allows outputting the
1110 /// results of this search in a programmer-friendly way
1111 crate fn show_candidates(
1112 err: &mut DiagnosticBuilder<'_>,
1113 // This is `None` if all placement locations are inside expansions
1115 candidates: &[ImportSuggestion],
1119 // we want consistent results across executions, but candidates are produced
1120 // by iterating through a hash map, so make sure they are ordered:
1121 let mut path_strings: Vec<_> =
1122 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
1123 path_strings.sort();
1125 let better = if better { "better " } else { "" };
1126 let msg_diff = match path_strings.len() {
1127 1 => " is found in another module, you can import it",
1128 _ => "s are found in other modules, you can import them",
1130 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1132 if let Some(span) = span {
1133 for candidate in &mut path_strings {
1134 // produce an additional newline to separate the new use statement
1135 // from the directly following item.
1136 let additional_newline = if found_use {
1141 *candidate = format!("use {};\n{}", candidate, additional_newline);
1144 err.span_suggestions(
1147 path_strings.into_iter(),
1148 Applicability::Unspecified,
1153 for candidate in path_strings {
1155 msg.push_str(&candidate);