]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Refactor away NameBindings, NsDef, ImportResolutionPerNamespace, DuplicateCheckingMod...
[rust.git] / src / librustc_resolve / resolve_imports.rs
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.
4 //
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.
10
11 use self::ImportDirectiveSubclass::*;
12
13 use DefModifiers;
14 use Module;
15 use Namespace::{self, TypeNS, ValueNS};
16 use NameBinding;
17 use ResolveResult;
18 use ResolveResult::*;
19 use Resolver;
20 use UseLexicalScopeFlag;
21 use {names_to_string, module_to_string};
22 use {resolve_error, ResolutionError};
23
24 use build_reduced_graph;
25
26 use rustc::lint;
27 use rustc::middle::def::*;
28 use rustc::middle::def_id::DefId;
29 use rustc::middle::privacy::*;
30
31 use syntax::ast::{NodeId, Name};
32 use syntax::attr::AttrMetaMethods;
33 use syntax::codemap::Span;
34 use syntax::util::lev_distance::find_best_match_for_name;
35
36 use std::mem::replace;
37
38 /// Contains data for specific types of import directives.
39 #[derive(Copy, Clone,Debug)]
40 pub enum ImportDirectiveSubclass {
41     SingleImport(Name /* target */, Name /* source */),
42     GlobImport,
43 }
44
45 /// Whether an import can be shadowed by another import.
46 #[derive(Debug,PartialEq,Clone,Copy)]
47 pub enum Shadowable {
48     Always,
49     Never,
50 }
51
52 /// One import directive.
53 #[derive(Debug)]
54 pub struct ImportDirective {
55     pub module_path: Vec<Name>,
56     pub subclass: ImportDirectiveSubclass,
57     pub span: Span,
58     pub id: NodeId,
59     pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
60     pub shadowable: Shadowable,
61 }
62
63 impl ImportDirective {
64     pub fn new(module_path: Vec<Name>,
65                subclass: ImportDirectiveSubclass,
66                span: Span,
67                id: NodeId,
68                is_public: bool,
69                shadowable: Shadowable)
70                -> ImportDirective {
71         ImportDirective {
72             module_path: module_path,
73             subclass: subclass,
74             span: span,
75             id: id,
76             is_public: is_public,
77             shadowable: shadowable,
78         }
79     }
80 }
81
82 /// The item that an import resolves to.
83 #[derive(Clone,Debug)]
84 pub struct Target<'a> {
85     pub target_module: Module<'a>,
86     pub binding: NameBinding<'a>,
87     pub shadowable: Shadowable,
88 }
89
90 impl<'a> Target<'a> {
91     pub fn new(target_module: Module<'a>, binding: NameBinding<'a>, shadowable: Shadowable)
92                -> Self {
93         Target {
94             target_module: target_module,
95             binding: binding,
96             shadowable: shadowable,
97         }
98     }
99 }
100
101 #[derive(Debug)]
102 /// An ImportResolution records what we know about an imported name in a given namespace.
103 /// More specifically, it records the number of unresolved `use` directives that import the name,
104 /// the `use` directive importing the name in the namespace, and the `NameBinding` to which the
105 /// name in the namespace resolves (if applicable).
106 /// Different `use` directives may import the same name in different namespaces.
107 pub struct ImportResolution<'a> {
108     // When outstanding_references reaches zero, outside modules can count on the targets being
109     // correct. Before then, all bets are off; future `use` directives could override the name.
110     // Since shadowing is forbidden, the only way outstanding_references > 1 in a legal program
111     // is if the name is imported by exactly two `use` directives, one of which resolves to a
112     // value and the other of which resolves to a type.
113     pub outstanding_references: usize,
114
115     /// Whether this resolution came from a `use` or a `pub use`.
116     pub is_public: bool,
117
118     /// Resolution of the name in the namespace
119     pub target: Option<Target<'a>>,
120
121     /// The source node of the `use` directive
122     pub id: NodeId,
123 }
124
125 impl<'a> ImportResolution<'a> {
126     pub fn new(id: NodeId, is_public: bool) -> Self {
127         ImportResolution {
128             outstanding_references: 0,
129             id: id,
130             target: None,
131             is_public: is_public,
132         }
133     }
134
135     pub fn shadowable(&self) -> Shadowable {
136         match self.target {
137             Some(ref target) => target.shadowable,
138             None => Shadowable::Always,
139         }
140     }
141 }
142
143 struct ImportResolvingError {
144     span: Span,
145     path: String,
146     help: String,
147 }
148
149 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
150     resolver: &'a mut Resolver<'b, 'tcx>,
151 }
152
153 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
154     // Import resolution
155     //
156     // This is a fixed-point algorithm. We resolve imports until our efforts
157     // are stymied by an unresolved import; then we bail out of the current
158     // module and continue. We terminate successfully once no more imports
159     // remain or unsuccessfully when no forward progress in resolving imports
160     // is made.
161
162     /// Resolves all imports for the crate. This method performs the fixed-
163     /// point iteration.
164     fn resolve_imports(&mut self) {
165         let mut i = 0;
166         let mut prev_unresolved_imports = 0;
167         loop {
168             debug!("(resolving imports) iteration {}, {} imports left",
169                    i,
170                    self.resolver.unresolved_imports);
171
172             let module_root = self.resolver.graph_root;
173             let errors = self.resolve_imports_for_module_subtree(module_root);
174
175             if self.resolver.unresolved_imports == 0 {
176                 debug!("(resolving imports) success");
177                 break;
178             }
179
180             if self.resolver.unresolved_imports == prev_unresolved_imports {
181                 // resolving failed
182                 if errors.len() > 0 {
183                     for e in errors {
184                         resolve_error(self.resolver,
185                                       e.span,
186                                       ResolutionError::UnresolvedImport(Some((&e.path, &e.help))));
187                     }
188                 } else {
189                     // Report unresolved imports only if no hard error was already reported
190                     // to avoid generating multiple errors on the same import.
191                     // Imports that are still indeterminate at this point are actually blocked
192                     // by errored imports, so there is no point reporting them.
193                     self.resolver.report_unresolved_imports(module_root);
194                 }
195                 break;
196             }
197
198             i += 1;
199             prev_unresolved_imports = self.resolver.unresolved_imports;
200         }
201     }
202
203     /// Attempts to resolve imports for the given module and all of its
204     /// submodules.
205     fn resolve_imports_for_module_subtree(&mut self,
206                                           module_: Module<'b>)
207                                           -> Vec<ImportResolvingError> {
208         let mut errors = Vec::new();
209         debug!("(resolving imports for module subtree) resolving {}",
210                module_to_string(&*module_));
211         let orig_module = replace(&mut self.resolver.current_module, module_);
212         errors.extend(self.resolve_imports_for_module(module_));
213         self.resolver.current_module = orig_module;
214
215         build_reduced_graph::populate_module_if_necessary(self.resolver, &module_);
216         for (_, child_node) in module_.children.borrow().iter() {
217             match child_node.module() {
218                 None => {
219                     // Nothing to do.
220                 }
221                 Some(child_module) => {
222                     errors.extend(self.resolve_imports_for_module_subtree(child_module));
223                 }
224             }
225         }
226
227         for (_, child_module) in module_.anonymous_children.borrow().iter() {
228             errors.extend(self.resolve_imports_for_module_subtree(child_module));
229         }
230
231         errors
232     }
233
234     /// Attempts to resolve imports for the given module only.
235     fn resolve_imports_for_module(&mut self, module: Module<'b>) -> Vec<ImportResolvingError> {
236         let mut errors = Vec::new();
237
238         if module.all_imports_resolved() {
239             debug!("(resolving imports for module) all imports resolved for {}",
240                    module_to_string(&*module));
241             return errors;
242         }
243
244         let mut imports = module.imports.borrow_mut();
245         let import_count = imports.len();
246         let mut indeterminate_imports = Vec::new();
247         while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
248             let import_index = module.resolved_import_count.get();
249             match self.resolve_import_for_module(module, &imports[import_index]) {
250                 ResolveResult::Failed(err) => {
251                     let import_directive = &imports[import_index];
252                     let (span, help) = match err {
253                         Some((span, msg)) => (span, format!(". {}", msg)),
254                         None => (import_directive.span, String::new()),
255                     };
256                     errors.push(ImportResolvingError {
257                         span: span,
258                         path: import_path_to_string(&import_directive.module_path,
259                                                     import_directive.subclass),
260                         help: help,
261                     });
262                 }
263                 ResolveResult::Indeterminate => {}
264                 ResolveResult::Success(()) => {
265                     // count success
266                     module.resolved_import_count
267                           .set(module.resolved_import_count.get() + 1);
268                     continue;
269                 }
270             }
271             // This resolution was not successful, keep it for later
272             indeterminate_imports.push(imports.swap_remove(import_index));
273
274         }
275
276         imports.extend(indeterminate_imports);
277
278         errors
279     }
280
281     /// Attempts to resolve the given import. The return value indicates
282     /// failure if we're certain the name does not exist, indeterminate if we
283     /// don't know whether the name exists at the moment due to other
284     /// currently-unresolved imports, or success if we know the name exists.
285     /// If successful, the resolved bindings are written into the module.
286     fn resolve_import_for_module(&mut self,
287                                  module_: Module<'b>,
288                                  import_directive: &ImportDirective)
289                                  -> ResolveResult<()> {
290         let mut resolution_result = ResolveResult::Failed(None);
291         let module_path = &import_directive.module_path;
292
293         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
294                names_to_string(&module_path[..]),
295                module_to_string(&*module_));
296
297         // First, resolve the module path for the directive, if necessary.
298         let container = if module_path.is_empty() {
299             // Use the crate root.
300             Some((self.resolver.graph_root, LastMod(AllPublic)))
301         } else {
302             match self.resolver.resolve_module_path(module_,
303                                                     &module_path[..],
304                                                     UseLexicalScopeFlag::DontUseLexicalScope,
305                                                     import_directive.span) {
306                 ResolveResult::Failed(err) => {
307                     resolution_result = ResolveResult::Failed(err);
308                     None
309                 }
310                 ResolveResult::Indeterminate => {
311                     resolution_result = ResolveResult::Indeterminate;
312                     None
313                 }
314                 ResolveResult::Success(container) => Some(container),
315             }
316         };
317
318         match container {
319             None => {}
320             Some((containing_module, lp)) => {
321                 // We found the module that the target is contained
322                 // within. Attempt to resolve the import within it.
323
324                 match import_directive.subclass {
325                     SingleImport(target, source) => {
326                         resolution_result = self.resolve_single_import(&module_,
327                                                                        containing_module,
328                                                                        target,
329                                                                        source,
330                                                                        import_directive,
331                                                                        lp);
332                     }
333                     GlobImport => {
334                         resolution_result = self.resolve_glob_import(&module_,
335                                                                      containing_module,
336                                                                      import_directive,
337                                                                      lp);
338                     }
339                 }
340             }
341         }
342
343         // Decrement the count of unresolved imports.
344         match resolution_result {
345             ResolveResult::Success(()) => {
346                 assert!(self.resolver.unresolved_imports >= 1);
347                 self.resolver.unresolved_imports -= 1;
348             }
349             _ => {
350                 // Nothing to do here; just return the error.
351             }
352         }
353
354         // Decrement the count of unresolved globs if necessary. But only if
355         // the resolution result is a success -- other cases will
356         // be handled by the main loop.
357
358         if resolution_result.success() {
359             match import_directive.subclass {
360                 GlobImport => {
361                     module_.dec_glob_count();
362                     if import_directive.is_public {
363                         module_.dec_pub_glob_count();
364                     }
365                 }
366                 SingleImport(..) => {
367                     // Ignore.
368                 }
369             }
370             if import_directive.is_public {
371                 module_.dec_pub_count();
372             }
373         }
374
375         return resolution_result;
376     }
377
378     fn resolve_imported_name_in_module(&mut self,
379                                        module: Module<'b>, // Module containing the name
380                                        name: Name,
381                                        ns: Namespace,
382                                        importing_module: Module<'b>) // Module importing the name
383                                        -> ResolveResult<(Module<'b>, NameBinding<'b>)> {
384         match module.import_resolutions.borrow().get(&(name, ns)) {
385             // The containing module definitely doesn't have an exported import with the
386             // name in question. We can therefore accurately report that names are unbound.
387             None => Failed(None),
388
389             // The name is an import which has been fully resolved, so we just follow it.
390             Some(resolution) if resolution.outstanding_references == 0 => {
391                 // Import resolutions must be declared with "pub" in order to be exported.
392                 if !resolution.is_public {
393                     return Failed(None);
394                 }
395
396                 let target = resolution.target.clone();
397                 if let Some(Target { target_module, binding, shadowable: _ }) = target {
398                     // track used imports and extern crates as well
399                     self.resolver.used_imports.insert((resolution.id, ns));
400                     self.resolver.record_import_use(resolution.id, name);
401                     if let Some(DefId { krate, .. }) = target_module.def_id() {
402                         self.resolver.used_crates.insert(krate);
403                     }
404                     Success((target_module, binding))
405                 } else {
406                     Failed(None)
407                 }
408             }
409
410             // If module is the same module whose import we are resolving and
411             // it has an unresolved import with the same name as `name`, then the user
412             // is actually trying to import an item that is declared in the same scope
413             //
414             // e.g
415             // use self::submodule;
416             // pub mod submodule;
417             //
418             // In this case we continue as if we resolved the import and let the
419             // check_for_conflicts_between_imports_and_items call below handle the conflict
420             Some(_) => match (importing_module.def_id(), module.def_id()) {
421                 (Some(id1), Some(id2)) if id1 == id2 => Failed(None),
422                 _ => Indeterminate,
423             },
424         }
425     }
426
427     fn resolve_single_import(&mut self,
428                              module_: Module<'b>,
429                              target_module: Module<'b>,
430                              target: Name,
431                              source: Name,
432                              directive: &ImportDirective,
433                              lp: LastPrivate)
434                              -> ResolveResult<()> {
435         debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
436                 private {:?}",
437                target,
438                module_to_string(&*target_module),
439                source,
440                module_to_string(module_),
441                directive.id,
442                lp);
443
444         let lp = match lp {
445             LastMod(lp) => lp,
446             LastImport {..} => {
447                 self.resolver
448                     .session
449                     .span_bug(directive.span, "not expecting Import here, must be LastMod")
450             }
451         };
452
453         // We need to resolve both namespaces for this to succeed.
454         let mut value_result = Indeterminate;
455         let mut type_result = Indeterminate;
456         let mut lev_suggestion = "".to_owned();
457
458         // Search for direct children of the containing module.
459         build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
460
461         // pub_err makes sure we don't give the same error twice.
462         let mut pub_err = false;
463
464         if let Some(name_binding) = target_module.get_child(source, ValueNS) {
465             debug!("(resolving single import) found value binding");
466             value_result = Success((target_module, name_binding.clone()));
467             if directive.is_public && !name_binding.is_public() {
468                 let msg = format!("`{}` is private, and cannot be reexported", source);
469                 let note_msg = format!("Consider marking `{}` as `pub` in the imported module",
470                                         source);
471                 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
472                     .span_note(directive.span, &note_msg)
473                     .emit();
474                 pub_err = true;
475             }
476         }
477
478         if let Some(name_binding) = target_module.get_child(source, TypeNS) {
479             debug!("(resolving single import) found type binding");
480             type_result = Success((target_module, name_binding.clone()));
481             if !pub_err && directive.is_public {
482                 if !name_binding.is_public() {
483                     let msg = format!("`{}` is private, and cannot be reexported", source);
484                     let note_msg =
485                         format!("Consider declaring type or module `{}` with `pub`", source);
486                     struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
487                         .span_note(directive.span, &note_msg)
488                         .emit();
489                 } else if name_binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
490                     let msg = format!("variant `{}` is private, and cannot be reexported \
491                                        (error E0364), consider declaring its enum as `pub`",
492                                        source);
493                     self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
494                                                    directive.id,
495                                                    directive.span,
496                                                    msg);
497                 }
498             }
499         }
500
501         if let (&Indeterminate, &Indeterminate) = (&value_result, &type_result) {
502             let names = target_module.children.borrow();
503             let names = names.keys().map(|&(ref name, _)| name);
504             if let Some(name) = find_best_match_for_name(names, &source.as_str(), None) {
505                 lev_suggestion = format!(". Did you mean to use `{}`?", name);
506             }
507         }
508
509         match (&value_result, &type_result) {
510             // If there is an unresolved glob at this point in the containing module, bail out.
511             // We don't know enough to be able to resolve this import.
512             (&Indeterminate, _) | (_, &Indeterminate) if target_module.pub_glob_count.get() > 0 =>
513                 return Indeterminate,
514             _ => ()
515         }
516
517         let mut value_used_reexport = false;
518         if let Indeterminate = value_result {
519             value_result =
520                 self.resolve_imported_name_in_module(&target_module, source, ValueNS, module_);
521             value_used_reexport = match value_result { Success(_) => true, _ => false };
522         }
523
524         let mut type_used_reexport = false;
525         if let Indeterminate = type_result {
526             type_result =
527                 self.resolve_imported_name_in_module(&target_module, source, TypeNS, module_);
528             type_used_reexport = match type_result { Success(_) => true, _ => false };
529         }
530
531         match (&value_result, &type_result) {
532             (&Indeterminate, _) | (_, &Indeterminate) => return Indeterminate,
533             (&Failed(_), &Failed(_)) => {
534                 if lev_suggestion.is_empty() {  // skip if we already have a suggestion
535                     let names = target_module.import_resolutions.borrow();
536                     let names = names.keys().map(|&(ref name, _)| name);
537                     if let Some(name) = find_best_match_for_name(names,
538                                                                  &source.as_str(),
539                                                                  None) {
540                         lev_suggestion =
541                             format!(". Did you mean to use the re-exported import `{}`?",
542                                     name);
543                     }
544                 }
545             }
546             _ => (),
547         }
548
549         let mut value_used_public = false;
550         let mut type_used_public = false;
551
552         // If we didn't find a result in the type namespace, search the
553         // external modules.
554         match type_result {
555             Success(..) => {}
556             _ => {
557                 match target_module.external_module_children.borrow_mut().get(&source).cloned() {
558                     None => {} // Continue.
559                     Some(module) => {
560                         debug!("(resolving single import) found external module");
561                         // track the module as used.
562                         match module.def_id() {
563                             Some(DefId{krate: kid, ..}) => {
564                                 self.resolver.used_crates.insert(kid);
565                             }
566                             _ => {}
567                         }
568                         let name_binding = NameBinding::create_from_module(module, None);
569                         type_result = Success((target_module, name_binding));
570                         type_used_public = true;
571                     }
572                 }
573             }
574         }
575
576         // We've successfully resolved the import. Write the results in.
577         let mut import_resolutions = module_.import_resolutions.borrow_mut();
578
579         {
580             let mut check_and_write_import = |namespace, result, used_public: &mut bool| {
581                 let result: &ResolveResult<(Module<'b>, NameBinding)> = result;
582
583                 let import_resolution = import_resolutions.get_mut(&(target, namespace)).unwrap();
584                 let namespace_name = match namespace {
585                     TypeNS => "type",
586                     ValueNS => "value",
587                 };
588
589                 match *result {
590                     Success((ref target_module, ref name_binding)) => {
591                         debug!("(resolving single import) found {:?} target: {:?}",
592                                namespace_name,
593                                name_binding.def());
594                         self.check_for_conflicting_import(&import_resolution,
595                                                           directive.span,
596                                                           target,
597                                                           namespace);
598
599                         self.check_that_import_is_importable(&name_binding,
600                                                              directive.span,
601                                                              target);
602
603                         import_resolution.target = Some(Target::new(target_module,
604                                                                     name_binding.clone(),
605                                                                     directive.shadowable));
606                         import_resolution.id = directive.id;
607                         import_resolution.is_public = directive.is_public;
608
609                         self.add_export(module_, target, &import_resolution);
610                         *used_public = name_binding.is_public();
611                     }
612                     Failed(_) => {
613                         // Continue.
614                     }
615                     Indeterminate => {
616                         panic!("{:?} result should be known at this point", namespace_name);
617                     }
618                 }
619
620                 self.check_for_conflicts_between_imports_and_items(module_,
621                                                                    import_resolution,
622                                                                    directive.span,
623                                                                    (target, namespace));
624
625             };
626             check_and_write_import(ValueNS, &value_result, &mut value_used_public);
627             check_and_write_import(TypeNS, &type_result, &mut type_used_public);
628         }
629
630         if let (&Failed(_), &Failed(_)) = (&value_result, &type_result) {
631             let msg = format!("There is no `{}` in `{}`{}",
632                               source,
633                               module_to_string(&target_module), lev_suggestion);
634             return ResolveResult::Failed(Some((directive.span, msg)));
635         }
636         let value_used_public = value_used_reexport || value_used_public;
637         let type_used_public = type_used_reexport || type_used_public;
638
639         let value_def_and_priv = {
640             let import_resolution_value = import_resolutions.get_mut(&(target, ValueNS)).unwrap();
641             assert!(import_resolution_value.outstanding_references >= 1);
642             import_resolution_value.outstanding_references -= 1;
643
644             // Record what this import resolves to for later uses in documentation,
645             // this may resolve to either a value or a type, but for documentation
646             // purposes it's good enough to just favor one over the other.
647             import_resolution_value.target.as_ref().map(|target| {
648                 let def = target.binding.def().unwrap();
649                 (def,
650                  if value_used_public {
651                     lp
652                 } else {
653                     DependsOn(def.def_id())
654                 })
655             })
656         };
657
658         let type_def_and_priv = {
659             let import_resolution_type = import_resolutions.get_mut(&(target, TypeNS)).unwrap();
660             assert!(import_resolution_type.outstanding_references >= 1);
661             import_resolution_type.outstanding_references -= 1;
662
663             import_resolution_type.target.as_ref().map(|target| {
664                 let def = target.binding.def().unwrap();
665                 (def,
666                 if type_used_public {
667                     lp
668                 } else {
669                     DependsOn(def.def_id())
670                 })
671             })
672         };
673
674         let import_lp = LastImport {
675             value_priv: value_def_and_priv.map(|(_, p)| p),
676             value_used: Used,
677             type_priv: type_def_and_priv.map(|(_, p)| p),
678             type_used: Used,
679         };
680
681         if let Some((def, _)) = value_def_and_priv {
682             self.resolver.def_map.borrow_mut().insert(directive.id,
683                                                       PathResolution {
684                                                           base_def: def,
685                                                           last_private: import_lp,
686                                                           depth: 0,
687                                                       });
688         }
689         if let Some((def, _)) = type_def_and_priv {
690             self.resolver.def_map.borrow_mut().insert(directive.id,
691                                                       PathResolution {
692                                                           base_def: def,
693                                                           last_private: import_lp,
694                                                           depth: 0,
695                                                       });
696         }
697
698         debug!("(resolving single import) successfully resolved import");
699         return ResolveResult::Success(());
700     }
701
702     // Resolves a glob import. Note that this function cannot fail; it either
703     // succeeds or bails out (as importing * from an empty module or a module
704     // that exports nothing is valid). target_module is the module we are
705     // actually importing, i.e., `foo` in `use foo::*`.
706     fn resolve_glob_import(&mut self,
707                            module_: Module<'b>,
708                            target_module: Module<'b>,
709                            import_directive: &ImportDirective,
710                            lp: LastPrivate)
711                            -> ResolveResult<()> {
712         let id = import_directive.id;
713         let is_public = import_directive.is_public;
714
715         // This function works in a highly imperative manner; it eagerly adds
716         // everything it can to the list of import resolutions of the module
717         // node.
718         debug!("(resolving glob import) resolving glob import {}", id);
719
720         // We must bail out if the node has unresolved imports of any kind
721         // (including globs).
722         if (*target_module).pub_count.get() > 0 {
723             debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
724             return ResolveResult::Indeterminate;
725         }
726
727         // Add all resolved imports from the containing module.
728         let import_resolutions = target_module.import_resolutions.borrow();
729
730         if module_.import_resolutions.borrow_state() != ::std::cell::BorrowState::Unused {
731             // In this case, target_module == module_
732             // This means we are trying to glob import a module into itself,
733             // and it is a no-go
734             debug!("(resolving glob imports) target module is current module; giving up");
735             return ResolveResult::Failed(Some((import_directive.span,
736                                                "Cannot glob-import a module into itself.".into())));
737         }
738
739         for (&(name, ns), target_import_resolution) in import_resolutions.iter() {
740             debug!("(resolving glob import) writing module resolution {} into `{}`",
741                    name,
742                    module_to_string(module_));
743
744             // Here we merge two import resolutions.
745             let mut import_resolutions = module_.import_resolutions.borrow_mut();
746             let mut dest_import_resolution =
747                 import_resolutions.entry((name, ns))
748                                   .or_insert_with(|| ImportResolution::new(id, is_public));
749
750             match target_import_resolution.target {
751                 Some(ref target) if target_import_resolution.is_public => {
752                     self.check_for_conflicting_import(&dest_import_resolution,
753                                                       import_directive.span,
754                                                       name,
755                                                       ns);
756                     dest_import_resolution.id = id;
757                     dest_import_resolution.is_public = is_public;
758                     dest_import_resolution.target = Some(target.clone());
759                     self.add_export(module_, name, &dest_import_resolution);
760                 }
761                 _ => {}
762             }
763         }
764
765         // Add all children from the containing module.
766         build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
767
768         for (&name, name_binding) in target_module.children.borrow().iter() {
769             self.merge_import_resolution(module_,
770                                          target_module,
771                                          import_directive,
772                                          name,
773                                          name_binding.clone());
774         }
775
776         // Record the destination of this import
777         if let Some(did) = target_module.def_id() {
778             self.resolver.def_map.borrow_mut().insert(id,
779                                                       PathResolution {
780                                                           base_def: Def::Mod(did),
781                                                           last_private: lp,
782                                                           depth: 0,
783                                                       });
784         }
785
786         debug!("(resolving glob import) successfully resolved import");
787         return ResolveResult::Success(());
788     }
789
790     fn merge_import_resolution(&mut self,
791                                module_: Module<'b>,
792                                containing_module: Module<'b>,
793                                import_directive: &ImportDirective,
794                                (name, ns): (Name, Namespace),
795                                name_binding: NameBinding<'b>) {
796         let id = import_directive.id;
797         let is_public = import_directive.is_public;
798
799         let mut import_resolutions = module_.import_resolutions.borrow_mut();
800         let dest_import_resolution = import_resolutions.entry((name, ns)).or_insert_with(|| {
801             ImportResolution::new(id, is_public)
802         });
803
804         debug!("(resolving glob import) writing resolution `{}` in `{}` to `{}`",
805                name,
806                module_to_string(&*containing_module),
807                module_to_string(module_));
808
809         // Merge the child item into the import resolution.
810         let modifier = DefModifiers::IMPORTABLE | DefModifiers::PUBLIC;
811
812         if ns == TypeNS && is_public && name_binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
813             let msg = format!("variant `{}` is private, and cannot be reexported (error \
814                                E0364), consider declaring its enum as `pub`", name);
815             self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
816                                            import_directive.id,
817                                            import_directive.span,
818                                            msg);
819         }
820
821         if name_binding.defined_with(modifier) {
822             let namespace_name = match ns {
823                 TypeNS => "type",
824                 ValueNS => "value",
825             };
826             debug!("(resolving glob import) ... for {} target", namespace_name);
827             if dest_import_resolution.shadowable() == Shadowable::Never {
828                 let msg = format!("a {} named `{}` has already been imported in this module",
829                                  namespace_name,
830                                  name);
831                 span_err!(self.resolver.session, import_directive.span, E0251, "{}", msg);
832            } else {
833                 let target = Target::new(containing_module,
834                                          name_binding.clone(),
835                                          import_directive.shadowable);
836                 dest_import_resolution.target = Some(target);
837                 dest_import_resolution.id = id;
838                 dest_import_resolution.is_public = is_public;
839                 self.add_export(module_, name, &dest_import_resolution);
840             }
841         } else {
842             // FIXME #30159: This is required for backwards compatability.
843             dest_import_resolution.is_public |= is_public;
844         }
845
846         self.check_for_conflicts_between_imports_and_items(module_,
847                                                            dest_import_resolution,
848                                                            import_directive.span,
849                                                            (name, ns));
850     }
851
852     fn add_export(&mut self, module: Module<'b>, name: Name, resolution: &ImportResolution<'b>) {
853         if !resolution.is_public { return }
854         let node_id = match module.def_id() {
855             Some(def_id) => self.resolver.ast_map.as_local_node_id(def_id).unwrap(),
856             None => return,
857         };
858         let export = match resolution.target.as_ref().unwrap().binding.def() {
859             Some(def) => Export { name: name, def_id: def.def_id() },
860             None => return,
861         };
862         self.resolver.export_map.entry(node_id).or_insert(Vec::new()).push(export);
863     }
864
865     /// Checks that imported names and items don't have the same name.
866     fn check_for_conflicting_import(&mut self,
867                                     import_resolution: &ImportResolution,
868                                     import_span: Span,
869                                     name: Name,
870                                     namespace: Namespace) {
871         let target = &import_resolution.target;
872         debug!("check_for_conflicting_import: {}; target exists: {}",
873                name,
874                target.is_some());
875
876         match *target {
877             Some(ref target) if target.shadowable != Shadowable::Always => {
878                 let ns_word = match namespace {
879                     TypeNS => {
880                         match target.binding.module() {
881                             Some(ref module) if module.is_normal() => "module",
882                             Some(ref module) if module.is_trait() => "trait",
883                             _ => "type",
884                         }
885                     }
886                     ValueNS => "value",
887                 };
888                 let use_id = import_resolution.id;
889                 let item = self.resolver.ast_map.expect_item(use_id);
890                 let mut err = struct_span_err!(self.resolver.session,
891                                                import_span,
892                                                E0252,
893                                                "a {} named `{}` has already been imported \
894                                                 in this module",
895                                                ns_word,
896                                                name);
897                 span_note!(&mut err,
898                            item.span,
899                            "previous import of `{}` here",
900                            name);
901                 err.emit();
902             }
903             Some(_) | None => {}
904         }
905     }
906
907     /// Checks that an import is actually importable
908     fn check_that_import_is_importable(&mut self,
909                                        name_binding: &NameBinding,
910                                        import_span: Span,
911                                        name: Name) {
912         if !name_binding.defined_with(DefModifiers::IMPORTABLE) {
913             let msg = format!("`{}` is not directly importable", name);
914             span_err!(self.resolver.session, import_span, E0253, "{}", &msg[..]);
915         }
916     }
917
918     /// Checks that imported names and items don't have the same name.
919     fn check_for_conflicts_between_imports_and_items(&mut self,
920                                                      module: Module<'b>,
921                                                      import: &ImportResolution<'b>,
922                                                      import_span: Span,
923                                                      (name, ns): (Name, Namespace)) {
924         // First, check for conflicts between imports and `extern crate`s.
925         if let TypeNS = ns {
926             if module.external_module_children.borrow().contains_key(&name) {
927                 match import.target {
928                     Some(ref target) if target.shadowable != Shadowable::Always => {
929                         let msg = format!("import `{0}` conflicts with imported crate \
930                                            in this module (maybe you meant `use {0}::*`?)",
931                                           name);
932                         span_err!(self.resolver.session, import_span, E0254, "{}", &msg[..]);
933                     }
934                     Some(_) | None => {}
935                 }
936             }
937         }
938
939         // Check for item conflicts.
940         let name_binding = match module.get_child(name, ns) {
941             None => {
942                 // There can't be any conflicts.
943                 return;
944             }
945             Some(name_binding) => name_binding,
946         };
947
948         if let ValueNS = ns {
949             match import.target {
950                 Some(ref target) if target.shadowable != Shadowable::Always => {
951                     let mut err = struct_span_err!(self.resolver.session,
952                                                    import_span,
953                                                    E0255,
954                                                    "import `{}` conflicts with \
955                                                     value in this module",
956                                                    name);
957                     if let Some(span) = name_binding.span {
958                         err.span_note(span, "conflicting value here");
959                     }
960                     err.emit();
961                 }
962                 Some(_) | None => {}
963             }
964         } else {
965             match import.target {
966                 Some(ref target) if target.shadowable != Shadowable::Always => {
967                     let (what, note) = match name_binding.module() {
968                         Some(ref module) if module.is_normal() =>
969                             ("existing submodule", "note conflicting module here"),
970                         Some(ref module) if module.is_trait() =>
971                             ("trait in this module", "note conflicting trait here"),
972                         _ => ("type in this module", "note conflicting type here"),
973                     };
974                     let mut err = struct_span_err!(self.resolver.session,
975                                                    import_span,
976                                                    E0256,
977                                                    "import `{}` conflicts with {}",
978                                                    name,
979                                                    what);
980                     if let Some(span) = name_binding.span {
981                         err.span_note(span, note);
982                     }
983                     err.emit();
984                 }
985                 Some(_) | None => {}
986             }
987         }
988     }
989 }
990
991 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
992     if names.is_empty() {
993         import_directive_subclass_to_string(subclass)
994     } else {
995         (format!("{}::{}",
996                  names_to_string(names),
997                  import_directive_subclass_to_string(subclass)))
998             .to_string()
999     }
1000 }
1001
1002 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
1003     match subclass {
1004         SingleImport(_, source) => source.to_string(),
1005         GlobImport => "*".to_string(),
1006     }
1007 }
1008
1009 pub fn resolve_imports(resolver: &mut Resolver) {
1010     let mut import_resolver = ImportResolver { resolver: resolver };
1011     import_resolver.resolve_imports();
1012 }