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