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