1 //! A bunch of methods and structures more or less related to resolving imports.
3 use ImportDirectiveSubclass::*;
5 use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
6 use crate::{CrateLint, Module, ModuleOrUniformRoot, PerNS, ScopeSet, ParentScope, Weak};
7 use crate::Determinacy::{self, *};
8 use crate::Namespace::{self, TypeNS, MacroNS};
9 use crate::{NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
10 use crate::{Resolver, ResolutionError, BindingKey, Segment, ModuleKind};
11 use crate::{names_to_string, module_to_string};
12 use crate::diagnostics::Suggestion;
14 use errors::{Applicability, pluralize};
16 use rustc_data_structures::ptr_key::PtrKey;
18 use rustc::lint::builtin::BuiltinLintDiagnostics;
19 use rustc::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
20 use rustc::hir::def_id::DefId;
21 use rustc::hir::def::{self, PartialRes, Export};
22 use rustc::session::DiagnosticMessageId;
23 use rustc::util::nodemap::FxHashSet;
24 use rustc::{bug, span_bug};
26 use syntax::ast::{Ident, Name, NodeId};
27 use syntax::symbol::kw;
28 use syntax::util::lev_distance::find_best_match_for_name;
29 use syntax::{struct_span_err, unwrap_or};
30 use syntax_pos::hygiene::ExpnId;
31 use syntax_pos::{MultiSpan, Span};
33 use rustc_error_codes::*;
40 type Res = def::Res<NodeId>;
42 /// Contains data for specific types of import directives.
43 #[derive(Clone, Debug)]
44 pub enum ImportDirectiveSubclass<'a> {
46 /// `source` in `use prefix::source as target`.
48 /// `target` in `use prefix::source as target`.
50 /// Bindings to which `source` refers to.
51 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
52 /// Bindings introduced by `target`.
53 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
54 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
56 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
61 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
62 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
71 /// One import directive.
72 #[derive(Debug, Clone)]
73 crate struct ImportDirective<'a> {
74 /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
76 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
77 /// this id is the ID of the leaf tree. For example:
79 /// ```ignore (pacify the mercilous tidy)
80 /// use foo::bar::{a, b}
83 /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
84 /// for `a` in this field.
87 /// The `id` of the "root" use-kind -- this is always the same as
88 /// `id` except in the case of "nested" use trees, in which case
89 /// it will be the `id` of the root use tree. e.g., in the example
90 /// from `id`, this would be the ID of the `use foo::bar`
94 /// Span of the entire use statement.
97 /// Span of the entire use statement with attributes.
98 pub use_span_with_attributes: Span,
100 /// Did the use statement have any attributes?
101 pub has_attributes: bool,
103 /// Span of this use tree.
106 /// Span of the *root* use tree (see `root_id`).
109 pub parent_scope: ParentScope<'a>,
110 pub module_path: Vec<Segment>,
111 /// The resolution of `module_path`.
112 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
113 pub subclass: ImportDirectiveSubclass<'a>,
114 pub vis: Cell<ty::Visibility>,
115 pub used: Cell<bool>,
118 impl<'a> ImportDirective<'a> {
119 pub fn is_glob(&self) -> bool {
120 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
123 pub fn is_nested(&self) -> bool {
124 match self.subclass {
125 ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
130 crate fn crate_lint(&self) -> CrateLint {
131 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
135 #[derive(Clone, Default, Debug)]
136 /// Records information about the resolution of a name in a namespace of a module.
137 pub struct NameResolution<'a> {
138 /// Single imports that may define the name in the namespace.
139 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
140 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
141 /// The least shadowable known binding for this name, or None if there are no known bindings.
142 pub binding: Option<&'a NameBinding<'a>>,
143 shadowed_glob: Option<&'a NameBinding<'a>>,
146 impl<'a> NameResolution<'a> {
147 // Returns the binding for the name if it is known or None if it not known.
148 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
149 self.binding.and_then(|binding| {
150 if !binding.is_glob_import() ||
151 self.single_imports.is_empty() { Some(binding) } else { None }
155 crate fn add_single_import(&mut self, directive: &'a ImportDirective<'a>) {
156 self.single_imports.insert(PtrKey(directive));
160 impl<'a> Resolver<'a> {
161 crate fn resolve_ident_in_module_unadjusted(
163 module: ModuleOrUniformRoot<'a>,
166 parent_scope: &ParentScope<'a>,
169 ) -> Result<&'a NameBinding<'a>, Determinacy> {
170 self.resolve_ident_in_module_unadjusted_ext(
171 module, ident, ns, parent_scope, false, record_used, path_span
172 ).map_err(|(determinacy, _)| determinacy)
175 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
176 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
177 crate fn resolve_ident_in_module_unadjusted_ext(
179 module: ModuleOrUniformRoot<'a>,
182 parent_scope: &ParentScope<'a>,
183 restricted_shadowing: bool,
186 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
187 let module = match module {
188 ModuleOrUniformRoot::Module(module) => module,
189 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
190 assert!(!restricted_shadowing);
191 let binding = self.early_resolve_ident_in_lexical_scope(
192 ident, ScopeSet::AbsolutePath(ns), parent_scope,
193 record_used, record_used, path_span,
195 return binding.map_err(|determinacy| (determinacy, Weak::No));
197 ModuleOrUniformRoot::ExternPrelude => {
198 assert!(!restricted_shadowing);
199 return if ns != TypeNS {
200 Err((Determined, Weak::No))
201 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
203 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
204 // Macro-expanded `extern crate` items can add names to extern prelude.
205 Err((Undetermined, Weak::No))
207 Err((Determined, Weak::No))
210 ModuleOrUniformRoot::CurrentScope => {
211 assert!(!restricted_shadowing);
213 if ident.name == kw::Crate ||
214 ident.name == kw::DollarCrate {
215 let module = self.resolve_crate_root(ident);
216 let binding = (module, ty::Visibility::Public,
217 module.span, ExpnId::root())
218 .to_name_binding(self.arenas);
220 } else if ident.name == kw::Super ||
221 ident.name == kw::SelfLower {
222 // FIXME: Implement these with renaming requirements so that e.g.
223 // `use super;` doesn't work, but `use super as name;` does.
224 // Fall through here to get an error from `early_resolve_...`.
228 let scopes = ScopeSet::All(ns, true);
229 let binding = self.early_resolve_ident_in_lexical_scope(
230 ident, scopes, parent_scope, record_used, record_used, path_span
232 return binding.map_err(|determinacy| (determinacy, Weak::No));
236 let key = self.new_key(ident, ns);
237 let resolution = self.resolution(module, key)
239 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
241 if let Some(binding) = resolution.binding {
242 if !restricted_shadowing && binding.expansion != ExpnId::root() {
243 if let NameBindingKind::Res(_, true) = binding.kind {
244 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
249 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
250 if let Some(blacklisted_binding) = this.blacklisted_binding {
251 if ptr::eq(binding, blacklisted_binding) {
252 return Err((Determined, Weak::No));
255 // `extern crate` are always usable for backwards compatibility, see issue #37020,
256 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
257 let usable = this.is_accessible_from(binding.vis, parent_scope.module) ||
258 binding.is_extern_crate();
259 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
263 return resolution.binding.and_then(|binding| {
264 // If the primary binding is blacklisted, search further and return the shadowed
265 // glob binding if it exists. What we really want here is having two separate
266 // scopes in a module - one for non-globs and one for globs, but until that's done
267 // use this hack to avoid inconsistent resolution ICEs during import validation.
268 if let Some(blacklisted_binding) = self.blacklisted_binding {
269 if ptr::eq(binding, blacklisted_binding) {
270 return resolution.shadowed_glob;
274 }).ok_or((Determined, Weak::No)).and_then(|binding| {
275 if self.last_import_segment && check_usable(self, binding).is_err() {
276 Err((Determined, Weak::No))
278 self.record_use(ident, ns, binding, restricted_shadowing);
280 if let Some(shadowed_glob) = resolution.shadowed_glob {
281 // Forbid expanded shadowing to avoid time travel.
282 if restricted_shadowing &&
283 binding.expansion != ExpnId::root() &&
284 binding.res() != shadowed_glob.res() {
285 self.ambiguity_errors.push(AmbiguityError {
286 kind: AmbiguityKind::GlobVsExpanded,
290 misc1: AmbiguityErrorMisc::None,
291 misc2: AmbiguityErrorMisc::None,
296 if !self.is_accessible_from(binding.vis, parent_scope.module) &&
297 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
298 !(self.last_import_segment && binding.is_extern_crate()) {
299 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
307 // Items and single imports are not shadowable, if we have one, then it's determined.
308 if let Some(binding) = resolution.binding {
309 if !binding.is_glob_import() {
310 return check_usable(self, binding);
314 // --- From now on we either have a glob resolution or no resolution. ---
316 // Check if one of single imports can still define the name,
317 // if it can then our result is not determined and can be invalidated.
318 for single_import in &resolution.single_imports {
319 if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
322 let module = unwrap_or!(single_import.imported_module.get(),
323 return Err((Undetermined, Weak::No)));
324 let ident = match single_import.subclass {
325 SingleImport { source, .. } => source,
328 match self.resolve_ident_in_module(module, ident, ns, &single_import.parent_scope,
330 Err(Determined) => continue,
331 Ok(binding) if !self.is_accessible_from(
332 binding.vis, single_import.parent_scope.module
334 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
338 // So we have a resolution that's from a glob import. This resolution is determined
339 // if it cannot be shadowed by some new item/import expanded from a macro.
340 // This happens either if there are no unexpanded macros, or expanded names cannot
341 // shadow globs (that happens in macro namespace or with restricted shadowing).
343 // Additionally, any macro in any module can plant names in the root module if it creates
344 // `macro_export` macros, so the root module effectively has unresolved invocations if any
345 // module has unresolved invocations.
346 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
347 // progress, we have to ignore those potential unresolved invocations from other modules
348 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
349 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
350 let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
351 if let Some(binding) = resolution.binding {
352 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
353 return check_usable(self, binding);
355 return Err((Undetermined, Weak::No));
359 // --- From now on we have no resolution. ---
361 // Now we are in situation when new item/import can appear only from a glob or a macro
362 // expansion. With restricted shadowing names from globs and macro expansions cannot
363 // shadow names from outer scopes, so we can freely fallback from module search to search
364 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
365 // scopes we return `Undetermined` with `Weak::Yes`.
367 // Check if one of unexpanded macros can still define the name,
368 // if it can then our "no resolution" result is not determined and can be invalidated.
369 if unexpanded_macros {
370 return Err((Undetermined, Weak::Yes));
373 // Check if one of glob imports can still define the name,
374 // if it can then our "no resolution" result is not determined and can be invalidated.
375 for glob_import in module.globs.borrow().iter() {
376 if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
379 let module = match glob_import.imported_module.get() {
380 Some(ModuleOrUniformRoot::Module(module)) => module,
382 None => return Err((Undetermined, Weak::Yes)),
384 let tmp_parent_scope;
385 let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident.modern());
386 match ident.span.glob_adjust(module.expansion, glob_import.span) {
389 ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
390 adjusted_parent_scope = &tmp_parent_scope;
395 let result = self.resolve_ident_in_module_unadjusted(
396 ModuleOrUniformRoot::Module(module),
399 adjusted_parent_scope,
405 Err(Determined) => continue,
406 Ok(binding) if !self.is_accessible_from(
407 binding.vis, glob_import.parent_scope.module
409 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
413 // No resolution and no one else can define the name - determinate error.
414 Err((Determined, Weak::No))
417 // Given a binding and an import directive that resolves to it,
418 // return the corresponding binding defined by the import directive.
419 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
420 -> &'a NameBinding<'a> {
421 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
422 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
423 !directive.is_glob() && binding.is_extern_crate() {
429 if let GlobImport { ref max_vis, .. } = directive.subclass {
430 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
435 self.arenas.alloc_name_binding(NameBinding {
436 kind: NameBindingKind::Import {
439 used: Cell::new(false),
442 span: directive.span,
444 expansion: directive.parent_scope.expansion,
448 // Define the name or return the existing binding if there is a collision.
453 binding: &'a NameBinding<'a>,
454 ) -> Result<(), &'a NameBinding<'a>> {
455 let res = binding.res();
456 self.check_reserved_macro_name(key.ident, res);
457 self.set_binding_parent_module(binding, module);
458 self.update_resolution(module, key, |this, resolution| {
459 if let Some(old_binding) = resolution.binding {
461 // Do not override real bindings with `Res::Err`s from error recovery.
464 match (old_binding.is_glob_import(), binding.is_glob_import()) {
466 if res != old_binding.res() {
467 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
468 old_binding, binding));
469 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
470 // We are glob-importing the same item but with greater visibility.
471 resolution.binding = Some(binding);
474 (old_glob @ true, false) | (old_glob @ false, true) => {
475 let (glob_binding, nonglob_binding) = if old_glob {
476 (old_binding, binding)
478 (binding, old_binding)
480 if glob_binding.res() != nonglob_binding.res()
481 && key.ns == MacroNS && nonglob_binding.expansion != ExpnId::root()
483 resolution.binding = Some(this.ambiguity(
484 AmbiguityKind::GlobVsExpanded,
489 resolution.binding = Some(nonglob_binding);
491 resolution.shadowed_glob = Some(glob_binding);
494 if let (&NameBindingKind::Res(_, true), &NameBindingKind::Res(_, true)) =
495 (&old_binding.kind, &binding.kind) {
497 this.session.struct_span_err(
499 &format!("a macro named `{}` has already been exported", key.ident),
501 .span_label(binding.span, format!("`{}` already exported", key.ident))
502 .span_note(old_binding.span, "previous macro export is now shadowed")
505 resolution.binding = Some(binding);
507 return Err(old_binding);
512 resolution.binding = Some(binding);
520 &self, kind: AmbiguityKind,
521 primary_binding: &'a NameBinding<'a>,
522 secondary_binding: &'a NameBinding<'a>,
523 ) -> &'a NameBinding<'a> {
524 self.arenas.alloc_name_binding(NameBinding {
525 ambiguity: Some((secondary_binding, kind)),
526 ..primary_binding.clone()
530 // Use `f` to mutate the resolution of the name in the module.
531 // If the resolution becomes a success, define it in the module's glob importers.
532 fn update_resolution<T, F>(
538 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
540 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
541 // during which the resolution might end up getting re-defined via a glob cycle.
543 let resolution = &mut *self.resolution(module, key).borrow_mut();
544 let old_binding = resolution.binding();
546 let t = f(self, resolution);
548 match resolution.binding() {
549 _ if old_binding.is_some() => return t,
551 Some(binding) => match old_binding {
552 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
558 // Define `binding` in `module`s glob importers.
559 for directive in module.glob_importers.borrow_mut().iter() {
560 let mut ident = key.ident;
561 let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
562 Some(Some(def)) => self.macro_def_scope(def),
563 Some(None) => directive.parent_scope.module,
566 if self.is_accessible_from(binding.vis, scope) {
567 let imported_binding = self.import(binding, directive);
568 let key = BindingKey { ident, ..key };
569 let _ = self.try_define(directive.parent_scope.module, key, imported_binding);
576 // Define a "dummy" resolution containing a Res::Err as a placeholder for a
578 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
579 if let SingleImport { target, .. } = directive.subclass {
580 let dummy_binding = self.dummy_binding;
581 let dummy_binding = self.import(dummy_binding, directive);
582 self.per_ns(|this, ns| {
583 let key = this.new_key(target, ns);
584 let _ = this.try_define(directive.parent_scope.module, key, dummy_binding);
585 // Consider erroneous imports used to avoid duplicate diagnostics.
586 this.record_use(target, ns, dummy_binding, false);
592 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
593 /// import errors within the same use tree into a single diagnostic.
594 #[derive(Debug, Clone)]
595 struct UnresolvedImportError {
597 label: Option<String>,
599 suggestion: Option<Suggestion>,
602 pub struct ImportResolver<'a, 'b> {
603 pub r: &'a mut Resolver<'b>,
606 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
607 fn parent(self, id: DefId) -> Option<DefId> {
612 impl<'a, 'b> ImportResolver<'a, 'b> {
615 // This is a fixed-point algorithm. We resolve imports until our efforts
616 // are stymied by an unresolved import; then we bail out of the current
617 // module and continue. We terminate successfully once no more imports
618 // remain or unsuccessfully when no forward progress in resolving imports
621 /// Resolves all imports for the crate. This method performs the fixed-
623 pub fn resolve_imports(&mut self) {
624 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
625 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
626 prev_num_indeterminates = self.r.indeterminate_imports.len();
627 for import in mem::take(&mut self.r.indeterminate_imports) {
628 match self.resolve_import(&import) {
629 true => self.r.determined_imports.push(import),
630 false => self.r.indeterminate_imports.push(import),
636 pub fn finalize_imports(&mut self) {
637 for module in self.r.arenas.local_modules().iter() {
638 self.finalize_resolutions_in(module);
641 let mut seen_spans = FxHashSet::default();
642 let mut errors = vec![];
643 let mut prev_root_id: NodeId = NodeId::from_u32(0);
644 let determined_imports = mem::take(&mut self.r.determined_imports);
645 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
647 for (is_indeterminate, import) in determined_imports
650 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
652 if let Some(err) = self.finalize_import(import) {
654 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
655 if source.name == kw::SelfLower {
656 // Silence `unresolved import` error if E0429 is already emitted
657 if let Err(Determined) = source_bindings.value_ns.get() {
663 // If the error is a single failed import then create a "fake" import
664 // resolution for it so that later resolve stages won't complain.
665 self.r.import_dummy_binding(import);
666 if prev_root_id.as_u32() != 0
667 && prev_root_id.as_u32() != import.root_id.as_u32()
668 && !errors.is_empty() {
669 // In the case of a new import line, throw a diagnostic message
670 // for the previous line.
671 self.throw_unresolved_import_error(errors, None);
674 if seen_spans.insert(err.span) {
675 let path = import_path_to_string(
676 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
680 errors.push((path, err));
681 prev_root_id = import.root_id;
683 } else if is_indeterminate {
684 // Consider erroneous imports used to avoid duplicate diagnostics.
685 self.r.used_imports.insert((import.id, TypeNS));
686 let path = import_path_to_string(
687 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
691 let err = UnresolvedImportError {
697 errors.push((path, err));
701 if !errors.is_empty() {
702 self.throw_unresolved_import_error(errors.clone(), None);
706 fn throw_unresolved_import_error(
708 errors: Vec<(String, UnresolvedImportError)>,
709 span: Option<MultiSpan>,
711 /// Upper limit on the number of `span_label` messages.
712 const MAX_LABEL_COUNT: usize = 10;
714 let (span, msg) = if errors.is_empty() {
715 (span.unwrap(), "unresolved import".to_string())
717 let span = MultiSpan::from_spans(
720 .map(|(_, err)| err.span)
726 .map(|(path, _)| format!("`{}`", path))
727 .collect::<Vec<_>>();
730 "unresolved import{} {}",
731 pluralize!(paths.len()),
738 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
740 if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
741 for message in note {
746 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
747 if let Some(label) = err.label {
748 diag.span_label(err.span, label);
751 if let Some((suggestions, msg, applicability)) = err.suggestion {
752 diag.multipart_suggestion(&msg, suggestions, applicability);
759 /// Attempts to resolve the given import, returning true if its resolution is determined.
760 /// If successful, the resolved bindings are written into the module.
761 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
763 "(resolving import for module) resolving import `{}::...` in `{}`",
764 Segment::names_to_string(&directive.module_path),
765 module_to_string(directive.parent_scope.module).unwrap_or_else(|| "???".to_string()),
768 let module = if let Some(module) = directive.imported_module.get() {
771 // For better failure detection, pretend that the import will
772 // not define any names while resolving its module path.
773 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
774 let path_res = self.r.resolve_path(
775 &directive.module_path,
777 &directive.parent_scope,
780 directive.crate_lint(),
782 directive.vis.set(orig_vis);
785 PathResult::Module(module) => module,
786 PathResult::Indeterminate => return false,
787 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
791 directive.imported_module.set(Some(module));
792 let (source, target, source_bindings, target_bindings, type_ns_only) =
793 match directive.subclass {
794 SingleImport { source, target, ref source_bindings,
795 ref target_bindings, type_ns_only, .. } =>
796 (source, target, source_bindings, target_bindings, type_ns_only),
797 GlobImport { .. } => {
798 self.resolve_glob_import(directive);
804 let mut indeterminate = false;
805 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
806 if let Err(Undetermined) = source_bindings[ns].get() {
807 // For better failure detection, pretend that the import will
808 // not define any names while resolving its module path.
809 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
810 let binding = this.resolve_ident_in_module(
811 module, source, ns, &directive.parent_scope, false, directive.span
813 directive.vis.set(orig_vis);
815 source_bindings[ns].set(binding);
820 let parent = directive.parent_scope.module;
821 match source_bindings[ns].get() {
822 Err(Undetermined) => indeterminate = true,
823 // Don't update the resolution, because it was never added.
824 Err(Determined) if target.name == kw::Underscore => {}
826 let key = this.new_key(target, ns);
827 this.update_resolution(parent, key, |_, resolution| {
828 resolution.single_imports.remove(&PtrKey(directive));
831 Ok(binding) if !binding.is_importable() => {
832 let msg = format!("`{}` is not directly importable", target);
833 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
834 .span_label(directive.span, "cannot be imported directly")
836 // Do not import this illegal binding. Import a dummy binding and pretend
837 // everything is fine
838 this.import_dummy_binding(directive);
841 let imported_binding = this.import(binding, directive);
842 target_bindings[ns].set(Some(imported_binding));
843 this.define(parent, target, ns, imported_binding);
851 /// Performs final import resolution, consistency checks and error reporting.
853 /// Optionally returns an unresolved import error. This error is buffered and used to
854 /// consolidate multiple unresolved import errors into a single diagnostic.
857 directive: &'b ImportDirective<'b>
858 ) -> Option<UnresolvedImportError> {
859 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
860 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
861 let path_res = self.r.resolve_path(
862 &directive.module_path,
864 &directive.parent_scope,
867 directive.crate_lint(),
869 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
870 directive.vis.set(orig_vis);
871 if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
872 // Consider erroneous imports used to avoid duplicate diagnostics.
873 self.r.used_imports.insert((directive.id, TypeNS));
875 let module = match path_res {
876 PathResult::Module(module) => {
877 // Consistency checks, analogous to `finalize_macro_resolutions`.
878 if let Some(initial_module) = directive.imported_module.get() {
879 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
880 span_bug!(directive.span, "inconsistent resolution for an import");
883 if self.r.privacy_errors.is_empty() {
884 let msg = "cannot determine resolution for the import";
885 let msg_note = "import resolution is stuck, try simplifying other imports";
886 self.r.session.struct_span_err(directive.span, msg).note(msg_note).emit();
892 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
894 assert!(directive.imported_module.get().is_none());
895 self.r.report_error(span, ResolutionError::FailedToResolve {
902 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
904 assert!(directive.imported_module.get().is_none());
905 let err = match self.make_path_suggestion(
907 directive.module_path.clone(),
908 &directive.parent_scope,
910 Some((suggestion, note)) => {
911 UnresolvedImportError {
916 vec![(span, Segment::names_to_string(&suggestion))],
917 String::from("a similar path exists"),
918 Applicability::MaybeIncorrect,
923 UnresolvedImportError {
935 PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
937 assert!(directive.imported_module.get().is_none());
939 // The error was already reported earlier.
942 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
945 let (ident, target, source_bindings, target_bindings, type_ns_only) =
946 match directive.subclass {
947 SingleImport { source, target, ref source_bindings,
948 ref target_bindings, type_ns_only, .. } =>
949 (source, target, source_bindings, target_bindings, type_ns_only),
950 GlobImport { is_prelude, ref max_vis } => {
951 if directive.module_path.len() <= 1 {
952 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
953 // 2 segments, so the `resolve_path` above won't trigger it.
954 let mut full_path = directive.module_path.clone();
955 full_path.push(Segment::from_ident(Ident::invalid()));
956 self.r.lint_if_path_starts_with_module(
957 directive.crate_lint(),
964 if let ModuleOrUniformRoot::Module(module) = module {
965 if module.def_id() == directive.parent_scope.module.def_id() {
966 // Importing a module into itself is not allowed.
967 return Some(UnresolvedImportError {
968 span: directive.span,
969 label: Some(String::from("cannot glob-import a module into itself")),
976 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
977 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
979 "glob import doesn't reexport anything because no candidate is public enough";
980 self.r.lint_buffer.buffer_lint(
981 UNUSED_IMPORTS, directive.id, directive.span, msg,
989 let mut all_ns_err = true;
990 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
991 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
992 let orig_blacklisted_binding =
993 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
994 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
995 let binding = this.resolve_ident_in_module(
996 module, ident, ns, &directive.parent_scope, true, directive.span
998 this.last_import_segment = orig_last_import_segment;
999 this.blacklisted_binding = orig_blacklisted_binding;
1000 directive.vis.set(orig_vis);
1004 // Consistency checks, analogous to `finalize_macro_resolutions`.
1005 let initial_res = source_bindings[ns].get().map(|initial_binding| {
1007 if let Some(target_binding) = target_bindings[ns].get() {
1008 // Note that as_str() de-gensyms the Symbol
1009 if target.name.as_str() == "_" &&
1010 initial_binding.is_extern_crate() && !initial_binding.is_import() {
1011 this.record_use(ident, ns, target_binding,
1012 directive.module_path.is_empty());
1015 initial_binding.res()
1017 let res = binding.res();
1018 if let Ok(initial_res) = initial_res {
1019 if res != initial_res && this.ambiguity_errors.is_empty() {
1020 span_bug!(directive.span, "inconsistent resolution for an import");
1023 if res != Res::Err &&
1024 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
1025 let msg = "cannot determine resolution for the import";
1027 "import resolution is stuck, try simplifying other imports";
1028 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
1033 // FIXME: This assert may fire if public glob is later shadowed by a private
1034 // single import (see test `issue-55884-2.rs`). In theory single imports should
1035 // always block globs, even if they are not yet resolved, so that this kind of
1036 // self-inconsistent resolution never happens.
1037 // Reenable the assert when the issue is fixed.
1038 // assert!(result[ns].get().is_err());
1044 let mut all_ns_failed = true;
1045 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1046 let binding = this.resolve_ident_in_module(
1047 module, ident, ns, &directive.parent_scope, true, directive.span
1049 if binding.is_ok() {
1050 all_ns_failed = false;
1054 return if all_ns_failed {
1055 let resolutions = match module {
1056 ModuleOrUniformRoot::Module(module) =>
1057 Some(self.r.resolutions(module).borrow()),
1060 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1061 let names = resolutions.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1062 if *i == ident { return None; } // Never suggest the same name
1063 match *resolution.borrow() {
1064 NameResolution { binding: Some(name_binding), .. } => {
1065 match name_binding.kind {
1066 NameBindingKind::Import { binding, .. } => {
1067 match binding.kind {
1068 // Never suggest the name that has binding error
1069 // i.e., the name that cannot be previously resolved
1070 NameBindingKind::Res(Res::Err, _) => return None,
1077 NameResolution { ref single_imports, .. }
1078 if single_imports.is_empty() => None,
1083 let lev_suggestion = find_best_match_for_name(names, &ident.as_str(), None)
1085 (vec![(ident.span, suggestion.to_string())],
1086 String::from("a similar name exists in the module"),
1087 Applicability::MaybeIncorrect)
1090 let (suggestion, note) = match self.check_for_module_export_macro(
1091 directive, module, ident,
1093 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1094 _ => (lev_suggestion, Vec::new()),
1097 let label = match module {
1098 ModuleOrUniformRoot::Module(module) => {
1099 let module_str = module_to_string(module);
1100 if let Some(module_str) = module_str {
1101 format!("no `{}` in `{}`", ident, module_str)
1103 format!("no `{}` in the root", ident)
1107 if !ident.is_path_segment_keyword() {
1108 format!("no `{}` external crate", ident)
1110 // HACK(eddyb) this shows up for `self` & `super`, which
1111 // should work instead - for now keep the same error message.
1112 format!("no `{}` in the root", ident)
1117 Some(UnresolvedImportError {
1118 span: directive.span,
1124 // `resolve_ident_in_module` reported a privacy error.
1125 self.r.import_dummy_binding(directive);
1130 let mut reexport_error = None;
1131 let mut any_successful_reexport = false;
1132 self.r.per_ns(|this, ns| {
1133 if let Ok(binding) = source_bindings[ns].get() {
1134 let vis = directive.vis.get();
1135 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1136 reexport_error = Some((ns, binding));
1138 any_successful_reexport = true;
1143 // All namespaces must be re-exported with extra visibility for an error to occur.
1144 if !any_successful_reexport {
1145 let (ns, binding) = reexport_error.unwrap();
1146 if ns == TypeNS && binding.is_extern_crate() {
1147 let msg = format!("extern crate `{}` is private, and cannot be \
1148 re-exported (error E0365), consider declaring with \
1151 self.r.lint_buffer.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1155 } else if ns == TypeNS {
1156 struct_span_err!(self.r.session, directive.span, E0365,
1157 "`{}` is private, and cannot be re-exported", ident)
1158 .span_label(directive.span, format!("re-export of private `{}`", ident))
1159 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1162 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1164 format!("consider marking `{}` as `pub` in the imported module", ident);
1165 struct_span_err!(self.r.session, directive.span, E0364, "{}", &msg)
1166 .span_note(directive.span, ¬e_msg)
1171 if directive.module_path.len() <= 1 {
1172 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1173 // 2 segments, so the `resolve_path` above won't trigger it.
1174 let mut full_path = directive.module_path.clone();
1175 full_path.push(Segment::from_ident(ident));
1176 self.r.per_ns(|this, ns| {
1177 if let Ok(binding) = source_bindings[ns].get() {
1178 this.lint_if_path_starts_with_module(
1179 directive.crate_lint(),
1188 // Record what this import resolves to for later uses in documentation,
1189 // this may resolve to either a value or a type, but for documentation
1190 // purposes it's good enough to just favor one over the other.
1191 self.r.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1192 this.import_res_map.entry(directive.id).or_default()[ns] = Some(binding.res());
1195 self.check_for_redundant_imports(
1203 debug!("(resolving single import) successfully resolved import");
1207 fn check_for_redundant_imports(
1210 directive: &'b ImportDirective<'b>,
1211 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1212 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1215 // Skip if the import was produced by a macro.
1216 if directive.parent_scope.expansion != ExpnId::root() {
1220 // Skip if we are inside a named module (in contrast to an anonymous
1221 // module defined by a block).
1222 if let ModuleKind::Def(..) = directive.parent_scope.module.kind {
1226 let mut is_redundant = PerNS {
1232 let mut redundant_span = PerNS {
1238 self.r.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1239 if binding.res() == Res::Err {
1243 let orig_blacklisted_binding = mem::replace(
1244 &mut this.blacklisted_binding,
1245 target_bindings[ns].get()
1248 match this.early_resolve_ident_in_lexical_scope(
1250 ScopeSet::All(ns, false),
1251 &directive.parent_scope,
1256 Ok(other_binding) => {
1257 is_redundant[ns] = Some(
1258 binding.res() == other_binding.res()
1259 && !other_binding.is_ambiguity()
1261 redundant_span[ns] =
1262 Some((other_binding.span, other_binding.is_import()));
1264 Err(_) => is_redundant[ns] = Some(false)
1267 this.blacklisted_binding = orig_blacklisted_binding;
1270 if !is_redundant.is_empty() &&
1271 is_redundant.present_items().all(|is_redundant| is_redundant)
1273 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1274 redundant_spans.sort();
1275 redundant_spans.dedup();
1276 self.r.lint_buffer.buffer_lint_with_diagnostic(
1280 &format!("the item `{}` is imported redundantly", ident),
1281 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1286 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1287 let module = match directive.imported_module.get().unwrap() {
1288 ModuleOrUniformRoot::Module(module) => module,
1290 self.r.session.span_err(directive.span, "cannot glob-import all possible crates");
1295 if module.is_trait() {
1296 self.r.session.span_err(directive.span, "items in traits are not importable.");
1298 } else if module.def_id() == directive.parent_scope.module.def_id() {
1300 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1301 self.r.prelude = Some(module);
1305 // Add to module's glob_importers
1306 module.glob_importers.borrow_mut().push(directive);
1308 // Ensure that `resolutions` isn't borrowed during `try_define`,
1309 // since it might get updated via a glob cycle.
1310 let bindings = self.r.resolutions(module).borrow().iter().filter_map(|(key, resolution)| {
1311 resolution.borrow().binding().map(|binding| (*key, binding))
1312 }).collect::<Vec<_>>();
1313 for (mut key, binding) in bindings {
1314 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, directive.span) {
1315 Some(Some(def)) => self.r.macro_def_scope(def),
1316 Some(None) => directive.parent_scope.module,
1319 if self.r.is_accessible_from(binding.pseudo_vis(), scope) {
1320 let imported_binding = self.r.import(binding, directive);
1321 let _ = self.r.try_define(directive.parent_scope.module, key, imported_binding);
1325 // Record the destination of this import
1326 self.r.record_partial_res(directive.id, PartialRes::new(module.res().unwrap()));
1329 // Miscellaneous post-processing, including recording re-exports,
1330 // reporting conflicts, and reporting unresolved imports.
1331 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1332 // Since import resolution is finished, globs will not define any more names.
1333 *module.globs.borrow_mut() = Vec::new();
1335 let mut reexports = Vec::new();
1337 module.for_each_child(self.r, |this, ident, ns, binding| {
1338 // Filter away ambiguous imports and anything that has def-site
1340 // FIXME: Implement actual cross-crate hygiene.
1341 let is_good_import = binding.is_import() && !binding.is_ambiguity()
1342 && !ident.span.from_expansion();
1343 if is_good_import || binding.is_macro_def() {
1344 let res = binding.res();
1345 if res != Res::Err {
1346 if let Some(def_id) = res.opt_def_id() {
1347 if !def_id.is_local() {
1348 this.cstore().export_macros_untracked(def_id.krate);
1351 reexports.push(Export {
1360 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1361 if ns == TypeNS && orig_binding.is_variant() &&
1362 !orig_binding.vis.is_at_least(binding.vis, &*this) {
1363 let msg = match directive.subclass {
1364 ImportDirectiveSubclass::SingleImport { .. } => {
1365 format!("variant `{}` is private and cannot be re-exported",
1368 ImportDirectiveSubclass::GlobImport { .. } => {
1369 let msg = "enum is private and its variants \
1370 cannot be re-exported".to_owned();
1371 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1374 let fresh = this.session.one_time_diagnostics
1375 .borrow_mut().insert(error_id);
1381 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1383 let mut err = this.session.struct_span_err(binding.span, &msg);
1385 let imported_module = match directive.imported_module.get() {
1386 Some(ModuleOrUniformRoot::Module(module)) => module,
1387 _ => bug!("module should exist"),
1389 let parent_module = imported_module.parent.expect("parent should exist");
1390 let resolutions = this.resolutions(parent_module).borrow();
1391 let enum_path_segment_index = directive.module_path.len() - 1;
1392 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1394 let key = this.new_key(enum_ident, TypeNS);
1395 let enum_resolution = resolutions.get(&key)
1396 .expect("resolution should exist");
1397 let enum_span = enum_resolution.borrow()
1398 .binding.expect("binding should exist")
1400 let enum_def_span = this.session.source_map().def_span(enum_span);
1401 let enum_def_snippet = this.session.source_map()
1402 .span_to_snippet(enum_def_span).expect("snippet should exist");
1403 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1404 let after_vis_index = enum_def_snippet.find("enum")
1405 .expect("`enum` keyword should exist in snippet");
1406 let suggestion = format!("pub {}",
1407 &enum_def_snippet[after_vis_index..]);
1410 .diag_span_suggestion_once(&mut err,
1411 DiagnosticMessageId::ErrorId(0),
1413 "consider making the enum public",
1420 if reexports.len() > 0 {
1421 if let Some(def_id) = module.def_id() {
1422 self.r.export_map.insert(def_id, reexports);
1428 fn import_path_to_string(names: &[Ident],
1429 subclass: &ImportDirectiveSubclass<'_>,
1430 span: Span) -> String {
1431 let pos = names.iter()
1432 .position(|p| span == p.span && p.name != kw::PathRoot);
1433 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1434 if let Some(pos) = pos {
1435 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1436 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1438 let names = if global { &names[1..] } else { names };
1439 if names.is_empty() {
1440 import_directive_subclass_to_string(subclass)
1444 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1445 import_directive_subclass_to_string(subclass),
1451 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1453 SingleImport { source, .. } => source.to_string(),
1454 GlobImport { .. } => "*".to_string(),
1455 ExternCrate { .. } => "<extern crate>".to_string(),
1456 MacroUse => "#[macro_use]".to_string(),