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 {NameBindings, NameBinding};
17 use NamespaceResult::{BoundResult, UnboundResult, UnknownResult};
22 use UseLexicalScopeFlag;
23 use {names_to_string, module_to_string};
24 use {resolve_error, ResolutionError};
26 use build_reduced_graph;
29 use rustc::middle::def::*;
30 use rustc::middle::def_id::DefId;
31 use rustc::middle::privacy::*;
33 use syntax::ast::{NodeId, Name};
34 use syntax::attr::AttrMetaMethods;
35 use syntax::codemap::Span;
36 use syntax::util::lev_distance::find_best_match_for_name;
38 use std::mem::replace;
40 /// Contains data for specific types of import directives.
41 #[derive(Copy, Clone,Debug)]
42 pub enum ImportDirectiveSubclass {
43 SingleImport(Name /* target */, Name /* source */),
47 /// Whether an import can be shadowed by another import.
48 #[derive(Debug,PartialEq,Clone,Copy)]
54 /// One import directive.
56 pub struct ImportDirective {
57 pub module_path: Vec<Name>,
58 pub subclass: ImportDirectiveSubclass,
61 pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
62 pub shadowable: Shadowable,
65 impl ImportDirective {
66 pub fn new(module_path: Vec<Name>,
67 subclass: ImportDirectiveSubclass,
71 shadowable: Shadowable)
74 module_path: module_path,
79 shadowable: shadowable,
84 /// The item that an import resolves to.
85 #[derive(Clone,Debug)]
86 pub struct Target<'a> {
87 pub target_module: Module<'a>,
88 pub binding: NameBinding<'a>,
89 pub shadowable: Shadowable,
93 pub fn new(target_module: Module<'a>, binding: NameBinding<'a>, shadowable: Shadowable)
96 target_module: target_module,
98 shadowable: shadowable,
104 /// An ImportResolutionPerNamespace records what we know about an imported name.
105 /// More specifically, it records the number of unresolved `use` directives that import the name,
106 /// and for each namespace, it records the `use` directive importing the name in the namespace
107 /// and the `Target` to which the name in the namespace resolves (if applicable).
108 /// Different `use` directives may import the same name in different namespaces.
109 pub struct ImportResolutionPerNamespace<'a> {
110 // When outstanding_references reaches zero, outside modules can count on the targets being
111 // correct. Before then, all bets are off; future `use` directives could override the name.
112 // Since shadowing is forbidden, the only way outstanding_references > 1 in a legal program
113 // is if the name is imported by exactly two `use` directives, one of which resolves to a
114 // value and the other of which resolves to a type.
115 pub outstanding_references: usize,
116 pub type_ns: ImportResolution<'a>,
117 pub value_ns: ImportResolution<'a>,
120 /// Records what we know about an imported name in a namespace (see `ImportResolutionPerNamespace`).
121 #[derive(Clone,Debug)]
122 pub struct ImportResolution<'a> {
123 /// Whether the name in the namespace was imported with a `use` or a `pub use`.
126 /// Resolution of the name in the namespace
127 pub target: Option<Target<'a>>,
129 /// The source node of the `use` directive
133 impl<'a> ::std::ops::Index<Namespace> for ImportResolutionPerNamespace<'a> {
134 type Output = ImportResolution<'a>;
135 fn index(&self, ns: Namespace) -> &ImportResolution<'a> {
136 match ns { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
140 impl<'a> ::std::ops::IndexMut<Namespace> for ImportResolutionPerNamespace<'a> {
141 fn index_mut(&mut self, ns: Namespace) -> &mut ImportResolution<'a> {
142 match ns { TypeNS => &mut self.type_ns, ValueNS => &mut self.value_ns }
146 impl<'a> ImportResolutionPerNamespace<'a> {
147 pub fn new(id: NodeId, is_public: bool) -> Self {
148 let resolution = ImportResolution { id: id, is_public: is_public, target: None };
149 ImportResolutionPerNamespace {
150 outstanding_references: 0, type_ns: resolution.clone(), value_ns: resolution,
154 pub fn shadowable(&self, namespace: Namespace) -> Shadowable {
155 match self[namespace].target {
156 Some(ref target) => target.shadowable,
157 None => Shadowable::Always,
162 struct ImportResolvingError {
168 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
169 resolver: &'a mut Resolver<'b, 'tcx>,
172 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
175 // This is a fixed-point algorithm. We resolve imports until our efforts
176 // are stymied by an unresolved import; then we bail out of the current
177 // module and continue. We terminate successfully once no more imports
178 // remain or unsuccessfully when no forward progress in resolving imports
181 /// Resolves all imports for the crate. This method performs the fixed-
183 fn resolve_imports(&mut self) {
185 let mut prev_unresolved_imports = 0;
187 debug!("(resolving imports) iteration {}, {} imports left",
189 self.resolver.unresolved_imports);
191 let module_root = self.resolver.graph_root;
192 let errors = self.resolve_imports_for_module_subtree(module_root);
194 if self.resolver.unresolved_imports == 0 {
195 debug!("(resolving imports) success");
199 if self.resolver.unresolved_imports == prev_unresolved_imports {
201 if errors.len() > 0 {
203 resolve_error(self.resolver,
205 ResolutionError::UnresolvedImport(Some((&e.path, &e.help))));
208 // Report unresolved imports only if no hard error was already reported
209 // to avoid generating multiple errors on the same import.
210 // Imports that are still indeterminate at this point are actually blocked
211 // by errored imports, so there is no point reporting them.
212 self.resolver.report_unresolved_imports(module_root);
218 prev_unresolved_imports = self.resolver.unresolved_imports;
222 /// Attempts to resolve imports for the given module and all of its
224 fn resolve_imports_for_module_subtree(&mut self,
226 -> Vec<ImportResolvingError> {
227 let mut errors = Vec::new();
228 debug!("(resolving imports for module subtree) resolving {}",
229 module_to_string(&*module_));
230 let orig_module = replace(&mut self.resolver.current_module, module_);
231 errors.extend(self.resolve_imports_for_module(module_));
232 self.resolver.current_module = orig_module;
234 build_reduced_graph::populate_module_if_necessary(self.resolver, &module_);
235 for (_, child_node) in module_.children.borrow().iter() {
236 match child_node.type_ns.module() {
240 Some(child_module) => {
241 errors.extend(self.resolve_imports_for_module_subtree(child_module));
246 for (_, child_module) in module_.anonymous_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> {
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 {
277 path: import_path_to_string(&import_directive.module_path,
278 import_directive.subclass),
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 let mut resolution_result = ResolveResult::Failed(None);
310 let module_path = &import_directive.module_path;
312 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
313 names_to_string(&module_path[..]),
314 module_to_string(&*module_));
316 // First, resolve the module path for the directive, if necessary.
317 let container = if module_path.is_empty() {
318 // Use the crate root.
319 Some((self.resolver.graph_root, LastMod(AllPublic)))
321 match self.resolver.resolve_module_path(module_,
323 UseLexicalScopeFlag::DontUseLexicalScope,
324 import_directive.span,
325 NameSearchType::ImportSearch) {
326 ResolveResult::Failed(err) => {
327 resolution_result = ResolveResult::Failed(err);
330 ResolveResult::Indeterminate => {
331 resolution_result = ResolveResult::Indeterminate;
334 ResolveResult::Success(container) => Some(container),
340 Some((containing_module, lp)) => {
341 // We found the module that the target is contained
342 // within. Attempt to resolve the import within it.
344 match import_directive.subclass {
345 SingleImport(target, source) => {
346 resolution_result = self.resolve_single_import(&module_,
354 resolution_result = self.resolve_glob_import(&module_,
363 // Decrement the count of unresolved imports.
364 match resolution_result {
365 ResolveResult::Success(()) => {
366 assert!(self.resolver.unresolved_imports >= 1);
367 self.resolver.unresolved_imports -= 1;
370 // Nothing to do here; just return the error.
374 // Decrement the count of unresolved globs if necessary. But only if
375 // the resolution result is a success -- other cases will
376 // be handled by the main loop.
378 if resolution_result.success() {
379 match import_directive.subclass {
381 module_.dec_glob_count();
382 if import_directive.is_public {
383 module_.dec_pub_glob_count();
386 SingleImport(..) => {
390 if import_directive.is_public {
391 module_.dec_pub_count();
395 return resolution_result;
398 fn resolve_single_import(&mut self,
400 target_module: Module<'b>,
403 directive: &ImportDirective,
405 -> ResolveResult<()> {
406 debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
409 module_to_string(&*target_module),
411 module_to_string(module_),
420 .span_bug(directive.span, "not expecting Import here, must be LastMod")
424 // We need to resolve both namespaces for this to succeed.
426 let mut value_result = UnknownResult;
427 let mut type_result = UnknownResult;
428 let mut lev_suggestion = "".to_owned();
430 // Search for direct children of the containing module.
431 build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
433 match target_module.children.borrow().get(&source) {
435 let names = target_module.children.borrow();
436 if let Some(name) = find_best_match_for_name(names.keys(),
439 lev_suggestion = format!(". Did you mean to use `{}`?", name);
442 Some(ref child_name_bindings) => {
443 // pub_err makes sure we don't give the same error twice.
444 let mut pub_err = false;
445 if child_name_bindings.value_ns.defined() {
446 debug!("(resolving single import) found value binding");
447 value_result = BoundResult(target_module,
448 child_name_bindings.value_ns.clone());
449 if directive.is_public && !child_name_bindings.value_ns.is_public() {
450 let msg = format!("`{}` is private, and cannot be reexported", source);
451 let note_msg = format!("Consider marking `{}` as `pub` in the imported \
454 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
455 .span_note(directive.span, ¬e_msg)
459 if directive.is_public && child_name_bindings.value_ns.
460 defined_with(DefModifiers::PRIVATE_VARIANT) {
461 let msg = format!("variant `{}` is private, and cannot be reexported ( \
462 error E0364), consider declaring its enum as `pub`",
464 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
471 if child_name_bindings.type_ns.defined() {
472 debug!("(resolving single import) found type binding");
473 type_result = BoundResult(target_module,
474 child_name_bindings.type_ns.clone());
475 if !pub_err && directive.is_public &&
476 !child_name_bindings.type_ns.is_public() {
477 let msg = format!("`{}` is private, and cannot be reexported", source);
478 let note_msg = format!("Consider declaring module `{}` as a `pub mod`",
480 struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
481 .span_note(directive.span, ¬e_msg)
484 if !pub_err && directive.is_public && child_name_bindings.type_ns.
485 defined_with(DefModifiers::PRIVATE_VARIANT) {
486 let msg = format!("variant `{}` is private, and cannot be reexported ( \
487 error E0365), consider declaring its enum as `pub`",
489 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
498 // Unless we managed to find a result in both namespaces (unlikely),
499 // search imports as well.
500 let mut value_used_reexport = false;
501 let mut type_used_reexport = false;
502 match (value_result.clone(), type_result.clone()) {
503 (BoundResult(..), BoundResult(..)) => {} // Continue.
505 // If there is an unresolved glob at this point in the
506 // containing module, bail out. We don't know enough to be
507 // able to resolve this import.
509 if target_module.pub_glob_count.get() > 0 {
510 debug!("(resolving single import) unresolved pub glob; bailing out");
511 return ResolveResult::Indeterminate;
514 // Now search the exported imports within the containing module.
515 match target_module.import_resolutions.borrow().get(&source) {
517 debug!("(resolving single import) no import");
518 // The containing module definitely doesn't have an
519 // exported import with the name in question. We can
520 // therefore accurately report that the names are
523 if lev_suggestion.is_empty() { // skip if we already have a suggestion
524 let names = target_module.import_resolutions.borrow();
525 if let Some(name) = find_best_match_for_name(names.keys(),
529 format!(". Did you mean to use the re-exported import `{}`?",
534 if value_result.is_unknown() {
535 value_result = UnboundResult;
537 if type_result.is_unknown() {
538 type_result = UnboundResult;
541 Some(import_resolution) if import_resolution.outstanding_references == 0 => {
543 fn get_binding<'a>(this: &mut Resolver,
544 import_resolution: &ImportResolutionPerNamespace<'a>,
545 namespace: Namespace,
547 -> NamespaceResult<'a> {
549 // Import resolutions must be declared with "pub"
550 // in order to be exported.
551 if !import_resolution[namespace].is_public {
552 return UnboundResult;
555 match import_resolution[namespace].target.clone() {
557 return UnboundResult;
564 debug!("(resolving single import) found import in ns {:?}",
566 let id = import_resolution[namespace].id;
567 // track used imports and extern crates as well
568 this.used_imports.insert((id, namespace));
569 this.record_import_use(id, source);
570 match target_module.def_id() {
571 Some(DefId{krate: kid, ..}) => {
572 this.used_crates.insert(kid);
576 return BoundResult(target_module, binding);
581 // The name is an import which has been fully
582 // resolved. We can, therefore, just follow it.
583 if value_result.is_unknown() {
584 value_result = get_binding(self.resolver,
588 value_used_reexport = import_resolution.value_ns.is_public;
590 if type_result.is_unknown() {
591 type_result = get_binding(self.resolver,
595 type_used_reexport = import_resolution.type_ns.is_public;
600 // If target_module is the same module whose import we are resolving
601 // and there it has an unresolved import with the same name as `source`,
602 // then the user is actually trying to import an item that is declared
606 // use self::submodule;
607 // pub mod submodule;
609 // In this case we continue as if we resolved the import and let the
610 // check_for_conflicts_between_imports_and_items call below handle
612 match (module_.def_id(), target_module.def_id()) {
613 (Some(id1), Some(id2)) if id1 == id2 => {
614 if value_result.is_unknown() {
615 value_result = UnboundResult;
617 if type_result.is_unknown() {
618 type_result = UnboundResult;
622 // The import is unresolved. Bail out.
623 debug!("(resolving single import) unresolved import; bailing out");
624 return ResolveResult::Indeterminate;
632 let mut value_used_public = false;
633 let mut type_used_public = false;
635 // If we didn't find a result in the type namespace, search the
638 BoundResult(..) => {}
640 match target_module.external_module_children.borrow_mut().get(&source) {
641 None => {} // Continue.
643 debug!("(resolving single import) found external module");
644 // track the module as used.
645 match module.def_id() {
646 Some(DefId{krate: kid, ..}) => {
647 self.resolver.used_crates.insert(kid);
651 let name_binding = NameBinding::create_from_module(module);
652 type_result = BoundResult(target_module, name_binding);
653 type_used_public = true;
659 // We've successfully resolved the import. Write the results in.
660 let mut import_resolutions = module_.import_resolutions.borrow_mut();
661 let import_resolution = import_resolutions.get_mut(&target).unwrap();
664 let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
665 let namespace_name = match namespace {
671 BoundResult(ref target_module, ref name_binding) => {
672 debug!("(resolving single import) found {:?} target: {:?}",
675 self.check_for_conflicting_import(&import_resolution,
680 self.check_that_import_is_importable(&name_binding,
684 import_resolution[namespace] = ImportResolution {
685 target: Some(Target::new(target_module,
686 name_binding.clone(),
687 directive.shadowable)),
689 is_public: directive.is_public
692 self.add_export(module_, target, &import_resolution[namespace]);
693 *used_public = name_binding.is_public();
699 panic!("{:?} result should be known at this point", namespace_name);
703 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
704 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
707 self.check_for_conflicts_between_imports_and_items(module_,
712 if value_result.is_unbound() && type_result.is_unbound() {
713 let msg = format!("There is no `{}` in `{}`{}",
715 module_to_string(&target_module), lev_suggestion);
716 return ResolveResult::Failed(Some((directive.span, msg)));
718 let value_used_public = value_used_reexport || value_used_public;
719 let type_used_public = type_used_reexport || type_used_public;
721 assert!(import_resolution.outstanding_references >= 1);
722 import_resolution.outstanding_references -= 1;
724 // Record what this import resolves to for later uses in documentation,
725 // this may resolve to either a value or a type, but for documentation
726 // purposes it's good enough to just favor one over the other.
727 let value_def_and_priv = import_resolution.value_ns.target.as_ref().map(|target| {
728 let def = target.binding.def().unwrap();
730 if value_used_public {
733 DependsOn(def.def_id())
736 let type_def_and_priv = import_resolution.type_ns.target.as_ref().map(|target| {
737 let def = target.binding.def().unwrap();
739 if type_used_public {
742 DependsOn(def.def_id())
746 let import_lp = LastImport {
747 value_priv: value_def_and_priv.map(|(_, p)| p),
749 type_priv: type_def_and_priv.map(|(_, p)| p),
753 if let Some((def, _)) = value_def_and_priv {
754 self.resolver.def_map.borrow_mut().insert(directive.id,
757 last_private: import_lp,
761 if let Some((def, _)) = type_def_and_priv {
762 self.resolver.def_map.borrow_mut().insert(directive.id,
765 last_private: import_lp,
770 debug!("(resolving single import) successfully resolved import");
771 return ResolveResult::Success(());
774 // Resolves a glob import. Note that this function cannot fail; it either
775 // succeeds or bails out (as importing * from an empty module or a module
776 // that exports nothing is valid). target_module is the module we are
777 // actually importing, i.e., `foo` in `use foo::*`.
778 fn resolve_glob_import(&mut self,
780 target_module: Module<'b>,
781 import_directive: &ImportDirective,
783 -> ResolveResult<()> {
784 let id = import_directive.id;
785 let is_public = import_directive.is_public;
787 // This function works in a highly imperative manner; it eagerly adds
788 // everything it can to the list of import resolutions of the module
790 debug!("(resolving glob import) resolving glob import {}", id);
792 // We must bail out if the node has unresolved imports of any kind
793 // (including globs).
794 if (*target_module).pub_count.get() > 0 {
795 debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
796 return ResolveResult::Indeterminate;
799 // Add all resolved imports from the containing module.
800 let import_resolutions = target_module.import_resolutions.borrow();
802 if module_.import_resolutions.borrow_state() != ::std::cell::BorrowState::Unused {
803 // In this case, target_module == module_
804 // This means we are trying to glob import a module into itself,
806 debug!("(resolving glob imports) target module is current module; giving up");
807 return ResolveResult::Failed(Some((import_directive.span,
808 "Cannot glob-import a module into itself.".into())));
811 for (name, target_import_resolution) in import_resolutions.iter() {
812 debug!("(resolving glob import) writing module resolution {} into `{}`",
814 module_to_string(module_));
816 // Here we merge two import resolutions.
817 let mut import_resolutions = module_.import_resolutions.borrow_mut();
818 let mut dest_import_resolution = import_resolutions.entry(*name).or_insert_with(|| {
819 ImportResolutionPerNamespace::new(id, is_public)
822 for &ns in [TypeNS, ValueNS].iter() {
823 match target_import_resolution[ns].target {
824 Some(ref target) if target_import_resolution[ns].is_public => {
825 self.check_for_conflicting_import(&dest_import_resolution,
826 import_directive.span,
829 dest_import_resolution[ns] = ImportResolution {
830 id: id, is_public: is_public, target: Some(target.clone())
832 self.add_export(module_, *name, &dest_import_resolution[ns]);
839 // Add all children from the containing module.
840 build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
842 for (&name, name_bindings) in target_module.children.borrow().iter() {
843 self.merge_import_resolution(module_,
847 name_bindings.clone());
851 // Record the destination of this import
852 if let Some(did) = target_module.def_id() {
853 self.resolver.def_map.borrow_mut().insert(id,
855 base_def: Def::Mod(did),
861 debug!("(resolving glob import) successfully resolved import");
862 return ResolveResult::Success(());
865 fn merge_import_resolution(&mut self,
867 containing_module: Module<'b>,
868 import_directive: &ImportDirective,
870 name_bindings: NameBindings<'b>) {
871 let id = import_directive.id;
872 let is_public = import_directive.is_public;
874 let mut import_resolutions = module_.import_resolutions.borrow_mut();
875 let dest_import_resolution = import_resolutions.entry(name).or_insert_with(|| {
876 ImportResolutionPerNamespace::new(id, is_public)
879 debug!("(resolving glob import) writing resolution `{}` in `{}` to `{}`",
881 module_to_string(&*containing_module),
882 module_to_string(module_));
884 // Merge the child item into the import resolution.
885 // pub_err makes sure we don't give the same error twice.
886 let mut pub_err = false;
888 let mut merge_child_item = |namespace| {
889 if !pub_err && is_public &&
890 name_bindings[namespace].defined_with(DefModifiers::PRIVATE_VARIANT) {
891 let msg = format!("variant `{}` is private, and cannot be reexported (error \
892 E0364), consider declaring its enum as `pub`", name);
893 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
895 import_directive.span,
900 let modifier = DefModifiers::IMPORTABLE | DefModifiers::PUBLIC;
901 if name_bindings[namespace].defined_with(modifier) {
902 let namespace_name = match namespace {
906 debug!("(resolving glob import) ... for {} target", namespace_name);
907 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
908 let msg = format!("a {} named `{}` has already been imported in this \
912 span_err!(self.resolver.session,
913 import_directive.span,
918 dest_import_resolution[namespace] = ImportResolution {
919 target: Some(Target::new(containing_module,
920 name_bindings[namespace].clone(),
921 import_directive.shadowable)),
925 self.add_export(module_, name, &dest_import_resolution[namespace]);
928 // FIXME #30159: This is required for backwards compatability.
929 dest_import_resolution[namespace].is_public |= is_public;
932 merge_child_item(ValueNS);
933 merge_child_item(TypeNS);
936 self.check_for_conflicts_between_imports_and_items(module_,
937 dest_import_resolution,
938 import_directive.span,
942 fn add_export(&mut self, module: Module<'b>, name: Name, resolution: &ImportResolution<'b>) {
943 if !resolution.is_public { return }
944 let node_id = match module.def_id() {
945 Some(def_id) => self.resolver.ast_map.as_local_node_id(def_id).unwrap(),
948 let export = match resolution.target.as_ref().unwrap().binding.def() {
949 Some(def) => Export { name: name, def_id: def.def_id() },
952 self.resolver.export_map.entry(node_id).or_insert(Vec::new()).push(export);
955 /// Checks that imported names and items don't have the same name.
956 fn check_for_conflicting_import(&mut self,
957 import_resolution: &ImportResolutionPerNamespace,
960 namespace: Namespace) {
961 let target = &import_resolution[namespace].target;
962 debug!("check_for_conflicting_import: {}; target exists: {}",
967 Some(ref target) if target.shadowable != Shadowable::Always => {
968 let ns_word = match namespace {
970 match target.binding.module() {
971 Some(ref module) if module.is_normal() => "module",
972 Some(ref module) if module.is_trait() => "trait",
978 let use_id = import_resolution[namespace].id;
979 let item = self.resolver.ast_map.expect_item(use_id);
980 let mut err = struct_span_err!(self.resolver.session,
983 "a {} named `{}` has already been imported \
989 "previous import of `{}` here",
997 /// Checks that an import is actually importable
998 fn check_that_import_is_importable(&mut self,
999 name_binding: &NameBinding,
1002 if !name_binding.defined_with(DefModifiers::IMPORTABLE) {
1003 let msg = format!("`{}` is not directly importable", name);
1004 span_err!(self.resolver.session, import_span, E0253, "{}", &msg[..]);
1008 /// Checks that imported names and items don't have the same name.
1009 fn check_for_conflicts_between_imports_and_items(&mut self,
1011 import: &ImportResolutionPerNamespace<'b>,
1014 // First, check for conflicts between imports and `extern crate`s.
1015 if module.external_module_children
1017 .contains_key(&name) {
1018 match import.type_ns.target {
1019 Some(ref target) if target.shadowable != Shadowable::Always => {
1020 let msg = format!("import `{0}` conflicts with imported crate in this module \
1021 (maybe you meant `use {0}::*`?)",
1023 span_err!(self.resolver.session, import_span, E0254, "{}", &msg[..]);
1025 Some(_) | None => {}
1029 // Check for item conflicts.
1030 let name_bindings = match module.children.borrow().get(&name) {
1032 // There can't be any conflicts.
1035 Some(ref name_bindings) => (*name_bindings).clone(),
1038 match import.value_ns.target {
1039 Some(ref target) if target.shadowable != Shadowable::Always => {
1040 if let Some(ref value) = *name_bindings.value_ns.borrow() {
1041 let mut err = struct_span_err!(self.resolver.session,
1044 "import `{}` conflicts with \
1045 value in this module",
1047 if let Some(span) = value.span {
1048 err.span_note(span, "conflicting value here");
1053 Some(_) | None => {}
1056 match import.type_ns.target {
1057 Some(ref target) if target.shadowable != Shadowable::Always => {
1058 if let Some(ref ty) = *name_bindings.type_ns.borrow() {
1059 let (what, note) = match ty.module() {
1060 Some(ref module) if module.is_normal() =>
1061 ("existing submodule", "note conflicting module here"),
1062 Some(ref module) if module.is_trait() =>
1063 ("trait in this module", "note conflicting trait here"),
1064 _ => ("type in this module", "note conflicting type here"),
1066 let mut err = struct_span_err!(self.resolver.session,
1069 "import `{}` conflicts with {}",
1072 if let Some(span) = ty.span {
1073 err.span_note(span, note);
1078 Some(_) | None => {}
1083 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
1084 if names.is_empty() {
1085 import_directive_subclass_to_string(subclass)
1088 names_to_string(names),
1089 import_directive_subclass_to_string(subclass)))
1094 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
1096 SingleImport(_, source) => source.to_string(),
1097 GlobImport => "*".to_string(),
1101 pub fn resolve_imports(resolver: &mut Resolver) {
1102 let mut import_resolver = ImportResolver { resolver: resolver };
1103 import_resolver.resolve_imports();