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