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