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};
21 use UseLexicalScopeFlag;
22 use {names_to_string, module_to_string};
23 use {resolve_error, ResolutionError};
25 use build_reduced_graph;
28 use rustc::middle::def::*;
29 use rustc::middle::def_id::DefId;
30 use rustc::middle::privacy::*;
32 use syntax::ast::{NodeId, Name};
33 use syntax::attr::AttrMetaMethods;
34 use syntax::codemap::Span;
35 use syntax::util::lev_distance::find_best_match_for_name;
37 use std::mem::replace;
39 /// Contains data for specific types of import directives.
40 #[derive(Copy, Clone,Debug)]
41 pub enum ImportDirectiveSubclass {
42 SingleImport(Name /* target */, Name /* source */),
46 /// Whether an import can be shadowed by another import.
47 #[derive(Debug,PartialEq,Clone,Copy)]
53 /// One import directive.
55 pub struct ImportDirective {
56 pub module_path: Vec<Name>,
57 pub subclass: ImportDirectiveSubclass,
60 pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
61 pub shadowable: Shadowable,
64 impl ImportDirective {
65 pub fn new(module_path: Vec<Name>,
66 subclass: ImportDirectiveSubclass,
70 shadowable: Shadowable)
73 module_path: module_path,
78 shadowable: shadowable,
83 /// The item that an import resolves to.
84 #[derive(Clone,Debug)]
85 pub struct Target<'a> {
86 pub target_module: Module<'a>,
87 pub binding: NameBinding<'a>,
88 pub shadowable: Shadowable,
92 pub fn new(target_module: Module<'a>, binding: NameBinding<'a>, shadowable: Shadowable)
95 target_module: target_module,
97 shadowable: shadowable,
103 /// An ImportResolutionPerNamespace records what we know about an imported name.
104 /// More specifically, it records the number of unresolved `use` directives that import the name,
105 /// and for each namespace, it records the `use` directive importing the name in the namespace
106 /// and the `Target` to which the name in the namespace resolves (if applicable).
107 /// Different `use` directives may import the same name in different namespaces.
108 pub struct ImportResolutionPerNamespace<'a> {
109 // When outstanding_references reaches zero, outside modules can count on the targets being
110 // correct. Before then, all bets are off; future `use` directives could override the name.
111 // Since shadowing is forbidden, the only way outstanding_references > 1 in a legal program
112 // is if the name is imported by exactly two `use` directives, one of which resolves to a
113 // value and the other of which resolves to a type.
114 pub outstanding_references: usize,
115 pub type_ns: ImportResolution<'a>,
116 pub value_ns: ImportResolution<'a>,
119 /// Records what we know about an imported name in a namespace (see `ImportResolutionPerNamespace`).
120 #[derive(Clone,Debug)]
121 pub struct ImportResolution<'a> {
122 /// Whether the name in the namespace was imported with a `use` or a `pub use`.
125 /// Resolution of the name in the namespace
126 pub target: Option<Target<'a>>,
128 /// The source node of the `use` directive
132 impl<'a> ::std::ops::Index<Namespace> for ImportResolutionPerNamespace<'a> {
133 type Output = ImportResolution<'a>;
134 fn index(&self, ns: Namespace) -> &ImportResolution<'a> {
135 match ns { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
139 impl<'a> ::std::ops::IndexMut<Namespace> for ImportResolutionPerNamespace<'a> {
140 fn index_mut(&mut self, ns: Namespace) -> &mut ImportResolution<'a> {
141 match ns { TypeNS => &mut self.type_ns, ValueNS => &mut self.value_ns }
145 impl<'a> ImportResolutionPerNamespace<'a> {
146 pub fn new(id: NodeId, is_public: bool) -> Self {
147 let resolution = ImportResolution { id: id, is_public: is_public, target: None };
148 ImportResolutionPerNamespace {
149 outstanding_references: 0, type_ns: resolution.clone(), value_ns: resolution,
153 pub fn shadowable(&self, namespace: Namespace) -> Shadowable {
154 match self[namespace].target {
155 Some(ref target) => target.shadowable,
156 None => Shadowable::Always,
161 struct ImportResolvingError {
167 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
168 resolver: &'a mut Resolver<'b, 'tcx>,
171 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
174 // This is a fixed-point algorithm. We resolve imports until our efforts
175 // are stymied by an unresolved import; then we bail out of the current
176 // module and continue. We terminate successfully once no more imports
177 // remain or unsuccessfully when no forward progress in resolving imports
180 /// Resolves all imports for the crate. This method performs the fixed-
182 fn resolve_imports(&mut self) {
184 let mut prev_unresolved_imports = 0;
186 debug!("(resolving imports) iteration {}, {} imports left",
188 self.resolver.unresolved_imports);
190 let module_root = self.resolver.graph_root;
191 let errors = self.resolve_imports_for_module_subtree(module_root);
193 if self.resolver.unresolved_imports == 0 {
194 debug!("(resolving imports) success");
198 if self.resolver.unresolved_imports == prev_unresolved_imports {
200 if errors.len() > 0 {
202 resolve_error(self.resolver,
204 ResolutionError::UnresolvedImport(Some((&e.path, &e.help))));
207 // Report unresolved imports only if no hard error was already reported
208 // to avoid generating multiple errors on the same import.
209 // Imports that are still indeterminate at this point are actually blocked
210 // by errored imports, so there is no point reporting them.
211 self.resolver.report_unresolved_imports(module_root);
217 prev_unresolved_imports = self.resolver.unresolved_imports;
221 /// Attempts to resolve imports for the given module and all of its
223 fn resolve_imports_for_module_subtree(&mut self,
225 -> Vec<ImportResolvingError> {
226 let mut errors = Vec::new();
227 debug!("(resolving imports for module subtree) resolving {}",
228 module_to_string(&*module_));
229 let orig_module = replace(&mut self.resolver.current_module, module_);
230 errors.extend(self.resolve_imports_for_module(module_));
231 self.resolver.current_module = orig_module;
233 build_reduced_graph::populate_module_if_necessary(self.resolver, &module_);
234 for (_, child_node) in module_.children.borrow().iter() {
235 match child_node.type_ns.module() {
239 Some(child_module) => {
240 errors.extend(self.resolve_imports_for_module_subtree(child_module));
245 for (_, child_module) in module_.anonymous_children.borrow().iter() {
246 errors.extend(self.resolve_imports_for_module_subtree(child_module));
252 /// Attempts to resolve imports for the given module only.
253 fn resolve_imports_for_module(&mut self, module: Module<'b>) -> Vec<ImportResolvingError> {
254 let mut errors = Vec::new();
256 if module.all_imports_resolved() {
257 debug!("(resolving imports for module) all imports resolved for {}",
258 module_to_string(&*module));
262 let mut imports = module.imports.borrow_mut();
263 let import_count = imports.len();
264 let mut indeterminate_imports = Vec::new();
265 while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
266 let import_index = module.resolved_import_count.get();
267 match self.resolve_import_for_module(module, &imports[import_index]) {
268 ResolveResult::Failed(err) => {
269 let import_directive = &imports[import_index];
270 let (span, help) = match err {
271 Some((span, msg)) => (span, format!(". {}", msg)),
272 None => (import_directive.span, String::new()),
274 errors.push(ImportResolvingError {
276 path: import_path_to_string(&import_directive.module_path,
277 import_directive.subclass),
281 ResolveResult::Indeterminate => {}
282 ResolveResult::Success(()) => {
284 module.resolved_import_count
285 .set(module.resolved_import_count.get() + 1);
289 // This resolution was not successful, keep it for later
290 indeterminate_imports.push(imports.swap_remove(import_index));
294 imports.extend(indeterminate_imports);
299 /// Attempts to resolve the given import. The return value indicates
300 /// failure if we're certain the name does not exist, indeterminate if we
301 /// don't know whether the name exists at the moment due to other
302 /// currently-unresolved imports, or success if we know the name exists.
303 /// If successful, the resolved bindings are written into the module.
304 fn resolve_import_for_module(&mut self,
306 import_directive: &ImportDirective)
307 -> ResolveResult<()> {
308 let mut resolution_result = ResolveResult::Failed(None);
309 let module_path = &import_directive.module_path;
311 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
312 names_to_string(&module_path[..]),
313 module_to_string(&*module_));
315 // First, resolve the module path for the directive, if necessary.
316 let container = if module_path.is_empty() {
317 // Use the crate root.
318 Some((self.resolver.graph_root, LastMod(AllPublic)))
320 match self.resolver.resolve_module_path(module_,
322 UseLexicalScopeFlag::DontUseLexicalScope,
323 import_directive.span) {
324 ResolveResult::Failed(err) => {
325 resolution_result = ResolveResult::Failed(err);
328 ResolveResult::Indeterminate => {
329 resolution_result = ResolveResult::Indeterminate;
332 ResolveResult::Success(container) => Some(container),
338 Some((containing_module, lp)) => {
339 // We found the module that the target is contained
340 // within. Attempt to resolve the import within it.
342 match import_directive.subclass {
343 SingleImport(target, source) => {
344 resolution_result = self.resolve_single_import(&module_,
352 resolution_result = self.resolve_glob_import(&module_,
361 // Decrement the count of unresolved imports.
362 match resolution_result {
363 ResolveResult::Success(()) => {
364 assert!(self.resolver.unresolved_imports >= 1);
365 self.resolver.unresolved_imports -= 1;
368 // Nothing to do here; just return the error.
372 // Decrement the count of unresolved globs if necessary. But only if
373 // the resolution result is a success -- other cases will
374 // be handled by the main loop.
376 if resolution_result.success() {
377 match import_directive.subclass {
379 module_.dec_glob_count();
380 if import_directive.is_public {
381 module_.dec_pub_glob_count();
384 SingleImport(..) => {
388 if import_directive.is_public {
389 module_.dec_pub_count();
393 return resolution_result;
396 fn resolve_single_import(&mut self,
398 target_module: Module<'b>,
401 directive: &ImportDirective,
403 -> ResolveResult<()> {
404 debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
407 module_to_string(&*target_module),
409 module_to_string(module_),
418 .span_bug(directive.span, "not expecting Import here, must be LastMod")
422 // We need to resolve both namespaces for this to succeed.
424 let mut value_result = UnknownResult;
425 let mut type_result = UnknownResult;
426 let mut lev_suggestion = "".to_owned();
428 // Search for direct children of the containing module.
429 build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
431 match target_module.children.borrow().get(&source) {
433 let names = target_module.children.borrow();
434 if let Some(name) = find_best_match_for_name(names.keys(),
437 lev_suggestion = format!(". Did you mean to use `{}`?", name);
440 Some(ref child_name_bindings) => {
441 // pub_err makes sure we don't give the same error twice.
442 let mut pub_err = false;
443 if child_name_bindings.value_ns.defined() {
444 debug!("(resolving single import) found value binding");
445 value_result = BoundResult(target_module,
446 child_name_bindings.value_ns.clone());
447 if directive.is_public && !child_name_bindings.value_ns.is_public() {
448 let msg = format!("`{}` is private, and cannot be reexported", source);
449 let note_msg = format!("Consider marking `{}` as `pub` in the imported \
452 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
453 .span_note(directive.span, ¬e_msg)
457 if directive.is_public && child_name_bindings.value_ns.
458 defined_with(DefModifiers::PRIVATE_VARIANT) {
459 let msg = format!("variant `{}` is private, and cannot be reexported ( \
460 error E0364), consider declaring its enum as `pub`",
462 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
469 if child_name_bindings.type_ns.defined() {
470 debug!("(resolving single import) found type binding");
471 type_result = BoundResult(target_module,
472 child_name_bindings.type_ns.clone());
473 if !pub_err && directive.is_public &&
474 !child_name_bindings.type_ns.is_public() {
475 let msg = format!("`{}` is private, and cannot be reexported", source);
476 let note_msg = format!("Consider declaring module `{}` as a `pub mod`",
478 struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
479 .span_note(directive.span, ¬e_msg)
482 if !pub_err && directive.is_public && child_name_bindings.type_ns.
483 defined_with(DefModifiers::PRIVATE_VARIANT) {
484 let msg = format!("variant `{}` is private, and cannot be reexported ( \
485 error E0365), consider declaring its enum as `pub`",
487 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
496 // Unless we managed to find a result in both namespaces (unlikely),
497 // search imports as well.
498 let mut value_used_reexport = false;
499 let mut type_used_reexport = false;
500 match (value_result.clone(), type_result.clone()) {
501 (BoundResult(..), BoundResult(..)) => {} // Continue.
503 // If there is an unresolved glob at this point in the
504 // containing module, bail out. We don't know enough to be
505 // able to resolve this import.
507 if target_module.pub_glob_count.get() > 0 {
508 debug!("(resolving single import) unresolved pub glob; bailing out");
509 return ResolveResult::Indeterminate;
512 // Now search the exported imports within the containing module.
513 match target_module.import_resolutions.borrow().get(&source) {
515 debug!("(resolving single import) no import");
516 // The containing module definitely doesn't have an
517 // exported import with the name in question. We can
518 // therefore accurately report that the names are
521 if lev_suggestion.is_empty() { // skip if we already have a suggestion
522 let names = target_module.import_resolutions.borrow();
523 if let Some(name) = find_best_match_for_name(names.keys(),
527 format!(". Did you mean to use the re-exported import `{}`?",
532 if value_result.is_unknown() {
533 value_result = UnboundResult;
535 if type_result.is_unknown() {
536 type_result = UnboundResult;
539 Some(import_resolution) if import_resolution.outstanding_references == 0 => {
541 fn get_binding<'a>(this: &mut Resolver,
542 import_resolution: &ImportResolutionPerNamespace<'a>,
543 namespace: Namespace,
545 -> NamespaceResult<'a> {
547 // Import resolutions must be declared with "pub"
548 // in order to be exported.
549 if !import_resolution[namespace].is_public {
550 return UnboundResult;
553 match import_resolution[namespace].target.clone() {
555 return UnboundResult;
562 debug!("(resolving single import) found import in ns {:?}",
564 let id = import_resolution[namespace].id;
565 // track used imports and extern crates as well
566 this.used_imports.insert((id, namespace));
567 this.record_import_use(id, source);
568 match target_module.def_id() {
569 Some(DefId{krate: kid, ..}) => {
570 this.used_crates.insert(kid);
574 return BoundResult(target_module, binding);
579 // The name is an import which has been fully
580 // resolved. We can, therefore, just follow it.
581 if value_result.is_unknown() {
582 value_result = get_binding(self.resolver,
586 value_used_reexport = import_resolution.value_ns.is_public;
588 if type_result.is_unknown() {
589 type_result = get_binding(self.resolver,
593 type_used_reexport = import_resolution.type_ns.is_public;
598 // If target_module is the same module whose import we are resolving
599 // and there it has an unresolved import with the same name as `source`,
600 // then the user is actually trying to import an item that is declared
604 // use self::submodule;
605 // pub mod submodule;
607 // In this case we continue as if we resolved the import and let the
608 // check_for_conflicts_between_imports_and_items call below handle
610 match (module_.def_id(), target_module.def_id()) {
611 (Some(id1), Some(id2)) if id1 == id2 => {
612 if value_result.is_unknown() {
613 value_result = UnboundResult;
615 if type_result.is_unknown() {
616 type_result = UnboundResult;
620 // The import is unresolved. Bail out.
621 debug!("(resolving single import) unresolved import; bailing out");
622 return ResolveResult::Indeterminate;
630 let mut value_used_public = false;
631 let mut type_used_public = false;
633 // If we didn't find a result in the type namespace, search the
636 BoundResult(..) => {}
638 match target_module.external_module_children.borrow_mut().get(&source) {
639 None => {} // Continue.
641 debug!("(resolving single import) found external module");
642 // track the module as used.
643 match module.def_id() {
644 Some(DefId{krate: kid, ..}) => {
645 self.resolver.used_crates.insert(kid);
649 let name_binding = NameBinding::create_from_module(module);
650 type_result = BoundResult(target_module, name_binding);
651 type_used_public = true;
657 // We've successfully resolved the import. Write the results in.
658 let mut import_resolutions = module_.import_resolutions.borrow_mut();
659 let import_resolution = import_resolutions.get_mut(&target).unwrap();
662 let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
663 let namespace_name = match namespace {
669 BoundResult(ref target_module, ref name_binding) => {
670 debug!("(resolving single import) found {:?} target: {:?}",
673 self.check_for_conflicting_import(&import_resolution,
678 self.check_that_import_is_importable(&name_binding,
682 import_resolution[namespace] = ImportResolution {
683 target: Some(Target::new(target_module,
684 name_binding.clone(),
685 directive.shadowable)),
687 is_public: directive.is_public
690 self.add_export(module_, target, &import_resolution[namespace]);
691 *used_public = name_binding.is_public();
697 panic!("{:?} result should be known at this point", namespace_name);
701 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
702 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
705 self.check_for_conflicts_between_imports_and_items(module_,
710 if value_result.is_unbound() && type_result.is_unbound() {
711 let msg = format!("There is no `{}` in `{}`{}",
713 module_to_string(&target_module), lev_suggestion);
714 return ResolveResult::Failed(Some((directive.span, msg)));
716 let value_used_public = value_used_reexport || value_used_public;
717 let type_used_public = type_used_reexport || type_used_public;
719 assert!(import_resolution.outstanding_references >= 1);
720 import_resolution.outstanding_references -= 1;
722 // Record what this import resolves to for later uses in documentation,
723 // this may resolve to either a value or a type, but for documentation
724 // purposes it's good enough to just favor one over the other.
725 let value_def_and_priv = import_resolution.value_ns.target.as_ref().map(|target| {
726 let def = target.binding.def().unwrap();
728 if value_used_public {
731 DependsOn(def.def_id())
734 let type_def_and_priv = import_resolution.type_ns.target.as_ref().map(|target| {
735 let def = target.binding.def().unwrap();
737 if type_used_public {
740 DependsOn(def.def_id())
744 let import_lp = LastImport {
745 value_priv: value_def_and_priv.map(|(_, p)| p),
747 type_priv: type_def_and_priv.map(|(_, p)| p),
751 if let Some((def, _)) = value_def_and_priv {
752 self.resolver.def_map.borrow_mut().insert(directive.id,
755 last_private: import_lp,
759 if let Some((def, _)) = type_def_and_priv {
760 self.resolver.def_map.borrow_mut().insert(directive.id,
763 last_private: import_lp,
768 debug!("(resolving single import) successfully resolved import");
769 return ResolveResult::Success(());
772 // Resolves a glob import. Note that this function cannot fail; it either
773 // succeeds or bails out (as importing * from an empty module or a module
774 // that exports nothing is valid). target_module is the module we are
775 // actually importing, i.e., `foo` in `use foo::*`.
776 fn resolve_glob_import(&mut self,
778 target_module: Module<'b>,
779 import_directive: &ImportDirective,
781 -> ResolveResult<()> {
782 let id = import_directive.id;
783 let is_public = import_directive.is_public;
785 // This function works in a highly imperative manner; it eagerly adds
786 // everything it can to the list of import resolutions of the module
788 debug!("(resolving glob import) resolving glob import {}", id);
790 // We must bail out if the node has unresolved imports of any kind
791 // (including globs).
792 if (*target_module).pub_count.get() > 0 {
793 debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
794 return ResolveResult::Indeterminate;
797 // Add all resolved imports from the containing module.
798 let import_resolutions = target_module.import_resolutions.borrow();
800 if module_.import_resolutions.borrow_state() != ::std::cell::BorrowState::Unused {
801 // In this case, target_module == module_
802 // This means we are trying to glob import a module into itself,
804 debug!("(resolving glob imports) target module is current module; giving up");
805 return ResolveResult::Failed(Some((import_directive.span,
806 "Cannot glob-import a module into itself.".into())));
809 for (name, target_import_resolution) in import_resolutions.iter() {
810 debug!("(resolving glob import) writing module resolution {} into `{}`",
812 module_to_string(module_));
814 // Here we merge two import resolutions.
815 let mut import_resolutions = module_.import_resolutions.borrow_mut();
816 let mut dest_import_resolution = import_resolutions.entry(*name).or_insert_with(|| {
817 ImportResolutionPerNamespace::new(id, is_public)
820 for &ns in [TypeNS, ValueNS].iter() {
821 match target_import_resolution[ns].target {
822 Some(ref target) if target_import_resolution[ns].is_public => {
823 self.check_for_conflicting_import(&dest_import_resolution,
824 import_directive.span,
827 dest_import_resolution[ns] = ImportResolution {
828 id: id, is_public: is_public, target: Some(target.clone())
830 self.add_export(module_, *name, &dest_import_resolution[ns]);
837 // Add all children from the containing module.
838 build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
840 for (&name, name_bindings) in target_module.children.borrow().iter() {
841 self.merge_import_resolution(module_,
845 name_bindings.clone());
849 // Record the destination of this import
850 if let Some(did) = target_module.def_id() {
851 self.resolver.def_map.borrow_mut().insert(id,
853 base_def: Def::Mod(did),
859 debug!("(resolving glob import) successfully resolved import");
860 return ResolveResult::Success(());
863 fn merge_import_resolution(&mut self,
865 containing_module: Module<'b>,
866 import_directive: &ImportDirective,
868 name_bindings: NameBindings<'b>) {
869 let id = import_directive.id;
870 let is_public = import_directive.is_public;
872 let mut import_resolutions = module_.import_resolutions.borrow_mut();
873 let dest_import_resolution = import_resolutions.entry(name).or_insert_with(|| {
874 ImportResolutionPerNamespace::new(id, is_public)
877 debug!("(resolving glob import) writing resolution `{}` in `{}` to `{}`",
879 module_to_string(&*containing_module),
880 module_to_string(module_));
882 // Merge the child item into the import resolution.
883 // pub_err makes sure we don't give the same error twice.
884 let mut pub_err = false;
886 let mut merge_child_item = |namespace| {
887 if !pub_err && is_public &&
888 name_bindings[namespace].defined_with(DefModifiers::PRIVATE_VARIANT) {
889 let msg = format!("variant `{}` is private, and cannot be reexported (error \
890 E0364), consider declaring its enum as `pub`", name);
891 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
893 import_directive.span,
898 let modifier = DefModifiers::IMPORTABLE | DefModifiers::PUBLIC;
899 if name_bindings[namespace].defined_with(modifier) {
900 let namespace_name = match namespace {
904 debug!("(resolving glob import) ... for {} target", namespace_name);
905 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
906 let msg = format!("a {} named `{}` has already been imported in this \
910 span_err!(self.resolver.session,
911 import_directive.span,
916 dest_import_resolution[namespace] = ImportResolution {
917 target: Some(Target::new(containing_module,
918 name_bindings[namespace].clone(),
919 import_directive.shadowable)),
923 self.add_export(module_, name, &dest_import_resolution[namespace]);
926 // FIXME #30159: This is required for backwards compatability.
927 dest_import_resolution[namespace].is_public |= is_public;
930 merge_child_item(ValueNS);
931 merge_child_item(TypeNS);
934 self.check_for_conflicts_between_imports_and_items(module_,
935 dest_import_resolution,
936 import_directive.span,
940 fn add_export(&mut self, module: Module<'b>, name: Name, resolution: &ImportResolution<'b>) {
941 if !resolution.is_public { return }
942 let node_id = match module.def_id() {
943 Some(def_id) => self.resolver.ast_map.as_local_node_id(def_id).unwrap(),
946 let export = match resolution.target.as_ref().unwrap().binding.def() {
947 Some(def) => Export { name: name, def_id: def.def_id() },
950 self.resolver.export_map.entry(node_id).or_insert(Vec::new()).push(export);
953 /// Checks that imported names and items don't have the same name.
954 fn check_for_conflicting_import(&mut self,
955 import_resolution: &ImportResolutionPerNamespace,
958 namespace: Namespace) {
959 let target = &import_resolution[namespace].target;
960 debug!("check_for_conflicting_import: {}; target exists: {}",
965 Some(ref target) if target.shadowable != Shadowable::Always => {
966 let ns_word = match namespace {
968 match target.binding.module() {
969 Some(ref module) if module.is_normal() => "module",
970 Some(ref module) if module.is_trait() => "trait",
976 let use_id = import_resolution[namespace].id;
977 let item = self.resolver.ast_map.expect_item(use_id);
978 let mut err = struct_span_err!(self.resolver.session,
981 "a {} named `{}` has already been imported \
987 "previous import of `{}` here",
995 /// Checks that an import is actually importable
996 fn check_that_import_is_importable(&mut self,
997 name_binding: &NameBinding,
1000 if !name_binding.defined_with(DefModifiers::IMPORTABLE) {
1001 let msg = format!("`{}` is not directly importable", name);
1002 span_err!(self.resolver.session, import_span, E0253, "{}", &msg[..]);
1006 /// Checks that imported names and items don't have the same name.
1007 fn check_for_conflicts_between_imports_and_items(&mut self,
1009 import: &ImportResolutionPerNamespace<'b>,
1012 // First, check for conflicts between imports and `extern crate`s.
1013 if module.external_module_children
1015 .contains_key(&name) {
1016 match import.type_ns.target {
1017 Some(ref target) if target.shadowable != Shadowable::Always => {
1018 let msg = format!("import `{0}` conflicts with imported crate in this module \
1019 (maybe you meant `use {0}::*`?)",
1021 span_err!(self.resolver.session, import_span, E0254, "{}", &msg[..]);
1023 Some(_) | None => {}
1027 // Check for item conflicts.
1028 let name_bindings = match module.children.borrow().get(&name) {
1030 // There can't be any conflicts.
1033 Some(ref name_bindings) => (*name_bindings).clone(),
1036 match import.value_ns.target {
1037 Some(ref target) if target.shadowable != Shadowable::Always => {
1038 if let Some(ref value) = *name_bindings.value_ns.borrow() {
1039 let mut err = struct_span_err!(self.resolver.session,
1042 "import `{}` conflicts with \
1043 value in this module",
1045 if let Some(span) = value.span {
1046 err.span_note(span, "conflicting value here");
1051 Some(_) | None => {}
1054 match import.type_ns.target {
1055 Some(ref target) if target.shadowable != Shadowable::Always => {
1056 if let Some(ref ty) = *name_bindings.type_ns.borrow() {
1057 let (what, note) = match ty.module() {
1058 Some(ref module) if module.is_normal() =>
1059 ("existing submodule", "note conflicting module here"),
1060 Some(ref module) if module.is_trait() =>
1061 ("trait in this module", "note conflicting trait here"),
1062 _ => ("type in this module", "note conflicting type here"),
1064 let mut err = struct_span_err!(self.resolver.session,
1067 "import `{}` conflicts with {}",
1070 if let Some(span) = ty.span {
1071 err.span_note(span, note);
1076 Some(_) | None => {}
1081 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
1082 if names.is_empty() {
1083 import_directive_subclass_to_string(subclass)
1086 names_to_string(names),
1087 import_directive_subclass_to_string(subclass)))
1092 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
1094 SingleImport(_, source) => source.to_string(),
1095 GlobImport => "*".to_string(),
1099 pub fn resolve_imports(resolver: &mut Resolver) {
1100 let mut import_resolver = ImportResolver { resolver: resolver };
1101 import_resolver.resolve_imports();