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