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