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