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;
41 /// Contains data for specific types of import directives.
42 #[derive(Copy, Clone,Debug)]
43 pub enum ImportDirectiveSubclass {
44 SingleImport(Name /* target */, Name /* source */),
48 /// Whether an import can be shadowed by another import.
49 #[derive(Debug,PartialEq,Clone,Copy)]
55 /// One import directive.
57 pub struct ImportDirective {
58 pub module_path: Vec<Name>,
59 pub subclass: ImportDirectiveSubclass,
62 pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
63 pub shadowable: Shadowable,
66 impl ImportDirective {
67 pub fn new(module_path: Vec<Name>,
68 subclass: ImportDirectiveSubclass,
72 shadowable: Shadowable)
75 module_path: module_path,
80 shadowable: shadowable,
85 /// The item that an import resolves to.
86 #[derive(Clone,Debug)]
88 pub target_module: Rc<Module>,
89 pub binding: NameBinding,
90 pub shadowable: Shadowable,
94 pub fn new(target_module: Rc<Module>,
96 shadowable: Shadowable)
99 target_module: target_module,
101 shadowable: shadowable,
107 /// An ImportResolutionPerNamespace records what we know about an imported name.
108 /// More specifically, it records the number of unresolved `use` directives that import the name,
109 /// and for each namespace, it records the `use` directive importing the name in the namespace
110 /// and the `Target` to which the name in the namespace resolves (if applicable).
111 /// Different `use` directives may import the same name in different namespaces.
112 pub struct ImportResolutionPerNamespace {
113 // When outstanding_references reaches zero, outside modules can count on the targets being
114 // correct. Before then, all bets are off; future `use` directives could override the name.
115 // Since shadowing is forbidden, the only way outstanding_references > 1 in a legal program
116 // is if the name is imported by exactly two `use` directives, one of which resolves to a
117 // value and the other of which resolves to a type.
118 pub outstanding_references: usize,
119 pub type_ns: ImportResolution,
120 pub value_ns: ImportResolution,
123 /// Records what we know about an imported name in a namespace (see `ImportResolutionPerNamespace`).
124 #[derive(Clone,Debug)]
125 pub struct ImportResolution {
126 /// Whether the name in the namespace was imported with a `use` or a `pub use`.
129 /// Resolution of the name in the namespace
130 pub target: Option<Target>,
132 /// The source node of the `use` directive
136 impl ::std::ops::Index<Namespace> for ImportResolutionPerNamespace {
137 type Output = ImportResolution;
138 fn index(&self, ns: Namespace) -> &ImportResolution {
139 match ns { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
143 impl ::std::ops::IndexMut<Namespace> for ImportResolutionPerNamespace {
144 fn index_mut(&mut self, ns: Namespace) -> &mut ImportResolution {
145 match ns { TypeNS => &mut self.type_ns, ValueNS => &mut self.value_ns }
149 impl ImportResolutionPerNamespace {
150 pub fn new(id: NodeId, is_public: bool) -> Self {
151 let resolution = ImportResolution { id: id, is_public: is_public, target: None };
152 ImportResolutionPerNamespace {
153 outstanding_references: 0, type_ns: resolution.clone(), value_ns: resolution,
157 pub fn shadowable(&self, namespace: Namespace) -> Shadowable {
158 match self[namespace].target {
159 Some(ref target) => target.shadowable,
160 None => Shadowable::Always,
165 struct ImportResolvingError {
171 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
172 resolver: &'a mut Resolver<'b, 'tcx>,
175 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
178 // This is a fixed-point algorithm. We resolve imports until our efforts
179 // are stymied by an unresolved import; then we bail out of the current
180 // module and continue. We terminate successfully once no more imports
181 // remain or unsuccessfully when no forward progress in resolving imports
184 /// Resolves all imports for the crate. This method performs the fixed-
186 fn resolve_imports(&mut self) {
188 let mut prev_unresolved_imports = 0;
190 debug!("(resolving imports) iteration {}, {} imports left",
192 self.resolver.unresolved_imports);
194 let module_root = self.resolver.graph_root.clone();
195 let errors = self.resolve_imports_for_module_subtree(module_root.clone());
197 if self.resolver.unresolved_imports == 0 {
198 debug!("(resolving imports) success");
202 if self.resolver.unresolved_imports == prev_unresolved_imports {
204 if errors.len() > 0 {
206 resolve_error(self.resolver,
208 ResolutionError::UnresolvedImport(Some((&e.path, &e.help))));
211 // Report unresolved imports only if no hard error was already reported
212 // to avoid generating multiple errors on the same import.
213 // Imports that are still indeterminate at this point are actually blocked
214 // by errored imports, so there is no point reporting them.
215 self.resolver.report_unresolved_imports(module_root);
221 prev_unresolved_imports = self.resolver.unresolved_imports;
225 /// Attempts to resolve imports for the given module and all of its
227 fn resolve_imports_for_module_subtree(&mut self,
229 -> Vec<ImportResolvingError> {
230 let mut errors = Vec::new();
231 debug!("(resolving imports for module subtree) resolving {}",
232 module_to_string(&*module_));
233 let orig_module = replace(&mut self.resolver.current_module, module_.clone());
234 errors.extend(self.resolve_imports_for_module(module_.clone()));
235 self.resolver.current_module = orig_module;
237 build_reduced_graph::populate_module_if_necessary(self.resolver, &module_);
238 for (_, child_node) in module_.children.borrow().iter() {
239 match child_node.type_ns.module() {
243 Some(child_module) => {
244 errors.extend(self.resolve_imports_for_module_subtree(child_module));
249 for (_, child_module) in module_.anonymous_children.borrow().iter() {
250 errors.extend(self.resolve_imports_for_module_subtree(child_module.clone()));
256 /// Attempts to resolve imports for the given module only.
257 fn resolve_imports_for_module(&mut self, module: Rc<Module>) -> Vec<ImportResolvingError> {
258 let mut errors = Vec::new();
260 if module.all_imports_resolved() {
261 debug!("(resolving imports for module) all imports resolved for {}",
262 module_to_string(&*module));
266 let mut imports = module.imports.borrow_mut();
267 let import_count = imports.len();
268 let mut indeterminate_imports = Vec::new();
269 while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
270 let import_index = module.resolved_import_count.get();
271 match self.resolve_import_for_module(module.clone(), &imports[import_index]) {
272 ResolveResult::Failed(err) => {
273 let import_directive = &imports[import_index];
274 let (span, help) = match err {
275 Some((span, msg)) => (span, format!(". {}", msg)),
276 None => (import_directive.span, String::new()),
278 errors.push(ImportResolvingError {
280 path: import_path_to_string(&import_directive.module_path,
281 import_directive.subclass),
285 ResolveResult::Indeterminate => {}
286 ResolveResult::Success(()) => {
288 module.resolved_import_count
289 .set(module.resolved_import_count.get() + 1);
293 // This resolution was not successful, keep it for later
294 indeterminate_imports.push(imports.swap_remove(import_index));
298 imports.extend(indeterminate_imports);
303 /// Attempts to resolve the given import. The return value indicates
304 /// failure if we're certain the name does not exist, indeterminate if we
305 /// don't know whether the name exists at the moment due to other
306 /// currently-unresolved imports, or success if we know the name exists.
307 /// If successful, the resolved bindings are written into the module.
308 fn resolve_import_for_module(&mut self,
310 import_directive: &ImportDirective)
311 -> ResolveResult<()> {
312 let mut resolution_result = ResolveResult::Failed(None);
313 let module_path = &import_directive.module_path;
315 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
316 names_to_string(&module_path[..]),
317 module_to_string(&*module_));
319 // First, resolve the module path for the directive, if necessary.
320 let container = if module_path.is_empty() {
321 // Use the crate root.
322 Some((self.resolver.graph_root.clone(), LastMod(AllPublic)))
324 match self.resolver.resolve_module_path(module_.clone(),
326 UseLexicalScopeFlag::DontUseLexicalScope,
327 import_directive.span,
328 NameSearchType::ImportSearch) {
329 ResolveResult::Failed(err) => {
330 resolution_result = ResolveResult::Failed(err);
333 ResolveResult::Indeterminate => {
334 resolution_result = ResolveResult::Indeterminate;
337 ResolveResult::Success(container) => Some(container),
343 Some((containing_module, lp)) => {
344 // We found the module that the target is contained
345 // within. Attempt to resolve the import within it.
347 match import_directive.subclass {
348 SingleImport(target, source) => {
349 resolution_result = self.resolve_single_import(&module_,
357 resolution_result = self.resolve_glob_import(&module_,
366 // Decrement the count of unresolved imports.
367 match resolution_result {
368 ResolveResult::Success(()) => {
369 assert!(self.resolver.unresolved_imports >= 1);
370 self.resolver.unresolved_imports -= 1;
373 // Nothing to do here; just return the error.
377 // Decrement the count of unresolved globs if necessary. But only if
378 // the resolution result is a success -- other cases will
379 // be handled by the main loop.
381 if resolution_result.success() {
382 match import_directive.subclass {
384 module_.dec_glob_count();
385 if import_directive.is_public {
386 module_.dec_pub_glob_count();
389 SingleImport(..) => {
393 if import_directive.is_public {
394 module_.dec_pub_count();
398 return resolution_result;
401 fn resolve_single_import(&mut self,
403 target_module: Rc<Module>,
406 directive: &ImportDirective,
408 -> ResolveResult<()> {
409 debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
412 module_to_string(&*target_module),
414 module_to_string(module_),
423 .span_bug(directive.span, "not expecting Import here, must be LastMod")
427 // We need to resolve both namespaces for this to succeed.
429 let mut value_result = UnknownResult;
430 let mut type_result = UnknownResult;
431 let mut lev_suggestion = "".to_owned();
433 // Search for direct children of the containing module.
434 build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
436 match target_module.children.borrow().get(&source) {
438 let names = target_module.children.borrow();
439 if let Some(name) = find_best_match_for_name(names.keys(),
442 lev_suggestion = format!(". Did you mean to use `{}`?", name);
445 Some(ref child_name_bindings) => {
446 // pub_err makes sure we don't give the same error twice.
447 let mut pub_err = false;
448 if child_name_bindings.value_ns.defined() {
449 debug!("(resolving single import) found value binding");
450 value_result = BoundResult(target_module.clone(),
451 child_name_bindings.value_ns.clone());
452 if directive.is_public && !child_name_bindings.value_ns.is_public() {
453 let msg = format!("`{}` is private, and cannot be reexported", source);
454 let note_msg = format!("Consider marking `{}` as `pub` in the imported \
457 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
458 .span_note(directive.span, ¬e_msg)
462 if directive.is_public && child_name_bindings.value_ns.
463 defined_with(DefModifiers::PRIVATE_VARIANT) {
464 let msg = format!("variant `{}` is private, and cannot be reexported ( \
465 error E0364), consider declaring its enum as `pub`",
467 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
474 if child_name_bindings.type_ns.defined() {
475 debug!("(resolving single import) found type binding");
476 type_result = BoundResult(target_module.clone(),
477 child_name_bindings.type_ns.clone());
478 if !pub_err && directive.is_public &&
479 !child_name_bindings.type_ns.is_public() {
480 let msg = format!("`{}` is private, and cannot be reexported", source);
481 let note_msg = format!("Consider declaring module `{}` as a `pub mod`",
483 struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
484 .span_note(directive.span, ¬e_msg)
487 if !pub_err && directive.is_public && child_name_bindings.type_ns.
488 defined_with(DefModifiers::PRIVATE_VARIANT) {
489 let msg = format!("variant `{}` is private, and cannot be reexported ( \
490 error E0365), consider declaring its enum as `pub`",
492 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
501 // Unless we managed to find a result in both namespaces (unlikely),
502 // search imports as well.
503 let mut value_used_reexport = false;
504 let mut type_used_reexport = false;
505 match (value_result.clone(), type_result.clone()) {
506 (BoundResult(..), BoundResult(..)) => {} // Continue.
508 // If there is an unresolved glob at this point in the
509 // containing module, bail out. We don't know enough to be
510 // able to resolve this import.
512 if target_module.pub_glob_count.get() > 0 {
513 debug!("(resolving single import) unresolved pub glob; bailing out");
514 return ResolveResult::Indeterminate;
517 // Now search the exported imports within the containing module.
518 match target_module.import_resolutions.borrow().get(&source) {
520 debug!("(resolving single import) no import");
521 // The containing module definitely doesn't have an
522 // exported import with the name in question. We can
523 // therefore accurately report that the names are
526 if lev_suggestion.is_empty() { // skip if we already have a suggestion
527 let names = target_module.import_resolutions.borrow();
528 if let Some(name) = find_best_match_for_name(names.keys(),
532 format!(". Did you mean to use the re-exported import `{}`?",
537 if value_result.is_unknown() {
538 value_result = UnboundResult;
540 if type_result.is_unknown() {
541 type_result = UnboundResult;
544 Some(import_resolution) if import_resolution.outstanding_references == 0 => {
546 fn get_binding(this: &mut Resolver,
547 import_resolution: &ImportResolutionPerNamespace,
548 namespace: Namespace,
552 // Import resolutions must be declared with "pub"
553 // in order to be exported.
554 if !import_resolution[namespace].is_public {
555 return UnboundResult;
558 match import_resolution[namespace].target.clone() {
560 return UnboundResult;
567 debug!("(resolving single import) found import in ns {:?}",
569 let id = import_resolution[namespace].id;
570 // track used imports and extern crates as well
571 this.used_imports.insert((id, namespace));
572 this.record_import_use(id, source);
573 match target_module.def_id() {
574 Some(DefId{krate: kid, ..}) => {
575 this.used_crates.insert(kid);
579 return BoundResult(target_module, binding);
584 // The name is an import which has been fully
585 // resolved. We can, therefore, just follow it.
586 if value_result.is_unknown() {
587 value_result = get_binding(self.resolver,
591 value_used_reexport = import_resolution.value_ns.is_public;
593 if type_result.is_unknown() {
594 type_result = get_binding(self.resolver,
598 type_used_reexport = import_resolution.type_ns.is_public;
603 // If target_module is the same module whose import we are resolving
604 // and there it has an unresolved import with the same name as `source`,
605 // then the user is actually trying to import an item that is declared
609 // use self::submodule;
610 // pub mod submodule;
612 // In this case we continue as if we resolved the import and let the
613 // check_for_conflicts_between_imports_and_items call below handle
615 match (module_.def_id(), target_module.def_id()) {
616 (Some(id1), Some(id2)) if id1 == id2 => {
617 if value_result.is_unknown() {
618 value_result = UnboundResult;
620 if type_result.is_unknown() {
621 type_result = UnboundResult;
625 // The import is unresolved. Bail out.
626 debug!("(resolving single import) unresolved import; bailing out");
627 return ResolveResult::Indeterminate;
635 let mut value_used_public = false;
636 let mut type_used_public = false;
638 // If we didn't find a result in the type namespace, search the
641 BoundResult(..) => {}
643 match target_module.external_module_children.borrow_mut().get(&source).cloned() {
644 None => {} // Continue.
646 debug!("(resolving single import) found external module");
647 // track the module as used.
648 match module.def_id() {
649 Some(DefId{krate: kid, ..}) => {
650 self.resolver.used_crates.insert(kid);
654 let name_binding = NameBinding::create_from_module(module);
655 type_result = BoundResult(target_module.clone(), name_binding);
656 type_used_public = true;
662 // We've successfully resolved the import. Write the results in.
663 let mut import_resolutions = module_.import_resolutions.borrow_mut();
664 let import_resolution = import_resolutions.get_mut(&target).unwrap();
667 let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
668 let namespace_name = match namespace {
674 BoundResult(ref target_module, ref name_binding) => {
675 debug!("(resolving single import) found {:?} target: {:?}",
678 self.check_for_conflicting_import(&import_resolution,
683 self.check_that_import_is_importable(&name_binding,
687 import_resolution[namespace] = ImportResolution {
688 target: Some(Target::new(target_module.clone(),
689 name_binding.clone(),
690 directive.shadowable)),
692 is_public: directive.is_public
694 *used_public = name_binding.is_public();
700 panic!("{:?} result should be known at this point", namespace_name);
704 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
705 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
708 self.check_for_conflicts_between_imports_and_items(module_,
713 if value_result.is_unbound() && type_result.is_unbound() {
714 let msg = format!("There is no `{}` in `{}`{}",
716 module_to_string(&target_module), lev_suggestion);
717 return ResolveResult::Failed(Some((directive.span, msg)));
719 let value_used_public = value_used_reexport || value_used_public;
720 let type_used_public = type_used_reexport || type_used_public;
722 assert!(import_resolution.outstanding_references >= 1);
723 import_resolution.outstanding_references -= 1;
725 // Record what this import resolves to for later uses in documentation,
726 // this may resolve to either a value or a type, but for documentation
727 // purposes it's good enough to just favor one over the other.
728 let value_def_and_priv = import_resolution.value_ns.target.as_ref().map(|target| {
729 let def = target.binding.def().unwrap();
731 if value_used_public {
734 DependsOn(def.def_id())
737 let type_def_and_priv = import_resolution.type_ns.target.as_ref().map(|target| {
738 let def = target.binding.def().unwrap();
740 if type_used_public {
743 DependsOn(def.def_id())
747 let import_lp = LastImport {
748 value_priv: value_def_and_priv.map(|(_, p)| p),
750 type_priv: type_def_and_priv.map(|(_, p)| p),
754 if let Some((def, _)) = value_def_and_priv {
755 self.resolver.def_map.borrow_mut().insert(directive.id,
758 last_private: import_lp,
762 if let Some((def, _)) = type_def_and_priv {
763 self.resolver.def_map.borrow_mut().insert(directive.id,
766 last_private: import_lp,
771 debug!("(resolving single import) successfully resolved import");
772 return ResolveResult::Success(());
775 // Resolves a glob import. Note that this function cannot fail; it either
776 // succeeds or bails out (as importing * from an empty module or a module
777 // that exports nothing is valid). target_module is the module we are
778 // actually importing, i.e., `foo` in `use foo::*`.
779 fn resolve_glob_import(&mut self,
781 target_module: Rc<Module>,
782 import_directive: &ImportDirective,
784 -> ResolveResult<()> {
785 let id = import_directive.id;
786 let is_public = import_directive.is_public;
788 // This function works in a highly imperative manner; it eagerly adds
789 // everything it can to the list of import resolutions of the module
791 debug!("(resolving glob import) resolving glob import {}", id);
793 // We must bail out if the node has unresolved imports of any kind
794 // (including globs).
795 if (*target_module).pub_count.get() > 0 {
796 debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
797 return ResolveResult::Indeterminate;
800 // Add all resolved imports from the containing module.
801 let import_resolutions = target_module.import_resolutions.borrow();
803 if module_.import_resolutions.borrow_state() != ::std::cell::BorrowState::Unused {
804 // In this case, target_module == module_
805 // This means we are trying to glob import a module into itself,
807 debug!("(resolving glob imports) target module is current module; giving up");
808 return ResolveResult::Failed(Some((import_directive.span,
809 "Cannot glob-import a module into itself.".into())));
812 for (name, target_import_resolution) in import_resolutions.iter() {
813 debug!("(resolving glob import) writing module resolution {} into `{}`",
815 module_to_string(module_));
817 // Here we merge two import resolutions.
818 let mut import_resolutions = module_.import_resolutions.borrow_mut();
819 let mut dest_import_resolution = import_resolutions.entry(*name).or_insert_with(|| {
820 ImportResolutionPerNamespace::new(id, is_public)
823 for &ns in [TypeNS, ValueNS].iter() {
824 match target_import_resolution[ns].target {
825 Some(ref target) if target_import_resolution[ns].is_public => {
826 self.check_for_conflicting_import(&dest_import_resolution,
827 import_directive.span,
830 dest_import_resolution[ns] = ImportResolution {
831 id: id, is_public: is_public, target: Some(target.clone())
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_,
844 target_module.clone(),
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: DefMod(did),
861 debug!("(resolving glob import) successfully resolved import");
862 return ResolveResult::Success(());
865 fn merge_import_resolution(&mut self,
867 containing_module: Rc<Module>,
868 import_directive: &ImportDirective,
870 name_bindings: NameBindings) {
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.clone(),
920 name_bindings[namespace].clone(),
921 import_directive.shadowable)),
927 // FIXME #30159: This is required for backwards compatability.
928 dest_import_resolution[namespace].is_public |= is_public;
931 merge_child_item(ValueNS);
932 merge_child_item(TypeNS);
935 self.check_for_conflicts_between_imports_and_items(module_,
936 dest_import_resolution,
937 import_directive.span,
941 /// Checks that imported names and items don't have the same name.
942 fn check_for_conflicting_import(&mut self,
943 import_resolution: &ImportResolutionPerNamespace,
946 namespace: Namespace) {
947 let target = &import_resolution[namespace].target;
948 debug!("check_for_conflicting_import: {}; target exists: {}",
953 Some(ref target) if target.shadowable != Shadowable::Always => {
954 let ns_word = match namespace {
956 match target.binding.module() {
957 Some(ref module) if module.is_normal() => "module",
958 Some(ref module) if module.is_trait() => "trait",
964 let use_id = import_resolution[namespace].id;
965 let item = self.resolver.ast_map.expect_item(use_id);
966 let mut err = struct_span_err!(self.resolver.session,
969 "a {} named `{}` has already been imported \
975 "previous import of `{}` here",
983 /// Checks that an import is actually importable
984 fn check_that_import_is_importable(&mut self,
985 name_binding: &NameBinding,
988 if !name_binding.defined_with(DefModifiers::IMPORTABLE) {
989 let msg = format!("`{}` is not directly importable", name);
990 span_err!(self.resolver.session, import_span, E0253, "{}", &msg[..]);
994 /// Checks that imported names and items don't have the same name.
995 fn check_for_conflicts_between_imports_and_items(&mut self,
997 import: &ImportResolutionPerNamespace,
1000 // First, check for conflicts between imports and `extern crate`s.
1001 if module.external_module_children
1003 .contains_key(&name) {
1004 match import.type_ns.target {
1005 Some(ref target) if target.shadowable != Shadowable::Always => {
1006 let msg = format!("import `{0}` conflicts with imported crate in this module \
1007 (maybe you meant `use {0}::*`?)",
1009 span_err!(self.resolver.session, import_span, E0254, "{}", &msg[..]);
1011 Some(_) | None => {}
1015 // Check for item conflicts.
1016 let children = module.children.borrow();
1017 let name_bindings = match children.get(&name) {
1019 // There can't be any conflicts.
1022 Some(ref name_bindings) => (*name_bindings).clone(),
1025 match import.value_ns.target {
1026 Some(ref target) if target.shadowable != Shadowable::Always => {
1027 if let Some(ref value) = *name_bindings.value_ns.borrow() {
1028 let mut err = struct_span_err!(self.resolver.session,
1031 "import `{}` conflicts with \
1032 value in this module",
1034 if let Some(span) = value.span {
1035 err.span_note(span, "conflicting value here");
1040 Some(_) | None => {}
1043 match import.type_ns.target {
1044 Some(ref target) if target.shadowable != Shadowable::Always => {
1045 if let Some(ref ty) = *name_bindings.type_ns.borrow() {
1046 let (what, note) = match ty.module() {
1047 Some(ref module) if module.is_normal() =>
1048 ("existing submodule", "note conflicting module here"),
1049 Some(ref module) if module.is_trait() =>
1050 ("trait in this module", "note conflicting trait here"),
1051 _ => ("type in this module", "note conflicting type here"),
1053 let mut err = struct_span_err!(self.resolver.session,
1056 "import `{}` conflicts with {}",
1059 if let Some(span) = ty.span {
1060 err.span_note(span, note);
1065 Some(_) | None => {}
1070 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
1071 if names.is_empty() {
1072 import_directive_subclass_to_string(subclass)
1075 names_to_string(names),
1076 import_directive_subclass_to_string(subclass)))
1081 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
1083 SingleImport(_, source) => source.to_string(),
1084 GlobImport => "*".to_string(),
1088 pub fn resolve_imports(resolver: &mut Resolver) {
1089 let mut import_resolver = ImportResolver { resolver: resolver };
1090 import_resolver.resolve_imports();