1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::ImportDirectiveSubclass::*;
14 use Namespace::{self, TypeNS, ValueNS};
15 use {NameBinding, NameBindingKind, PrivacyError, ToNameBinding};
19 use UseLexicalScopeFlag::DontUseLexicalScope;
20 use {names_to_string, module_to_string};
21 use {resolve_error, ResolutionError};
24 use rustc::lint::builtin::PRIVATE_IN_PUBLIC;
25 use rustc::hir::def::*;
27 use syntax::ast::{NodeId, Name};
28 use syntax::util::lev_distance::find_best_match_for_name;
29 use syntax_pos::{Span, DUMMY_SP};
31 use std::cell::{Cell, RefCell};
33 impl<'a> Resolver<'a> {
34 pub fn resolve_imports(&mut self) {
35 ImportResolver { resolver: self }.resolve_imports();
39 /// Contains data for specific types of import directives.
40 #[derive(Clone, Debug)]
41 pub enum ImportDirectiveSubclass {
45 type_determined: Cell<bool>,
46 value_determined: Cell<bool>,
48 GlobImport { is_prelude: bool },
51 impl ImportDirectiveSubclass {
52 pub fn single(target: Name, source: Name) -> Self {
56 type_determined: Cell::new(false),
57 value_determined: Cell::new(false),
62 /// One import directive.
63 #[derive(Debug,Clone)]
64 pub struct ImportDirective<'a> {
67 module_path: Vec<Name>,
68 target_module: Cell<Option<Module<'a>>>, // the resolution of `module_path`
69 subclass: ImportDirectiveSubclass,
71 vis: ty::Visibility, // see note in ImportResolutionPerNamespace about how to use this
74 impl<'a> ImportDirective<'a> {
75 pub fn is_glob(&self) -> bool {
76 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
80 #[derive(Clone, Default)]
81 /// Records information about the resolution of a name in a namespace of a module.
82 pub struct NameResolution<'a> {
83 /// The single imports that define the name in the namespace.
84 single_imports: SingleImports<'a>,
85 /// The least shadowable known binding for this name, or None if there are no known bindings.
86 pub binding: Option<&'a NameBinding<'a>>,
87 duplicate_globs: Vec<&'a NameBinding<'a>>,
90 #[derive(Clone, Debug)]
91 enum SingleImports<'a> {
92 /// No single imports can define the name in the namespace.
94 /// Only the given single import can define the name in the namespace.
95 MaybeOne(&'a ImportDirective<'a>),
96 /// At least one single import will define the name in the namespace.
100 impl<'a> Default for SingleImports<'a> {
101 fn default() -> Self {
106 impl<'a> SingleImports<'a> {
107 fn add_directive(&mut self, directive: &'a ImportDirective<'a>) {
109 SingleImports::None => *self = SingleImports::MaybeOne(directive),
110 // If two single imports can define the name in the namespace, we can assume that at
111 // least one of them will define it since otherwise both would have to define only one
112 // namespace, leading to a duplicate error.
113 SingleImports::MaybeOne(_) => *self = SingleImports::AtLeastOne,
114 SingleImports::AtLeastOne => {}
118 fn directive_failed(&mut self) {
120 SingleImports::None => unreachable!(),
121 SingleImports::MaybeOne(_) => *self = SingleImports::None,
122 SingleImports::AtLeastOne => {}
127 impl<'a> NameResolution<'a> {
128 // Returns the binding for the name if it is known or None if it not known.
129 fn binding(&self) -> Option<&'a NameBinding<'a>> {
130 self.binding.and_then(|binding| match self.single_imports {
131 SingleImports::None => Some(binding),
132 _ if !binding.is_glob_import() => Some(binding),
133 _ => None, // The binding could be shadowed by a single import, so it is not known.
137 // Returns Some(the resolution of the name), or None if the resolution depends
138 // on whether more globs can define the name.
139 fn try_result(&self, ns: Namespace, allow_private_imports: bool)
140 -> Option<ResolveResult<&'a NameBinding<'a>>> {
142 Some(binding) if !binding.is_glob_import() =>
143 return Some(Success(binding)),
144 _ => {} // Items and single imports are not shadowable
147 // Check if a single import can still define the name.
148 match self.single_imports {
149 SingleImports::None => {},
150 SingleImports::AtLeastOne => return Some(Indeterminate),
151 SingleImports::MaybeOne(directive) => {
152 // If (1) we don't allow private imports, (2) no public single import can define
153 // the name, and (3) no public glob has defined the name, the resolution depends
154 // on whether more globs can define the name.
155 if !allow_private_imports && directive.vis != ty::Visibility::Public &&
156 !self.binding.map(NameBinding::is_pseudo_public).unwrap_or(false) {
160 let target_module = match directive.target_module.get() {
161 Some(target_module) => target_module,
162 None => return Some(Indeterminate),
164 let name = match directive.subclass {
165 SingleImport { source, .. } => source,
166 GlobImport { .. } => unreachable!(),
168 match target_module.resolve_name(name, ns, false) {
170 _ => return Some(Indeterminate),
175 self.binding.map(Success)
179 impl<'a> ::ModuleS<'a> {
180 fn resolution(&self, name: Name, ns: Namespace) -> &'a RefCell<NameResolution<'a>> {
181 *self.resolutions.borrow_mut().entry((name, ns))
182 .or_insert_with(|| self.arenas.alloc_name_resolution())
185 pub fn resolve_name(&self, name: Name, ns: Namespace, allow_private_imports: bool)
186 -> ResolveResult<&'a NameBinding<'a>> {
187 let resolution = self.resolution(name, ns);
188 let resolution = match resolution.borrow_state() {
189 ::std::cell::BorrowState::Unused => resolution.borrow_mut(),
190 _ => return Failed(None), // This happens when there is a cycle of imports
193 if let Some(result) = resolution.try_result(ns, allow_private_imports) {
194 // If the resolution doesn't depend on glob definability, check privacy and return.
195 return result.and_then(|binding| {
196 let allowed = allow_private_imports || !binding.is_import() ||
197 binding.is_pseudo_public();
198 if allowed { Success(binding) } else { Failed(None) }
202 // Check if the globs are determined
203 for directive in self.globs.borrow().iter() {
204 if !allow_private_imports && directive.vis != ty::Visibility::Public { continue }
205 match directive.target_module.get() {
206 None => return Indeterminate,
207 Some(target_module) => match target_module.resolve_name(name, ns, false) {
208 Indeterminate => return Indeterminate,
218 impl<'a> Resolver<'a> {
219 // Add an import directive to the current module.
220 pub fn add_import_directive(&mut self,
221 module_path: Vec<Name>,
222 subclass: ImportDirectiveSubclass,
225 vis: ty::Visibility) {
226 let directive = self.arenas.alloc_import_directive(ImportDirective {
227 parent: self.current_module,
228 module_path: module_path,
229 target_module: Cell::new(None),
236 self.indeterminate_imports.push(directive);
237 match directive.subclass {
238 SingleImport { target, .. } => {
239 for &ns in &[ValueNS, TypeNS] {
240 let mut resolution = self.current_module.resolution(target, ns).borrow_mut();
241 resolution.single_imports.add_directive(directive);
244 // We don't add prelude imports to the globs since they only affect lexical scopes,
245 // which are not relevant to import resolution.
246 GlobImport { is_prelude: true } => {}
247 GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
251 // Given a binding and an import directive that resolves to it,
252 // return the corresponding binding defined by the import directive.
253 fn import(&mut self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
256 kind: NameBindingKind::Import {
258 directive: directive,
260 span: directive.span,
265 // Define the name or return the existing binding if there is a collision.
266 pub fn try_define<T>(&mut self, module: Module<'a>, name: Name, ns: Namespace, binding: T)
267 -> Result<(), &'a NameBinding<'a>>
268 where T: ToNameBinding<'a>
270 let binding = self.arenas.alloc_name_binding(binding.to_name_binding());
271 self.update_resolution(module, name, ns, |_, resolution| {
272 if let Some(old_binding) = resolution.binding {
273 if binding.is_glob_import() {
274 resolution.duplicate_globs.push(binding);
275 } else if old_binding.is_glob_import() {
276 resolution.duplicate_globs.push(old_binding);
277 resolution.binding = Some(binding);
279 return Err(old_binding);
282 resolution.binding = Some(binding);
289 // Use `f` to mutate the resolution of the name in the module.
290 // If the resolution becomes a success, define it in the module's glob importers.
291 fn update_resolution<T, F>(&mut self, module: Module<'a>, name: Name, ns: Namespace, f: F) -> T
292 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
294 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
295 // during which the resolution might end up getting re-defined via a glob cycle.
296 let (new_binding, t) = {
297 let mut resolution = &mut *module.resolution(name, ns).borrow_mut();
298 let was_known = resolution.binding().is_some();
300 let t = f(self, resolution);
302 if was_known { return t; }
303 match resolution.binding() {
304 Some(binding) => (binding, t),
309 // Define `new_binding` in `module`s glob importers.
310 if new_binding.is_importable() && new_binding.is_pseudo_public() {
311 for directive in module.glob_importers.borrow_mut().iter() {
312 let imported_binding = self.import(new_binding, directive);
313 let _ = self.try_define(directive.parent, name, ns, imported_binding);
321 struct ImportResolvingError<'a> {
322 import_directive: &'a ImportDirective<'a>,
327 struct ImportResolver<'a, 'b: 'a> {
328 resolver: &'a mut Resolver<'b>,
331 impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> {
332 type Target = Resolver<'b>;
333 fn deref(&self) -> &Resolver<'b> {
338 impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> {
339 fn deref_mut(&mut self) -> &mut Resolver<'b> {
344 impl<'a, 'b: 'a> ty::NodeIdTree for ImportResolver<'a, 'b> {
345 fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
346 self.resolver.is_descendant_of(node, ancestor)
350 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
353 // This is a fixed-point algorithm. We resolve imports until our efforts
354 // are stymied by an unresolved import; then we bail out of the current
355 // module and continue. We terminate successfully once no more imports
356 // remain or unsuccessfully when no forward progress in resolving imports
359 /// Resolves all imports for the crate. This method performs the fixed-
361 fn resolve_imports(&mut self) {
363 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
364 let mut errors = Vec::new();
366 while self.indeterminate_imports.len() < prev_num_indeterminates {
367 prev_num_indeterminates = self.indeterminate_imports.len();
368 debug!("(resolving imports) iteration {}, {} imports left", i, prev_num_indeterminates);
370 let mut imports = Vec::new();
371 ::std::mem::swap(&mut imports, &mut self.indeterminate_imports);
373 for import in imports {
374 match self.resolve_import(&import) {
376 let (span, help) = match err {
377 Some((span, msg)) => (span, format!(". {}", msg)),
378 None => (import.span, String::new()),
380 errors.push(ImportResolvingError {
381 import_directive: import,
386 Indeterminate => self.indeterminate_imports.push(import),
394 for module in self.arenas.local_modules().iter() {
395 self.finalize_resolutions_in(module);
398 // Report unresolved imports only if no hard error was already reported
399 // to avoid generating multiple errors on the same import.
400 if errors.len() == 0 {
401 if let Some(import) = self.indeterminate_imports.iter().next() {
402 let error = ResolutionError::UnresolvedImport(None);
403 resolve_error(self.resolver, import.span, error);
408 self.import_resolving_error(e)
412 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
414 fn import_dummy_binding(&mut self, directive: &'b ImportDirective<'b>) {
415 if let SingleImport { target, .. } = directive.subclass {
416 let dummy_binding = self.arenas.alloc_name_binding(NameBinding {
417 kind: NameBindingKind::Def(Def::Err),
419 vis: ty::Visibility::Public,
421 let dummy_binding = self.import(dummy_binding, directive);
423 let _ = self.try_define(directive.parent, target, ValueNS, dummy_binding.clone());
424 let _ = self.try_define(directive.parent, target, TypeNS, dummy_binding);
428 /// Resolves an `ImportResolvingError` into the correct enum discriminant
429 /// and passes that on to `resolve_error`.
430 fn import_resolving_error(&mut self, e: ImportResolvingError<'b>) {
431 // If the error is a single failed import then create a "fake" import
432 // resolution for it so that later resolve stages won't complain.
433 self.import_dummy_binding(e.import_directive);
434 let path = import_path_to_string(&e.import_directive.module_path,
435 &e.import_directive.subclass);
436 resolve_error(self.resolver,
438 ResolutionError::UnresolvedImport(Some((&path, &e.help))));
441 /// Attempts to resolve the given import. The return value indicates
442 /// failure if we're certain the name does not exist, indeterminate if we
443 /// don't know whether the name exists at the moment due to other
444 /// currently-unresolved imports, or success if we know the name exists.
445 /// If successful, the resolved bindings are written into the module.
446 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> ResolveResult<()> {
447 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
448 names_to_string(&directive.module_path),
449 module_to_string(self.current_module));
451 let module = directive.parent;
452 self.current_module = module;
454 let target_module = match directive.target_module.get() {
455 Some(module) => module,
456 _ => match self.resolve_module_path(&directive.module_path,
459 Success(module) => module,
460 Indeterminate => return Indeterminate,
461 Failed(err) => return Failed(err),
465 directive.target_module.set(Some(target_module));
466 let (source, target, value_determined, type_determined) = match directive.subclass {
467 SingleImport { source, target, ref value_determined, ref type_determined } =>
468 (source, target, value_determined, type_determined),
469 GlobImport { .. } => return self.resolve_glob_import(target_module, directive),
472 // We need to resolve both namespaces for this to succeed.
473 let value_result = self.resolve_name_in_module(target_module, source, ValueNS, false, true);
474 let type_result = self.resolve_name_in_module(target_module, source, TypeNS, false, true);
476 let mut privacy_error = true;
477 for &(ns, result, determined) in &[(ValueNS, &value_result, value_determined),
478 (TypeNS, &type_result, type_determined)] {
480 Failed(..) if !determined.get() => {
481 determined.set(true);
482 self.update_resolution(module, target, ns, |_, resolution| {
483 resolution.single_imports.directive_failed()
486 Success(binding) if !binding.is_importable() => {
487 let msg = format!("`{}` is not directly importable", target);
488 struct_span_err!(self.session, directive.span, E0253, "{}", &msg)
489 .span_label(directive.span, &format!("cannot be imported directly"))
491 // Do not import this illegal binding. Import a dummy binding and pretend
492 // everything is fine
493 self.import_dummy_binding(directive);
496 Success(binding) if !self.is_accessible(binding.vis) => {}
497 Success(binding) if !determined.get() => {
498 determined.set(true);
499 let imported_binding = self.import(binding, directive);
500 let conflict = self.try_define(module, target, ns, imported_binding);
501 if let Err(old_binding) = conflict {
502 let binding = &self.import(binding, directive);
503 self.report_conflict(module, target, ns, binding, old_binding);
505 privacy_error = false;
507 Success(_) => privacy_error = false,
512 match (&value_result, &type_result) {
513 (&Indeterminate, _) | (_, &Indeterminate) => return Indeterminate,
514 (&Failed(_), &Failed(_)) => {
515 let resolutions = target_module.resolutions.borrow();
516 let names = resolutions.iter().filter_map(|(&(ref name, _), resolution)| {
517 if *name == source { return None; } // Never suggest the same name
518 match *resolution.borrow() {
519 NameResolution { binding: Some(_), .. } => Some(name),
520 NameResolution { single_imports: SingleImports::None, .. } => None,
524 let lev_suggestion = match find_best_match_for_name(names, &source.as_str(), None) {
525 Some(name) => format!(". Did you mean to use `{}`?", name),
526 None => "".to_owned(),
528 let module_str = module_to_string(target_module);
529 let msg = if &module_str == "???" {
530 format!("There is no `{}` in the crate root{}", source, lev_suggestion)
532 format!("There is no `{}` in `{}`{}", source, module_str, lev_suggestion)
534 return Failed(Some((directive.span, msg)));
540 for &(ns, result) in &[(ValueNS, &value_result), (TypeNS, &type_result)] {
541 let binding = match *result { Success(binding) => binding, _ => continue };
542 self.privacy_errors.push(PrivacyError(directive.span, source, binding));
543 let imported_binding = self.import(binding, directive);
544 let _ = self.try_define(module, target, ns, imported_binding);
548 match (&value_result, &type_result) {
549 (&Success(binding), _) if !binding.pseudo_vis().is_at_least(directive.vis, self) &&
550 self.is_accessible(binding.vis) => {
551 let msg = format!("`{}` is private, and cannot be reexported", source);
552 let note_msg = format!("consider marking `{}` as `pub` in the imported module",
554 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
555 .span_note(directive.span, ¬e_msg)
559 (_, &Success(binding)) if !binding.pseudo_vis().is_at_least(directive.vis, self) &&
560 self.is_accessible(binding.vis) => {
561 if binding.is_extern_crate() {
562 let msg = format!("extern crate `{}` is private, and cannot be reexported \
563 (error E0364), consider declaring with `pub`",
565 self.session.add_lint(PRIVATE_IN_PUBLIC, directive.id, directive.span, msg);
567 let mut err = struct_span_err!(self.session, directive.span, E0365,
568 "`{}` is private, and cannot be reexported",
570 err.span_label(directive.span, &format!("reexport of private `{}`", source));
571 err.note(&format!("consider declaring type or module `{}` with `pub`", source));
579 // Record what this import resolves to for later uses in documentation,
580 // this may resolve to either a value or a type, but for documentation
581 // purposes it's good enough to just favor one over the other.
582 let def = match type_result.success().and_then(NameBinding::def) {
584 None => value_result.success().and_then(NameBinding::def).unwrap(),
586 let path_resolution = PathResolution::new(def);
587 self.def_map.insert(directive.id, path_resolution);
589 debug!("(resolving single import) successfully resolved import");
593 // Resolves a glob import. Note that this function cannot fail; it either
594 // succeeds or bails out (as importing * from an empty module or a module
595 // that exports nothing is valid). target_module is the module we are
596 // actually importing, i.e., `foo` in `use foo::*`.
597 fn resolve_glob_import(&mut self, target_module: Module<'b>, directive: &'b ImportDirective<'b>)
598 -> ResolveResult<()> {
599 if let Some(Def::Trait(_)) = target_module.def {
600 self.session.span_err(directive.span, "items in traits are not importable.");
603 let module = self.current_module;
604 if module.def_id() == target_module.def_id() {
605 // This means we are trying to glob import a module into itself, and it is a no-go
606 let msg = "Cannot glob-import a module into itself.".into();
607 return Failed(Some((directive.span, msg)));
609 self.populate_module_if_necessary(target_module);
611 if let GlobImport { is_prelude: true } = directive.subclass {
612 self.prelude = Some(target_module);
616 // Add to target_module's glob_importers
617 target_module.glob_importers.borrow_mut().push(directive);
619 // Ensure that `resolutions` isn't borrowed during `try_define`,
620 // since it might get updated via a glob cycle.
621 let bindings = target_module.resolutions.borrow().iter().filter_map(|(name, resolution)| {
622 resolution.borrow().binding().map(|binding| (*name, binding))
623 }).collect::<Vec<_>>();
624 for ((name, ns), binding) in bindings {
625 if binding.is_importable() && binding.is_pseudo_public() {
626 let imported_binding = self.import(binding, directive);
627 let _ = self.try_define(module, name, ns, imported_binding);
631 // Record the destination of this import
632 if let Some(did) = target_module.def_id() {
633 let resolution = PathResolution::new(Def::Mod(did));
634 self.def_map.insert(directive.id, resolution);
637 debug!("(resolving glob import) successfully resolved import");
641 // Miscellaneous post-processing, including recording reexports, reporting conflicts,
642 // reporting the PRIVATE_IN_PUBLIC lint, and reporting unresolved imports.
643 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
644 // Since import resolution is finished, globs will not define any more names.
645 *module.globs.borrow_mut() = Vec::new();
647 let mut reexports = Vec::new();
648 for (&(name, ns), resolution) in module.resolutions.borrow().iter() {
649 let resolution = resolution.borrow();
650 let binding = match resolution.binding {
651 Some(binding) => binding,
656 for duplicate_glob in resolution.duplicate_globs.iter() {
657 // FIXME #31337: We currently allow items to shadow glob-imported re-exports.
658 if !binding.is_import() {
659 if let NameBindingKind::Import { binding, .. } = duplicate_glob.kind {
660 if binding.is_import() { continue }
664 self.report_conflict(module, name, ns, duplicate_glob, binding);
667 if binding.vis == ty::Visibility::Public &&
668 (binding.is_import() || binding.is_extern_crate()) {
669 if let Some(def) = binding.def() {
670 reexports.push(Export { name: name, def_id: def.def_id() });
674 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
675 if ns == TypeNS && orig_binding.is_variant() &&
676 !orig_binding.vis.is_at_least(binding.vis, self) {
677 let msg = format!("variant `{}` is private, and cannot be reexported \
678 (error E0364), consider declaring its enum as `pub`",
680 self.session.add_lint(PRIVATE_IN_PUBLIC, directive.id, binding.span, msg);
685 if reexports.len() > 0 {
686 if let Some(def_id) = module.def_id() {
687 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
688 self.export_map.insert(node_id, reexports);
694 fn import_path_to_string(names: &[Name], subclass: &ImportDirectiveSubclass) -> String {
695 if names.is_empty() {
696 import_directive_subclass_to_string(subclass)
699 names_to_string(names),
700 import_directive_subclass_to_string(subclass)))
705 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
707 SingleImport { source, .. } => source.to_string(),
708 GlobImport { .. } => "*".to_string(),