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};
38 type Res = def::Res<NodeId>;
40 /// Contains data for specific types of import directives.
41 #[derive(Clone, Debug)]
42 pub enum ImportDirectiveSubclass<'a> {
44 /// `source` in `use prefix::source as target`.
46 /// `target` in `use prefix::source as target`.
48 /// Bindings to which `source` refers to.
49 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
50 /// Bindings introduced by `target`.
51 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
52 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
54 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
59 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
60 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
69 /// One import directive.
70 #[derive(Debug, Clone)]
71 crate struct ImportDirective<'a> {
72 /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
74 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
75 /// this id is the ID of the leaf tree. For example:
77 /// ```ignore (pacify the mercilous tidy)
78 /// use foo::bar::{a, b}
81 /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
82 /// for `a` in this field.
85 /// The `id` of the "root" use-kind -- this is always the same as
86 /// `id` except in the case of "nested" use trees, in which case
87 /// it will be the `id` of the root use tree. e.g., in the example
88 /// from `id`, this would be the ID of the `use foo::bar`
92 /// Span of the entire use statement.
95 /// Span of the entire use statement with attributes.
96 pub use_span_with_attributes: Span,
98 /// Did the use statement have any attributes?
99 pub has_attributes: bool,
101 /// Span of this use tree.
104 /// Span of the *root* use tree (see `root_id`).
107 pub parent_scope: ParentScope<'a>,
108 pub module_path: Vec<Segment>,
109 /// The resolution of `module_path`.
110 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
111 pub subclass: ImportDirectiveSubclass<'a>,
112 pub vis: Cell<ty::Visibility>,
113 pub used: Cell<bool>,
116 impl<'a> ImportDirective<'a> {
117 pub fn is_glob(&self) -> bool {
118 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
121 pub fn is_nested(&self) -> bool {
122 match self.subclass {
123 ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
128 crate fn crate_lint(&self) -> CrateLint {
129 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
133 #[derive(Clone, Default, Debug)]
134 /// Records information about the resolution of a name in a namespace of a module.
135 pub struct NameResolution<'a> {
136 /// Single imports that may define the name in the namespace.
137 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
138 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
139 /// The least shadowable known binding for this name, or None if there are no known bindings.
140 pub binding: Option<&'a NameBinding<'a>>,
141 shadowed_glob: Option<&'a NameBinding<'a>>,
144 impl<'a> NameResolution<'a> {
145 // Returns the binding for the name if it is known or None if it not known.
146 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
147 self.binding.and_then(|binding| {
148 if !binding.is_glob_import() ||
149 self.single_imports.is_empty() { Some(binding) } else { None }
153 crate fn add_single_import(&mut self, directive: &'a ImportDirective<'a>) {
154 self.single_imports.insert(PtrKey(directive));
158 impl<'a> Resolver<'a> {
159 crate fn resolve_ident_in_module_unadjusted(
161 module: ModuleOrUniformRoot<'a>,
164 parent_scope: &ParentScope<'a>,
167 ) -> Result<&'a NameBinding<'a>, Determinacy> {
168 self.resolve_ident_in_module_unadjusted_ext(
169 module, ident, ns, parent_scope, false, record_used, path_span
170 ).map_err(|(determinacy, _)| determinacy)
173 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
174 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
175 crate fn resolve_ident_in_module_unadjusted_ext(
177 module: ModuleOrUniformRoot<'a>,
180 parent_scope: &ParentScope<'a>,
181 restricted_shadowing: bool,
184 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
185 let module = match module {
186 ModuleOrUniformRoot::Module(module) => module,
187 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
188 assert!(!restricted_shadowing);
189 let binding = self.early_resolve_ident_in_lexical_scope(
190 ident, ScopeSet::AbsolutePath(ns), parent_scope,
191 record_used, record_used, path_span,
193 return binding.map_err(|determinacy| (determinacy, Weak::No));
195 ModuleOrUniformRoot::ExternPrelude => {
196 assert!(!restricted_shadowing);
197 return if ns != TypeNS {
198 Err((Determined, Weak::No))
199 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
201 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
202 // Macro-expanded `extern crate` items can add names to extern prelude.
203 Err((Undetermined, Weak::No))
205 Err((Determined, Weak::No))
208 ModuleOrUniformRoot::CurrentScope => {
209 assert!(!restricted_shadowing);
211 if ident.name == kw::Crate ||
212 ident.name == kw::DollarCrate {
213 let module = self.resolve_crate_root(ident);
214 let binding = (module, ty::Visibility::Public,
215 module.span, ExpnId::root())
216 .to_name_binding(self.arenas);
218 } else if ident.name == kw::Super ||
219 ident.name == kw::SelfLower {
220 // FIXME: Implement these with renaming requirements so that e.g.
221 // `use super;` doesn't work, but `use super as name;` does.
222 // Fall through here to get an error from `early_resolve_...`.
226 let scopes = ScopeSet::All(ns, true);
227 let binding = self.early_resolve_ident_in_lexical_scope(
228 ident, scopes, parent_scope, record_used, record_used, path_span
230 return binding.map_err(|determinacy| (determinacy, Weak::No));
234 let key = self.new_key(ident, ns);
235 let resolution = self.resolution(module, key)
237 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
239 if let Some(binding) = resolution.binding {
240 if !restricted_shadowing && binding.expansion != ExpnId::root() {
241 if let NameBindingKind::Res(_, true) = binding.kind {
242 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
247 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
248 if let Some(blacklisted_binding) = this.blacklisted_binding {
249 if ptr::eq(binding, blacklisted_binding) {
250 return Err((Determined, Weak::No));
253 // `extern crate` are always usable for backwards compatibility, see issue #37020,
254 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
255 let usable = this.is_accessible_from(binding.vis, parent_scope.module) ||
256 binding.is_extern_crate();
257 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
261 return resolution.binding.and_then(|binding| {
262 // If the primary binding is blacklisted, search further and return the shadowed
263 // glob binding if it exists. What we really want here is having two separate
264 // scopes in a module - one for non-globs and one for globs, but until that's done
265 // use this hack to avoid inconsistent resolution ICEs during import validation.
266 if let Some(blacklisted_binding) = self.blacklisted_binding {
267 if ptr::eq(binding, blacklisted_binding) {
268 return resolution.shadowed_glob;
272 }).ok_or((Determined, Weak::No)).and_then(|binding| {
273 if self.last_import_segment && check_usable(self, binding).is_err() {
274 Err((Determined, Weak::No))
276 self.record_use(ident, ns, binding, restricted_shadowing);
278 if let Some(shadowed_glob) = resolution.shadowed_glob {
279 // Forbid expanded shadowing to avoid time travel.
280 if restricted_shadowing &&
281 binding.expansion != ExpnId::root() &&
282 binding.res() != shadowed_glob.res() {
283 self.ambiguity_errors.push(AmbiguityError {
284 kind: AmbiguityKind::GlobVsExpanded,
288 misc1: AmbiguityErrorMisc::None,
289 misc2: AmbiguityErrorMisc::None,
294 if !self.is_accessible_from(binding.vis, parent_scope.module) &&
295 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
296 !(self.last_import_segment && binding.is_extern_crate()) {
297 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
305 // Items and single imports are not shadowable, if we have one, then it's determined.
306 if let Some(binding) = resolution.binding {
307 if !binding.is_glob_import() {
308 return check_usable(self, binding);
312 // --- From now on we either have a glob resolution or no resolution. ---
314 // Check if one of single imports can still define the name,
315 // if it can then our result is not determined and can be invalidated.
316 for single_import in &resolution.single_imports {
317 if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
320 let module = unwrap_or!(single_import.imported_module.get(),
321 return Err((Undetermined, Weak::No)));
322 let ident = match single_import.subclass {
323 SingleImport { source, .. } => source,
326 match self.resolve_ident_in_module(module, ident, ns, &single_import.parent_scope,
328 Err(Determined) => continue,
329 Ok(binding) if !self.is_accessible_from(
330 binding.vis, single_import.parent_scope.module
332 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
336 // So we have a resolution that's from a glob import. This resolution is determined
337 // if it cannot be shadowed by some new item/import expanded from a macro.
338 // This happens either if there are no unexpanded macros, or expanded names cannot
339 // shadow globs (that happens in macro namespace or with restricted shadowing).
341 // Additionally, any macro in any module can plant names in the root module if it creates
342 // `macro_export` macros, so the root module effectively has unresolved invocations if any
343 // module has unresolved invocations.
344 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
345 // progress, we have to ignore those potential unresolved invocations from other modules
346 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
347 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
348 let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
349 if let Some(binding) = resolution.binding {
350 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
351 return check_usable(self, binding);
353 return Err((Undetermined, Weak::No));
357 // --- From now on we have no resolution. ---
359 // Now we are in situation when new item/import can appear only from a glob or a macro
360 // expansion. With restricted shadowing names from globs and macro expansions cannot
361 // shadow names from outer scopes, so we can freely fallback from module search to search
362 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
363 // scopes we return `Undetermined` with `Weak::Yes`.
365 // Check if one of unexpanded macros can still define the name,
366 // if it can then our "no resolution" result is not determined and can be invalidated.
367 if unexpanded_macros {
368 return Err((Undetermined, Weak::Yes));
371 // Check if one of glob imports can still define the name,
372 // if it can then our "no resolution" result is not determined and can be invalidated.
373 for glob_import in module.globs.borrow().iter() {
374 if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
377 let module = match glob_import.imported_module.get() {
378 Some(ModuleOrUniformRoot::Module(module)) => module,
380 None => return Err((Undetermined, Weak::Yes)),
382 let tmp_parent_scope;
383 let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident.modern());
384 match ident.span.glob_adjust(module.expansion, glob_import.span) {
387 ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
388 adjusted_parent_scope = &tmp_parent_scope;
393 let result = self.resolve_ident_in_module_unadjusted(
394 ModuleOrUniformRoot::Module(module),
397 adjusted_parent_scope,
403 Err(Determined) => continue,
404 Ok(binding) if !self.is_accessible_from(
405 binding.vis, glob_import.parent_scope.module
407 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
411 // No resolution and no one else can define the name - determinate error.
412 Err((Determined, Weak::No))
415 // Given a binding and an import directive that resolves to it,
416 // return the corresponding binding defined by the import directive.
417 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
418 -> &'a NameBinding<'a> {
419 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
420 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
421 !directive.is_glob() && binding.is_extern_crate() {
427 if let GlobImport { ref max_vis, .. } = directive.subclass {
428 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
433 self.arenas.alloc_name_binding(NameBinding {
434 kind: NameBindingKind::Import {
437 used: Cell::new(false),
440 span: directive.span,
442 expansion: directive.parent_scope.expansion,
446 // Define the name or return the existing binding if there is a collision.
451 binding: &'a NameBinding<'a>,
452 ) -> Result<(), &'a NameBinding<'a>> {
453 let res = binding.res();
454 self.check_reserved_macro_name(key.ident, res);
455 self.set_binding_parent_module(binding, module);
456 self.update_resolution(module, key, |this, resolution| {
457 if let Some(old_binding) = resolution.binding {
459 // Do not override real bindings with `Res::Err`s from error recovery.
462 match (old_binding.is_glob_import(), binding.is_glob_import()) {
464 if res != old_binding.res() {
465 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
466 old_binding, binding));
467 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
468 // We are glob-importing the same item but with greater visibility.
469 resolution.binding = Some(binding);
472 (old_glob @ true, false) | (old_glob @ false, true) => {
473 let (glob_binding, nonglob_binding) = if old_glob {
474 (old_binding, binding)
476 (binding, old_binding)
478 if glob_binding.res() != nonglob_binding.res()
479 && key.ns == MacroNS && nonglob_binding.expansion != ExpnId::root()
481 resolution.binding = Some(this.ambiguity(
482 AmbiguityKind::GlobVsExpanded,
487 resolution.binding = Some(nonglob_binding);
489 resolution.shadowed_glob = Some(glob_binding);
492 if let (&NameBindingKind::Res(_, true), &NameBindingKind::Res(_, true)) =
493 (&old_binding.kind, &binding.kind) {
495 this.session.struct_span_err(
497 &format!("a macro named `{}` has already been exported", key.ident),
499 .span_label(binding.span, format!("`{}` already exported", key.ident))
500 .span_note(old_binding.span, "previous macro export is now shadowed")
503 resolution.binding = Some(binding);
505 return Err(old_binding);
510 resolution.binding = Some(binding);
518 &self, kind: AmbiguityKind,
519 primary_binding: &'a NameBinding<'a>,
520 secondary_binding: &'a NameBinding<'a>,
521 ) -> &'a NameBinding<'a> {
522 self.arenas.alloc_name_binding(NameBinding {
523 ambiguity: Some((secondary_binding, kind)),
524 ..primary_binding.clone()
528 // Use `f` to mutate the resolution of the name in the module.
529 // If the resolution becomes a success, define it in the module's glob importers.
530 fn update_resolution<T, F>(
536 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
538 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
539 // during which the resolution might end up getting re-defined via a glob cycle.
541 let resolution = &mut *self.resolution(module, key).borrow_mut();
542 let old_binding = resolution.binding();
544 let t = f(self, resolution);
546 match resolution.binding() {
547 _ if old_binding.is_some() => return t,
549 Some(binding) => match old_binding {
550 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
556 // Define `binding` in `module`s glob importers.
557 for directive in module.glob_importers.borrow_mut().iter() {
558 let mut ident = key.ident;
559 let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
560 Some(Some(def)) => self.macro_def_scope(def),
561 Some(None) => directive.parent_scope.module,
564 if self.is_accessible_from(binding.vis, scope) {
565 let imported_binding = self.import(binding, directive);
566 let key = BindingKey { ident, ..key };
567 let _ = self.try_define(directive.parent_scope.module, key, imported_binding);
574 // Define a "dummy" resolution containing a Res::Err as a placeholder for a
576 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
577 if let SingleImport { target, .. } = directive.subclass {
578 let dummy_binding = self.dummy_binding;
579 let dummy_binding = self.import(dummy_binding, directive);
580 self.per_ns(|this, ns| {
581 let key = this.new_key(target, ns);
582 let _ = this.try_define(directive.parent_scope.module, key, dummy_binding);
583 // Consider erroneous imports used to avoid duplicate diagnostics.
584 this.record_use(target, ns, dummy_binding, false);
590 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
591 /// import errors within the same use tree into a single diagnostic.
592 #[derive(Debug, Clone)]
593 struct UnresolvedImportError {
595 label: Option<String>,
597 suggestion: Option<Suggestion>,
600 pub struct ImportResolver<'a, 'b> {
601 pub r: &'a mut Resolver<'b>,
604 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
605 fn parent(self, id: DefId) -> Option<DefId> {
610 impl<'a, 'b> ImportResolver<'a, 'b> {
613 // This is a fixed-point algorithm. We resolve imports until our efforts
614 // are stymied by an unresolved import; then we bail out of the current
615 // module and continue. We terminate successfully once no more imports
616 // remain or unsuccessfully when no forward progress in resolving imports
619 /// Resolves all imports for the crate. This method performs the fixed-
621 pub fn resolve_imports(&mut self) {
622 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
623 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
624 prev_num_indeterminates = self.r.indeterminate_imports.len();
625 for import in mem::take(&mut self.r.indeterminate_imports) {
626 match self.resolve_import(&import) {
627 true => self.r.determined_imports.push(import),
628 false => self.r.indeterminate_imports.push(import),
634 pub fn finalize_imports(&mut self) {
635 for module in self.r.arenas.local_modules().iter() {
636 self.finalize_resolutions_in(module);
639 let mut seen_spans = FxHashSet::default();
640 let mut errors = vec![];
641 let mut prev_root_id: NodeId = NodeId::from_u32(0);
642 let determined_imports = mem::take(&mut self.r.determined_imports);
643 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
645 for (is_indeterminate, import) in determined_imports
648 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
650 if let Some(err) = self.finalize_import(import) {
652 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
653 if source.name == kw::SelfLower {
654 // Silence `unresolved import` error if E0429 is already emitted
655 if let Err(Determined) = source_bindings.value_ns.get() {
661 // If the error is a single failed import then create a "fake" import
662 // resolution for it so that later resolve stages won't complain.
663 self.r.import_dummy_binding(import);
664 if prev_root_id.as_u32() != 0
665 && prev_root_id.as_u32() != import.root_id.as_u32()
666 && !errors.is_empty() {
667 // In the case of a new import line, throw a diagnostic message
668 // for the previous line.
669 self.throw_unresolved_import_error(errors, None);
672 if seen_spans.insert(err.span) {
673 let path = import_path_to_string(
674 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
678 errors.push((path, err));
679 prev_root_id = import.root_id;
681 } else if is_indeterminate {
682 // Consider erroneous imports used to avoid duplicate diagnostics.
683 self.r.used_imports.insert((import.id, TypeNS));
684 let path = import_path_to_string(
685 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
689 let err = UnresolvedImportError {
695 errors.push((path, err));
699 if !errors.is_empty() {
700 self.throw_unresolved_import_error(errors.clone(), None);
704 fn throw_unresolved_import_error(
706 errors: Vec<(String, UnresolvedImportError)>,
707 span: Option<MultiSpan>,
709 /// Upper limit on the number of `span_label` messages.
710 const MAX_LABEL_COUNT: usize = 10;
712 let (span, msg) = if errors.is_empty() {
713 (span.unwrap(), "unresolved import".to_string())
715 let span = MultiSpan::from_spans(
718 .map(|(_, err)| err.span)
724 .map(|(path, _)| format!("`{}`", path))
725 .collect::<Vec<_>>();
728 "unresolved import{} {}",
729 pluralize!(paths.len()),
736 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
738 if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
739 for message in note {
744 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
745 if let Some(label) = err.label {
746 diag.span_label(err.span, label);
749 if let Some((suggestions, msg, applicability)) = err.suggestion {
750 diag.multipart_suggestion(&msg, suggestions, applicability);
757 /// Attempts to resolve the given import, returning true if its resolution is determined.
758 /// If successful, the resolved bindings are written into the module.
759 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
761 "(resolving import for module) resolving import `{}::...` in `{}`",
762 Segment::names_to_string(&directive.module_path),
763 module_to_string(directive.parent_scope.module).unwrap_or_else(|| "???".to_string()),
766 let module = if let Some(module) = directive.imported_module.get() {
769 // For better failure detection, pretend that the import will
770 // not define any names while resolving its module path.
771 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
772 let path_res = self.r.resolve_path(
773 &directive.module_path,
775 &directive.parent_scope,
778 directive.crate_lint(),
780 directive.vis.set(orig_vis);
783 PathResult::Module(module) => module,
784 PathResult::Indeterminate => return false,
785 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
789 directive.imported_module.set(Some(module));
790 let (source, target, source_bindings, target_bindings, type_ns_only) =
791 match directive.subclass {
792 SingleImport { source, target, ref source_bindings,
793 ref target_bindings, type_ns_only, .. } =>
794 (source, target, source_bindings, target_bindings, type_ns_only),
795 GlobImport { .. } => {
796 self.resolve_glob_import(directive);
802 let mut indeterminate = false;
803 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
804 if let Err(Undetermined) = source_bindings[ns].get() {
805 // For better failure detection, pretend that the import will
806 // not define any names while resolving its module path.
807 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
808 let binding = this.resolve_ident_in_module(
809 module, source, ns, &directive.parent_scope, false, directive.span
811 directive.vis.set(orig_vis);
813 source_bindings[ns].set(binding);
818 let parent = directive.parent_scope.module;
819 match source_bindings[ns].get() {
820 Err(Undetermined) => indeterminate = true,
821 // Don't update the resolution, because it was never added.
822 Err(Determined) if target.name == kw::Underscore => {}
824 let key = this.new_key(target, ns);
825 this.update_resolution(parent, key, |_, resolution| {
826 resolution.single_imports.remove(&PtrKey(directive));
829 Ok(binding) if !binding.is_importable() => {
830 let msg = format!("`{}` is not directly importable", target);
831 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
832 .span_label(directive.span, "cannot be imported directly")
834 // Do not import this illegal binding. Import a dummy binding and pretend
835 // everything is fine
836 this.import_dummy_binding(directive);
839 let imported_binding = this.import(binding, directive);
840 target_bindings[ns].set(Some(imported_binding));
841 this.define(parent, target, ns, imported_binding);
849 /// Performs final import resolution, consistency checks and error reporting.
851 /// Optionally returns an unresolved import error. This error is buffered and used to
852 /// consolidate multiple unresolved import errors into a single diagnostic.
855 directive: &'b ImportDirective<'b>
856 ) -> Option<UnresolvedImportError> {
857 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
858 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
859 let path_res = self.r.resolve_path(
860 &directive.module_path,
862 &directive.parent_scope,
865 directive.crate_lint(),
867 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
868 directive.vis.set(orig_vis);
869 if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
870 // Consider erroneous imports used to avoid duplicate diagnostics.
871 self.r.used_imports.insert((directive.id, TypeNS));
873 let module = match path_res {
874 PathResult::Module(module) => {
875 // Consistency checks, analogous to `finalize_macro_resolutions`.
876 if let Some(initial_module) = directive.imported_module.get() {
877 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
878 span_bug!(directive.span, "inconsistent resolution for an import");
881 if self.r.privacy_errors.is_empty() {
882 let msg = "cannot determine resolution for the import";
883 let msg_note = "import resolution is stuck, try simplifying other imports";
884 self.r.session.struct_span_err(directive.span, msg).note(msg_note).emit();
890 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
892 assert!(directive.imported_module.get().is_none());
893 self.r.report_error(span, ResolutionError::FailedToResolve {
900 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
902 assert!(directive.imported_module.get().is_none());
903 let err = match self.make_path_suggestion(
905 directive.module_path.clone(),
906 &directive.parent_scope,
908 Some((suggestion, note)) => {
909 UnresolvedImportError {
914 vec![(span, Segment::names_to_string(&suggestion))],
915 String::from("a similar path exists"),
916 Applicability::MaybeIncorrect,
921 UnresolvedImportError {
933 PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
935 assert!(directive.imported_module.get().is_none());
937 // The error was already reported earlier.
940 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
943 let (ident, target, source_bindings, target_bindings, type_ns_only) =
944 match directive.subclass {
945 SingleImport { source, target, ref source_bindings,
946 ref target_bindings, type_ns_only, .. } =>
947 (source, target, source_bindings, target_bindings, type_ns_only),
948 GlobImport { is_prelude, ref max_vis } => {
949 if directive.module_path.len() <= 1 {
950 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
951 // 2 segments, so the `resolve_path` above won't trigger it.
952 let mut full_path = directive.module_path.clone();
953 full_path.push(Segment::from_ident(Ident::invalid()));
954 self.r.lint_if_path_starts_with_module(
955 directive.crate_lint(),
962 if let ModuleOrUniformRoot::Module(module) = module {
963 if module.def_id() == directive.parent_scope.module.def_id() {
964 // Importing a module into itself is not allowed.
965 return Some(UnresolvedImportError {
966 span: directive.span,
967 label: Some(String::from("cannot glob-import a module into itself")),
974 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
975 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
977 "glob import doesn't reexport anything because no candidate is public enough";
978 self.r.lint_buffer.buffer_lint(
979 UNUSED_IMPORTS, directive.id, directive.span, msg,
987 let mut all_ns_err = true;
988 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
989 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
990 let orig_blacklisted_binding =
991 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
992 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
993 let binding = this.resolve_ident_in_module(
994 module, ident, ns, &directive.parent_scope, true, directive.span
996 this.last_import_segment = orig_last_import_segment;
997 this.blacklisted_binding = orig_blacklisted_binding;
998 directive.vis.set(orig_vis);
1002 // Consistency checks, analogous to `finalize_macro_resolutions`.
1003 let initial_res = source_bindings[ns].get().map(|initial_binding| {
1005 if let Some(target_binding) = target_bindings[ns].get() {
1006 // Note that as_str() de-gensyms the Symbol
1007 if target.name.as_str() == "_" &&
1008 initial_binding.is_extern_crate() && !initial_binding.is_import() {
1009 this.record_use(ident, ns, target_binding,
1010 directive.module_path.is_empty());
1013 initial_binding.res()
1015 let res = binding.res();
1016 if let Ok(initial_res) = initial_res {
1017 if res != initial_res && this.ambiguity_errors.is_empty() {
1018 span_bug!(directive.span, "inconsistent resolution for an import");
1021 if res != Res::Err &&
1022 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
1023 let msg = "cannot determine resolution for the import";
1025 "import resolution is stuck, try simplifying other imports";
1026 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
1031 // FIXME: This assert may fire if public glob is later shadowed by a private
1032 // single import (see test `issue-55884-2.rs`). In theory single imports should
1033 // always block globs, even if they are not yet resolved, so that this kind of
1034 // self-inconsistent resolution never happens.
1035 // Reenable the assert when the issue is fixed.
1036 // assert!(result[ns].get().is_err());
1042 let mut all_ns_failed = true;
1043 self.r.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1044 let binding = this.resolve_ident_in_module(
1045 module, ident, ns, &directive.parent_scope, true, directive.span
1047 if binding.is_ok() {
1048 all_ns_failed = false;
1052 return if all_ns_failed {
1053 let resolutions = match module {
1054 ModuleOrUniformRoot::Module(module) =>
1055 Some(self.r.resolutions(module).borrow()),
1058 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1059 let names = resolutions.filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1060 if *i == ident { return None; } // Never suggest the same name
1061 match *resolution.borrow() {
1062 NameResolution { binding: Some(name_binding), .. } => {
1063 match name_binding.kind {
1064 NameBindingKind::Import { binding, .. } => {
1065 match binding.kind {
1066 // Never suggest the name that has binding error
1067 // i.e., the name that cannot be previously resolved
1068 NameBindingKind::Res(Res::Err, _) => return None,
1075 NameResolution { ref single_imports, .. }
1076 if single_imports.is_empty() => None,
1081 let lev_suggestion = find_best_match_for_name(names, &ident.as_str(), None)
1083 (vec![(ident.span, suggestion.to_string())],
1084 String::from("a similar name exists in the module"),
1085 Applicability::MaybeIncorrect)
1088 let (suggestion, note) = match self.check_for_module_export_macro(
1089 directive, module, ident,
1091 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1092 _ => (lev_suggestion, Vec::new()),
1095 let label = match module {
1096 ModuleOrUniformRoot::Module(module) => {
1097 let module_str = module_to_string(module);
1098 if let Some(module_str) = module_str {
1099 format!("no `{}` in `{}`", ident, module_str)
1101 format!("no `{}` in the root", ident)
1105 if !ident.is_path_segment_keyword() {
1106 format!("no `{}` external crate", ident)
1108 // HACK(eddyb) this shows up for `self` & `super`, which
1109 // should work instead - for now keep the same error message.
1110 format!("no `{}` in the root", ident)
1115 Some(UnresolvedImportError {
1116 span: directive.span,
1122 // `resolve_ident_in_module` reported a privacy error.
1123 self.r.import_dummy_binding(directive);
1128 let mut reexport_error = None;
1129 let mut any_successful_reexport = false;
1130 self.r.per_ns(|this, ns| {
1131 if let Ok(binding) = source_bindings[ns].get() {
1132 let vis = directive.vis.get();
1133 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1134 reexport_error = Some((ns, binding));
1136 any_successful_reexport = true;
1141 // All namespaces must be re-exported with extra visibility for an error to occur.
1142 if !any_successful_reexport {
1143 let (ns, binding) = reexport_error.unwrap();
1144 if ns == TypeNS && binding.is_extern_crate() {
1145 let msg = format!("extern crate `{}` is private, and cannot be \
1146 re-exported (error E0365), consider declaring with \
1149 self.r.lint_buffer.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1153 } else if ns == TypeNS {
1154 struct_span_err!(self.r.session, directive.span, E0365,
1155 "`{}` is private, and cannot be re-exported", ident)
1156 .span_label(directive.span, format!("re-export of private `{}`", ident))
1157 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1160 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1162 format!("consider marking `{}` as `pub` in the imported module", ident);
1163 struct_span_err!(self.r.session, directive.span, E0364, "{}", &msg)
1164 .span_note(directive.span, ¬e_msg)
1169 if directive.module_path.len() <= 1 {
1170 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1171 // 2 segments, so the `resolve_path` above won't trigger it.
1172 let mut full_path = directive.module_path.clone();
1173 full_path.push(Segment::from_ident(ident));
1174 self.r.per_ns(|this, ns| {
1175 if let Ok(binding) = source_bindings[ns].get() {
1176 this.lint_if_path_starts_with_module(
1177 directive.crate_lint(),
1186 // Record what this import resolves to for later uses in documentation,
1187 // this may resolve to either a value or a type, but for documentation
1188 // purposes it's good enough to just favor one over the other.
1189 self.r.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1190 this.import_res_map.entry(directive.id).or_default()[ns] = Some(binding.res());
1193 self.check_for_redundant_imports(
1201 debug!("(resolving single import) successfully resolved import");
1205 fn check_for_redundant_imports(
1208 directive: &'b ImportDirective<'b>,
1209 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1210 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1213 // Skip if the import was produced by a macro.
1214 if directive.parent_scope.expansion != ExpnId::root() {
1218 // Skip if we are inside a named module (in contrast to an anonymous
1219 // module defined by a block).
1220 if let ModuleKind::Def(..) = directive.parent_scope.module.kind {
1224 let mut is_redundant = PerNS {
1230 let mut redundant_span = PerNS {
1236 self.r.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1237 if binding.res() == Res::Err {
1241 let orig_blacklisted_binding = mem::replace(
1242 &mut this.blacklisted_binding,
1243 target_bindings[ns].get()
1246 match this.early_resolve_ident_in_lexical_scope(
1248 ScopeSet::All(ns, false),
1249 &directive.parent_scope,
1254 Ok(other_binding) => {
1255 is_redundant[ns] = Some(
1256 binding.res() == other_binding.res()
1257 && !other_binding.is_ambiguity()
1259 redundant_span[ns] =
1260 Some((other_binding.span, other_binding.is_import()));
1262 Err(_) => is_redundant[ns] = Some(false)
1265 this.blacklisted_binding = orig_blacklisted_binding;
1268 if !is_redundant.is_empty() &&
1269 is_redundant.present_items().all(|is_redundant| is_redundant)
1271 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1272 redundant_spans.sort();
1273 redundant_spans.dedup();
1274 self.r.lint_buffer.buffer_lint_with_diagnostic(
1278 &format!("the item `{}` is imported redundantly", ident),
1279 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1284 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1285 let module = match directive.imported_module.get().unwrap() {
1286 ModuleOrUniformRoot::Module(module) => module,
1288 self.r.session.span_err(directive.span, "cannot glob-import all possible crates");
1293 if module.is_trait() {
1294 self.r.session.span_err(directive.span, "items in traits are not importable.");
1296 } else if module.def_id() == directive.parent_scope.module.def_id() {
1298 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1299 self.r.prelude = Some(module);
1303 // Add to module's glob_importers
1304 module.glob_importers.borrow_mut().push(directive);
1306 // Ensure that `resolutions` isn't borrowed during `try_define`,
1307 // since it might get updated via a glob cycle.
1308 let bindings = self.r.resolutions(module).borrow().iter().filter_map(|(key, resolution)| {
1309 resolution.borrow().binding().map(|binding| (*key, binding))
1310 }).collect::<Vec<_>>();
1311 for (mut key, binding) in bindings {
1312 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, directive.span) {
1313 Some(Some(def)) => self.r.macro_def_scope(def),
1314 Some(None) => directive.parent_scope.module,
1317 if self.r.is_accessible_from(binding.pseudo_vis(), scope) {
1318 let imported_binding = self.r.import(binding, directive);
1319 let _ = self.r.try_define(directive.parent_scope.module, key, imported_binding);
1323 // Record the destination of this import
1324 self.r.record_partial_res(directive.id, PartialRes::new(module.res().unwrap()));
1327 // Miscellaneous post-processing, including recording re-exports,
1328 // reporting conflicts, and reporting unresolved imports.
1329 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1330 // Since import resolution is finished, globs will not define any more names.
1331 *module.globs.borrow_mut() = Vec::new();
1333 let mut reexports = Vec::new();
1335 module.for_each_child(self.r, |this, ident, ns, binding| {
1336 // Filter away ambiguous imports and anything that has def-site
1338 // FIXME: Implement actual cross-crate hygiene.
1339 let is_good_import = binding.is_import() && !binding.is_ambiguity()
1340 && !ident.span.from_expansion();
1341 if is_good_import || binding.is_macro_def() {
1342 let res = binding.res();
1343 if res != Res::Err {
1344 if let Some(def_id) = res.opt_def_id() {
1345 if !def_id.is_local() {
1346 this.cstore().export_macros_untracked(def_id.krate);
1349 reexports.push(Export {
1358 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1359 if ns == TypeNS && orig_binding.is_variant() &&
1360 !orig_binding.vis.is_at_least(binding.vis, &*this) {
1361 let msg = match directive.subclass {
1362 ImportDirectiveSubclass::SingleImport { .. } => {
1363 format!("variant `{}` is private and cannot be re-exported",
1366 ImportDirectiveSubclass::GlobImport { .. } => {
1367 let msg = "enum is private and its variants \
1368 cannot be re-exported".to_owned();
1369 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1372 let fresh = this.session.one_time_diagnostics
1373 .borrow_mut().insert(error_id);
1379 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1381 let mut err = this.session.struct_span_err(binding.span, &msg);
1383 let imported_module = match directive.imported_module.get() {
1384 Some(ModuleOrUniformRoot::Module(module)) => module,
1385 _ => bug!("module should exist"),
1387 let parent_module = imported_module.parent.expect("parent should exist");
1388 let resolutions = this.resolutions(parent_module).borrow();
1389 let enum_path_segment_index = directive.module_path.len() - 1;
1390 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1392 let key = this.new_key(enum_ident, TypeNS);
1393 let enum_resolution = resolutions.get(&key)
1394 .expect("resolution should exist");
1395 let enum_span = enum_resolution.borrow()
1396 .binding.expect("binding should exist")
1398 let enum_def_span = this.session.source_map().def_span(enum_span);
1399 let enum_def_snippet = this.session.source_map()
1400 .span_to_snippet(enum_def_span).expect("snippet should exist");
1401 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1402 let after_vis_index = enum_def_snippet.find("enum")
1403 .expect("`enum` keyword should exist in snippet");
1404 let suggestion = format!("pub {}",
1405 &enum_def_snippet[after_vis_index..]);
1408 .diag_span_suggestion_once(&mut err,
1409 DiagnosticMessageId::ErrorId(0),
1411 "consider making the enum public",
1418 if reexports.len() > 0 {
1419 if let Some(def_id) = module.def_id() {
1420 self.r.export_map.insert(def_id, reexports);
1426 fn import_path_to_string(names: &[Ident],
1427 subclass: &ImportDirectiveSubclass<'_>,
1428 span: Span) -> String {
1429 let pos = names.iter()
1430 .position(|p| span == p.span && p.name != kw::PathRoot);
1431 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1432 if let Some(pos) = pos {
1433 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1434 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1436 let names = if global { &names[1..] } else { names };
1437 if names.is_empty() {
1438 import_directive_subclass_to_string(subclass)
1442 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1443 import_directive_subclass_to_string(subclass),
1449 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1451 SingleImport { source, .. } => source.to_string(),
1452 GlobImport { .. } => "*".to_string(),
1453 ExternCrate { .. } => "<extern crate>".to_string(),
1454 MacroUse => "#[macro_use]".to_string(),