]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
43654c8ce6f6875b13aa5009fabec257024ae784
[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 {AmbiguityError, Module, PerNS};
14 use Namespace::{self, TypeNS, MacroNS};
15 use {NameBinding, NameBindingKind, PathResult, PrivacyError};
16 use Resolver;
17 use {names_to_string, module_to_string};
18 use {resolve_error, ResolutionError};
19
20 use rustc::ty;
21 use rustc::lint::builtin::PRIVATE_IN_PUBLIC;
22 use rustc::hir::def_id::DefId;
23 use rustc::hir::def::*;
24 use rustc::util::nodemap::FxHashMap;
25
26 use syntax::ast::{Ident, NodeId};
27 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
28 use syntax::ext::hygiene::Mark;
29 use syntax::parse::token;
30 use syntax::symbol::keywords;
31 use syntax::util::lev_distance::find_best_match_for_name;
32 use syntax_pos::Span;
33
34 use std::cell::{Cell, RefCell};
35 use std::mem;
36
37 /// Contains data for specific types of import directives.
38 #[derive(Clone, Debug)]
39 pub enum ImportDirectiveSubclass<'a> {
40     SingleImport {
41         target: Ident,
42         source: Ident,
43         result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
44         type_ns_only: bool,
45     },
46     GlobImport {
47         is_prelude: bool,
48         max_vis: Cell<ty::Visibility>, // The visibility of the greatest reexport.
49         // n.b. `max_vis` is only used in `finalize_import` to check for reexport errors.
50     },
51     ExternCrate,
52     MacroUse,
53 }
54
55 /// One import directive.
56 #[derive(Debug,Clone)]
57 pub struct ImportDirective<'a> {
58     pub id: NodeId,
59     pub parent: Module<'a>,
60     pub module_path: Vec<Ident>,
61     pub imported_module: Cell<Option<Module<'a>>>, // the resolution of `module_path`
62     pub subclass: ImportDirectiveSubclass<'a>,
63     pub span: Span,
64     pub vis: Cell<ty::Visibility>,
65     pub expansion: Mark,
66     pub used: Cell<bool>,
67 }
68
69 impl<'a> ImportDirective<'a> {
70     pub fn is_glob(&self) -> bool {
71         match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
72     }
73 }
74
75 #[derive(Clone, Default)]
76 /// Records information about the resolution of a name in a namespace of a module.
77 pub struct NameResolution<'a> {
78     /// The single imports that define the name in the namespace.
79     single_imports: SingleImports<'a>,
80     /// The least shadowable known binding for this name, or None if there are no known bindings.
81     pub binding: Option<&'a NameBinding<'a>>,
82     shadows_glob: Option<&'a NameBinding<'a>>,
83 }
84
85 #[derive(Clone, Debug)]
86 enum SingleImports<'a> {
87     /// No single imports can define the name in the namespace.
88     None,
89     /// Only the given single import can define the name in the namespace.
90     MaybeOne(&'a ImportDirective<'a>),
91     /// At least one single import will define the name in the namespace.
92     AtLeastOne,
93 }
94
95 impl<'a> Default for SingleImports<'a> {
96     /// Creates a `SingleImports<'a>` of None type.
97     fn default() -> Self {
98         SingleImports::None
99     }
100 }
101
102 impl<'a> SingleImports<'a> {
103     fn add_directive(&mut self, directive: &'a ImportDirective<'a>) {
104         match *self {
105             SingleImports::None => *self = SingleImports::MaybeOne(directive),
106             // If two single imports can define the name in the namespace, we can assume that at
107             // least one of them will define it since otherwise both would have to define only one
108             // namespace, leading to a duplicate error.
109             SingleImports::MaybeOne(_) => *self = SingleImports::AtLeastOne,
110             SingleImports::AtLeastOne => {}
111         };
112     }
113
114     fn directive_failed(&mut self) {
115         match *self {
116             SingleImports::None => unreachable!(),
117             SingleImports::MaybeOne(_) => *self = SingleImports::None,
118             SingleImports::AtLeastOne => {}
119         }
120     }
121 }
122
123 impl<'a> NameResolution<'a> {
124     // Returns the binding for the name if it is known or None if it not known.
125     fn binding(&self) -> Option<&'a NameBinding<'a>> {
126         self.binding.and_then(|binding| match self.single_imports {
127             SingleImports::None => Some(binding),
128             _ if !binding.is_glob_import() => Some(binding),
129             _ => None, // The binding could be shadowed by a single import, so it is not known.
130         })
131     }
132 }
133
134 impl<'a> Resolver<'a> {
135     fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
136                   -> &'a RefCell<NameResolution<'a>> {
137         let ident = ident.unhygienize();
138         *module.resolutions.borrow_mut().entry((ident, ns))
139                .or_insert_with(|| self.arenas.alloc_name_resolution())
140     }
141
142     /// Attempts to resolve `ident` in namespaces `ns` of `module`.
143     /// Invariant: if `record_used` is `Some`, import resolution must be complete.
144     pub fn resolve_ident_in_module(&mut self,
145                                    module: Module<'a>,
146                                    ident: Ident,
147                                    ns: Namespace,
148                                    restricted_shadowing: bool,
149                                    record_used: Option<Span>)
150                                    -> Result<&'a NameBinding<'a>, Determinacy> {
151         self.populate_module_if_necessary(module);
152
153         let resolution = self.resolution(module, ident, ns)
154             .try_borrow_mut()
155             .map_err(|_| Determined)?; // This happens when there is a cycle of imports
156
157         if let Some(span) = record_used {
158             if let Some(binding) = resolution.binding {
159                 if let Some(shadowed_glob) = resolution.shadows_glob {
160                     let name = ident.name;
161                     // Forbid expanded shadowing to avoid time travel.
162                     if restricted_shadowing &&
163                        binding.expansion != Mark::root() &&
164                        ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing
165                        binding.def() != shadowed_glob.def() {
166                         self.ambiguity_errors.push(AmbiguityError {
167                             span: span, name: name, lexical: false, b1: binding, b2: shadowed_glob,
168                             legacy: false,
169                         });
170                     }
171                 }
172                 if self.record_use(ident, ns, binding, span) {
173                     return Ok(self.dummy_binding);
174                 }
175                 if !self.is_accessible(binding.vis) {
176                     self.privacy_errors.push(PrivacyError(span, ident.name, binding));
177                 }
178             }
179
180             return resolution.binding.ok_or(Determined);
181         }
182
183         let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
184             // `extern crate` are always usable for backwards compatability, see issue #37020.
185             let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
186             if usable { Ok(binding) } else { Err(Determined) }
187         };
188
189         // Items and single imports are not shadowable.
190         if let Some(binding) = resolution.binding {
191             if !binding.is_glob_import() {
192                 return check_usable(self, binding);
193             }
194         }
195
196         // Check if a single import can still define the name.
197         match resolution.single_imports {
198             SingleImports::AtLeastOne => return Err(Undetermined),
199             SingleImports::MaybeOne(directive) if self.is_accessible(directive.vis.get()) => {
200                 let module = match directive.imported_module.get() {
201                     Some(module) => module,
202                     None => return Err(Undetermined),
203                 };
204                 let ident = match directive.subclass {
205                     SingleImport { source, .. } => source,
206                     _ => unreachable!(),
207                 };
208                 match self.resolve_ident_in_module(module, ident, ns, false, None) {
209                     Err(Determined) => {}
210                     _ => return Err(Undetermined),
211                 }
212             }
213             SingleImports::MaybeOne(_) | SingleImports::None => {},
214         }
215
216         let no_unresolved_invocations =
217             restricted_shadowing || module.unresolved_invocations.borrow().is_empty();
218         match resolution.binding {
219             // In `MacroNS`, expanded bindings do not shadow (enforced in `try_define`).
220             Some(binding) if no_unresolved_invocations || ns == MacroNS =>
221                 return check_usable(self, binding),
222             None if no_unresolved_invocations => {}
223             _ => return Err(Undetermined),
224         }
225
226         // Check if the globs are determined
227         if restricted_shadowing && module.def().is_some() {
228             return Err(Determined);
229         }
230         for directive in module.globs.borrow().iter() {
231             if self.is_accessible(directive.vis.get()) {
232                 if let Some(module) = directive.imported_module.get() {
233                     let result = self.resolve_ident_in_module(module, ident, ns, false, None);
234                     if let Err(Undetermined) = result {
235                         return Err(Undetermined);
236                     }
237                 } else {
238                     return Err(Undetermined);
239                 }
240             }
241         }
242
243         Err(Determined)
244     }
245
246     // Add an import directive to the current module.
247     pub fn add_import_directive(&mut self,
248                                 module_path: Vec<Ident>,
249                                 subclass: ImportDirectiveSubclass<'a>,
250                                 span: Span,
251                                 id: NodeId,
252                                 vis: ty::Visibility,
253                                 expansion: Mark) {
254         let current_module = self.current_module;
255         let directive = self.arenas.alloc_import_directive(ImportDirective {
256             parent: current_module,
257             module_path: module_path,
258             imported_module: Cell::new(None),
259             subclass: subclass,
260             span: span,
261             id: id,
262             vis: Cell::new(vis),
263             expansion: expansion,
264             used: Cell::new(false),
265         });
266
267         self.indeterminate_imports.push(directive);
268         match directive.subclass {
269             SingleImport { target, .. } => {
270                 self.per_ns(|this, ns| {
271                     let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
272                     resolution.single_imports.add_directive(directive);
273                 });
274             }
275             // We don't add prelude imports to the globs since they only affect lexical scopes,
276             // which are not relevant to import resolution.
277             GlobImport { is_prelude: true, .. } => {}
278             GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
279             _ => unreachable!(),
280         }
281     }
282
283     // Given a binding and an import directive that resolves to it,
284     // return the corresponding binding defined by the import directive.
285     pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
286                   -> &'a NameBinding<'a> {
287         let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
288                      !directive.is_glob() && binding.is_extern_crate() { // c.f. `PRIVATE_IN_PUBLIC`
289             directive.vis.get()
290         } else {
291             binding.pseudo_vis()
292         };
293
294         if let GlobImport { ref max_vis, .. } = directive.subclass {
295             if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
296                 max_vis.set(vis)
297             }
298         }
299
300         self.arenas.alloc_name_binding(NameBinding {
301             kind: NameBindingKind::Import {
302                 binding: binding,
303                 directive: directive,
304                 used: Cell::new(false),
305                 legacy_self_import: false,
306             },
307             span: directive.span,
308             vis: vis,
309             expansion: directive.expansion,
310         })
311     }
312
313     // Define the name or return the existing binding if there is a collision.
314     pub fn try_define(&mut self,
315                       module: Module<'a>,
316                       ident: Ident,
317                       ns: Namespace,
318                       binding: &'a NameBinding<'a>)
319                       -> Result<(), &'a NameBinding<'a>> {
320         self.update_resolution(module, ident, ns, |this, resolution| {
321             if let Some(old_binding) = resolution.binding {
322                 if binding.is_glob_import() {
323                     if !old_binding.is_glob_import() &&
324                        !(ns == MacroNS && old_binding.expansion != Mark::root()) {
325                         resolution.shadows_glob = Some(binding);
326                     } else if binding.def() != old_binding.def() {
327                         resolution.binding = Some(this.ambiguity(old_binding, binding));
328                     } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
329                         // We are glob-importing the same item but with greater visibility.
330                         resolution.binding = Some(binding);
331                     }
332                 } else if old_binding.is_glob_import() {
333                     if ns == MacroNS && binding.expansion != Mark::root() &&
334                        binding.def() != old_binding.def() {
335                         resolution.binding = Some(this.ambiguity(binding, old_binding));
336                     } else {
337                         resolution.binding = Some(binding);
338                         resolution.shadows_glob = Some(old_binding);
339                     }
340                 } else {
341                     return Err(old_binding);
342                 }
343             } else {
344                 resolution.binding = Some(binding);
345             }
346
347             Ok(())
348         })
349     }
350
351     pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
352                      -> &'a NameBinding<'a> {
353         self.arenas.alloc_name_binding(NameBinding {
354             kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: false },
355             vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
356             span: b1.span,
357             expansion: Mark::root(),
358         })
359     }
360
361     // Use `f` to mutate the resolution of the name in the module.
362     // If the resolution becomes a success, define it in the module's glob importers.
363     fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
364                                -> T
365         where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
366     {
367         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
368         // during which the resolution might end up getting re-defined via a glob cycle.
369         let (binding, t) = {
370             let mut resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
371             let old_binding = resolution.binding();
372
373             let t = f(self, resolution);
374
375             match resolution.binding() {
376                 _ if old_binding.is_some() => return t,
377                 None => return t,
378                 Some(binding) => match old_binding {
379                     Some(old_binding) if old_binding as *const _ == binding as *const _ => return t,
380                     _ => (binding, t),
381                 }
382             }
383         };
384
385         // Define `binding` in `module`s glob importers.
386         for directive in module.glob_importers.borrow_mut().iter() {
387             if self.is_accessible_from(binding.vis, directive.parent) {
388                 let imported_binding = self.import(binding, directive);
389                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
390             }
391         }
392
393         t
394     }
395
396     // Define a "dummy" resolution containing a Def::Err as a placeholder for a
397     // failed resolution
398     fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
399         if let SingleImport { target, .. } = directive.subclass {
400             let dummy_binding = self.dummy_binding;
401             let dummy_binding = self.import(dummy_binding, directive);
402             self.per_ns(|this, ns| {
403                 let _ = this.try_define(directive.parent, target, ns, dummy_binding);
404             });
405         }
406     }
407 }
408
409 pub struct ImportResolver<'a, 'b: 'a> {
410     pub resolver: &'a mut Resolver<'b>,
411 }
412
413 impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> {
414     type Target = Resolver<'b>;
415     fn deref(&self) -> &Resolver<'b> {
416         self.resolver
417     }
418 }
419
420 impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> {
421     fn deref_mut(&mut self) -> &mut Resolver<'b> {
422         self.resolver
423     }
424 }
425
426 impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
427     fn parent(self, id: DefId) -> Option<DefId> {
428         self.resolver.parent(id)
429     }
430 }
431
432 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
433     // Import resolution
434     //
435     // This is a fixed-point algorithm. We resolve imports until our efforts
436     // are stymied by an unresolved import; then we bail out of the current
437     // module and continue. We terminate successfully once no more imports
438     // remain or unsuccessfully when no forward progress in resolving imports
439     // is made.
440
441     /// Resolves all imports for the crate. This method performs the fixed-
442     /// point iteration.
443     pub fn resolve_imports(&mut self) {
444         let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
445         while self.indeterminate_imports.len() < prev_num_indeterminates {
446             prev_num_indeterminates = self.indeterminate_imports.len();
447             for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
448                 match self.resolve_import(&import) {
449                     true => self.determined_imports.push(import),
450                     false => self.indeterminate_imports.push(import),
451                 }
452             }
453         }
454     }
455
456     pub fn finalize_imports(&mut self) {
457         for module in self.arenas.local_modules().iter() {
458             self.finalize_resolutions_in(module);
459         }
460
461         let mut errors = false;
462         for i in 0 .. self.determined_imports.len() {
463             let import = self.determined_imports[i];
464             if let Some(err) = self.finalize_import(import) {
465                 errors = true;
466
467                 // If the error is a single failed import then create a "fake" import
468                 // resolution for it so that later resolve stages won't complain.
469                 self.import_dummy_binding(import);
470                 let path = import_path_to_string(&import.module_path, &import.subclass);
471                 let error = ResolutionError::UnresolvedImport(Some((&path, &err)));
472                 resolve_error(self.resolver, import.span, error);
473             }
474         }
475
476         // Report unresolved imports only if no hard error was already reported
477         // to avoid generating multiple errors on the same import.
478         if !errors {
479             if let Some(import) = self.indeterminate_imports.iter().next() {
480                 let error = ResolutionError::UnresolvedImport(None);
481                 resolve_error(self.resolver, import.span, error);
482             }
483         }
484     }
485
486     /// Attempts to resolve the given import, returning true if its resolution is determined.
487     /// If successful, the resolved bindings are written into the module.
488     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
489         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
490                names_to_string(&directive.module_path),
491                module_to_string(self.current_module));
492
493         self.current_module = directive.parent;
494
495         let module = if let Some(module) = directive.imported_module.get() {
496             module
497         } else {
498             let vis = directive.vis.get();
499             // For better failure detection, pretend that the import will not define any names
500             // while resolving its module path.
501             directive.vis.set(ty::Visibility::Invisible);
502             let result = self.resolve_path(&directive.module_path, None, None);
503             directive.vis.set(vis);
504
505             match result {
506                 PathResult::Module(module) => module,
507                 PathResult::Indeterminate => return false,
508                 _ => return true,
509             }
510         };
511
512         directive.imported_module.set(Some(module));
513         let (source, target, result, type_ns_only) = match directive.subclass {
514             SingleImport { source, target, ref result, type_ns_only } =>
515                 (source, target, result, type_ns_only),
516             GlobImport { .. } => {
517                 self.resolve_glob_import(directive);
518                 return true;
519             }
520             _ => unreachable!(),
521         };
522
523         let mut indeterminate = false;
524         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
525             if let Err(Undetermined) = result[ns].get() {
526                 result[ns].set(this.resolve_ident_in_module(module, source, ns, false, None));
527             } else {
528                 return
529             };
530
531             let parent = directive.parent;
532             match result[ns].get() {
533                 Err(Undetermined) => indeterminate = true,
534                 Err(Determined) => {
535                     this.update_resolution(parent, target, ns, |_, resolution| {
536                         resolution.single_imports.directive_failed()
537                     });
538                 }
539                 Ok(binding) if !binding.is_importable() => {
540                     let msg = format!("`{}` is not directly importable", target);
541                     struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
542                         .span_label(directive.span, &format!("cannot be imported directly"))
543                         .emit();
544                     // Do not import this illegal binding. Import a dummy binding and pretend
545                     // everything is fine
546                     this.import_dummy_binding(directive);
547                 }
548                 Ok(binding) => {
549                     let imported_binding = this.import(binding, directive);
550                     let conflict = this.try_define(parent, target, ns, imported_binding);
551                     if let Err(old_binding) = conflict {
552                         this.report_conflict(parent, target, ns, imported_binding, old_binding);
553                     }
554                 }
555             }
556         });
557
558         !indeterminate
559     }
560
561     // If appropriate, returns an error to report.
562     fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<String> {
563         self.current_module = directive.parent;
564
565         let ImportDirective { ref module_path, span, .. } = *directive;
566         let module_result = self.resolve_path(&module_path, None, Some(span));
567         let module = match module_result {
568             PathResult::Module(module) => module,
569             PathResult::Failed(msg, _) => {
570                 let (mut self_path, mut self_result) = (module_path.clone(), None);
571                 if !self_path.is_empty() && !token::Ident(self_path[0]).is_path_segment_keyword() {
572                     self_path[0].name = keywords::SelfValue.name();
573                     self_result = Some(self.resolve_path(&self_path, None, None));
574                 }
575                 return if let Some(PathResult::Module(..)) = self_result {
576                     Some(format!("Did you mean `{}`?", names_to_string(&self_path)))
577                 } else {
578                     Some(msg)
579                 };
580             },
581             _ => return None,
582         };
583
584         let (ident, result, type_ns_only) = match directive.subclass {
585             SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
586             GlobImport { .. } if module.def_id() == directive.parent.def_id() => {
587                 // Importing a module into itself is not allowed.
588                 return Some("Cannot glob-import a module into itself.".to_string());
589             }
590             GlobImport { is_prelude, ref max_vis } => {
591                 if !is_prelude &&
592                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
593                    !max_vis.get().is_at_least(directive.vis.get(), &*self) {
594                     let msg = "A non-empty glob must import something with the glob's visibility";
595                     self.session.span_err(directive.span, msg);
596                 }
597                 return None;
598             }
599             _ => unreachable!(),
600         };
601
602         let mut all_ns_err = true;
603         let mut legacy_self_import = None;
604         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
605             if let Ok(binding) = result[ns].get() {
606                 all_ns_err = false;
607                 if this.record_use(ident, ns, binding, directive.span) {
608                     this.resolution(module, ident, ns).borrow_mut().binding =
609                         Some(this.dummy_binding);
610                 }
611             }
612         } else if let Ok(binding) = this.resolve_ident_in_module(module, ident, ns, false, None) {
613             legacy_self_import = Some(directive);
614             let binding = this.arenas.alloc_name_binding(NameBinding {
615                 kind: NameBindingKind::Import {
616                     binding: binding,
617                     directive: directive,
618                     used: Cell::new(false),
619                     legacy_self_import: true,
620                 },
621                 ..*binding
622             });
623             let _ = this.try_define(directive.parent, ident, ns, binding);
624         });
625
626         if all_ns_err {
627             if let Some(directive) = legacy_self_import {
628                 self.warn_legacy_self_import(directive);
629                 return None;
630             }
631             let mut all_ns_failed = true;
632             self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
633                 match this.resolve_ident_in_module(module, ident, ns, false, Some(span)) {
634                     Ok(_) => all_ns_failed = false,
635                     _ => {}
636                 }
637             });
638
639             return if all_ns_failed {
640                 let resolutions = module.resolutions.borrow();
641                 let names = resolutions.iter().filter_map(|(&(ref i, _), resolution)| {
642                     if *i == ident { return None; } // Never suggest the same name
643                     match *resolution.borrow() {
644                         NameResolution { binding: Some(name_binding), .. } => {
645                             match name_binding.kind {
646                                 NameBindingKind::Import { binding, .. } => {
647                                     match binding.kind {
648                                         // Never suggest the name that has binding error
649                                         // i.e. the name that cannot be previously resolved
650                                         NameBindingKind::Def(Def::Err) => return None,
651                                         _ => Some(&i.name),
652                                     }
653                                 },
654                                 _ => Some(&i.name),
655                             }
656                         },
657                         NameResolution { single_imports: SingleImports::None, .. } => None,
658                         _ => Some(&i.name),
659                     }
660                 });
661                 let lev_suggestion =
662                     match find_best_match_for_name(names, &ident.name.as_str(), None) {
663                         Some(name) => format!(". Did you mean to use `{}`?", name),
664                         None => "".to_owned(),
665                     };
666                 let module_str = module_to_string(module);
667                 let msg = if &module_str == "???" {
668                     format!("no `{}` in the root{}", ident, lev_suggestion)
669                 } else {
670                     format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
671                 };
672                 Some(msg)
673             } else {
674                 // `resolve_ident_in_module` reported a privacy error.
675                 self.import_dummy_binding(directive);
676                 None
677             }
678         }
679
680         let mut reexport_error = None;
681         let mut any_successful_reexport = false;
682         self.per_ns(|this, ns| {
683             if let Ok(binding) = result[ns].get() {
684                 let vis = directive.vis.get();
685                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
686                     reexport_error = Some((ns, binding));
687                 } else {
688                     any_successful_reexport = true;
689                 }
690             }
691         });
692
693         // All namespaces must be re-exported with extra visibility for an error to occur.
694         if !any_successful_reexport {
695             let (ns, binding) = reexport_error.unwrap();
696             if ns == TypeNS && binding.is_extern_crate() {
697                 let msg = format!("extern crate `{}` is private, and cannot be reexported \
698                                    (error E0364), consider declaring with `pub`",
699                                    ident);
700                 self.session.add_lint(PRIVATE_IN_PUBLIC, directive.id, directive.span, msg);
701             } else if ns == TypeNS {
702                 struct_span_err!(self.session, directive.span, E0365,
703                                  "`{}` is private, and cannot be reexported", ident)
704                     .span_label(directive.span, &format!("reexport of private `{}`", ident))
705                     .note(&format!("consider declaring type or module `{}` with `pub`", ident))
706                     .emit();
707             } else {
708                 let msg = format!("`{}` is private, and cannot be reexported", ident);
709                 let note_msg =
710                     format!("consider marking `{}` as `pub` in the imported module", ident);
711                 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
712                     .span_note(directive.span, &note_msg)
713                     .emit();
714             }
715         }
716
717         // Record what this import resolves to for later uses in documentation,
718         // this may resolve to either a value or a type, but for documentation
719         // purposes it's good enough to just favor one over the other.
720         self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
721             this.def_map.entry(directive.id).or_insert(PathResolution::new(binding.def()));
722         });
723
724         debug!("(resolving single import) successfully resolved import");
725         None
726     }
727
728     fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
729         let module = directive.imported_module.get().unwrap();
730         self.populate_module_if_necessary(module);
731
732         if let Some(Def::Trait(_)) = module.def() {
733             self.session.span_err(directive.span, "items in traits are not importable.");
734             return;
735         } else if module.def_id() == directive.parent.def_id()  {
736             return;
737         } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
738             self.prelude = Some(module);
739             return;
740         }
741
742         // Add to module's glob_importers
743         module.glob_importers.borrow_mut().push(directive);
744
745         // Ensure that `resolutions` isn't borrowed during `try_define`,
746         // since it might get updated via a glob cycle.
747         let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
748             resolution.borrow().binding().map(|binding| (ident, binding))
749         }).collect::<Vec<_>>();
750         for ((ident, ns), binding) in bindings {
751             if binding.pseudo_vis() == ty::Visibility::Public || self.is_accessible(binding.vis) {
752                 let imported_binding = self.import(binding, directive);
753                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
754             }
755         }
756
757         // Record the destination of this import
758         self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
759     }
760
761     // Miscellaneous post-processing, including recording reexports, reporting conflicts,
762     // reporting the PRIVATE_IN_PUBLIC lint, and reporting unresolved imports.
763     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
764         // Since import resolution is finished, globs will not define any more names.
765         *module.globs.borrow_mut() = Vec::new();
766
767         let mut reexports = Vec::new();
768         let mut exported_macro_names = FxHashMap();
769         if module as *const _ == self.graph_root as *const _ {
770             let macro_exports = mem::replace(&mut self.macro_exports, Vec::new());
771             for export in macro_exports.into_iter().rev() {
772                 if exported_macro_names.insert(export.name, export.span).is_none() {
773                     reexports.push(export);
774                 }
775             }
776         }
777
778         for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
779             let resolution = &mut *resolution.borrow_mut();
780             let binding = match resolution.binding {
781                 Some(binding) => binding,
782                 None => continue,
783             };
784
785             if binding.vis == ty::Visibility::Public &&
786                (binding.is_import() || binding.is_extern_crate()) {
787                 let def = binding.def();
788                 if def != Def::Err {
789                     if !def.def_id().is_local() {
790                         self.session.cstore.export_macros(def.def_id().krate);
791                     }
792                     if let Def::Macro(..) = def {
793                         if let Some(&span) = exported_macro_names.get(&ident.name) {
794                             let msg =
795                                 format!("a macro named `{}` has already been exported", ident);
796                             self.session.struct_span_err(span, &msg)
797                                 .span_label(span, &format!("`{}` already exported", ident))
798                                 .span_note(binding.span, "previous macro export here")
799                                 .emit();
800                         }
801                     }
802                     reexports.push(Export { name: ident.name, def: def, span: binding.span });
803                 }
804             }
805
806             match binding.kind {
807                 NameBindingKind::Import { binding: orig_binding, directive, .. } => {
808                     if ns == TypeNS && orig_binding.is_variant() &&
809                        !orig_binding.vis.is_at_least(binding.vis, &*self) {
810                         let msg = format!("variant `{}` is private, and cannot be reexported \
811                                            (error E0364), consider declaring its enum as `pub`",
812                                           ident);
813                         self.session.add_lint(PRIVATE_IN_PUBLIC, directive.id, binding.span, msg);
814                     }
815                 }
816                 NameBindingKind::Ambiguity { b1, b2, .. }
817                         if b1.is_glob_import() && b2.is_glob_import() => {
818                     let (orig_b1, orig_b2) = match (&b1.kind, &b2.kind) {
819                         (&NameBindingKind::Import { binding: b1, .. },
820                          &NameBindingKind::Import { binding: b2, .. }) => (b1, b2),
821                         _ => continue,
822                     };
823                     let (b1, b2) = match (orig_b1.vis, orig_b2.vis) {
824                         (ty::Visibility::Public, ty::Visibility::Public) => continue,
825                         (ty::Visibility::Public, _) => (b1, b2),
826                         (_, ty::Visibility::Public) => (b2, b1),
827                         _ => continue,
828                     };
829                     resolution.binding = Some(self.arenas.alloc_name_binding(NameBinding {
830                         kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: true }, ..*b1
831                     }));
832                 }
833                 _ => {}
834             }
835         }
836
837         if reexports.len() > 0 {
838             if let Some(def_id) = module.def_id() {
839                 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
840                 self.export_map.insert(node_id, reexports);
841             }
842         }
843     }
844 }
845
846 fn import_path_to_string(names: &[Ident], subclass: &ImportDirectiveSubclass) -> String {
847     let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name();
848     let names = if global { &names[1..] } else { names };
849     if names.is_empty() {
850         import_directive_subclass_to_string(subclass)
851     } else {
852         (format!("{}::{}",
853                  names_to_string(names),
854                  import_directive_subclass_to_string(subclass)))
855             .to_string()
856     }
857 }
858
859 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
860     match *subclass {
861         SingleImport { source, .. } => source.to_string(),
862         GlobImport { .. } => "*".to_string(),
863         ExternCrate => "<extern crate>".to_string(),
864         MacroUse => "#[macro_use]".to_string(),
865     }
866 }