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