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