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