]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
0757ff7ddbfd87a23f5f8608971e989923ab7afe
[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 Module;
14 use Namespace::{self, TypeNS, ValueNS};
15 use {NameBinding, NameBindingKind, PrivacyError, ToNameBinding};
16 use ResolveResult;
17 use ResolveResult::*;
18 use Resolver;
19 use UseLexicalScopeFlag::DontUseLexicalScope;
20 use {names_to_string, module_to_string};
21 use {resolve_error, ResolutionError};
22
23 use rustc::ty;
24 use rustc::lint::builtin::PRIVATE_IN_PUBLIC;
25 use rustc::hir::def::*;
26
27 use syntax::ast::{NodeId, Name};
28 use syntax::util::lev_distance::find_best_match_for_name;
29 use syntax_pos::{Span, DUMMY_SP};
30
31 use std::cell::{Cell, RefCell};
32
33 impl<'a> Resolver<'a> {
34     pub fn resolve_imports(&mut self) {
35         ImportResolver { resolver: self }.resolve_imports();
36     }
37 }
38
39 /// Contains data for specific types of import directives.
40 #[derive(Clone, Debug)]
41 pub enum ImportDirectiveSubclass<'a> {
42     SingleImport {
43         target: Name,
44         source: Name,
45         value_result: Cell<Result<&'a NameBinding<'a>, bool /* determined? */>>,
46         type_result: Cell<Result<&'a NameBinding<'a>, bool /* determined? */>>,
47     },
48     GlobImport { is_prelude: bool },
49 }
50
51 impl<'a> ImportDirectiveSubclass<'a> {
52     pub fn single(target: Name, source: Name) -> Self {
53         SingleImport {
54             target: target,
55             source: source,
56             type_result: Cell::new(Err(false)),
57             value_result: Cell::new(Err(false)),
58         }
59     }
60 }
61
62 /// One import directive.
63 #[derive(Debug,Clone)]
64 pub struct ImportDirective<'a> {
65     pub id: NodeId,
66     parent: Module<'a>,
67     module_path: Vec<Name>,
68     target_module: Cell<Option<Module<'a>>>, // the resolution of `module_path`
69     subclass: ImportDirectiveSubclass<'a>,
70     span: Span,
71     vis: ty::Visibility, // see note in ImportResolutionPerNamespace about how to use this
72 }
73
74 impl<'a> ImportDirective<'a> {
75     pub fn is_glob(&self) -> bool {
76         match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
77     }
78 }
79
80 #[derive(Clone, Default)]
81 /// Records information about the resolution of a name in a namespace of a module.
82 pub struct NameResolution<'a> {
83     /// The single imports that define the name in the namespace.
84     single_imports: SingleImports<'a>,
85     /// The least shadowable known binding for this name, or None if there are no known bindings.
86     pub binding: Option<&'a NameBinding<'a>>,
87     duplicate_globs: Vec<&'a NameBinding<'a>>,
88 }
89
90 #[derive(Clone, Debug)]
91 enum SingleImports<'a> {
92     /// No single imports can define the name in the namespace.
93     None,
94     /// Only the given single import can define the name in the namespace.
95     MaybeOne(&'a ImportDirective<'a>),
96     /// At least one single import will define the name in the namespace.
97     AtLeastOne,
98 }
99
100 impl<'a> Default for SingleImports<'a> {
101     fn default() -> Self {
102         SingleImports::None
103     }
104 }
105
106 impl<'a> SingleImports<'a> {
107     fn add_directive(&mut self, directive: &'a ImportDirective<'a>) {
108         match *self {
109             SingleImports::None => *self = SingleImports::MaybeOne(directive),
110             // If two single imports can define the name in the namespace, we can assume that at
111             // least one of them will define it since otherwise both would have to define only one
112             // namespace, leading to a duplicate error.
113             SingleImports::MaybeOne(_) => *self = SingleImports::AtLeastOne,
114             SingleImports::AtLeastOne => {}
115         };
116     }
117
118     fn directive_failed(&mut self) {
119         match *self {
120             SingleImports::None => unreachable!(),
121             SingleImports::MaybeOne(_) => *self = SingleImports::None,
122             SingleImports::AtLeastOne => {}
123         }
124     }
125 }
126
127 impl<'a> NameResolution<'a> {
128     // Returns the binding for the name if it is known or None if it not known.
129     fn binding(&self) -> Option<&'a NameBinding<'a>> {
130         self.binding.and_then(|binding| match self.single_imports {
131             SingleImports::None => Some(binding),
132             _ if !binding.is_glob_import() => Some(binding),
133             _ => None, // The binding could be shadowed by a single import, so it is not known.
134         })
135     }
136 }
137
138 impl<'a> Resolver<'a> {
139     fn resolution(&self, module: Module<'a>, name: Name, ns: Namespace)
140                   -> &'a RefCell<NameResolution<'a>> {
141         *module.resolutions.borrow_mut().entry((name, ns))
142                .or_insert_with(|| self.arenas.alloc_name_resolution())
143     }
144
145     /// Attempts to resolve the supplied name in the given module for the given namespace.
146     /// If successful, returns the binding corresponding to the name.
147     pub fn resolve_name_in_module(&mut self,
148                                   module: Module<'a>,
149                                   name: Name,
150                                   ns: Namespace,
151                                   allow_private_imports: bool,
152                                   record_used: Option<Span>)
153                                   -> ResolveResult<&'a NameBinding<'a>> {
154         self.populate_module_if_necessary(module);
155
156         let resolution = self.resolution(module, name, ns);
157         let resolution = match resolution.borrow_state() {
158             ::std::cell::BorrowState::Unused => resolution.borrow_mut(),
159             _ => return Failed(None), // This happens when there is a cycle of imports
160         };
161
162         if let Some(result) = self.try_result(&resolution, ns, allow_private_imports) {
163             // If the resolution doesn't depend on glob definability, check privacy and return.
164             return result.and_then(|binding| {
165                 if !allow_private_imports && binding.is_import() && !binding.is_pseudo_public() {
166                     return Failed(None);
167                 }
168                 if let Some(span) = record_used {
169                     self.record_use(name, ns, binding);
170                     if !self.is_accessible(binding.vis) {
171                         self.privacy_errors.push(PrivacyError(span, name, binding));
172                     }
173                 }
174                 Success(binding)
175             });
176         }
177
178         // Check if the globs are determined
179         for directive in module.globs.borrow().iter() {
180             if !allow_private_imports && directive.vis != ty::Visibility::Public { continue }
181             if let Some(target_module) = directive.target_module.get() {
182                 let result = self.resolve_name_in_module(target_module, name, ns, false, None);
183                 if let Indeterminate = result {
184                     return Indeterminate;
185                 }
186             } else {
187                 return Indeterminate;
188             }
189         }
190
191         Failed(None)
192     }
193
194     // Returns Some(the resolution of the name), or None if the resolution depends
195     // on whether more globs can define the name.
196     fn try_result(&mut self,
197                   resolution: &NameResolution<'a>,
198                   ns: Namespace,
199                   allow_private_imports: bool)
200                   -> Option<ResolveResult<&'a NameBinding<'a>>> {
201         match resolution.binding {
202             Some(binding) if !binding.is_glob_import() =>
203                 return Some(Success(binding)), // Items and single imports are not shadowable.
204             _ => {}
205         };
206
207         // Check if a single import can still define the name.
208         match resolution.single_imports {
209             SingleImports::None => {},
210             SingleImports::AtLeastOne => return Some(Indeterminate),
211             SingleImports::MaybeOne(directive) => {
212                 // If (1) we don't allow private imports, (2) no public single import can define
213                 // the name, and (3) no public glob has defined the name, the resolution depends
214                 // on whether more globs can define the name.
215                 if !allow_private_imports && directive.vis != ty::Visibility::Public &&
216                    !resolution.binding.map(NameBinding::is_pseudo_public).unwrap_or(false) {
217                     return None;
218                 }
219
220                 let target_module = match directive.target_module.get() {
221                     Some(target_module) => target_module,
222                     None => return Some(Indeterminate),
223                 };
224                 let name = match directive.subclass {
225                     SingleImport { source, .. } => source,
226                     GlobImport { .. } => unreachable!(),
227                 };
228                 match self.resolve_name_in_module(target_module, name, ns, false, None) {
229                     Failed(_) => {}
230                     _ => return Some(Indeterminate),
231                 }
232             }
233         }
234
235         resolution.binding.map(Success)
236     }
237
238     // Add an import directive to the current module.
239     pub fn add_import_directive(&mut self,
240                                 module_path: Vec<Name>,
241                                 subclass: ImportDirectiveSubclass<'a>,
242                                 span: Span,
243                                 id: NodeId,
244                                 vis: ty::Visibility) {
245         let current_module = self.current_module;
246         let directive = self.arenas.alloc_import_directive(ImportDirective {
247             parent: current_module,
248             module_path: module_path,
249             target_module: Cell::new(None),
250             subclass: subclass,
251             span: span,
252             id: id,
253             vis: vis,
254         });
255
256         self.indeterminate_imports.push(directive);
257         match directive.subclass {
258             SingleImport { target, .. } => {
259                 for &ns in &[ValueNS, TypeNS] {
260                     let mut resolution = self.resolution(current_module, target, ns).borrow_mut();
261                     resolution.single_imports.add_directive(directive);
262                 }
263             }
264             // We don't add prelude imports to the globs since they only affect lexical scopes,
265             // which are not relevant to import resolution.
266             GlobImport { is_prelude: true } => {}
267             GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
268         }
269     }
270
271     // Given a binding and an import directive that resolves to it,
272     // return the corresponding binding defined by the import directive.
273     fn import(&mut self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
274               -> NameBinding<'a> {
275         NameBinding {
276             kind: NameBindingKind::Import {
277                 binding: binding,
278                 directive: directive,
279             },
280             span: directive.span,
281             vis: directive.vis,
282         }
283     }
284
285     // Define the name or return the existing binding if there is a collision.
286     pub fn try_define<T>(&mut self, module: Module<'a>, name: Name, ns: Namespace, binding: T)
287                          -> Result<(), &'a NameBinding<'a>>
288         where T: ToNameBinding<'a>
289     {
290         let binding = self.arenas.alloc_name_binding(binding.to_name_binding());
291         self.update_resolution(module, name, ns, |_, resolution| {
292             if let Some(old_binding) = resolution.binding {
293                 if binding.is_glob_import() {
294                     resolution.duplicate_globs.push(binding);
295                 } else if old_binding.is_glob_import() {
296                     resolution.duplicate_globs.push(old_binding);
297                     resolution.binding = Some(binding);
298                 } else {
299                     return Err(old_binding);
300                 }
301             } else {
302                 resolution.binding = Some(binding);
303             }
304
305             Ok(())
306         })
307     }
308
309     // Use `f` to mutate the resolution of the name in the module.
310     // If the resolution becomes a success, define it in the module's glob importers.
311     fn update_resolution<T, F>(&mut self, module: Module<'a>, name: Name, ns: Namespace, f: F) -> T
312         where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
313     {
314         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
315         // during which the resolution might end up getting re-defined via a glob cycle.
316         let (new_binding, t) = {
317             let mut resolution = &mut *self.resolution(module, name, ns).borrow_mut();
318             let was_known = resolution.binding().is_some();
319
320             let t = f(self, resolution);
321
322             if was_known { return t; }
323             match resolution.binding() {
324                 Some(binding) => (binding, t),
325                 None => return t,
326             }
327         };
328
329         // Define `new_binding` in `module`s glob importers.
330         if new_binding.is_importable() && new_binding.is_pseudo_public() {
331             for directive in module.glob_importers.borrow_mut().iter() {
332                 let imported_binding = self.import(new_binding, directive);
333                 let _ = self.try_define(directive.parent, name, ns, imported_binding);
334             }
335         }
336
337         t
338     }
339 }
340
341 struct ImportResolvingError<'a> {
342     import_directive: &'a ImportDirective<'a>,
343     span: Span,
344     help: String,
345 }
346
347 struct ImportResolver<'a, 'b: 'a> {
348     resolver: &'a mut Resolver<'b>,
349 }
350
351 impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> {
352     type Target = Resolver<'b>;
353     fn deref(&self) -> &Resolver<'b> {
354         self.resolver
355     }
356 }
357
358 impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> {
359     fn deref_mut(&mut self) -> &mut Resolver<'b> {
360         self.resolver
361     }
362 }
363
364 impl<'a, 'b: 'a> ty::NodeIdTree for ImportResolver<'a, 'b> {
365     fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
366         self.resolver.is_descendant_of(node, ancestor)
367     }
368 }
369
370 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
371     // Import resolution
372     //
373     // This is a fixed-point algorithm. We resolve imports until our efforts
374     // are stymied by an unresolved import; then we bail out of the current
375     // module and continue. We terminate successfully once no more imports
376     // remain or unsuccessfully when no forward progress in resolving imports
377     // is made.
378
379     fn set_current_module(&mut self, module: Module<'b>) {
380         self.current_module = module;
381         self.current_vis = ty::Visibility::Restricted({
382             let normal_module = self.get_nearest_normal_module_parent_or_self(module);
383             self.definitions.as_local_node_id(normal_module.def_id().unwrap()).unwrap()
384         });
385     }
386
387     /// Resolves all imports for the crate. This method performs the fixed-
388     /// point iteration.
389     fn resolve_imports(&mut self) {
390         let mut i = 0;
391         let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
392         let mut errors = Vec::new();
393
394         while self.indeterminate_imports.len() < prev_num_indeterminates {
395             prev_num_indeterminates = self.indeterminate_imports.len();
396             debug!("(resolving imports) iteration {}, {} imports left", i, prev_num_indeterminates);
397
398             let mut imports = Vec::new();
399             ::std::mem::swap(&mut imports, &mut self.indeterminate_imports);
400
401             for import in imports {
402                 match self.resolve_import(&import) {
403                     Failed(err) => {
404                         let (span, help) = match err {
405                             Some((span, msg)) => (span, format!(". {}", msg)),
406                             None => (import.span, String::new()),
407                         };
408                         errors.push(ImportResolvingError {
409                             import_directive: import,
410                             span: span,
411                             help: help,
412                         });
413                     }
414                     Indeterminate => self.indeterminate_imports.push(import),
415                     Success(()) => {}
416                 }
417             }
418
419             i += 1;
420         }
421
422         for module in self.arenas.local_modules().iter() {
423             self.finalize_resolutions_in(module);
424         }
425
426         // Report unresolved imports only if no hard error was already reported
427         // to avoid generating multiple errors on the same import.
428         if errors.len() == 0 {
429             if let Some(import) = self.indeterminate_imports.iter().next() {
430                 let error = ResolutionError::UnresolvedImport(None);
431                 resolve_error(self.resolver, import.span, error);
432             }
433         }
434
435         for e in errors {
436             self.import_resolving_error(e)
437         }
438     }
439
440     // Define a "dummy" resolution containing a Def::Err as a placeholder for a
441     // failed resolution
442     fn import_dummy_binding(&mut self, directive: &'b ImportDirective<'b>) {
443         if let SingleImport { target, .. } = directive.subclass {
444             let dummy_binding = self.arenas.alloc_name_binding(NameBinding {
445                 kind: NameBindingKind::Def(Def::Err),
446                 span: DUMMY_SP,
447                 vis: ty::Visibility::Public,
448             });
449             let dummy_binding = self.import(dummy_binding, directive);
450
451             let _ = self.try_define(directive.parent, target, ValueNS, dummy_binding.clone());
452             let _ = self.try_define(directive.parent, target, TypeNS, dummy_binding);
453         }
454     }
455
456     /// Resolves an `ImportResolvingError` into the correct enum discriminant
457     /// and passes that on to `resolve_error`.
458     fn import_resolving_error(&mut self, e: ImportResolvingError<'b>) {
459         // If the error is a single failed import then create a "fake" import
460         // resolution for it so that later resolve stages won't complain.
461         self.import_dummy_binding(e.import_directive);
462         let path = import_path_to_string(&e.import_directive.module_path,
463                                          &e.import_directive.subclass);
464         resolve_error(self.resolver,
465                       e.span,
466                       ResolutionError::UnresolvedImport(Some((&path, &e.help))));
467     }
468
469     /// Attempts to resolve the given import. The return value indicates
470     /// failure if we're certain the name does not exist, indeterminate if we
471     /// don't know whether the name exists at the moment due to other
472     /// currently-unresolved imports, or success if we know the name exists.
473     /// If successful, the resolved bindings are written into the module.
474     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> ResolveResult<()> {
475         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
476                names_to_string(&directive.module_path),
477                module_to_string(self.current_module));
478
479         let module = directive.parent;
480         self.set_current_module(module);
481
482         let target_module = match directive.target_module.get() {
483             Some(module) => module,
484             _ => match self.resolve_module_path(&directive.module_path,
485                                                 DontUseLexicalScope,
486                                                 Some(directive.span)) {
487                 Success(module) => module,
488                 Indeterminate => return Indeterminate,
489                 Failed(err) => return Failed(err),
490             },
491         };
492
493         directive.target_module.set(Some(target_module));
494         let (source, target, value_result, type_result) = match directive.subclass {
495             SingleImport { source, target, ref value_result, ref type_result } =>
496                 (source, target, value_result, type_result),
497             GlobImport { .. } => return self.resolve_glob_import(target_module, directive),
498         };
499
500         let mut privacy_error = true;
501         for &(ns, result) in &[(ValueNS, value_result), (TypeNS, type_result)] {
502             let was_determined = if let Err(false) = result.get() {
503                 result.set({
504                     let span = Some(directive.span);
505                     match self.resolve_name_in_module(target_module, source, ns, false, span) {
506                         Success(binding) => Ok(binding),
507                         Indeterminate => Err(false),
508                         Failed(_) => Err(true),
509                     }
510                 });
511                 false
512             } else {
513                 true
514             };
515
516             match result.get() {
517                 Err(true) if !was_determined => {
518                     self.update_resolution(module, target, ns, |_, resolution| {
519                         resolution.single_imports.directive_failed()
520                     });
521                 }
522                 Ok(binding) if !binding.is_importable() => {
523                     let msg = format!("`{}` is not directly importable", target);
524                     struct_span_err!(self.session, directive.span, E0253, "{}", &msg)
525                         .span_label(directive.span, &format!("cannot be imported directly"))
526                         .emit();
527                     // Do not import this illegal binding. Import a dummy binding and pretend
528                     // everything is fine
529                     self.import_dummy_binding(directive);
530                     return Success(());
531                 }
532                 Ok(binding) if !self.is_accessible(binding.vis) => {}
533                 Ok(binding) if !was_determined => {
534                     let imported_binding = self.import(binding, directive);
535                     let conflict = self.try_define(module, target, ns, imported_binding);
536                     if let Err(old_binding) = conflict {
537                         let binding = &self.import(binding, directive);
538                         self.report_conflict(module, target, ns, binding, old_binding);
539                     }
540                     privacy_error = false;
541                 }
542                 Ok(_) => privacy_error = false,
543                 _ => {}
544             }
545         }
546
547         let (value_result, type_result) = (value_result.get(), type_result.get());
548         match (value_result, type_result) {
549             (Err(false), _) | (_, Err(false)) => return Indeterminate,
550             (Err(true), Err(true)) => {
551                 let resolutions = target_module.resolutions.borrow();
552                 let names = resolutions.iter().filter_map(|(&(ref name, _), resolution)| {
553                     if *name == source { return None; } // Never suggest the same name
554                     match *resolution.borrow() {
555                         NameResolution { binding: Some(_), .. } => Some(name),
556                         NameResolution { single_imports: SingleImports::None, .. } => None,
557                         _ => Some(name),
558                     }
559                 });
560                 let lev_suggestion = match find_best_match_for_name(names, &source.as_str(), None) {
561                     Some(name) => format!(". Did you mean to use `{}`?", name),
562                     None => "".to_owned(),
563                 };
564                 let module_str = module_to_string(target_module);
565                 let msg = if &module_str == "???" {
566                     format!("There is no `{}` in the crate root{}", source, lev_suggestion)
567                 } else {
568                     format!("There is no `{}` in `{}`{}", source, module_str, lev_suggestion)
569                 };
570                 return Failed(Some((directive.span, msg)));
571             }
572             _ => (),
573         }
574
575         if privacy_error {
576             for &(ns, result) in &[(ValueNS, value_result), (TypeNS, type_result)] {
577                 let binding = match result { Ok(binding) => binding, _ => continue };
578                 self.privacy_errors.push(PrivacyError(directive.span, source, binding));
579                 let imported_binding = self.import(binding, directive);
580                 let _ = self.try_define(module, target, ns, imported_binding);
581             }
582         }
583
584         match (value_result, type_result) {
585             (Ok(binding), _) if !binding.pseudo_vis().is_at_least(directive.vis, self) &&
586                                 self.is_accessible(binding.vis) => {
587                 let msg = format!("`{}` is private, and cannot be reexported", source);
588                 let note_msg = format!("consider marking `{}` as `pub` in the imported module",
589                                         source);
590                 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
591                     .span_note(directive.span, &note_msg)
592                     .emit();
593             }
594
595             (_, Ok(binding)) if !binding.pseudo_vis().is_at_least(directive.vis, self) &&
596                                 self.is_accessible(binding.vis) => {
597                 if binding.is_extern_crate() {
598                     let msg = format!("extern crate `{}` is private, and cannot be reexported \
599                                        (error E0364), consider declaring with `pub`",
600                                        source);
601                     self.session.add_lint(PRIVATE_IN_PUBLIC, directive.id, directive.span, msg);
602                 } else {
603                     let mut err = struct_span_err!(self.session, directive.span, E0365,
604                                                      "`{}` is private, and cannot be reexported",
605                                                      source);
606                     err.span_label(directive.span, &format!("reexport of private `{}`", source));
607                     err.note(&format!("consider declaring type or module `{}` with `pub`", source));
608                     err.emit();
609                 }
610             }
611
612             _ => {}
613         }
614
615         // Record what this import resolves to for later uses in documentation,
616         // this may resolve to either a value or a type, but for documentation
617         // purposes it's good enough to just favor one over the other.
618         let def = match type_result.ok().and_then(NameBinding::def) {
619             Some(def) => def,
620             None => value_result.ok().and_then(NameBinding::def).unwrap(),
621         };
622         let path_resolution = PathResolution::new(def);
623         self.def_map.insert(directive.id, path_resolution);
624
625         debug!("(resolving single import) successfully resolved import");
626         return Success(());
627     }
628
629     // Resolves a glob import. Note that this function cannot fail; it either
630     // succeeds or bails out (as importing * from an empty module or a module
631     // that exports nothing is valid). target_module is the module we are
632     // actually importing, i.e., `foo` in `use foo::*`.
633     fn resolve_glob_import(&mut self, target_module: Module<'b>, directive: &'b ImportDirective<'b>)
634                            -> ResolveResult<()> {
635         if let Some(Def::Trait(_)) = target_module.def {
636             self.session.span_err(directive.span, "items in traits are not importable.");
637         }
638
639         let module = self.current_module;
640         if module.def_id() == target_module.def_id() {
641             // This means we are trying to glob import a module into itself, and it is a no-go
642             let msg = "Cannot glob-import a module into itself.".into();
643             return Failed(Some((directive.span, msg)));
644         }
645         self.populate_module_if_necessary(target_module);
646
647         if let GlobImport { is_prelude: true } = directive.subclass {
648             self.prelude = Some(target_module);
649             return Success(());
650         }
651
652         // Add to target_module's glob_importers
653         target_module.glob_importers.borrow_mut().push(directive);
654
655         // Ensure that `resolutions` isn't borrowed during `try_define`,
656         // since it might get updated via a glob cycle.
657         let bindings = target_module.resolutions.borrow().iter().filter_map(|(name, resolution)| {
658             resolution.borrow().binding().map(|binding| (*name, binding))
659         }).collect::<Vec<_>>();
660         for ((name, ns), binding) in bindings {
661             if binding.is_importable() && binding.is_pseudo_public() {
662                 let imported_binding = self.import(binding, directive);
663                 let _ = self.try_define(module, name, ns, imported_binding);
664             }
665         }
666
667         // Record the destination of this import
668         if let Some(did) = target_module.def_id() {
669             let resolution = PathResolution::new(Def::Mod(did));
670             self.def_map.insert(directive.id, resolution);
671         }
672
673         debug!("(resolving glob import) successfully resolved import");
674         return Success(());
675     }
676
677     // Miscellaneous post-processing, including recording reexports, reporting conflicts,
678     // reporting the PRIVATE_IN_PUBLIC lint, and reporting unresolved imports.
679     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
680         // Since import resolution is finished, globs will not define any more names.
681         *module.globs.borrow_mut() = Vec::new();
682
683         let mut reexports = Vec::new();
684         for (&(name, ns), resolution) in module.resolutions.borrow().iter() {
685             let resolution = resolution.borrow();
686             let binding = match resolution.binding {
687                 Some(binding) => binding,
688                 None => continue,
689             };
690
691             // Report conflicts
692             for duplicate_glob in resolution.duplicate_globs.iter() {
693                 // FIXME #31337: We currently allow items to shadow glob-imported re-exports.
694                 if !binding.is_import() {
695                     if let NameBindingKind::Import { binding, .. } = duplicate_glob.kind {
696                         if binding.is_import() { continue }
697                     }
698                 }
699
700                 self.report_conflict(module, name, ns, duplicate_glob, binding);
701             }
702
703             if binding.vis == ty::Visibility::Public &&
704                (binding.is_import() || binding.is_extern_crate()) {
705                 if let Some(def) = binding.def() {
706                     reexports.push(Export { name: name, def_id: def.def_id() });
707                 }
708             }
709
710             if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
711                 if ns == TypeNS && orig_binding.is_variant() &&
712                    !orig_binding.vis.is_at_least(binding.vis, self) {
713                     let msg = format!("variant `{}` is private, and cannot be reexported \
714                                        (error E0364), consider declaring its enum as `pub`",
715                                       name);
716                     self.session.add_lint(PRIVATE_IN_PUBLIC, directive.id, binding.span, msg);
717                 }
718             }
719         }
720
721         if reexports.len() > 0 {
722             if let Some(def_id) = module.def_id() {
723                 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
724                 self.export_map.insert(node_id, reexports);
725             }
726         }
727     }
728 }
729
730 fn import_path_to_string(names: &[Name], subclass: &ImportDirectiveSubclass) -> String {
731     if names.is_empty() {
732         import_directive_subclass_to_string(subclass)
733     } else {
734         (format!("{}::{}",
735                  names_to_string(names),
736                  import_directive_subclass_to_string(subclass)))
737             .to_string()
738     }
739 }
740
741 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
742     match *subclass {
743         SingleImport { source, .. } => source.to_string(),
744         GlobImport { .. } => "*".to_string(),
745     }
746 }