1 use self::ImportDirectiveSubclass::*;
3 use {AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
4 use {CrateLint, Module, ModuleOrUniformRoot, PerNS, ScopeSet, Weak};
5 use Namespace::{self, TypeNS, MacroNS};
6 use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
7 use {Resolver, Segment};
8 use {names_to_string, module_to_string};
9 use {resolve_error, ResolutionError};
10 use macros::ParentScope;
12 use rustc_data_structures::ptr_key::PtrKey;
14 use rustc::lint::builtin::BuiltinLintDiagnostics;
15 use rustc::lint::builtin::{DUPLICATE_MACRO_EXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE};
16 use rustc::hir::def_id::{CrateNum, DefId};
17 use rustc::hir::def::*;
18 use rustc::session::DiagnosticMessageId;
19 use rustc::util::nodemap::FxHashSet;
21 use syntax::ast::{Ident, Name, NodeId, CRATE_NODE_ID};
22 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
23 use syntax::ext::hygiene::Mark;
24 use syntax::symbol::keywords;
25 use syntax::util::lev_distance::find_best_match_for_name;
26 use syntax_pos::{MultiSpan, Span};
28 use std::cell::{Cell, RefCell};
31 /// Contains data for specific types of import directives.
32 #[derive(Clone, Debug)]
33 pub enum ImportDirectiveSubclass<'a> {
35 /// `source` in `use prefix::source as target`.
37 /// `target` in `use prefix::source as target`.
39 /// Bindings to which `source` refers to.
40 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
41 /// Bindings introduced by `target`.
42 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
43 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
48 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
49 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
58 /// One import directive.
59 #[derive(Debug,Clone)]
60 crate struct ImportDirective<'a> {
61 /// The id of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
63 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
64 /// this id is the id of the leaf tree. For example:
66 /// ```ignore (pacify the mercilous tidy)
67 /// use foo::bar::{a, b}
70 /// If this is the import directive for `foo::bar::a`, we would have the id of the `UseTree`
71 /// for `a` in this field.
74 /// The `id` of the "root" use-kind -- this is always the same as
75 /// `id` except in the case of "nested" use trees, in which case
76 /// it will be the `id` of the root use tree. e.g., in the example
77 /// from `id`, this would be the id of the `use foo::bar`
81 /// Span of this use tree.
84 /// Span of the *root* use tree (see `root_id`).
87 pub parent_scope: ParentScope<'a>,
88 pub module_path: Vec<Segment>,
89 /// The resolution of `module_path`.
90 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
91 pub subclass: ImportDirectiveSubclass<'a>,
92 pub vis: Cell<ty::Visibility>,
96 impl<'a> ImportDirective<'a> {
97 pub fn is_glob(&self) -> bool {
98 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
101 crate fn crate_lint(&self) -> CrateLint {
102 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
106 #[derive(Clone, Default, Debug)]
107 /// Records information about the resolution of a name in a namespace of a module.
108 pub struct NameResolution<'a> {
109 /// Single imports that may define the name in the namespace.
110 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
111 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
112 /// The least shadowable known binding for this name, or None if there are no known bindings.
113 pub binding: Option<&'a NameBinding<'a>>,
114 shadowed_glob: Option<&'a NameBinding<'a>>,
117 impl<'a> NameResolution<'a> {
118 // Returns the binding for the name if it is known or None if it not known.
119 fn binding(&self) -> Option<&'a NameBinding<'a>> {
120 self.binding.and_then(|binding| {
121 if !binding.is_glob_import() ||
122 self.single_imports.is_empty() { Some(binding) } else { None }
127 impl<'a> Resolver<'a> {
128 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
129 -> &'a RefCell<NameResolution<'a>> {
130 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
131 .or_insert_with(|| self.arenas.alloc_name_resolution())
134 crate fn resolve_ident_in_module_unadjusted(
136 module: ModuleOrUniformRoot<'a>,
141 ) -> Result<&'a NameBinding<'a>, Determinacy> {
142 self.resolve_ident_in_module_unadjusted_ext(
143 module, ident, ns, None, false, record_used, path_span
144 ).map_err(|(determinacy, _)| determinacy)
147 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
148 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
149 crate fn resolve_ident_in_module_unadjusted_ext(
151 module: ModuleOrUniformRoot<'a>,
154 parent_scope: Option<&ParentScope<'a>>,
155 restricted_shadowing: bool,
158 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
159 let module = match module {
160 ModuleOrUniformRoot::Module(module) => module,
161 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
162 assert!(!restricted_shadowing);
163 let parent_scope = self.dummy_parent_scope();
164 let binding = self.early_resolve_ident_in_lexical_scope(
165 ident, ScopeSet::AbsolutePath(ns), &parent_scope,
166 record_used, record_used, path_span,
168 return binding.map_err(|determinacy| (determinacy, Weak::No));
170 ModuleOrUniformRoot::ExternPrelude => {
171 assert!(!restricted_shadowing);
172 return if ns != TypeNS {
173 Err((Determined, Weak::No))
174 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
176 } else if !self.graph_root.unresolved_invocations.borrow().is_empty() {
177 // Macro-expanded `extern crate` items can add names to extern prelude.
178 Err((Undetermined, Weak::No))
180 Err((Determined, Weak::No))
183 ModuleOrUniformRoot::CurrentScope => {
184 assert!(!restricted_shadowing);
186 parent_scope.expect("no parent scope for a single-segment import");
189 if ident.name == keywords::Crate.name() ||
190 ident.name == keywords::DollarCrate.name() {
191 let module = self.resolve_crate_root(ident);
192 let binding = (module, ty::Visibility::Public,
193 module.span, Mark::root())
194 .to_name_binding(self.arenas);
196 } else if ident.name == keywords::Super.name() ||
197 ident.name == keywords::SelfLower.name() {
198 // FIXME: Implement these with renaming requirements so that e.g.
199 // `use super;` doesn't work, but `use super as name;` does.
200 // Fall through here to get an error from `early_resolve_...`.
204 let binding = self.early_resolve_ident_in_lexical_scope(
205 ident, ScopeSet::Import(ns), parent_scope, record_used, record_used, path_span
207 return binding.map_err(|determinacy| (determinacy, Weak::No));
211 self.populate_module_if_necessary(module);
213 let resolution = self.resolution(module, ident, ns)
215 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
217 if let Some(binding) = resolution.binding {
218 if !restricted_shadowing && binding.expansion != Mark::root() {
219 if let NameBindingKind::Def(_, true) = binding.kind {
220 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
225 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
226 if let Some(blacklisted_binding) = this.blacklisted_binding {
227 if ptr::eq(binding, blacklisted_binding) {
228 return Err((Determined, Weak::No));
231 // `extern crate` are always usable for backwards compatibility, see issue #37020,
232 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
233 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
234 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
238 return resolution.binding.and_then(|binding| {
239 // If the primary binding is blacklisted, search further and return the shadowed
240 // glob binding if it exists. What we really want here is having two separate
241 // scopes in a module - one for non-globs and one for globs, but until that's done
242 // use this hack to avoid inconsistent resolution ICEs during import validation.
243 if let Some(blacklisted_binding) = self.blacklisted_binding {
244 if ptr::eq(binding, blacklisted_binding) {
245 return resolution.shadowed_glob;
249 }).ok_or((Determined, Weak::No)).and_then(|binding| {
250 if self.last_import_segment && check_usable(self, binding).is_err() {
251 Err((Determined, Weak::No))
253 self.record_use(ident, ns, binding, restricted_shadowing);
255 if let Some(shadowed_glob) = resolution.shadowed_glob {
256 // Forbid expanded shadowing to avoid time travel.
257 if restricted_shadowing &&
258 binding.expansion != Mark::root() &&
259 binding.def() != shadowed_glob.def() {
260 self.ambiguity_errors.push(AmbiguityError {
261 kind: AmbiguityKind::GlobVsExpanded,
265 misc1: AmbiguityErrorMisc::None,
266 misc2: AmbiguityErrorMisc::None,
271 if !self.is_accessible(binding.vis) &&
272 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
273 !(self.last_import_segment && binding.is_extern_crate()) {
274 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
282 // Items and single imports are not shadowable, if we have one, then it's determined.
283 if let Some(binding) = resolution.binding {
284 if !binding.is_glob_import() {
285 return check_usable(self, binding);
289 // --- From now on we either have a glob resolution or no resolution. ---
291 // Check if one of single imports can still define the name,
292 // if it can then our result is not determined and can be invalidated.
293 for single_import in &resolution.single_imports {
294 if !self.is_accessible(single_import.vis.get()) {
297 let module = unwrap_or!(single_import.imported_module.get(),
298 return Err((Undetermined, Weak::No)));
299 let ident = match single_import.subclass {
300 SingleImport { source, .. } => source,
303 match self.resolve_ident_in_module(module, ident, ns, Some(&single_import.parent_scope),
305 Err(Determined) => continue,
306 Ok(binding) if !self.is_accessible_from(
307 binding.vis, single_import.parent_scope.module
309 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
313 // So we have a resolution that's from a glob import. This resolution is determined
314 // if it cannot be shadowed by some new item/import expanded from a macro.
315 // This happens either if there are no unexpanded macros, or expanded names cannot
316 // shadow globs (that happens in macro namespace or with restricted shadowing).
318 // Additionally, any macro in any module can plant names in the root module if it creates
319 // `macro_export` macros, so the root module effectively has unresolved invocations if any
320 // module has unresolved invocations.
321 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
322 // progress, we have to ignore those potential unresolved invocations from other modules
323 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
324 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
325 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
326 if let Some(binding) = resolution.binding {
327 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
328 return check_usable(self, binding);
330 return Err((Undetermined, Weak::No));
334 // --- From now on we have no resolution. ---
336 // Now we are in situation when new item/import can appear only from a glob or a macro
337 // expansion. With restricted shadowing names from globs and macro expansions cannot
338 // shadow names from outer scopes, so we can freely fallback from module search to search
339 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
340 // scopes we return `Undetermined` with `Weak::Yes`.
342 // Check if one of unexpanded macros can still define the name,
343 // if it can then our "no resolution" result is not determined and can be invalidated.
344 if unexpanded_macros {
345 return Err((Undetermined, Weak::Yes));
348 // Check if one of glob imports can still define the name,
349 // if it can then our "no resolution" result is not determined and can be invalidated.
350 for glob_import in module.globs.borrow().iter() {
351 if !self.is_accessible(glob_import.vis.get()) {
354 let module = match glob_import.imported_module.get() {
355 Some(ModuleOrUniformRoot::Module(module)) => module,
357 None => return Err((Undetermined, Weak::Yes)),
359 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
360 match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
361 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
365 let result = self.resolve_ident_in_module_unadjusted(
366 ModuleOrUniformRoot::Module(module),
372 self.current_module = orig_current_module;
375 Err(Determined) => continue,
376 Ok(binding) if !self.is_accessible_from(
377 binding.vis, glob_import.parent_scope.module
379 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
383 // No resolution and no one else can define the name - determinate error.
384 Err((Determined, Weak::No))
387 // Add an import directive to the current module.
388 pub fn add_import_directive(&mut self,
389 module_path: Vec<Segment>,
390 subclass: ImportDirectiveSubclass<'a>,
396 parent_scope: ParentScope<'a>) {
397 let current_module = parent_scope.module;
398 let directive = self.arenas.alloc_import_directive(ImportDirective {
401 imported_module: Cell::new(None),
408 used: Cell::new(false),
411 debug!("add_import_directive({:?})", directive);
413 self.indeterminate_imports.push(directive);
414 match directive.subclass {
415 SingleImport { target, type_ns_only, .. } => {
416 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
417 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
418 resolution.single_imports.insert(PtrKey(directive));
421 // We don't add prelude imports to the globs since they only affect lexical scopes,
422 // which are not relevant to import resolution.
423 GlobImport { is_prelude: true, .. } => {}
424 GlobImport { .. } => current_module.globs.borrow_mut().push(directive),
429 // Given a binding and an import directive that resolves to it,
430 // return the corresponding binding defined by the import directive.
431 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
432 -> &'a NameBinding<'a> {
433 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
434 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
435 !directive.is_glob() && binding.is_extern_crate() {
441 if let GlobImport { ref max_vis, .. } = directive.subclass {
442 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
447 self.arenas.alloc_name_binding(NameBinding {
448 kind: NameBindingKind::Import {
451 used: Cell::new(false),
454 span: directive.span,
456 expansion: directive.parent_scope.expansion,
460 crate fn check_reserved_macro_name(&self, ident: Ident, ns: Namespace) {
461 // Reserve some names that are not quite covered by the general check
462 // performed on `Resolver::builtin_attrs`.
464 (ident.name == "cfg" || ident.name == "cfg_attr" || ident.name == "derive") {
465 self.session.span_err(ident.span,
466 &format!("name `{}` is reserved in macro namespace", ident));
470 // Define the name or return the existing binding if there is a collision.
471 pub fn try_define(&mut self,
475 binding: &'a NameBinding<'a>)
476 -> Result<(), &'a NameBinding<'a>> {
477 self.check_reserved_macro_name(ident, ns);
478 self.set_binding_parent_module(binding, module);
479 self.update_resolution(module, ident, ns, |this, resolution| {
480 if let Some(old_binding) = resolution.binding {
481 if binding.def() == Def::Err {
482 // Do not override real bindings with `Def::Err`s from error recovery.
485 match (old_binding.is_glob_import(), binding.is_glob_import()) {
487 if binding.def() != old_binding.def() {
488 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
489 old_binding, binding));
490 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
491 // We are glob-importing the same item but with greater visibility.
492 resolution.binding = Some(binding);
495 (old_glob @ true, false) | (old_glob @ false, true) => {
496 let (glob_binding, nonglob_binding) = if old_glob {
497 (old_binding, binding)
499 (binding, old_binding)
501 if glob_binding.def() != nonglob_binding.def() &&
502 ns == MacroNS && nonglob_binding.expansion != Mark::root() {
503 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsExpanded,
504 nonglob_binding, glob_binding));
506 resolution.binding = Some(nonglob_binding);
508 resolution.shadowed_glob = Some(glob_binding);
511 if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
512 (&old_binding.kind, &binding.kind) {
514 this.session.buffer_lint_with_diagnostic(
515 DUPLICATE_MACRO_EXPORTS,
518 &format!("a macro named `{}` has already been exported", ident),
519 BuiltinLintDiagnostics::DuplicatedMacroExports(
520 ident, old_binding.span, binding.span));
522 resolution.binding = Some(binding);
524 return Err(old_binding);
529 resolution.binding = Some(binding);
536 fn ambiguity(&self, kind: AmbiguityKind,
537 primary_binding: &'a NameBinding<'a>, secondary_binding: &'a NameBinding<'a>)
538 -> &'a NameBinding<'a> {
539 self.arenas.alloc_name_binding(NameBinding {
540 ambiguity: Some((secondary_binding, kind)),
541 ..primary_binding.clone()
545 // Use `f` to mutate the resolution of the name in the module.
546 // If the resolution becomes a success, define it in the module's glob importers.
547 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
549 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
551 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
552 // during which the resolution might end up getting re-defined via a glob cycle.
554 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
555 let old_binding = resolution.binding();
557 let t = f(self, resolution);
559 match resolution.binding() {
560 _ if old_binding.is_some() => return t,
562 Some(binding) => match old_binding {
563 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
569 // Define `binding` in `module`s glob importers.
570 for directive in module.glob_importers.borrow_mut().iter() {
571 let mut ident = ident.modern();
572 let scope = match ident.span.reverse_glob_adjust(module.expansion,
573 directive.span.ctxt().modern()) {
574 Some(Some(def)) => self.macro_def_scope(def),
575 Some(None) => directive.parent_scope.module,
578 if self.is_accessible_from(binding.vis, scope) {
579 let imported_binding = self.import(binding, directive);
580 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
587 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
589 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
590 if let SingleImport { target, .. } = directive.subclass {
591 let dummy_binding = self.dummy_binding;
592 let dummy_binding = self.import(dummy_binding, directive);
593 self.per_ns(|this, ns| {
594 let _ = this.try_define(directive.parent_scope.module, target, ns, dummy_binding);
600 pub struct ImportResolver<'a, 'b: 'a> {
601 pub resolver: &'a mut Resolver<'b>,
604 impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> {
605 type Target = Resolver<'b>;
606 fn deref(&self) -> &Resolver<'b> {
611 impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> {
612 fn deref_mut(&mut self) -> &mut Resolver<'b> {
617 impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
618 fn parent(self, id: DefId) -> Option<DefId> {
619 self.resolver.parent(id)
623 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
626 // This is a fixed-point algorithm. We resolve imports until our efforts
627 // are stymied by an unresolved import; then we bail out of the current
628 // module and continue. We terminate successfully once no more imports
629 // remain or unsuccessfully when no forward progress in resolving imports
632 /// Resolves all imports for the crate. This method performs the fixed-
634 pub fn resolve_imports(&mut self) {
635 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
636 while self.indeterminate_imports.len() < prev_num_indeterminates {
637 prev_num_indeterminates = self.indeterminate_imports.len();
638 for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
639 match self.resolve_import(&import) {
640 true => self.determined_imports.push(import),
641 false => self.indeterminate_imports.push(import),
647 pub fn finalize_imports(&mut self) {
648 for module in self.arenas.local_modules().iter() {
649 self.finalize_resolutions_in(module);
652 let mut errors = false;
653 let mut seen_spans = FxHashSet::default();
654 let mut error_vec = Vec::new();
655 let mut prev_root_id: NodeId = NodeId::from_u32(0);
656 for i in 0 .. self.determined_imports.len() {
657 let import = self.determined_imports[i];
658 if let Some((span, err, note)) = self.finalize_import(import) {
661 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
662 if source.name == "self" {
663 // Silence `unresolved import` error if E0429 is already emitted
664 if let Err(Determined) = source_bindings.value_ns.get() {
670 // If the error is a single failed import then create a "fake" import
671 // resolution for it so that later resolve stages won't complain.
672 self.import_dummy_binding(import);
673 if prev_root_id.as_u32() != 0 &&
674 prev_root_id.as_u32() != import.root_id.as_u32() &&
675 !error_vec.is_empty(){
676 // in case of new import line, throw diagnostic message
677 // for previous line.
678 let mut empty_vec = vec![];
679 mem::swap(&mut empty_vec, &mut error_vec);
680 self.throw_unresolved_import_error(empty_vec, None);
682 if !seen_spans.contains(&span) {
683 let path = import_path_to_string(
684 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
688 error_vec.push((span, path, err, note));
689 seen_spans.insert(span);
690 prev_root_id = import.root_id;
695 if !error_vec.is_empty() {
696 self.throw_unresolved_import_error(error_vec.clone(), None);
699 // Report unresolved imports only if no hard error was already reported
700 // to avoid generating multiple errors on the same import.
702 for import in &self.indeterminate_imports {
703 self.throw_unresolved_import_error(error_vec, Some(MultiSpan::from(import.span)));
709 fn throw_unresolved_import_error(
711 error_vec: Vec<(Span, String, String, Option<String>)>,
712 span: Option<MultiSpan>,
714 let max_span_label_msg_count = 10; // upper limit on number of span_label message.
715 let (span, msg, note) = if error_vec.is_empty() {
716 (span.unwrap(), "unresolved import".to_string(), None)
718 let span = MultiSpan::from_spans(
719 error_vec.clone().into_iter()
720 .map(|elem: (Span, String, String, Option<String>)| elem.0)
724 let note: Option<String> = error_vec.clone().into_iter()
725 .filter_map(|elem: (Span, String, String, Option<String>)| elem.3)
728 let path_vec: Vec<String> = error_vec.clone().into_iter()
729 .map(|elem: (Span, String, String, Option<String>)| format!("`{}`", elem.1))
731 let path = path_vec.join(", ");
733 "unresolved import{} {}",
734 if path_vec.len() > 1 { "s" } else { "" },
741 let mut err = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
742 for span_error in error_vec.into_iter().take(max_span_label_msg_count) {
743 err.span_label(span_error.0, span_error.2);
745 if let Some(note) = note {
751 /// Attempts to resolve the given import, returning true if its resolution is determined.
752 /// If successful, the resolved bindings are written into the module.
753 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
754 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
755 Segment::names_to_string(&directive.module_path),
756 module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
758 self.current_module = directive.parent_scope.module;
760 let module = if let Some(module) = directive.imported_module.get() {
763 // For better failure detection, pretend that the import will
764 // not define any names while resolving its module path.
765 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
766 let path_res = self.resolve_path(
767 &directive.module_path,
769 &directive.parent_scope,
772 directive.crate_lint(),
774 directive.vis.set(orig_vis);
777 PathResult::Module(module) => module,
778 PathResult::Indeterminate => return false,
779 PathResult::NonModule(..) | PathResult::Failed(..) => return true,
783 directive.imported_module.set(Some(module));
784 let (source, target, source_bindings, target_bindings, type_ns_only) =
785 match directive.subclass {
786 SingleImport { source, target, ref source_bindings,
787 ref target_bindings, type_ns_only } =>
788 (source, target, source_bindings, target_bindings, type_ns_only),
789 GlobImport { .. } => {
790 self.resolve_glob_import(directive);
796 let mut indeterminate = false;
797 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
798 if let Err(Undetermined) = source_bindings[ns].get() {
799 // For better failure detection, pretend that the import will
800 // not define any names while resolving its module path.
801 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
802 let binding = this.resolve_ident_in_module(
803 module, source, ns, Some(&directive.parent_scope), false, directive.span
805 directive.vis.set(orig_vis);
807 source_bindings[ns].set(binding);
812 let parent = directive.parent_scope.module;
813 match source_bindings[ns].get() {
814 Err(Undetermined) => indeterminate = true,
816 this.update_resolution(parent, target, ns, |_, resolution| {
817 resolution.single_imports.remove(&PtrKey(directive));
820 Ok(binding) if !binding.is_importable() => {
821 let msg = format!("`{}` is not directly importable", target);
822 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
823 .span_label(directive.span, "cannot be imported directly")
825 // Do not import this illegal binding. Import a dummy binding and pretend
826 // everything is fine
827 this.import_dummy_binding(directive);
830 let imported_binding = this.import(binding, directive);
831 target_bindings[ns].set(Some(imported_binding));
832 let conflict = this.try_define(parent, target, ns, imported_binding);
833 if let Err(old_binding) = conflict {
834 this.report_conflict(parent, target, ns, imported_binding, old_binding);
843 // If appropriate, returns an error to report.
846 directive: &'b ImportDirective<'b>
847 ) -> Option<(Span, String, Option<String>)> {
848 self.current_module = directive.parent_scope.module;
850 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
851 let prev_ambiguity_errors_len = self.ambiguity_errors.len();
852 let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
853 true, directive.span, directive.crate_lint());
854 let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
855 directive.vis.set(orig_vis);
856 let module = match path_res {
857 PathResult::Module(module) => {
858 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
859 if let Some(initial_module) = directive.imported_module.get() {
860 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
861 span_bug!(directive.span, "inconsistent resolution for an import");
864 if self.privacy_errors.is_empty() {
865 let msg = "cannot determine resolution for the import";
866 let msg_note = "import resolution is stuck, try simplifying other imports";
867 self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
873 PathResult::Failed(span, msg, false) => {
875 assert!(directive.imported_module.get().is_none());
876 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
880 PathResult::Failed(span, msg, true) => {
882 assert!(directive.imported_module.get().is_none());
883 return Some(match self.make_path_suggestion(span, directive.module_path.clone(),
884 &directive.parent_scope) {
885 Some((suggestion, note)) => (
887 format!("did you mean `{}`?", Segment::names_to_string(&suggestion)),
890 None => (span, msg, None),
895 PathResult::NonModule(path_res) if path_res.base_def() == Def::Err => {
897 assert!(directive.imported_module.get().is_none());
899 // The error was already reported earlier.
902 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
905 let (ident, target, source_bindings, target_bindings, type_ns_only) =
906 match directive.subclass {
907 SingleImport { source, target, ref source_bindings,
908 ref target_bindings, type_ns_only } =>
909 (source, target, source_bindings, target_bindings, type_ns_only),
910 GlobImport { is_prelude, ref max_vis } => {
911 if directive.module_path.len() <= 1 {
912 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
913 // 2 segments, so the `resolve_path` above won't trigger it.
914 let mut full_path = directive.module_path.clone();
915 full_path.push(Segment::from_ident(keywords::Invalid.ident()));
916 self.lint_if_path_starts_with_module(
917 directive.crate_lint(),
924 if let ModuleOrUniformRoot::Module(module) = module {
925 if module.def_id() == directive.parent_scope.module.def_id() {
926 // Importing a module into itself is not allowed.
929 "Cannot glob-import a module into itself.".to_string(),
935 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
936 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
937 let msg = "A non-empty glob must import something with the glob's visibility";
938 self.session.span_err(directive.span, msg);
945 let mut all_ns_err = true;
946 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
947 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
948 let orig_blacklisted_binding =
949 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
950 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
951 let binding = this.resolve_ident_in_module(
952 module, ident, ns, Some(&directive.parent_scope), true, directive.span
954 this.last_import_segment = orig_last_import_segment;
955 this.blacklisted_binding = orig_blacklisted_binding;
956 directive.vis.set(orig_vis);
960 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
961 let initial_def = source_bindings[ns].get().map(|initial_binding| {
963 if let Some(target_binding) = target_bindings[ns].get() {
964 if target.name == "_" &&
965 initial_binding.is_extern_crate() && !initial_binding.is_import() {
966 this.record_use(ident, ns, target_binding,
967 directive.module_path.is_empty());
970 initial_binding.def()
972 let def = binding.def();
973 if let Ok(initial_def) = initial_def {
974 if def != initial_def && this.ambiguity_errors.is_empty() {
975 span_bug!(directive.span, "inconsistent resolution for an import");
978 if def != Def::Err &&
979 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
980 let msg = "cannot determine resolution for the import";
982 "import resolution is stuck, try simplifying other imports";
983 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
988 // FIXME: This assert may fire if public glob is later shadowed by a private
989 // single import (see test `issue-55884-2.rs`). In theory single imports should
990 // always block globs, even if they are not yet resolved, so that this kind of
991 // self-inconsistent resolution never happens.
992 // Reenable the assert when the issue is fixed.
993 // assert!(result[ns].get().is_err());
999 let mut all_ns_failed = true;
1000 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1001 let binding = this.resolve_ident_in_module(
1002 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1004 if binding.is_ok() {
1005 all_ns_failed = false;
1009 return if all_ns_failed {
1010 let resolutions = match module {
1011 ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1014 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1015 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1016 if *i == ident { return None; } // Never suggest the same name
1017 match *resolution.borrow() {
1018 NameResolution { binding: Some(name_binding), .. } => {
1019 match name_binding.kind {
1020 NameBindingKind::Import { binding, .. } => {
1021 match binding.kind {
1022 // Never suggest the name that has binding error
1023 // i.e., the name that cannot be previously resolved
1024 NameBindingKind::Def(Def::Err, _) => return None,
1031 NameResolution { ref single_imports, .. }
1032 if single_imports.is_empty() => None,
1036 let lev_suggestion =
1037 match find_best_match_for_name(names, &ident.as_str(), None) {
1038 Some(name) => format!(". Did you mean to use `{}`?", name),
1039 None => String::new(),
1041 let msg = match module {
1042 ModuleOrUniformRoot::Module(module) => {
1043 let module_str = module_to_string(module);
1044 if let Some(module_str) = module_str {
1045 format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
1047 format!("no `{}` in the root{}", ident, lev_suggestion)
1051 if !ident.is_path_segment_keyword() {
1052 format!("no `{}` external crate{}", ident, lev_suggestion)
1054 // HACK(eddyb) this shows up for `self` & `super`, which
1055 // should work instead - for now keep the same error message.
1056 format!("no `{}` in the root{}", ident, lev_suggestion)
1060 Some((directive.span, msg, None))
1062 // `resolve_ident_in_module` reported a privacy error.
1063 self.import_dummy_binding(directive);
1068 let mut reexport_error = None;
1069 let mut any_successful_reexport = false;
1070 self.per_ns(|this, ns| {
1071 if let Ok(binding) = source_bindings[ns].get() {
1072 let vis = directive.vis.get();
1073 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1074 reexport_error = Some((ns, binding));
1076 any_successful_reexport = true;
1081 // All namespaces must be re-exported with extra visibility for an error to occur.
1082 if !any_successful_reexport {
1083 let (ns, binding) = reexport_error.unwrap();
1084 if ns == TypeNS && binding.is_extern_crate() {
1085 let msg = format!("extern crate `{}` is private, and cannot be \
1086 re-exported (error E0365), consider declaring with \
1089 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1093 } else if ns == TypeNS {
1094 struct_span_err!(self.session, directive.span, E0365,
1095 "`{}` is private, and cannot be re-exported", ident)
1096 .span_label(directive.span, format!("re-export of private `{}`", ident))
1097 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1100 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1102 format!("consider marking `{}` as `pub` in the imported module", ident);
1103 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1104 .span_note(directive.span, ¬e_msg)
1109 if directive.module_path.len() <= 1 {
1110 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1111 // 2 segments, so the `resolve_path` above won't trigger it.
1112 let mut full_path = directive.module_path.clone();
1113 full_path.push(Segment::from_ident(ident));
1114 self.per_ns(|this, ns| {
1115 if let Ok(binding) = source_bindings[ns].get() {
1116 this.lint_if_path_starts_with_module(
1117 directive.crate_lint(),
1126 // Record what this import resolves to for later uses in documentation,
1127 // this may resolve to either a value or a type, but for documentation
1128 // purposes it's good enough to just favor one over the other.
1129 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1130 let mut def = binding.def();
1131 if let Def::Macro(def_id, _) = def {
1132 // `DefId`s from the "built-in macro crate" should not leak from resolve because
1133 // later stages are not ready to deal with them and produce lots of ICEs. Replace
1134 // them with `Def::Err` until some saner scheme is implemented for built-in macros.
1135 if def_id.krate == CrateNum::BuiltinMacros {
1136 this.session.span_err(directive.span, "cannot import a built-in macro");
1140 let import = this.import_map.entry(directive.id).or_default();
1141 import[ns] = Some(PathResolution::new(def));
1144 debug!("(resolving single import) successfully resolved import");
1148 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1149 let module = match directive.imported_module.get().unwrap() {
1150 ModuleOrUniformRoot::Module(module) => module,
1152 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1157 self.populate_module_if_necessary(module);
1159 if let Some(Def::Trait(_)) = module.def() {
1160 self.session.span_err(directive.span, "items in traits are not importable.");
1162 } else if module.def_id() == directive.parent_scope.module.def_id() {
1164 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1165 self.prelude = Some(module);
1169 // Add to module's glob_importers
1170 module.glob_importers.borrow_mut().push(directive);
1172 // Ensure that `resolutions` isn't borrowed during `try_define`,
1173 // since it might get updated via a glob cycle.
1174 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1175 resolution.borrow().binding().map(|binding| (ident, binding))
1176 }).collect::<Vec<_>>();
1177 for ((mut ident, ns), binding) in bindings {
1178 let scope = match ident.span.reverse_glob_adjust(module.expansion,
1179 directive.span.ctxt().modern()) {
1180 Some(Some(def)) => self.macro_def_scope(def),
1181 Some(None) => self.current_module,
1184 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1185 let imported_binding = self.import(binding, directive);
1186 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1190 // Record the destination of this import
1191 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1194 // Miscellaneous post-processing, including recording re-exports,
1195 // reporting conflicts, and reporting unresolved imports.
1196 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1197 // Since import resolution is finished, globs will not define any more names.
1198 *module.globs.borrow_mut() = Vec::new();
1200 let mut reexports = Vec::new();
1202 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1203 let resolution = &mut *resolution.borrow_mut();
1204 let binding = match resolution.binding {
1205 Some(binding) => binding,
1209 // Filter away "empty import canaries" and ambiguous imports.
1210 let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
1211 binding.vis != ty::Visibility::Invisible;
1212 if is_good_import || binding.is_macro_def() {
1213 let def = binding.def();
1214 if def != Def::Err {
1215 if let Some(def_id) = def.opt_def_id() {
1216 if !def_id.is_local() && def_id.krate != CrateNum::BuiltinMacros {
1217 self.cstore.export_macros_untracked(def_id.krate);
1220 reexports.push(Export {
1221 ident: ident.modern(),
1229 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1230 if ns == TypeNS && orig_binding.is_variant() &&
1231 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1232 let msg = match directive.subclass {
1233 ImportDirectiveSubclass::SingleImport { .. } => {
1234 format!("variant `{}` is private and cannot be re-exported",
1237 ImportDirectiveSubclass::GlobImport { .. } => {
1238 let msg = "enum is private and its variants \
1239 cannot be re-exported".to_owned();
1240 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1243 let fresh = self.session.one_time_diagnostics
1244 .borrow_mut().insert(error_id);
1250 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1252 let mut err = self.session.struct_span_err(binding.span, &msg);
1254 let imported_module = match directive.imported_module.get() {
1255 Some(ModuleOrUniformRoot::Module(module)) => module,
1256 _ => bug!("module should exist"),
1258 let resolutions = imported_module.parent.expect("parent should exist")
1259 .resolutions.borrow();
1260 let enum_path_segment_index = directive.module_path.len() - 1;
1261 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1263 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1264 .expect("resolution should exist");
1265 let enum_span = enum_resolution.borrow()
1266 .binding.expect("binding should exist")
1268 let enum_def_span = self.session.source_map().def_span(enum_span);
1269 let enum_def_snippet = self.session.source_map()
1270 .span_to_snippet(enum_def_span).expect("snippet should exist");
1271 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1272 let after_vis_index = enum_def_snippet.find("enum")
1273 .expect("`enum` keyword should exist in snippet");
1274 let suggestion = format!("pub {}",
1275 &enum_def_snippet[after_vis_index..]);
1278 .diag_span_suggestion_once(&mut err,
1279 DiagnosticMessageId::ErrorId(0),
1281 "consider making the enum public",
1288 if reexports.len() > 0 {
1289 if let Some(def_id) = module.def_id() {
1290 self.export_map.insert(def_id, reexports);
1296 fn import_path_to_string(names: &[Ident],
1297 subclass: &ImportDirectiveSubclass,
1298 span: Span) -> String {
1299 let pos = names.iter()
1300 .position(|p| span == p.span && p.name != keywords::PathRoot.name());
1301 let global = !names.is_empty() && names[0].name == keywords::PathRoot.name();
1302 if let Some(pos) = pos {
1303 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1304 names_to_string(names)
1306 let names = if global { &names[1..] } else { names };
1307 if names.is_empty() {
1308 import_directive_subclass_to_string(subclass)
1311 names_to_string(names),
1312 import_directive_subclass_to_string(subclass))
1317 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1319 SingleImport { source, .. } => source.to_string(),
1320 GlobImport { .. } => "*".to_string(),
1321 ExternCrate { .. } => "<extern crate>".to_string(),
1322 MacroUse => "#[macro_use]".to_string(),