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::*;
15 use Namespace::{self, TypeNS, ValueNS};
16 use {NameBinding, NameBindingKind};
20 use UseLexicalScopeFlag;
21 use {names_to_string, module_to_string};
22 use {resolve_error, ResolutionError};
24 use build_reduced_graph;
27 use rustc::middle::def::*;
28 use rustc::middle::privacy::*;
30 use syntax::ast::{NodeId, Name};
31 use syntax::attr::AttrMetaMethods;
32 use syntax::codemap::Span;
33 use syntax::util::lev_distance::find_best_match_for_name;
35 use std::mem::replace;
37 /// Contains data for specific types of import directives.
38 #[derive(Copy, Clone,Debug)]
39 pub enum ImportDirectiveSubclass {
40 SingleImport(Name /* target */, Name /* source */),
44 /// Whether an import can be shadowed by another import.
45 #[derive(Debug,PartialEq,Clone,Copy)]
51 /// One import directive.
52 #[derive(Debug,Clone)]
53 pub struct ImportDirective {
54 pub module_path: Vec<Name>,
55 pub subclass: ImportDirectiveSubclass,
58 pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
59 pub shadowable: Shadowable,
62 impl ImportDirective {
63 pub fn new(module_path: Vec<Name>,
64 subclass: ImportDirectiveSubclass,
68 shadowable: Shadowable)
71 module_path: module_path,
76 shadowable: shadowable,
80 // Given the binding to which this directive resolves in a particular namespace,
81 // this returns the binding for the name this directive defines in that namespace.
82 fn import<'a>(&self, binding: &'a NameBinding<'a>) -> NameBinding<'a> {
83 let mut modifiers = match self.is_public {
84 true => DefModifiers::PUBLIC | DefModifiers::IMPORTABLE,
85 false => DefModifiers::empty(),
87 if let GlobImport = self.subclass {
88 modifiers = modifiers | DefModifiers::GLOB_IMPORTED;
90 if self.shadowable == Shadowable::Always {
91 modifiers = modifiers | DefModifiers::PRELUDE;
95 kind: NameBindingKind::Import { binding: binding, id: self.id },
96 span: Some(self.span),
102 #[derive(Clone, Default)]
103 /// Records information about the resolution of a name in a module.
104 pub struct NameResolution<'a> {
105 /// The number of unresolved single imports that could define the name.
106 pub outstanding_references: usize,
107 /// The least shadowable known binding for this name, or None if there are no known bindings.
108 pub binding: Option<&'a NameBinding<'a>>,
111 impl<'a> NameResolution<'a> {
112 pub fn result(&self, outstanding_globs: usize) -> ResolveResult<&'a NameBinding<'a>> {
113 // If no unresolved imports (single or glob) can define the name, self.binding is final.
114 if self.outstanding_references == 0 && outstanding_globs == 0 {
115 return self.binding.map(Success).unwrap_or(Failed(None));
118 if let Some(binding) = self.binding {
119 // Single imports will never be shadowable by other single or glob imports.
120 if !binding.defined_with(DefModifiers::GLOB_IMPORTED) { return Success(binding); }
121 // Non-PRELUDE glob imports will never be shadowable by other glob imports.
122 if self.outstanding_references == 0 && !binding.defined_with(DefModifiers::PRELUDE) {
123 return Success(binding);
130 // Define the name or return the existing binding if there is a collision.
131 pub fn try_define(&mut self, binding: &'a NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> {
132 let is_prelude = |binding: &NameBinding| binding.defined_with(DefModifiers::PRELUDE);
133 let old_binding = match self.binding {
134 Some(_) if is_prelude(binding) => return Ok(()),
135 Some(old_binding) if !is_prelude(old_binding) => old_binding,
136 _ => { self.binding = Some(binding); return Ok(()); }
139 // FIXME #31337: We currently allow items to shadow glob-imported re-exports.
140 if !old_binding.is_import() && binding.defined_with(DefModifiers::GLOB_IMPORTED) {
141 if let NameBindingKind::Import { binding, .. } = binding.kind {
142 if binding.is_import() { return Ok(()); }
150 struct ImportResolvingError<'a> {
151 /// Module where the error happened
152 source_module: Module<'a>,
153 import_directive: ImportDirective,
158 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
159 resolver: &'a mut Resolver<'b, 'tcx>,
162 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
165 // This is a fixed-point algorithm. We resolve imports until our efforts
166 // are stymied by an unresolved import; then we bail out of the current
167 // module and continue. We terminate successfully once no more imports
168 // remain or unsuccessfully when no forward progress in resolving imports
171 /// Resolves all imports for the crate. This method performs the fixed-
173 fn resolve_imports(&mut self) {
175 let mut prev_unresolved_imports = 0;
177 debug!("(resolving imports) iteration {}, {} imports left",
179 self.resolver.unresolved_imports);
181 let module_root = self.resolver.graph_root;
182 let errors = self.resolve_imports_for_module_subtree(module_root);
184 if self.resolver.unresolved_imports == 0 {
185 debug!("(resolving imports) success");
189 if self.resolver.unresolved_imports == prev_unresolved_imports {
191 if errors.len() > 0 {
193 self.import_resolving_error(e)
196 // Report unresolved imports only if no hard error was already reported
197 // to avoid generating multiple errors on the same import.
198 // Imports that are still indeterminate at this point are actually blocked
199 // by errored imports, so there is no point reporting them.
200 self.resolver.report_unresolved_imports(module_root);
206 prev_unresolved_imports = self.resolver.unresolved_imports;
210 /// Resolves an `ImportResolvingError` into the correct enum discriminant
211 /// and passes that on to `resolve_error`.
212 fn import_resolving_error(&self, e: ImportResolvingError<'b>) {
213 // If it's a single failed import then create a "fake" import
214 // resolution for it so that later resolve stages won't complain.
215 if let SingleImport(target, _) = e.import_directive.subclass {
216 let dummy_binding = self.resolver.new_name_binding(NameBinding {
217 modifiers: DefModifiers::PRELUDE,
218 kind: NameBindingKind::Def(Def::Err),
222 let _ = e.source_module.try_define_child(target, ValueNS, dummy_binding);
223 let _ = e.source_module.try_define_child(target, TypeNS, dummy_binding);
226 let path = import_path_to_string(&e.import_directive.module_path,
227 e.import_directive.subclass);
229 resolve_error(self.resolver,
231 ResolutionError::UnresolvedImport(Some((&path, &e.help))));
234 /// Attempts to resolve imports for the given module and all of its
236 fn resolve_imports_for_module_subtree(&mut self,
238 -> Vec<ImportResolvingError<'b>> {
239 let mut errors = Vec::new();
240 debug!("(resolving imports for module subtree) resolving {}",
241 module_to_string(&module_));
242 let orig_module = replace(&mut self.resolver.current_module, module_);
243 errors.extend(self.resolve_imports_for_module(module_));
244 self.resolver.current_module = orig_module;
246 for (_, child_module) in module_.module_children.borrow().iter() {
247 errors.extend(self.resolve_imports_for_module_subtree(child_module));
253 /// Attempts to resolve imports for the given module only.
254 fn resolve_imports_for_module(&mut self, module: Module<'b>) -> Vec<ImportResolvingError<'b>> {
255 let mut errors = Vec::new();
257 if module.all_imports_resolved() {
258 debug!("(resolving imports for module) all imports resolved for {}",
259 module_to_string(&module));
263 let mut imports = module.imports.borrow_mut();
264 let import_count = imports.len();
265 let mut indeterminate_imports = Vec::new();
266 while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
267 let import_index = module.resolved_import_count.get();
268 match self.resolve_import_for_module(module, &imports[import_index]) {
269 ResolveResult::Failed(err) => {
270 let import_directive = &imports[import_index];
271 let (span, help) = match err {
272 Some((span, msg)) => (span, format!(". {}", msg)),
273 None => (import_directive.span, String::new()),
275 errors.push(ImportResolvingError {
276 source_module: module,
277 import_directive: import_directive.clone(),
282 ResolveResult::Indeterminate => {}
283 ResolveResult::Success(()) => {
285 module.resolved_import_count
286 .set(module.resolved_import_count.get() + 1);
290 // This resolution was not successful, keep it for later
291 indeterminate_imports.push(imports.swap_remove(import_index));
295 imports.extend(indeterminate_imports);
300 /// Attempts to resolve the given import. The return value indicates
301 /// failure if we're certain the name does not exist, indeterminate if we
302 /// don't know whether the name exists at the moment due to other
303 /// currently-unresolved imports, or success if we know the name exists.
304 /// If successful, the resolved bindings are written into the module.
305 fn resolve_import_for_module(&mut self,
307 import_directive: &ImportDirective)
308 -> ResolveResult<()> {
309 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
310 names_to_string(&import_directive.module_path),
311 module_to_string(&module_));
314 .resolve_module_path(module_,
315 &import_directive.module_path,
316 UseLexicalScopeFlag::DontUseLexicalScope,
317 import_directive.span)
318 .and_then(|(containing_module, lp)| {
319 // We found the module that the target is contained
320 // within. Attempt to resolve the import within it.
321 if let SingleImport(target, source) = import_directive.subclass {
322 self.resolve_single_import(module_,
329 self.resolve_glob_import(module_, containing_module, import_directive, lp)
333 // Decrement the count of unresolved imports.
334 assert!(self.resolver.unresolved_imports >= 1);
335 self.resolver.unresolved_imports -= 1;
337 if let GlobImport = import_directive.subclass {
338 module_.dec_glob_count();
339 if import_directive.is_public {
340 module_.dec_pub_glob_count();
343 if import_directive.is_public {
344 module_.dec_pub_count();
350 fn resolve_single_import(&mut self,
352 target_module: Module<'b>,
355 directive: &ImportDirective,
357 -> ResolveResult<()> {
358 debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
361 module_to_string(&target_module),
363 module_to_string(module_),
372 .span_bug(directive.span, "not expecting Import here, must be LastMod")
376 // If this is a circular import, we temporarily count it as determined so that
377 // it fails (as opposed to being indeterminate) when nothing else can define it.
378 if target_module.def_id() == module_.def_id() && source == target {
379 module_.decrement_outstanding_references_for(target, ValueNS);
380 module_.decrement_outstanding_references_for(target, TypeNS);
383 // We need to resolve both namespaces for this to succeed.
385 self.resolver.resolve_name_in_module(target_module, source, ValueNS, false, true);
387 self.resolver.resolve_name_in_module(target_module, source, TypeNS, false, true);
389 if target_module.def_id() == module_.def_id() && source == target {
390 module_.increment_outstanding_references_for(target, ValueNS);
391 module_.increment_outstanding_references_for(target, TypeNS);
394 match (&value_result, &type_result) {
395 (&Indeterminate, _) | (_, &Indeterminate) => return Indeterminate,
396 (&Failed(_), &Failed(_)) => {
397 let children = target_module.resolutions.borrow();
398 let names = children.keys().map(|&(ref name, _)| name);
399 let lev_suggestion = match find_best_match_for_name(names, &source.as_str(), None) {
400 Some(name) => format!(". Did you mean to use `{}`?", name),
401 None => "".to_owned(),
403 let msg = format!("There is no `{}` in `{}`{}",
405 module_to_string(target_module), lev_suggestion);
406 return Failed(Some((directive.span, msg)));
411 match (&value_result, &type_result) {
412 (&Success(name_binding), _) if !name_binding.is_import() &&
413 directive.is_public &&
414 !name_binding.is_public() => {
415 let msg = format!("`{}` is private, and cannot be reexported", source);
416 let note_msg = format!("Consider marking `{}` as `pub` in the imported module",
418 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
419 .span_note(directive.span, ¬e_msg)
423 (_, &Success(name_binding)) if !name_binding.is_import() && directive.is_public => {
424 if !name_binding.is_public() {
425 let msg = format!("`{}` is private, and cannot be reexported", source);
427 format!("Consider declaring type or module `{}` with `pub`", source);
428 struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
429 .span_note(directive.span, ¬e_msg)
431 } else if name_binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
432 let msg = format!("variant `{}` is private, and cannot be reexported \
433 (error E0364), consider declaring its enum as `pub`",
435 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
445 for &(ns, result) in &[(ValueNS, &value_result), (TypeNS, &type_result)] {
446 if let Success(binding) = *result {
447 if !binding.defined_with(DefModifiers::IMPORTABLE) {
448 let msg = format!("`{}` is not directly importable", target);
449 span_err!(self.resolver.session, directive.span, E0253, "{}", &msg);
452 self.define(module_, target, ns, directive.import(binding));
456 // Record what this import resolves to for later uses in documentation,
457 // this may resolve to either a value or a type, but for documentation
458 // purposes it's good enough to just favor one over the other.
459 module_.decrement_outstanding_references_for(target, ValueNS);
460 module_.decrement_outstanding_references_for(target, TypeNS);
462 let def_and_priv = |binding: &NameBinding| {
463 let def = binding.def().unwrap();
464 let last_private = if binding.is_public() { lp } else { DependsOn(def.def_id()) };
467 let value_def_and_priv = value_result.success().map(&def_and_priv);
468 let type_def_and_priv = type_result.success().map(&def_and_priv);
470 let import_lp = LastImport {
471 value_priv: value_def_and_priv.map(|(_, p)| p),
473 type_priv: type_def_and_priv.map(|(_, p)| p),
477 let write_path_resolution = |(def, _)| {
478 let path_resolution =
479 PathResolution { base_def: def, last_private: import_lp, depth: 0 };
480 self.resolver.def_map.borrow_mut().insert(directive.id, path_resolution);
482 value_def_and_priv.map(&write_path_resolution);
483 type_def_and_priv.map(&write_path_resolution);
485 debug!("(resolving single import) successfully resolved import");
489 // Resolves a glob import. Note that this function cannot fail; it either
490 // succeeds or bails out (as importing * from an empty module or a module
491 // that exports nothing is valid). target_module is the module we are
492 // actually importing, i.e., `foo` in `use foo::*`.
493 fn resolve_glob_import(&mut self,
495 target_module: Module<'b>,
496 directive: &ImportDirective,
498 -> ResolveResult<()> {
499 // We must bail out if the node has unresolved imports of any kind (including globs).
500 if target_module.pub_count.get() > 0 {
501 debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
502 return Indeterminate;
505 if module_.def_id() == target_module.def_id() {
506 // This means we are trying to glob import a module into itself, and it is a no-go
507 let msg = "Cannot glob-import a module into itself.".into();
508 return Failed(Some((directive.span, msg)));
511 // Add all children from the containing module.
512 build_reduced_graph::populate_module_if_necessary(self.resolver, target_module);
513 target_module.for_each_child(|name, ns, binding| {
514 if !binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { return }
515 if binding.is_extern_crate() { return }
516 self.define(module_, name, ns, directive.import(binding));
518 if ns == TypeNS && directive.is_public &&
519 binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
520 let msg = format!("variant `{}` is private, and cannot be reexported (error \
521 E0364), consider declaring its enum as `pub`", name);
522 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
529 // Record the destination of this import
530 if let Some(did) = target_module.def_id() {
531 self.resolver.def_map.borrow_mut().insert(directive.id,
533 base_def: Def::Mod(did),
539 debug!("(resolving glob import) successfully resolved import");
547 binding: NameBinding<'b>) {
548 let binding = self.resolver.new_name_binding(binding);
549 if let Err(old_binding) = parent.try_define_child(name, ns, binding) {
550 self.report_conflict(name, ns, binding, old_binding);
551 } else if binding.is_public() { // Add to the export map
552 if let (Some(parent_def_id), Some(def)) = (parent.def_id(), binding.def()) {
553 let parent_node_id = self.resolver.ast_map.as_local_node_id(parent_def_id).unwrap();
554 let export = Export { name: name, def_id: def.def_id() };
555 self.resolver.export_map.entry(parent_node_id).or_insert(Vec::new()).push(export);
560 fn report_conflict(&mut self,
563 binding: &'b NameBinding<'b>,
564 old_binding: &'b NameBinding<'b>) {
565 if old_binding.is_extern_crate() {
566 let msg = format!("import `{0}` conflicts with imported crate \
567 in this module (maybe you meant `use {0}::*`?)",
569 span_err!(self.resolver.session, binding.span.unwrap(), E0254, "{}", &msg);
570 } else if old_binding.is_import() {
571 let ns_word = match (ns, old_binding.module()) {
572 (ValueNS, _) => "value",
573 (TypeNS, Some(module)) if module.is_normal() => "module",
574 (TypeNS, Some(module)) if module.is_trait() => "trait",
575 (TypeNS, _) => "type",
577 let mut err = struct_span_err!(self.resolver.session,
578 binding.span.unwrap(),
580 "a {} named `{}` has already been imported \
584 err.span_note(old_binding.span.unwrap(),
585 &format!("previous import of `{}` here", name));
587 } else if ns == ValueNS { // Check for item conflicts in the value namespace
588 let mut err = struct_span_err!(self.resolver.session,
589 binding.span.unwrap(),
591 "import `{}` conflicts with value in this module",
593 err.span_note(old_binding.span.unwrap(), "conflicting value here");
595 } else { // Check for item conflicts in the type namespace
596 let (what, note) = match old_binding.module() {
597 Some(ref module) if module.is_normal() =>
598 ("existing submodule", "note conflicting module here"),
599 Some(ref module) if module.is_trait() =>
600 ("trait in this module", "note conflicting trait here"),
601 _ => ("type in this module", "note conflicting type here"),
603 let mut err = struct_span_err!(self.resolver.session,
604 binding.span.unwrap(),
606 "import `{}` conflicts with {}",
609 err.span_note(old_binding.span.unwrap(), note);
615 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
616 if names.is_empty() {
617 import_directive_subclass_to_string(subclass)
620 names_to_string(names),
621 import_directive_subclass_to_string(subclass)))
626 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
628 SingleImport(_, source) => source.to_string(),
629 GlobImport => "*".to_string(),
633 pub fn resolve_imports(resolver: &mut Resolver) {
634 let mut import_resolver = ImportResolver { resolver: resolver };
635 import_resolver.resolve_imports();