1 //! A bunch of methods and structures more or less related to resolving imports.
3 use ImportDirectiveSubclass::*;
5 use crate::diagnostics::Suggestion;
6 use crate::Determinacy::{self, *};
7 use crate::Namespace::{self, MacroNS, TypeNS};
8 use crate::{module_to_string, names_to_string};
9 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
10 use crate::{BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
11 use crate::{CrateLint, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet, Weak};
12 use crate::{NameBinding, NameBindingKind, PathResult, PrivacyError, ToNameBinding};
14 use rustc::hir::exports::Export;
15 use rustc::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
17 use rustc::{bug, span_bug};
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_data_structures::ptr_key::PtrKey;
20 use rustc_errors::{pluralize, struct_span_err, Applicability};
21 use rustc_hir::def::{self, PartialRes};
22 use rustc_hir::def_id::DefId;
23 use rustc_session::lint::BuiltinLintDiagnostics;
24 use rustc_session::DiagnosticMessageId;
25 use rustc_span::hygiene::ExpnId;
26 use rustc_span::symbol::kw;
27 use rustc_span::{MultiSpan, Span};
28 use syntax::ast::{Ident, Name, NodeId};
29 use syntax::unwrap_or;
30 use syntax::util::lev_distance::find_best_match_for_name;
32 use rustc_error_codes::*;
39 type Res = def::Res<NodeId>;
41 /// Contains data for specific types of import directives.
42 #[derive(Clone, Debug)]
43 pub enum ImportDirectiveSubclass<'a> {
45 /// `source` in `use prefix::source as target`.
47 /// `target` in `use prefix::source as target`.
49 /// Bindings to which `source` refers to.
50 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
51 /// Bindings introduced by `target`.
52 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
53 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
55 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
60 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
61 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
70 /// One import directive.
71 #[derive(Debug, Clone)]
72 crate struct ImportDirective<'a> {
73 /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
75 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
76 /// this id is the ID of the leaf tree. For example:
78 /// ```ignore (pacify the mercilous tidy)
79 /// use foo::bar::{a, b}
82 /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
83 /// for `a` in this field.
86 /// The `id` of the "root" use-kind -- this is always the same as
87 /// `id` except in the case of "nested" use trees, in which case
88 /// it will be the `id` of the root use tree. e.g., in the example
89 /// from `id`, this would be the ID of the `use foo::bar`
93 /// Span of the entire use statement.
96 /// Span of the entire use statement with attributes.
97 pub use_span_with_attributes: Span,
99 /// Did the use statement have any attributes?
100 pub has_attributes: bool,
102 /// Span of this use tree.
105 /// Span of the *root* use tree (see `root_id`).
108 pub parent_scope: ParentScope<'a>,
109 pub module_path: Vec<Segment>,
110 /// The resolution of `module_path`.
111 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
112 pub subclass: ImportDirectiveSubclass<'a>,
113 pub vis: Cell<ty::Visibility>,
114 pub used: Cell<bool>,
117 impl<'a> ImportDirective<'a> {
118 pub fn is_glob(&self) -> bool {
119 match self.subclass {
120 ImportDirectiveSubclass::GlobImport { .. } => true,
125 pub fn is_nested(&self) -> bool {
126 match self.subclass {
127 ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
132 crate fn crate_lint(&self) -> CrateLint {
133 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
137 #[derive(Clone, Default, Debug)]
138 /// Records information about the resolution of a name in a namespace of a module.
139 pub struct NameResolution<'a> {
140 /// Single imports that may define the name in the namespace.
141 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
142 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
143 /// The least shadowable known binding for this name, or None if there are no known bindings.
144 pub binding: Option<&'a NameBinding<'a>>,
145 shadowed_glob: Option<&'a NameBinding<'a>>,
148 impl<'a> NameResolution<'a> {
149 // Returns the binding for the name if it is known or None if it not known.
150 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
151 self.binding.and_then(|binding| {
152 if !binding.is_glob_import() || self.single_imports.is_empty() {
160 crate fn add_single_import(&mut self, directive: &'a ImportDirective<'a>) {
161 self.single_imports.insert(PtrKey(directive));
165 impl<'a> Resolver<'a> {
166 crate fn resolve_ident_in_module_unadjusted(
168 module: ModuleOrUniformRoot<'a>,
171 parent_scope: &ParentScope<'a>,
174 ) -> Result<&'a NameBinding<'a>, Determinacy> {
175 self.resolve_ident_in_module_unadjusted_ext(
184 .map_err(|(determinacy, _)| determinacy)
187 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
188 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
189 crate fn resolve_ident_in_module_unadjusted_ext(
191 module: ModuleOrUniformRoot<'a>,
194 parent_scope: &ParentScope<'a>,
195 restricted_shadowing: bool,
198 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
199 let module = match module {
200 ModuleOrUniformRoot::Module(module) => module,
201 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
202 assert!(!restricted_shadowing);
203 let binding = self.early_resolve_ident_in_lexical_scope(
205 ScopeSet::AbsolutePath(ns),
211 return binding.map_err(|determinacy| (determinacy, Weak::No));
213 ModuleOrUniformRoot::ExternPrelude => {
214 assert!(!restricted_shadowing);
215 return if ns != TypeNS {
216 Err((Determined, Weak::No))
217 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
219 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
220 // Macro-expanded `extern crate` items can add names to extern prelude.
221 Err((Undetermined, Weak::No))
223 Err((Determined, Weak::No))
226 ModuleOrUniformRoot::CurrentScope => {
227 assert!(!restricted_shadowing);
229 if ident.name == kw::Crate || ident.name == kw::DollarCrate {
230 let module = self.resolve_crate_root(ident);
231 let binding = (module, ty::Visibility::Public, module.span, ExpnId::root())
232 .to_name_binding(self.arenas);
234 } else if ident.name == kw::Super || ident.name == kw::SelfLower {
235 // FIXME: Implement these with renaming requirements so that e.g.
236 // `use super;` doesn't work, but `use super as name;` does.
237 // Fall through here to get an error from `early_resolve_...`.
241 let scopes = ScopeSet::All(ns, true);
242 let binding = self.early_resolve_ident_in_lexical_scope(
250 return binding.map_err(|determinacy| (determinacy, Weak::No));
254 let key = self.new_key(ident, ns);
256 self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
258 if let Some(binding) = resolution.binding {
259 if !restricted_shadowing && binding.expansion != ExpnId::root() {
260 if let NameBindingKind::Res(_, true) = binding.kind {
261 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
266 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
267 if let Some(blacklisted_binding) = this.blacklisted_binding {
268 if ptr::eq(binding, blacklisted_binding) {
269 return Err((Determined, Weak::No));
272 // `extern crate` are always usable for backwards compatibility, see issue #37020,
273 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
274 let usable = this.is_accessible_from(binding.vis, parent_scope.module)
275 || binding.is_extern_crate();
276 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
282 .and_then(|binding| {
283 // If the primary binding is blacklisted, search further and return the shadowed
284 // glob binding if it exists. What we really want here is having two separate
285 // scopes in a module - one for non-globs and one for globs, but until that's done
286 // use this hack to avoid inconsistent resolution ICEs during import validation.
287 if let Some(blacklisted_binding) = self.blacklisted_binding {
288 if ptr::eq(binding, blacklisted_binding) {
289 return resolution.shadowed_glob;
294 .ok_or((Determined, Weak::No))
295 .and_then(|binding| {
296 if self.last_import_segment && check_usable(self, binding).is_err() {
297 Err((Determined, Weak::No))
299 self.record_use(ident, ns, binding, restricted_shadowing);
301 if let Some(shadowed_glob) = resolution.shadowed_glob {
302 // Forbid expanded shadowing to avoid time travel.
303 if restricted_shadowing
304 && binding.expansion != ExpnId::root()
305 && binding.res() != shadowed_glob.res()
307 self.ambiguity_errors.push(AmbiguityError {
308 kind: AmbiguityKind::GlobVsExpanded,
312 misc1: AmbiguityErrorMisc::None,
313 misc2: AmbiguityErrorMisc::None,
318 if !self.is_accessible_from(binding.vis, parent_scope.module) &&
319 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
320 !(self.last_import_segment && binding.is_extern_crate())
322 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
330 // Items and single imports are not shadowable, if we have one, then it's determined.
331 if let Some(binding) = resolution.binding {
332 if !binding.is_glob_import() {
333 return check_usable(self, binding);
337 // --- From now on we either have a glob resolution or no resolution. ---
339 // Check if one of single imports can still define the name,
340 // if it can then our result is not determined and can be invalidated.
341 for single_import in &resolution.single_imports {
342 if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
345 let module = unwrap_or!(
346 single_import.imported_module.get(),
347 return Err((Undetermined, Weak::No))
349 let ident = match single_import.subclass {
350 SingleImport { source, .. } => source,
353 match self.resolve_ident_in_module(
357 &single_import.parent_scope,
361 Err(Determined) => continue,
363 if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
367 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
371 // So we have a resolution that's from a glob import. This resolution is determined
372 // if it cannot be shadowed by some new item/import expanded from a macro.
373 // This happens either if there are no unexpanded macros, or expanded names cannot
374 // shadow globs (that happens in macro namespace or with restricted shadowing).
376 // Additionally, any macro in any module can plant names in the root module if it creates
377 // `macro_export` macros, so the root module effectively has unresolved invocations if any
378 // module has unresolved invocations.
379 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
380 // progress, we have to ignore those potential unresolved invocations from other modules
381 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
382 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
383 let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
384 if let Some(binding) = resolution.binding {
385 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
386 return check_usable(self, binding);
388 return Err((Undetermined, Weak::No));
392 // --- From now on we have no resolution. ---
394 // Now we are in situation when new item/import can appear only from a glob or a macro
395 // expansion. With restricted shadowing names from globs and macro expansions cannot
396 // shadow names from outer scopes, so we can freely fallback from module search to search
397 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
398 // scopes we return `Undetermined` with `Weak::Yes`.
400 // Check if one of unexpanded macros can still define the name,
401 // if it can then our "no resolution" result is not determined and can be invalidated.
402 if unexpanded_macros {
403 return Err((Undetermined, Weak::Yes));
406 // Check if one of glob imports can still define the name,
407 // if it can then our "no resolution" result is not determined and can be invalidated.
408 for glob_import in module.globs.borrow().iter() {
409 if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
412 let module = match glob_import.imported_module.get() {
413 Some(ModuleOrUniformRoot::Module(module)) => module,
415 None => return Err((Undetermined, Weak::Yes)),
417 let tmp_parent_scope;
418 let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident.modern());
419 match ident.span.glob_adjust(module.expansion, glob_import.span) {
422 ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
423 adjusted_parent_scope = &tmp_parent_scope;
428 let result = self.resolve_ident_in_module_unadjusted(
429 ModuleOrUniformRoot::Module(module),
432 adjusted_parent_scope,
438 Err(Determined) => continue,
440 if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
444 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
448 // No resolution and no one else can define the name - determinate error.
449 Err((Determined, Weak::No))
452 // Given a binding and an import directive that resolves to it,
453 // return the corresponding binding defined by the import directive.
456 binding: &'a NameBinding<'a>,
457 directive: &'a ImportDirective<'a>,
458 ) -> &'a NameBinding<'a> {
459 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
460 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
461 !directive.is_glob() && binding.is_extern_crate()
468 if let GlobImport { ref max_vis, .. } = directive.subclass {
469 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
474 self.arenas.alloc_name_binding(NameBinding {
475 kind: NameBindingKind::Import { binding, directive, used: Cell::new(false) },
477 span: directive.span,
479 expansion: directive.parent_scope.expansion,
483 // Define the name or return the existing binding if there is a collision.
488 binding: &'a NameBinding<'a>,
489 ) -> Result<(), &'a NameBinding<'a>> {
490 let res = binding.res();
491 self.check_reserved_macro_name(key.ident, res);
492 self.set_binding_parent_module(binding, module);
493 self.update_resolution(module, key, |this, resolution| {
494 if let Some(old_binding) = resolution.binding {
496 // Do not override real bindings with `Res::Err`s from error recovery.
499 match (old_binding.is_glob_import(), binding.is_glob_import()) {
501 if res != old_binding.res() {
502 resolution.binding = Some(this.ambiguity(
503 AmbiguityKind::GlobVsGlob,
507 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
508 // We are glob-importing the same item but with greater visibility.
509 resolution.binding = Some(binding);
512 (old_glob @ true, false) | (old_glob @ false, true) => {
513 let (glob_binding, nonglob_binding) =
514 if old_glob { (old_binding, binding) } else { (binding, old_binding) };
515 if glob_binding.res() != nonglob_binding.res()
517 && nonglob_binding.expansion != ExpnId::root()
519 resolution.binding = Some(this.ambiguity(
520 AmbiguityKind::GlobVsExpanded,
525 resolution.binding = Some(nonglob_binding);
527 resolution.shadowed_glob = Some(glob_binding);
530 return Err(old_binding);
534 resolution.binding = Some(binding);
544 primary_binding: &'a NameBinding<'a>,
545 secondary_binding: &'a NameBinding<'a>,
546 ) -> &'a NameBinding<'a> {
547 self.arenas.alloc_name_binding(NameBinding {
548 ambiguity: Some((secondary_binding, kind)),
549 ..primary_binding.clone()
553 // Use `f` to mutate the resolution of the name in the module.
554 // If the resolution becomes a success, define it in the module's glob importers.
555 fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
557 F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
559 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
560 // during which the resolution might end up getting re-defined via a glob cycle.
562 let resolution = &mut *self.resolution(module, key).borrow_mut();
563 let old_binding = resolution.binding();
565 let t = f(self, resolution);
567 match resolution.binding() {
568 _ if old_binding.is_some() => return t,
570 Some(binding) => match old_binding {
571 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
577 // Define `binding` in `module`s glob importers.
578 for directive in module.glob_importers.borrow_mut().iter() {
579 let mut ident = key.ident;
580 let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
581 Some(Some(def)) => self.macro_def_scope(def),
582 Some(None) => directive.parent_scope.module,
585 if self.is_accessible_from(binding.vis, scope) {
586 let imported_binding = self.import(binding, directive);
587 let key = BindingKey { ident, ..key };
588 let _ = self.try_define(directive.parent_scope.module, key, imported_binding);
595 // Define a "dummy" resolution containing a Res::Err as a placeholder for a
597 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
598 if let SingleImport { target, .. } = directive.subclass {
599 let dummy_binding = self.dummy_binding;
600 let dummy_binding = self.import(dummy_binding, directive);
601 self.per_ns(|this, ns| {
602 let key = this.new_key(target, ns);
603 let _ = this.try_define(directive.parent_scope.module, key, dummy_binding);
604 // Consider erroneous imports used to avoid duplicate diagnostics.
605 this.record_use(target, ns, dummy_binding, false);
611 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
612 /// import errors within the same use tree into a single diagnostic.
613 #[derive(Debug, Clone)]
614 struct UnresolvedImportError {
616 label: Option<String>,
618 suggestion: Option<Suggestion>,
621 pub struct ImportResolver<'a, 'b> {
622 pub r: &'a mut Resolver<'b>,
625 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
626 fn parent(self, id: DefId) -> Option<DefId> {
631 impl<'a, 'b> ImportResolver<'a, 'b> {
634 // This is a fixed-point algorithm. We resolve imports until our efforts
635 // are stymied by an unresolved import; then we bail out of the current
636 // module and continue. We terminate successfully once no more imports
637 // remain or unsuccessfully when no forward progress in resolving imports
640 /// Resolves all imports for the crate. This method performs the fixed-
642 pub fn resolve_imports(&mut self) {
643 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
644 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
645 prev_num_indeterminates = self.r.indeterminate_imports.len();
646 for import in mem::take(&mut self.r.indeterminate_imports) {
647 match self.resolve_import(&import) {
648 true => self.r.determined_imports.push(import),
649 false => self.r.indeterminate_imports.push(import),
655 pub fn finalize_imports(&mut self) {
656 for module in self.r.arenas.local_modules().iter() {
657 self.finalize_resolutions_in(module);
660 let mut seen_spans = FxHashSet::default();
661 let mut errors = vec![];
662 let mut prev_root_id: NodeId = NodeId::from_u32(0);
663 let determined_imports = mem::take(&mut self.r.determined_imports);
664 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
666 for (is_indeterminate, import) in determined_imports
669 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
671 if let Some(err) = self.finalize_import(import) {
672 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
673 if source.name == kw::SelfLower {
674 // Silence `unresolved import` error if E0429 is already emitted
675 if let Err(Determined) = source_bindings.value_ns.get() {
681 // If the error is a single failed import then create a "fake" import
682 // resolution for it so that later resolve stages won't complain.
683 self.r.import_dummy_binding(import);
684 if prev_root_id.as_u32() != 0
685 && prev_root_id.as_u32() != import.root_id.as_u32()
686 && !errors.is_empty()
688 // In the case of a new import line, throw a diagnostic message
689 // for the previous line.
690 self.throw_unresolved_import_error(errors, None);
693 if seen_spans.insert(err.span) {
694 let path = import_path_to_string(
695 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
699 errors.push((path, err));
700 prev_root_id = import.root_id;
702 } else if is_indeterminate {
703 // Consider erroneous imports used to avoid duplicate diagnostics.
704 self.r.used_imports.insert((import.id, TypeNS));
705 let path = import_path_to_string(
706 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
710 let err = UnresolvedImportError {
716 errors.push((path, err));
720 if !errors.is_empty() {
721 self.throw_unresolved_import_error(errors, None);
725 fn throw_unresolved_import_error(
727 errors: Vec<(String, UnresolvedImportError)>,
728 span: Option<MultiSpan>,
730 /// Upper limit on the number of `span_label` messages.
731 const MAX_LABEL_COUNT: usize = 10;
733 let (span, msg) = if errors.is_empty() {
734 (span.unwrap(), "unresolved import".to_string())
736 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
738 let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
740 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
745 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
747 if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
748 for message in note {
753 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
754 if let Some(label) = err.label {
755 diag.span_label(err.span, label);
758 if let Some((suggestions, msg, applicability)) = err.suggestion {
759 diag.multipart_suggestion(&msg, suggestions, applicability);
766 /// Attempts to resolve the given import, returning true if its resolution is determined.
767 /// If successful, the resolved bindings are written into the module.
768 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
770 "(resolving import for module) resolving import `{}::...` in `{}`",
771 Segment::names_to_string(&directive.module_path),
772 module_to_string(directive.parent_scope.module).unwrap_or_else(|| "???".to_string()),
775 let module = if let Some(module) = directive.imported_module.get() {
778 // For better failure detection, pretend that the import will
779 // not define any names while resolving its module path.
780 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
781 let path_res = self.r.resolve_path(
782 &directive.module_path,
784 &directive.parent_scope,
787 directive.crate_lint(),
789 directive.vis.set(orig_vis);
792 PathResult::Module(module) => module,
793 PathResult::Indeterminate => return false,
794 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
798 directive.imported_module.set(Some(module));
799 let (source, target, source_bindings, target_bindings, type_ns_only) =
800 match directive.subclass {
808 } => (source, target, source_bindings, target_bindings, type_ns_only),
809 GlobImport { .. } => {
810 self.resolve_glob_import(directive);
816 let mut indeterminate = false;
817 self.r.per_ns(|this, ns| {
818 if !type_ns_only || ns == TypeNS {
819 if let Err(Undetermined) = source_bindings[ns].get() {
820 // For better failure detection, pretend that the import will
821 // not define any names while resolving its module path.
822 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
823 let binding = this.resolve_ident_in_module(
827 &directive.parent_scope,
831 directive.vis.set(orig_vis);
833 source_bindings[ns].set(binding);
838 let parent = directive.parent_scope.module;
839 match source_bindings[ns].get() {
840 Err(Undetermined) => indeterminate = true,
841 // Don't update the resolution, because it was never added.
842 Err(Determined) if target.name == kw::Underscore => {}
844 let key = this.new_key(target, ns);
845 this.update_resolution(parent, key, |_, resolution| {
846 resolution.single_imports.remove(&PtrKey(directive));
849 Ok(binding) if !binding.is_importable() => {
850 let msg = format!("`{}` is not directly importable", target);
851 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
852 .span_label(directive.span, "cannot be imported directly")
854 // Do not import this illegal binding. Import a dummy binding and pretend
855 // everything is fine
856 this.import_dummy_binding(directive);
859 let imported_binding = this.import(binding, directive);
860 target_bindings[ns].set(Some(imported_binding));
861 this.define(parent, target, ns, imported_binding);
870 /// Performs final import resolution, consistency checks and error reporting.
872 /// Optionally returns an unresolved import error. This error is buffered and used to
873 /// consolidate multiple unresolved import errors into a single diagnostic.
876 directive: &'b ImportDirective<'b>,
877 ) -> Option<UnresolvedImportError> {
878 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
879 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
880 let path_res = self.r.resolve_path(
881 &directive.module_path,
883 &directive.parent_scope,
886 directive.crate_lint(),
888 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
889 directive.vis.set(orig_vis);
890 if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
891 // Consider erroneous imports used to avoid duplicate diagnostics.
892 self.r.used_imports.insert((directive.id, TypeNS));
894 let module = match path_res {
895 PathResult::Module(module) => {
896 // Consistency checks, analogous to `finalize_macro_resolutions`.
897 if let Some(initial_module) = directive.imported_module.get() {
898 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
899 span_bug!(directive.span, "inconsistent resolution for an import");
902 if self.r.privacy_errors.is_empty() {
903 let msg = "cannot determine resolution for the import";
904 let msg_note = "import resolution is stuck, try simplifying other imports";
905 self.r.session.struct_span_err(directive.span, msg).note(msg_note).emit();
911 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
913 assert!(directive.imported_module.get().is_none());
915 .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
919 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
921 assert!(directive.imported_module.get().is_none());
922 let err = match self.make_path_suggestion(
924 directive.module_path.clone(),
925 &directive.parent_scope,
927 Some((suggestion, note)) => UnresolvedImportError {
932 vec![(span, Segment::names_to_string(&suggestion))],
933 String::from("a similar path exists"),
934 Applicability::MaybeIncorrect,
937 None => UnresolvedImportError {
948 PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
950 assert!(directive.imported_module.get().is_none());
952 // The error was already reported earlier.
955 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
958 let (ident, target, source_bindings, target_bindings, type_ns_only) = match directive
968 } => (source, target, source_bindings, target_bindings, type_ns_only),
969 GlobImport { is_prelude, ref max_vis } => {
970 if directive.module_path.len() <= 1 {
971 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
972 // 2 segments, so the `resolve_path` above won't trigger it.
973 let mut full_path = directive.module_path.clone();
974 full_path.push(Segment::from_ident(Ident::invalid()));
975 self.r.lint_if_path_starts_with_module(
976 directive.crate_lint(),
983 if let ModuleOrUniformRoot::Module(module) = module {
984 if module.def_id() == directive.parent_scope.module.def_id() {
985 // Importing a module into itself is not allowed.
986 return Some(UnresolvedImportError {
987 span: directive.span,
988 label: Some(String::from("cannot glob-import a module into itself")),
995 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
996 !max_vis.get().is_at_least(directive.vis.get(), &*self)
998 let msg = "glob import doesn't reexport anything because no candidate is public enough";
999 self.r.lint_buffer.buffer_lint(
1008 _ => unreachable!(),
1011 let mut all_ns_err = true;
1012 self.r.per_ns(|this, ns| {
1013 if !type_ns_only || ns == TypeNS {
1014 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
1015 let orig_blacklisted_binding =
1016 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1017 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1018 let binding = this.resolve_ident_in_module(
1022 &directive.parent_scope,
1026 this.last_import_segment = orig_last_import_segment;
1027 this.blacklisted_binding = orig_blacklisted_binding;
1028 directive.vis.set(orig_vis);
1032 // Consistency checks, analogous to `finalize_macro_resolutions`.
1033 let initial_res = source_bindings[ns].get().map(|initial_binding| {
1035 if let Some(target_binding) = target_bindings[ns].get() {
1036 // Note that as_str() de-gensyms the Symbol
1037 if target.name.as_str() == "_"
1038 && initial_binding.is_extern_crate()
1039 && !initial_binding.is_import()
1045 directive.module_path.is_empty(),
1049 initial_binding.res()
1051 let res = binding.res();
1052 if let Ok(initial_res) = initial_res {
1053 if res != initial_res && this.ambiguity_errors.is_empty() {
1054 span_bug!(directive.span, "inconsistent resolution for an import");
1058 && this.ambiguity_errors.is_empty()
1059 && this.privacy_errors.is_empty()
1061 let msg = "cannot determine resolution for the import";
1063 "import resolution is stuck, try simplifying other imports";
1065 .struct_span_err(directive.span, msg)
1072 // FIXME: This assert may fire if public glob is later shadowed by a private
1073 // single import (see test `issue-55884-2.rs`). In theory single imports should
1074 // always block globs, even if they are not yet resolved, so that this kind of
1075 // self-inconsistent resolution never happens.
1076 // Reenable the assert when the issue is fixed.
1077 // assert!(result[ns].get().is_err());
1084 let mut all_ns_failed = true;
1085 self.r.per_ns(|this, ns| {
1086 if !type_ns_only || ns == TypeNS {
1087 let binding = this.resolve_ident_in_module(
1091 &directive.parent_scope,
1095 if binding.is_ok() {
1096 all_ns_failed = false;
1101 return if all_ns_failed {
1102 let resolutions = match module {
1103 ModuleOrUniformRoot::Module(module) => {
1104 Some(self.r.resolutions(module).borrow())
1108 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1109 let names = resolutions.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1112 } // Never suggest the same name
1113 match *resolution.borrow() {
1114 NameResolution { binding: Some(name_binding), .. } => {
1115 match name_binding.kind {
1116 NameBindingKind::Import { binding, .. } => {
1117 match binding.kind {
1118 // Never suggest the name that has binding error
1119 // i.e., the name that cannot be previously resolved
1120 NameBindingKind::Res(Res::Err, _) => return None,
1127 NameResolution { ref single_imports, .. } if single_imports.is_empty() => {
1134 let lev_suggestion =
1135 find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
1137 vec![(ident.span, suggestion.to_string())],
1138 String::from("a similar name exists in the module"),
1139 Applicability::MaybeIncorrect,
1143 let (suggestion, note) =
1144 match self.check_for_module_export_macro(directive, module, ident) {
1145 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1146 _ => (lev_suggestion, Vec::new()),
1149 let label = match module {
1150 ModuleOrUniformRoot::Module(module) => {
1151 let module_str = module_to_string(module);
1152 if let Some(module_str) = module_str {
1153 format!("no `{}` in `{}`", ident, module_str)
1155 format!("no `{}` in the root", ident)
1159 if !ident.is_path_segment_keyword() {
1160 format!("no `{}` external crate", ident)
1162 // HACK(eddyb) this shows up for `self` & `super`, which
1163 // should work instead - for now keep the same error message.
1164 format!("no `{}` in the root", ident)
1169 Some(UnresolvedImportError {
1170 span: directive.span,
1176 // `resolve_ident_in_module` reported a privacy error.
1177 self.r.import_dummy_binding(directive);
1182 let mut reexport_error = None;
1183 let mut any_successful_reexport = false;
1184 self.r.per_ns(|this, ns| {
1185 if let Ok(binding) = source_bindings[ns].get() {
1186 let vis = directive.vis.get();
1187 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1188 reexport_error = Some((ns, binding));
1190 any_successful_reexport = true;
1195 // All namespaces must be re-exported with extra visibility for an error to occur.
1196 if !any_successful_reexport {
1197 let (ns, binding) = reexport_error.unwrap();
1198 if ns == TypeNS && binding.is_extern_crate() {
1200 "extern crate `{}` is private, and cannot be \
1201 re-exported (error E0365), consider declaring with \
1205 self.r.lint_buffer.buffer_lint(
1206 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1211 } else if ns == TypeNS {
1216 "`{}` is private, and cannot be re-exported",
1219 .span_label(directive.span, format!("re-export of private `{}`", ident))
1220 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1223 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1225 format!("consider marking `{}` as `pub` in the imported module", ident,);
1226 struct_span_err!(self.r.session, directive.span, E0364, "{}", &msg)
1227 .span_note(directive.span, ¬e_msg)
1232 if directive.module_path.len() <= 1 {
1233 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1234 // 2 segments, so the `resolve_path` above won't trigger it.
1235 let mut full_path = directive.module_path.clone();
1236 full_path.push(Segment::from_ident(ident));
1237 self.r.per_ns(|this, ns| {
1238 if let Ok(binding) = source_bindings[ns].get() {
1239 this.lint_if_path_starts_with_module(
1240 directive.crate_lint(),
1249 // Record what this import resolves to for later uses in documentation,
1250 // this may resolve to either a value or a type, but for documentation
1251 // purposes it's good enough to just favor one over the other.
1252 self.r.per_ns(|this, ns| {
1253 if let Some(binding) = source_bindings[ns].get().ok() {
1254 this.import_res_map.entry(directive.id).or_default()[ns] = Some(binding.res());
1258 self.check_for_redundant_imports(
1266 debug!("(resolving single import) successfully resolved import");
1270 fn check_for_redundant_imports(
1273 directive: &'b ImportDirective<'b>,
1274 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1275 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1278 // Skip if the import was produced by a macro.
1279 if directive.parent_scope.expansion != ExpnId::root() {
1283 // Skip if we are inside a named module (in contrast to an anonymous
1284 // module defined by a block).
1285 if let ModuleKind::Def(..) = directive.parent_scope.module.kind {
1289 let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1291 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1293 self.r.per_ns(|this, ns| {
1294 if let Some(binding) = source_bindings[ns].get().ok() {
1295 if binding.res() == Res::Err {
1299 let orig_blacklisted_binding =
1300 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1302 match this.early_resolve_ident_in_lexical_scope(
1304 ScopeSet::All(ns, false),
1305 &directive.parent_scope,
1310 Ok(other_binding) => {
1311 is_redundant[ns] = Some(
1312 binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1314 redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1316 Err(_) => is_redundant[ns] = Some(false),
1319 this.blacklisted_binding = orig_blacklisted_binding;
1323 if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1325 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1326 redundant_spans.sort();
1327 redundant_spans.dedup();
1328 self.r.lint_buffer.buffer_lint_with_diagnostic(
1332 &format!("the item `{}` is imported redundantly", ident),
1333 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1338 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1339 let module = match directive.imported_module.get().unwrap() {
1340 ModuleOrUniformRoot::Module(module) => module,
1342 self.r.session.span_err(directive.span, "cannot glob-import all possible crates");
1347 if module.is_trait() {
1348 self.r.session.span_err(directive.span, "items in traits are not importable.");
1350 } else if module.def_id() == directive.parent_scope.module.def_id() {
1352 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1353 self.r.prelude = Some(module);
1357 // Add to module's glob_importers
1358 module.glob_importers.borrow_mut().push(directive);
1360 // Ensure that `resolutions` isn't borrowed during `try_define`,
1361 // since it might get updated via a glob cycle.
1364 .resolutions(module)
1367 .filter_map(|(key, resolution)| {
1368 resolution.borrow().binding().map(|binding| (*key, binding))
1370 .collect::<Vec<_>>();
1371 for (mut key, binding) in bindings {
1372 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, directive.span) {
1373 Some(Some(def)) => self.r.macro_def_scope(def),
1374 Some(None) => directive.parent_scope.module,
1377 if self.r.is_accessible_from(binding.pseudo_vis(), scope) {
1378 let imported_binding = self.r.import(binding, directive);
1379 let _ = self.r.try_define(directive.parent_scope.module, key, imported_binding);
1383 // Record the destination of this import
1384 self.r.record_partial_res(directive.id, PartialRes::new(module.res().unwrap()));
1387 // Miscellaneous post-processing, including recording re-exports,
1388 // reporting conflicts, and reporting unresolved imports.
1389 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1390 // Since import resolution is finished, globs will not define any more names.
1391 *module.globs.borrow_mut() = Vec::new();
1393 let mut reexports = Vec::new();
1395 module.for_each_child(self.r, |this, ident, ns, binding| {
1396 // Filter away ambiguous imports and anything that has def-site
1398 // FIXME: Implement actual cross-crate hygiene.
1399 let is_good_import =
1400 binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion();
1401 if is_good_import || binding.is_macro_def() {
1402 let res = binding.res();
1403 if res != Res::Err {
1404 if let Some(def_id) = res.opt_def_id() {
1405 if !def_id.is_local() {
1406 this.cstore().export_macros_untracked(def_id.krate);
1409 reexports.push(Export { ident, res, span: binding.span, vis: binding.vis });
1413 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1415 && orig_binding.is_variant()
1416 && !orig_binding.vis.is_at_least(binding.vis, &*this)
1418 let msg = match directive.subclass {
1419 ImportDirectiveSubclass::SingleImport { .. } => {
1420 format!("variant `{}` is private and cannot be re-exported", ident)
1422 ImportDirectiveSubclass::GlobImport { .. } => {
1423 let msg = "enum is private and its variants \
1424 cannot be re-exported"
1427 DiagnosticMessageId::ErrorId(0), // no code?!
1432 this.session.one_time_diagnostics.borrow_mut().insert(error_id);
1438 ref s @ _ => bug!("unexpected import subclass {:?}", s),
1440 let mut err = this.session.struct_span_err(binding.span, &msg);
1442 let imported_module = match directive.imported_module.get() {
1443 Some(ModuleOrUniformRoot::Module(module)) => module,
1444 _ => bug!("module should exist"),
1446 let parent_module = imported_module.parent.expect("parent should exist");
1447 let resolutions = this.resolutions(parent_module).borrow();
1448 let enum_path_segment_index = directive.module_path.len() - 1;
1449 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1451 let key = this.new_key(enum_ident, TypeNS);
1452 let enum_resolution = resolutions.get(&key).expect("resolution should exist");
1454 enum_resolution.borrow().binding.expect("binding should exist").span;
1455 let enum_def_span = this.session.source_map().def_span(enum_span);
1456 let enum_def_snippet = this
1459 .span_to_snippet(enum_def_span)
1460 .expect("snippet should exist");
1461 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1462 let after_vis_index = enum_def_snippet
1464 .expect("`enum` keyword should exist in snippet");
1465 let suggestion = format!("pub {}", &enum_def_snippet[after_vis_index..]);
1467 this.session.diag_span_suggestion_once(
1469 DiagnosticMessageId::ErrorId(0),
1471 "consider making the enum public",
1479 if reexports.len() > 0 {
1480 if let Some(def_id) = module.def_id() {
1481 self.r.export_map.insert(def_id, reexports);
1487 fn import_path_to_string(
1489 subclass: &ImportDirectiveSubclass<'_>,
1492 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1493 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1494 if let Some(pos) = pos {
1495 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1496 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1498 let names = if global { &names[1..] } else { names };
1499 if names.is_empty() {
1500 import_directive_subclass_to_string(subclass)
1504 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1505 import_directive_subclass_to_string(subclass),
1511 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1513 SingleImport { source, .. } => source.to_string(),
1514 GlobImport { .. } => "*".to_string(),
1515 ExternCrate { .. } => "<extern crate>".to_string(),
1516 MacroUse => "#[macro_use]".to_string(),