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 build_reduced_graph::populate_module_if_necessary(self.resolver, module_);
247 module_.for_each_local_child(|_, _, child_node| {
248 match child_node.module() {
252 Some(child_module) => {
253 errors.extend(self.resolve_imports_for_module_subtree(child_module));
258 for (_, child_module) in module_.anonymous_children.borrow().iter() {
259 errors.extend(self.resolve_imports_for_module_subtree(child_module));
265 /// Attempts to resolve imports for the given module only.
266 fn resolve_imports_for_module(&mut self, module: Module<'b>) -> Vec<ImportResolvingError<'b>> {
267 let mut errors = Vec::new();
269 if module.all_imports_resolved() {
270 debug!("(resolving imports for module) all imports resolved for {}",
271 module_to_string(&*module));
275 let mut imports = module.imports.borrow_mut();
276 let import_count = imports.len();
277 let mut indeterminate_imports = Vec::new();
278 while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
279 let import_index = module.resolved_import_count.get();
280 match self.resolve_import_for_module(module, &imports[import_index]) {
281 ResolveResult::Failed(err) => {
282 let import_directive = &imports[import_index];
283 let (span, help) = match err {
284 Some((span, msg)) => (span, format!(". {}", msg)),
285 None => (import_directive.span, String::new()),
287 errors.push(ImportResolvingError {
288 source_module: module,
289 import_directive: import_directive.clone(),
294 ResolveResult::Indeterminate => {}
295 ResolveResult::Success(()) => {
297 module.resolved_import_count
298 .set(module.resolved_import_count.get() + 1);
302 // This resolution was not successful, keep it for later
303 indeterminate_imports.push(imports.swap_remove(import_index));
307 imports.extend(indeterminate_imports);
312 /// Attempts to resolve the given import. The return value indicates
313 /// failure if we're certain the name does not exist, indeterminate if we
314 /// don't know whether the name exists at the moment due to other
315 /// currently-unresolved imports, or success if we know the name exists.
316 /// If successful, the resolved bindings are written into the module.
317 fn resolve_import_for_module(&mut self,
319 import_directive: &ImportDirective)
320 -> ResolveResult<()> {
321 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
322 names_to_string(&import_directive.module_path),
323 module_to_string(&*module_));
326 .resolve_module_path(module_,
327 &import_directive.module_path,
328 UseLexicalScopeFlag::DontUseLexicalScope,
329 import_directive.span)
330 .and_then(|(containing_module, lp)| {
331 // We found the module that the target is contained
332 // within. Attempt to resolve the import within it.
333 if let SingleImport(target, source) = import_directive.subclass {
334 self.resolve_single_import(module_,
341 self.resolve_glob_import(module_, containing_module, import_directive, lp)
345 // Decrement the count of unresolved imports.
346 assert!(self.resolver.unresolved_imports >= 1);
347 self.resolver.unresolved_imports -= 1;
349 if let GlobImport = import_directive.subclass {
350 module_.dec_glob_count();
351 if import_directive.is_public {
352 module_.dec_pub_glob_count();
355 if import_directive.is_public {
356 module_.dec_pub_count();
362 fn resolve_single_import(&mut self,
364 target_module: Module<'b>,
367 directive: &ImportDirective,
369 -> ResolveResult<()> {
370 debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
373 module_to_string(&*target_module),
375 module_to_string(module_),
384 .span_bug(directive.span, "not expecting Import here, must be LastMod")
388 // If this is a circular import, we temporarily count it as determined so that
389 // it fails (as opposed to being indeterminate) when nothing else can define it.
390 if target_module.def_id() == module_.def_id() && source == target {
391 module_.decrement_outstanding_references_for(target, ValueNS);
392 module_.decrement_outstanding_references_for(target, TypeNS);
395 // We need to resolve both namespaces for this to succeed.
397 self.resolver.resolve_name_in_module(target_module, source, ValueNS, false, true);
399 self.resolver.resolve_name_in_module(target_module, source, TypeNS, false, true);
401 if target_module.def_id() == module_.def_id() && source == target {
402 module_.increment_outstanding_references_for(target, ValueNS);
403 module_.increment_outstanding_references_for(target, TypeNS);
406 match (&value_result, &type_result) {
407 (&Success(name_binding), _) if !name_binding.is_import() &&
408 directive.is_public &&
409 !name_binding.is_public() => {
410 let msg = format!("`{}` is private, and cannot be reexported", source);
411 let note_msg = format!("Consider marking `{}` as `pub` in the imported module",
413 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
414 .span_note(directive.span, ¬e_msg)
418 (_, &Success(name_binding)) if !name_binding.is_import() && directive.is_public => {
419 if !name_binding.is_public() {
420 let msg = format!("`{}` is private, and cannot be reexported", source);
422 format!("Consider declaring type or module `{}` with `pub`", source);
423 struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
424 .span_note(directive.span, ¬e_msg)
426 } else if name_binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
427 let msg = format!("variant `{}` is private, and cannot be reexported \
428 (error E0364), consider declaring its enum as `pub`",
430 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
440 match (&value_result, &type_result) {
441 (&Indeterminate, _) | (_, &Indeterminate) => return Indeterminate,
442 (&Failed(_), &Failed(_)) => {
443 let children = target_module.children.borrow();
444 let names = children.keys().map(|&(ref name, _)| name);
445 let lev_suggestion = match find_best_match_for_name(names, &source.as_str(), None) {
446 Some(name) => format!(". Did you mean to use `{}`?", name),
447 None => "".to_owned(),
449 let msg = format!("There is no `{}` in `{}`{}",
451 module_to_string(target_module), lev_suggestion);
452 return Failed(Some((directive.span, msg)));
457 for &(ns, result) in &[(ValueNS, &value_result), (TypeNS, &type_result)] {
458 if let Success(binding) = *result {
459 if !binding.defined_with(DefModifiers::IMPORTABLE) {
460 let msg = format!("`{}` is not directly importable", target);
461 span_err!(self.resolver.session, directive.span, E0253, "{}", &msg);
464 self.define(module_, target, ns, directive.import(binding));
468 // Record what this import resolves to for later uses in documentation,
469 // this may resolve to either a value or a type, but for documentation
470 // purposes it's good enough to just favor one over the other.
471 module_.decrement_outstanding_references_for(target, ValueNS);
472 module_.decrement_outstanding_references_for(target, TypeNS);
474 let def_and_priv = |binding: &NameBinding| {
475 let def = binding.def().unwrap();
476 let last_private = if binding.is_public() { lp } else { DependsOn(def.def_id()) };
479 let value_def_and_priv = value_result.success().map(&def_and_priv);
480 let type_def_and_priv = type_result.success().map(&def_and_priv);
482 let import_lp = LastImport {
483 value_priv: value_def_and_priv.map(|(_, p)| p),
485 type_priv: type_def_and_priv.map(|(_, p)| p),
489 let write_path_resolution = |(def, _)| {
490 let path_resolution =
491 PathResolution { base_def: def, last_private: import_lp, depth: 0 };
492 self.resolver.def_map.borrow_mut().insert(directive.id, path_resolution);
494 value_def_and_priv.map(&write_path_resolution);
495 type_def_and_priv.map(&write_path_resolution);
497 debug!("(resolving single import) successfully resolved import");
501 // Resolves a glob import. Note that this function cannot fail; it either
502 // succeeds or bails out (as importing * from an empty module or a module
503 // that exports nothing is valid). target_module is the module we are
504 // actually importing, i.e., `foo` in `use foo::*`.
505 fn resolve_glob_import(&mut self,
507 target_module: Module<'b>,
508 directive: &ImportDirective,
510 -> ResolveResult<()> {
511 // We must bail out if the node has unresolved imports of any kind (including globs).
512 if target_module.pub_count.get() > 0 {
513 debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
514 return Indeterminate;
517 if module_.def_id() == target_module.def_id() {
518 // This means we are trying to glob import a module into itself, and it is a no-go
519 let msg = "Cannot glob-import a module into itself.".into();
520 return Failed(Some((directive.span, msg)));
523 // Add all children from the containing module.
524 build_reduced_graph::populate_module_if_necessary(self.resolver, target_module);
525 target_module.for_each_child(|name, ns, binding| {
526 if !binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { return }
527 if binding.is_extern_crate() { return }
528 self.define(module_, name, ns, directive.import(binding));
530 if ns == TypeNS && directive.is_public &&
531 binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
532 let msg = format!("variant `{}` is private, and cannot be reexported (error \
533 E0364), consider declaring its enum as `pub`", name);
534 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
541 // Record the destination of this import
542 if let Some(did) = target_module.def_id() {
543 self.resolver.def_map.borrow_mut().insert(directive.id,
545 base_def: Def::Mod(did),
551 debug!("(resolving glob import) successfully resolved import");
559 binding: NameBinding<'b>) {
560 let binding = self.resolver.new_name_binding(binding);
561 if let Err(old_binding) = parent.try_define_child(name, ns, binding) {
562 self.report_conflict(name, ns, binding, old_binding);
563 } else if binding.is_public() { // Add to the export map
564 if let (Some(parent_def_id), Some(def)) = (parent.def_id(), binding.def()) {
565 let parent_node_id = self.resolver.ast_map.as_local_node_id(parent_def_id).unwrap();
566 let export = Export { name: name, def_id: def.def_id() };
567 self.resolver.export_map.entry(parent_node_id).or_insert(Vec::new()).push(export);
572 fn report_conflict(&mut self,
575 binding: &'b NameBinding<'b>,
576 old_binding: &'b NameBinding<'b>) {
577 if old_binding.is_extern_crate() {
578 let msg = format!("import `{0}` conflicts with imported crate \
579 in this module (maybe you meant `use {0}::*`?)",
581 span_err!(self.resolver.session, binding.span.unwrap(), E0254, "{}", &msg);
582 } else if old_binding.is_import() {
583 let ns_word = match (ns, old_binding.module()) {
584 (ValueNS, _) => "value",
585 (TypeNS, Some(module)) if module.is_normal() => "module",
586 (TypeNS, Some(module)) if module.is_trait() => "trait",
587 (TypeNS, _) => "type",
589 let mut err = struct_span_err!(self.resolver.session,
590 binding.span.unwrap(),
592 "a {} named `{}` has already been imported \
596 err.span_note(old_binding.span.unwrap(),
597 &format!("previous import of `{}` here", name));
599 } else if ns == ValueNS { // Check for item conflicts in the value namespace
600 let mut err = struct_span_err!(self.resolver.session,
601 binding.span.unwrap(),
603 "import `{}` conflicts with value in this module",
605 err.span_note(old_binding.span.unwrap(), "conflicting value here");
607 } else { // Check for item conflicts in the type namespace
608 let (what, note) = match old_binding.module() {
609 Some(ref module) if module.is_normal() =>
610 ("existing submodule", "note conflicting module here"),
611 Some(ref module) if module.is_trait() =>
612 ("trait in this module", "note conflicting trait here"),
613 _ => ("type in this module", "note conflicting type here"),
615 let mut err = struct_span_err!(self.resolver.session,
616 binding.span.unwrap(),
618 "import `{}` conflicts with {}",
621 err.span_note(old_binding.span.unwrap(), note);
627 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
628 if names.is_empty() {
629 import_directive_subclass_to_string(subclass)
632 names_to_string(names),
633 import_directive_subclass_to_string(subclass)))
638 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
640 SingleImport(_, source) => source.to_string(),
641 GlobImport => "*".to_string(),
645 pub fn resolve_imports(resolver: &mut Resolver) {
646 let mut import_resolver = ImportResolver { resolver: resolver };
647 import_resolver.resolve_imports();