]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Add an unstable FileTypeExt extension trait for Windows
[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, ToNameBinding, 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::{CRATE_DEF_INDEX, DefId};
23 use rustc::hir::def::*;
24 use rustc::session::DiagnosticMessageId;
25 use rustc::util::nodemap::{FxHashMap, FxHashSet};
26
27 use syntax::ast::{Ident, Name, SpannedIdent, NodeId};
28 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
29 use syntax::ext::hygiene::Mark;
30 use syntax::parse::token;
31 use syntax::symbol::keywords;
32 use syntax::util::lev_distance::find_best_match_for_name;
33 use syntax_pos::Span;
34
35 use std::cell::{Cell, RefCell};
36 use std::mem;
37
38 /// Contains data for specific types of import directives.
39 #[derive(Clone, Debug)]
40 pub enum ImportDirectiveSubclass<'a> {
41     SingleImport {
42         target: Ident,
43         source: Ident,
44         result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
45         type_ns_only: bool,
46     },
47     GlobImport {
48         is_prelude: bool,
49         max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
50         // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
51     },
52     ExternCrate(Option<Name>),
53     MacroUse,
54 }
55
56 /// One import directive.
57 #[derive(Debug,Clone)]
58 pub struct ImportDirective<'a> {
59     pub id: NodeId,
60     pub parent: Module<'a>,
61     pub module_path: Vec<SpannedIdent>,
62     pub imported_module: Cell<Option<Module<'a>>>, // the resolution of `module_path`
63     pub subclass: ImportDirectiveSubclass<'a>,
64     pub span: Span,
65     pub vis: Cell<ty::Visibility>,
66     pub expansion: Mark,
67     pub used: Cell<bool>,
68 }
69
70 impl<'a> ImportDirective<'a> {
71     pub fn is_glob(&self) -> bool {
72         match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
73     }
74 }
75
76 #[derive(Clone, Default, Debug)]
77 /// Records information about the resolution of a name in a namespace of a module.
78 pub struct NameResolution<'a> {
79     /// The single imports that define the name in the namespace.
80     single_imports: SingleImports<'a>,
81     /// The least shadowable known binding for this name, or None if there are no known bindings.
82     pub binding: Option<&'a NameBinding<'a>>,
83     shadows_glob: Option<&'a NameBinding<'a>>,
84 }
85
86 #[derive(Clone, Debug)]
87 enum SingleImports<'a> {
88     /// No single imports can define the name in the namespace.
89     None,
90     /// Only the given single import can define the name in the namespace.
91     MaybeOne(&'a ImportDirective<'a>),
92     /// At least one single import will define the name in the namespace.
93     AtLeastOne,
94 }
95
96 impl<'a> Default for SingleImports<'a> {
97     /// Creates a `SingleImports<'a>` of None type.
98     fn default() -> Self {
99         SingleImports::None
100     }
101 }
102
103 impl<'a> SingleImports<'a> {
104     fn add_directive(&mut self, directive: &'a ImportDirective<'a>) {
105         match *self {
106             SingleImports::None => *self = SingleImports::MaybeOne(directive),
107             // If two single imports can define the name in the namespace, we can assume that at
108             // least one of them will define it since otherwise both would have to define only one
109             // namespace, leading to a duplicate error.
110             SingleImports::MaybeOne(_) => *self = SingleImports::AtLeastOne,
111             SingleImports::AtLeastOne => {}
112         };
113     }
114
115     fn directive_failed(&mut self) {
116         match *self {
117             SingleImports::None => unreachable!(),
118             SingleImports::MaybeOne(_) => *self = SingleImports::None,
119             SingleImports::AtLeastOne => {}
120         }
121     }
122 }
123
124 impl<'a> NameResolution<'a> {
125     // Returns the binding for the name if it is known or None if it not known.
126     fn binding(&self) -> Option<&'a NameBinding<'a>> {
127         self.binding.and_then(|binding| match self.single_imports {
128             SingleImports::None => Some(binding),
129             _ if !binding.is_glob_import() => Some(binding),
130             _ => None, // The binding could be shadowed by a single import, so it is not known.
131         })
132     }
133 }
134
135 impl<'a> Resolver<'a> {
136     fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
137                   -> &'a RefCell<NameResolution<'a>> {
138         *module.resolutions.borrow_mut().entry((ident.modern(), 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_unadjusted(&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,
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                 continue
238             }
239             let module = unwrap_or!(directive.imported_module.get(), return Err(Undetermined));
240             let (orig_current_module, mut ident) = (self.current_module, ident.modern());
241             match ident.ctxt.glob_adjust(module.expansion, directive.span.ctxt().modern()) {
242                 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
243                 Some(None) => {}
244                 None => continue,
245             };
246             let result = self.resolve_ident_in_module_unadjusted(
247                 module, ident, ns, false, false, path_span,
248             );
249             self.current_module = orig_current_module;
250             if let Err(Undetermined) = result {
251                 return Err(Undetermined);
252             }
253         }
254
255         Err(Determined)
256     }
257
258     // Add an import directive to the current module.
259     pub fn add_import_directive(&mut self,
260                                 module_path: Vec<SpannedIdent>,
261                                 subclass: ImportDirectiveSubclass<'a>,
262                                 span: Span,
263                                 id: NodeId,
264                                 vis: ty::Visibility,
265                                 expansion: Mark) {
266         let current_module = self.current_module;
267         let directive = self.arenas.alloc_import_directive(ImportDirective {
268             parent: current_module,
269             module_path,
270             imported_module: Cell::new(None),
271             subclass,
272             span,
273             id,
274             vis: Cell::new(vis),
275             expansion,
276             used: Cell::new(false),
277         });
278
279         self.indeterminate_imports.push(directive);
280         match directive.subclass {
281             SingleImport { target, .. } => {
282                 self.per_ns(|this, ns| {
283                     let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
284                     resolution.single_imports.add_directive(directive);
285                 });
286             }
287             // We don't add prelude imports to the globs since they only affect lexical scopes,
288             // which are not relevant to import resolution.
289             GlobImport { is_prelude: true, .. } => {}
290             GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
291             _ => unreachable!(),
292         }
293     }
294
295     // Given a binding and an import directive that resolves to it,
296     // return the corresponding binding defined by the import directive.
297     pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
298                   -> &'a NameBinding<'a> {
299         let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
300                      // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
301                      !directive.is_glob() && binding.is_extern_crate() {
302             directive.vis.get()
303         } else {
304             binding.pseudo_vis()
305         };
306
307         if let GlobImport { ref max_vis, .. } = directive.subclass {
308             if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
309                 max_vis.set(vis)
310             }
311         }
312
313         self.arenas.alloc_name_binding(NameBinding {
314             kind: NameBindingKind::Import {
315                 binding,
316                 directive,
317                 used: Cell::new(false),
318                 legacy_self_import: false,
319             },
320             span: directive.span,
321             vis,
322             expansion: directive.expansion,
323         })
324     }
325
326     // Define the name or return the existing binding if there is a collision.
327     pub fn try_define(&mut self,
328                       module: Module<'a>,
329                       ident: Ident,
330                       ns: Namespace,
331                       binding: &'a NameBinding<'a>)
332                       -> Result<(), &'a NameBinding<'a>> {
333         self.update_resolution(module, ident, ns, |this, resolution| {
334             if let Some(old_binding) = resolution.binding {
335                 if binding.is_glob_import() {
336                     if !old_binding.is_glob_import() &&
337                        !(ns == MacroNS && old_binding.expansion != Mark::root()) {
338                         resolution.shadows_glob = Some(binding);
339                     } else if binding.def() != old_binding.def() {
340                         resolution.binding = Some(this.ambiguity(old_binding, binding));
341                     } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
342                         // We are glob-importing the same item but with greater visibility.
343                         resolution.binding = Some(binding);
344                     }
345                 } else if old_binding.is_glob_import() {
346                     if ns == MacroNS && binding.expansion != Mark::root() &&
347                        binding.def() != old_binding.def() {
348                         resolution.binding = Some(this.ambiguity(binding, old_binding));
349                     } else {
350                         resolution.binding = Some(binding);
351                         resolution.shadows_glob = Some(old_binding);
352                     }
353                 } else {
354                     return Err(old_binding);
355                 }
356             } else {
357                 resolution.binding = Some(binding);
358             }
359
360             Ok(())
361         })
362     }
363
364     pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
365                      -> &'a NameBinding<'a> {
366         self.arenas.alloc_name_binding(NameBinding {
367             kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: false },
368             vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
369             span: b1.span,
370             expansion: Mark::root(),
371         })
372     }
373
374     // Use `f` to mutate the resolution of the name in the module.
375     // If the resolution becomes a success, define it in the module's glob importers.
376     fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
377                                -> T
378         where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
379     {
380         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
381         // during which the resolution might end up getting re-defined via a glob cycle.
382         let (binding, t) = {
383             let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
384             let old_binding = resolution.binding();
385
386             let t = f(self, resolution);
387
388             match resolution.binding() {
389                 _ if old_binding.is_some() => return t,
390                 None => return t,
391                 Some(binding) => match old_binding {
392                     Some(old_binding) if old_binding as *const _ == binding as *const _ => return t,
393                     _ => (binding, t),
394                 }
395             }
396         };
397
398         // Define `binding` in `module`s glob importers.
399         for directive in module.glob_importers.borrow_mut().iter() {
400             let mut ident = ident.modern();
401             let scope = match ident.ctxt.reverse_glob_adjust(module.expansion,
402                                                              directive.span.ctxt().modern()) {
403                 Some(Some(def)) => self.macro_def_scope(def),
404                 Some(None) => directive.parent,
405                 None => continue,
406             };
407             if self.is_accessible_from(binding.vis, scope) {
408                 let imported_binding = self.import(binding, directive);
409                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
410             }
411         }
412
413         t
414     }
415
416     // Define a "dummy" resolution containing a Def::Err as a placeholder for a
417     // failed resolution
418     fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
419         if let SingleImport { target, .. } = directive.subclass {
420             let dummy_binding = self.dummy_binding;
421             let dummy_binding = self.import(dummy_binding, directive);
422             self.per_ns(|this, ns| {
423                 let _ = this.try_define(directive.parent, target, ns, dummy_binding);
424             });
425         }
426     }
427 }
428
429 pub struct ImportResolver<'a, 'b: 'a> {
430     pub resolver: &'a mut Resolver<'b>,
431 }
432
433 impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> {
434     type Target = Resolver<'b>;
435     fn deref(&self) -> &Resolver<'b> {
436         self.resolver
437     }
438 }
439
440 impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> {
441     fn deref_mut(&mut self) -> &mut Resolver<'b> {
442         self.resolver
443     }
444 }
445
446 impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
447     fn parent(self, id: DefId) -> Option<DefId> {
448         self.resolver.parent(id)
449     }
450 }
451
452 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
453     // Import resolution
454     //
455     // This is a fixed-point algorithm. We resolve imports until our efforts
456     // are stymied by an unresolved import; then we bail out of the current
457     // module and continue. We terminate successfully once no more imports
458     // remain or unsuccessfully when no forward progress in resolving imports
459     // is made.
460
461     /// Resolves all imports for the crate. This method performs the fixed-
462     /// point iteration.
463     pub fn resolve_imports(&mut self) {
464         let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
465         while self.indeterminate_imports.len() < prev_num_indeterminates {
466             prev_num_indeterminates = self.indeterminate_imports.len();
467             for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
468                 match self.resolve_import(&import) {
469                     true => self.determined_imports.push(import),
470                     false => self.indeterminate_imports.push(import),
471                 }
472             }
473         }
474     }
475
476     pub fn finalize_imports(&mut self) {
477         for module in self.arenas.local_modules().iter() {
478             self.finalize_resolutions_in(module);
479         }
480
481         let mut errors = false;
482         let mut seen_spans = FxHashSet();
483         for i in 0 .. self.determined_imports.len() {
484             let import = self.determined_imports[i];
485             if let Some((span, err)) = self.finalize_import(import) {
486                 errors = true;
487
488                 if let SingleImport { source, ref result, .. } = import.subclass {
489                     if source.name == "self" {
490                         // Silence `unresolved import` error if E0429 is already emitted
491                         match result.value_ns.get() {
492                             Err(Determined) => continue,
493                             _ => {},
494                         }
495                     }
496                 }
497
498                 // If the error is a single failed import then create a "fake" import
499                 // resolution for it so that later resolve stages won't complain.
500                 self.import_dummy_binding(import);
501                 if !seen_spans.contains(&span) {
502                     let path = import_path_to_string(&import.module_path[..],
503                                                      &import.subclass,
504                                                      span);
505                     let error = ResolutionError::UnresolvedImport(Some((span, &path, &err)));
506                     resolve_error(self.resolver, span, error);
507                     seen_spans.insert(span);
508                 }
509             }
510         }
511
512         // Report unresolved imports only if no hard error was already reported
513         // to avoid generating multiple errors on the same import.
514         if !errors {
515             if let Some(import) = self.indeterminate_imports.iter().next() {
516                 let error = ResolutionError::UnresolvedImport(None);
517                 resolve_error(self.resolver, import.span, error);
518             }
519         }
520     }
521
522     /// Attempts to resolve the given import, returning true if its resolution is determined.
523     /// If successful, the resolved bindings are written into the module.
524     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
525         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
526                names_to_string(&directive.module_path[..]),
527                module_to_string(self.current_module).unwrap_or("???".to_string()));
528
529         self.current_module = directive.parent;
530
531         let module = if let Some(module) = directive.imported_module.get() {
532             module
533         } else {
534             let vis = directive.vis.get();
535             // For better failure detection, pretend that the import will not define any names
536             // while resolving its module path.
537             directive.vis.set(ty::Visibility::Invisible);
538             let result = self.resolve_path(&directive.module_path[..], None, false, directive.span);
539             directive.vis.set(vis);
540
541             match result {
542                 PathResult::Module(module) => module,
543                 PathResult::Indeterminate => return false,
544                 _ => return true,
545             }
546         };
547
548         directive.imported_module.set(Some(module));
549         let (source, target, result, type_ns_only) = match directive.subclass {
550             SingleImport { source, target, ref result, type_ns_only } =>
551                 (source, target, result, type_ns_only),
552             GlobImport { .. } => {
553                 self.resolve_glob_import(directive);
554                 return true;
555             }
556             _ => unreachable!(),
557         };
558
559         let mut indeterminate = false;
560         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
561             if let Err(Undetermined) = result[ns].get() {
562                 result[ns].set(this.resolve_ident_in_module(module,
563                                                             source,
564                                                             ns,
565                                                             false,
566                                                             false,
567                                                             directive.span));
568             } else {
569                 return
570             };
571
572             let parent = directive.parent;
573             match result[ns].get() {
574                 Err(Undetermined) => indeterminate = true,
575                 Err(Determined) => {
576                     this.update_resolution(parent, target, ns, |_, resolution| {
577                         resolution.single_imports.directive_failed()
578                     });
579                 }
580                 Ok(binding) if !binding.is_importable() => {
581                     let msg = format!("`{}` is not directly importable", target);
582                     struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
583                         .span_label(directive.span, "cannot be imported directly")
584                         .emit();
585                     // Do not import this illegal binding. Import a dummy binding and pretend
586                     // everything is fine
587                     this.import_dummy_binding(directive);
588                 }
589                 Ok(binding) => {
590                     let imported_binding = this.import(binding, directive);
591                     let conflict = this.try_define(parent, target, ns, imported_binding);
592                     if let Err(old_binding) = conflict {
593                         this.report_conflict(parent, target, ns, imported_binding, old_binding);
594                     }
595                 }
596             }
597         });
598
599         !indeterminate
600     }
601
602     // If appropriate, returns an error to report.
603     fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> {
604         self.current_module = directive.parent;
605         let ImportDirective { ref module_path, span, .. } = *directive;
606
607         // FIXME: Last path segment is treated specially in import resolution, so extern crate
608         // mode for absolute paths needs some special support for single-segment imports.
609         if module_path.len() == 1 && (module_path[0].node.name == keywords::CrateRoot.name() ||
610                                       module_path[0].node.name == keywords::Extern.name()) {
611             let is_extern = module_path[0].node.name == keywords::Extern.name() ||
612                             self.session.features.borrow().extern_absolute_paths;
613             match directive.subclass {
614                 GlobImport { .. } if is_extern => {
615                     return Some((directive.span,
616                                  "cannot glob-import all possible crates".to_string()));
617                 }
618                 SingleImport { source, target, .. } => {
619                     let crate_root = if source.name == keywords::Crate.name() &&
620                                         module_path[0].node.name != keywords::Extern.name() {
621                         if target.name == keywords::Crate.name() {
622                             return Some((directive.span,
623                                          "crate root imports need to be explicitly named: \
624                                           `use crate as name;`".to_string()));
625                         } else {
626                             Some(self.resolve_crate_root(source.ctxt.modern(), false))
627                         }
628                     } else if is_extern && !token::Ident(source).is_path_segment_keyword() {
629                         let crate_id =
630                             self.crate_loader.resolve_crate_from_path(source.name, directive.span);
631                         let crate_root =
632                             self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
633                         self.populate_module_if_necessary(crate_root);
634                         Some(crate_root)
635                     } else {
636                         None
637                     };
638
639                     if let Some(crate_root) = crate_root {
640                         let binding = (crate_root, ty::Visibility::Public, directive.span,
641                                        directive.expansion).to_name_binding(self.arenas);
642                         let binding = self.arenas.alloc_name_binding(NameBinding {
643                             kind: NameBindingKind::Import {
644                                 binding,
645                                 directive,
646                                 used: Cell::new(false),
647                                 legacy_self_import: false,
648                             },
649                             vis: directive.vis.get(),
650                             span: directive.span,
651                             expansion: directive.expansion,
652                         });
653                         let _ = self.try_define(directive.parent, target, TypeNS, binding);
654                         return None;
655                     }
656                 }
657                 _ => {}
658             }
659         }
660
661         let module_result = self.resolve_path(&module_path, None, true, span);
662         let module = match module_result {
663             PathResult::Module(module) => module,
664             PathResult::Failed(span, msg, false) => {
665                 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
666                 return None;
667             }
668             PathResult::Failed(span, msg, true) => {
669                 let (mut self_path, mut self_result) = (module_path.clone(), None);
670                 if !self_path.is_empty() &&
671                     !token::Ident(self_path[0].node).is_path_segment_keyword() &&
672                     !(self_path.len() > 1 &&
673                       token::Ident(self_path[1].node).is_path_segment_keyword())
674                 {
675                     self_path[0].node.name = keywords::SelfValue.name();
676                     self_result = Some(self.resolve_path(&self_path, None, false, span));
677                 }
678                 return if let Some(PathResult::Module(..)) = self_result {
679                     Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..]))))
680                 } else {
681                     Some((span, msg))
682                 };
683             },
684             _ => return None,
685         };
686
687         let (ident, result, type_ns_only) = match directive.subclass {
688             SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
689             GlobImport { .. } if module.def_id() == directive.parent.def_id() => {
690                 // Importing a module into itself is not allowed.
691                 return Some((directive.span,
692                              "Cannot glob-import a module into itself.".to_string()));
693             }
694             GlobImport { is_prelude, ref max_vis } => {
695                 if !is_prelude &&
696                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
697                    !max_vis.get().is_at_least(directive.vis.get(), &*self) {
698                     let msg = "A non-empty glob must import something with the glob's visibility";
699                     self.session.span_err(directive.span, msg);
700                 }
701                 return None;
702             }
703             _ => unreachable!(),
704         };
705
706         let mut all_ns_err = true;
707         let mut legacy_self_import = None;
708         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
709             if let Ok(binding) = result[ns].get() {
710                 all_ns_err = false;
711                 if this.record_use(ident, ns, binding, directive.span) {
712                     this.resolution(module, ident, ns).borrow_mut().binding =
713                         Some(this.dummy_binding);
714                 }
715             }
716         } else if let Ok(binding) = this.resolve_ident_in_module(module,
717                                                                  ident,
718                                                                  ns,
719                                                                  false,
720                                                                  false,
721                                                                  directive.span) {
722             legacy_self_import = Some(directive);
723             let binding = this.arenas.alloc_name_binding(NameBinding {
724                 kind: NameBindingKind::Import {
725                     binding,
726                     directive,
727                     used: Cell::new(false),
728                     legacy_self_import: true,
729                 },
730                 ..*binding
731             });
732             let _ = this.try_define(directive.parent, ident, ns, binding);
733         });
734
735         if all_ns_err {
736             if let Some(directive) = legacy_self_import {
737                 self.warn_legacy_self_import(directive);
738                 return None;
739             }
740             let mut all_ns_failed = true;
741             self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
742                 match this.resolve_ident_in_module(module, ident, ns, false, true, span) {
743                     Ok(_) => all_ns_failed = false,
744                     _ => {}
745                 }
746             });
747
748             return if all_ns_failed {
749                 let resolutions = module.resolutions.borrow();
750                 let names = resolutions.iter().filter_map(|(&(ref i, _), resolution)| {
751                     if *i == ident { return None; } // Never suggest the same name
752                     match *resolution.borrow() {
753                         NameResolution { binding: Some(name_binding), .. } => {
754                             match name_binding.kind {
755                                 NameBindingKind::Import { binding, .. } => {
756                                     match binding.kind {
757                                         // Never suggest the name that has binding error
758                                         // i.e. the name that cannot be previously resolved
759                                         NameBindingKind::Def(Def::Err) => return None,
760                                         _ => Some(&i.name),
761                                     }
762                                 },
763                                 _ => Some(&i.name),
764                             }
765                         },
766                         NameResolution { single_imports: SingleImports::None, .. } => None,
767                         _ => Some(&i.name),
768                     }
769                 });
770                 let lev_suggestion =
771                     match find_best_match_for_name(names, &ident.name.as_str(), None) {
772                         Some(name) => format!(". Did you mean to use `{}`?", name),
773                         None => "".to_owned(),
774                     };
775                 let module_str = module_to_string(module);
776                 let msg = if let Some(module_str) = module_str {
777                     format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
778                 } else {
779                     format!("no `{}` in the root{}", ident, lev_suggestion)
780                 };
781                 Some((span, msg))
782             } else {
783                 // `resolve_ident_in_module` reported a privacy error.
784                 self.import_dummy_binding(directive);
785                 None
786             }
787         }
788
789         let mut reexport_error = None;
790         let mut any_successful_reexport = false;
791         self.per_ns(|this, ns| {
792             if let Ok(binding) = result[ns].get() {
793                 let vis = directive.vis.get();
794                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
795                     reexport_error = Some((ns, binding));
796                 } else {
797                     any_successful_reexport = true;
798                 }
799             }
800         });
801
802         // All namespaces must be re-exported with extra visibility for an error to occur.
803         if !any_successful_reexport {
804             let (ns, binding) = reexport_error.unwrap();
805             if ns == TypeNS && binding.is_extern_crate() {
806                 let msg = format!("extern crate `{}` is private, and cannot be \
807                                    re-exported (error E0365), consider declaring with \
808                                    `pub`",
809                                    ident);
810                 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
811                                          directive.id,
812                                          directive.span,
813                                          &msg);
814             } else if ns == TypeNS {
815                 struct_span_err!(self.session, directive.span, E0365,
816                                  "`{}` is private, and cannot be re-exported", ident)
817                     .span_label(directive.span, format!("re-export of private `{}`", ident))
818                     .note(&format!("consider declaring type or module `{}` with `pub`", ident))
819                     .emit();
820             } else {
821                 let msg = format!("`{}` is private, and cannot be re-exported", ident);
822                 let note_msg =
823                     format!("consider marking `{}` as `pub` in the imported module", ident);
824                 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
825                     .span_note(directive.span, &note_msg)
826                     .emit();
827             }
828         }
829
830         // Record what this import resolves to for later uses in documentation,
831         // this may resolve to either a value or a type, but for documentation
832         // purposes it's good enough to just favor one over the other.
833         self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
834             this.def_map.entry(directive.id).or_insert(PathResolution::new(binding.def()));
835         });
836
837         debug!("(resolving single import) successfully resolved import");
838         None
839     }
840
841     fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
842         let module = directive.imported_module.get().unwrap();
843         self.populate_module_if_necessary(module);
844
845         if let Some(Def::Trait(_)) = module.def() {
846             self.session.span_err(directive.span, "items in traits are not importable.");
847             return;
848         } else if module.def_id() == directive.parent.def_id()  {
849             return;
850         } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
851             self.prelude = Some(module);
852             return;
853         }
854
855         // Add to module's glob_importers
856         module.glob_importers.borrow_mut().push(directive);
857
858         // Ensure that `resolutions` isn't borrowed during `try_define`,
859         // since it might get updated via a glob cycle.
860         let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
861             resolution.borrow().binding().map(|binding| (ident, binding))
862         }).collect::<Vec<_>>();
863         for ((mut ident, ns), binding) in bindings {
864             let scope = match ident.ctxt.reverse_glob_adjust(module.expansion,
865                                                              directive.span.ctxt().modern()) {
866                 Some(Some(def)) => self.macro_def_scope(def),
867                 Some(None) => self.current_module,
868                 None => continue,
869             };
870             if self.is_accessible_from(binding.pseudo_vis(), scope) {
871                 let imported_binding = self.import(binding, directive);
872                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
873             }
874         }
875
876         // Record the destination of this import
877         self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
878     }
879
880     // Miscellaneous post-processing, including recording re-exports,
881     // reporting conflicts, and reporting unresolved imports.
882     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
883         // Since import resolution is finished, globs will not define any more names.
884         *module.globs.borrow_mut() = Vec::new();
885
886         let mut reexports = Vec::new();
887         let mut exported_macro_names = FxHashMap();
888         if module as *const _ == self.graph_root as *const _ {
889             let macro_exports = mem::replace(&mut self.macro_exports, Vec::new());
890             for export in macro_exports.into_iter().rev() {
891                 if exported_macro_names.insert(export.ident.modern(), export.span).is_none() {
892                     reexports.push(export);
893                 }
894             }
895         }
896
897         for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
898             let resolution = &mut *resolution.borrow_mut();
899             let binding = match resolution.binding {
900                 Some(binding) => binding,
901                 None => continue,
902             };
903
904             if binding.is_import() || binding.is_macro_def() {
905                 let def = binding.def();
906                 if def != Def::Err {
907                     if !def.def_id().is_local() {
908                         self.cstore.export_macros_untracked(def.def_id().krate);
909                     }
910                     if let Def::Macro(..) = def {
911                         if let Some(&span) = exported_macro_names.get(&ident.modern()) {
912                             let msg =
913                                 format!("a macro named `{}` has already been exported", ident);
914                             self.session.struct_span_err(span, &msg)
915                                 .span_label(span, format!("`{}` already exported", ident))
916                                 .span_note(binding.span, "previous macro export here")
917                                 .emit();
918                         }
919                     }
920                     reexports.push(Export {
921                         ident: ident.modern(),
922                         def: def,
923                         span: binding.span,
924                         vis: binding.vis,
925                         is_import: true,
926                     });
927                 }
928             }
929
930             match binding.kind {
931                 NameBindingKind::Import { binding: orig_binding, directive, .. } => {
932                     if ns == TypeNS && orig_binding.is_variant() &&
933                         !orig_binding.vis.is_at_least(binding.vis, &*self) {
934                             let msg = match directive.subclass {
935                                 ImportDirectiveSubclass::SingleImport { .. } => {
936                                     format!("variant `{}` is private and cannot be re-exported",
937                                             ident)
938                                 },
939                                 ImportDirectiveSubclass::GlobImport { .. } => {
940                                     let msg = "enum is private and its variants \
941                                                cannot be re-exported".to_owned();
942                                     let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
943                                                     Some(binding.span),
944                                                     msg.clone());
945                                     let fresh = self.session.one_time_diagnostics
946                                         .borrow_mut().insert(error_id);
947                                     if !fresh {
948                                         continue;
949                                     }
950                                     msg
951                                 },
952                                 ref s @ _ => bug!("unexpected import subclass {:?}", s)
953                             };
954                             let mut err = self.session.struct_span_err(binding.span, &msg);
955
956                             let imported_module = directive.imported_module.get()
957                                 .expect("module should exist");
958                             let resolutions = imported_module.parent.expect("parent should exist")
959                                 .resolutions.borrow();
960                             let enum_path_segment_index = directive.module_path.len() - 1;
961                             let enum_ident = directive.module_path[enum_path_segment_index].node;
962
963                             let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
964                                 .expect("resolution should exist");
965                             let enum_span = enum_resolution.borrow()
966                                 .binding.expect("binding should exist")
967                                 .span;
968                             let enum_def_span = self.session.codemap().def_span(enum_span);
969                             let enum_def_snippet = self.session.codemap()
970                                 .span_to_snippet(enum_def_span).expect("snippet should exist");
971                             // potentially need to strip extant `crate`/`pub(path)` for suggestion
972                             let after_vis_index = enum_def_snippet.find("enum")
973                                 .expect("`enum` keyword should exist in snippet");
974                             let suggestion = format!("pub {}",
975                                                      &enum_def_snippet[after_vis_index..]);
976
977                             self.session
978                                 .diag_span_suggestion_once(&mut err,
979                                                            DiagnosticMessageId::ErrorId(0),
980                                                            enum_def_span,
981                                                            "consider making the enum public",
982                                                            suggestion);
983                             err.emit();
984                     }
985                 }
986                 NameBindingKind::Ambiguity { b1, b2, .. }
987                         if b1.is_glob_import() && b2.is_glob_import() => {
988                     let (orig_b1, orig_b2) = match (&b1.kind, &b2.kind) {
989                         (&NameBindingKind::Import { binding: b1, .. },
990                          &NameBindingKind::Import { binding: b2, .. }) => (b1, b2),
991                         _ => continue,
992                     };
993                     let (b1, b2) = match (orig_b1.vis, orig_b2.vis) {
994                         (ty::Visibility::Public, ty::Visibility::Public) => continue,
995                         (ty::Visibility::Public, _) => (b1, b2),
996                         (_, ty::Visibility::Public) => (b2, b1),
997                         _ => continue,
998                     };
999                     resolution.binding = Some(self.arenas.alloc_name_binding(NameBinding {
1000                         kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: true }, ..*b1
1001                     }));
1002                 }
1003                 _ => {}
1004             }
1005         }
1006
1007         if reexports.len() > 0 {
1008             if let Some(def_id) = module.def_id() {
1009                 self.export_map.insert(def_id, reexports);
1010             }
1011         }
1012     }
1013 }
1014
1015 fn import_path_to_string(names: &[SpannedIdent],
1016                          subclass: &ImportDirectiveSubclass,
1017                          span: Span) -> String {
1018     let pos = names.iter()
1019         .position(|p| span == p.span && p.node.name != keywords::CrateRoot.name());
1020     let global = !names.is_empty() && names[0].node.name == keywords::CrateRoot.name();
1021     if let Some(pos) = pos {
1022         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1023         names_to_string(names)
1024     } else {
1025         let names = if global { &names[1..] } else { names };
1026         if names.is_empty() {
1027             import_directive_subclass_to_string(subclass)
1028         } else {
1029             (format!("{}::{}",
1030                      names_to_string(names),
1031                      import_directive_subclass_to_string(subclass)))
1032         }
1033     }
1034 }
1035
1036 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1037     match *subclass {
1038         SingleImport { source, .. } => source.to_string(),
1039         GlobImport { .. } => "*".to_string(),
1040         ExternCrate(_) => "<extern crate>".to_string(),
1041         MacroUse => "#[macro_use]".to_string(),
1042     }
1043 }