]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Rollup merge of #31294 - steveklabnik:gh31284, 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::ImportDirectiveSubclass::*;
12
13 use DefModifiers;
14 use Module;
15 use Namespace::{self, TypeNS, ValueNS};
16 use {NameBindings, NameBinding};
17 use NamespaceResult::{BoundResult, UnboundResult, UnknownResult};
18 use NamespaceResult;
19 use ResolveResult;
20 use Resolver;
21 use UseLexicalScopeFlag;
22 use {names_to_string, module_to_string};
23 use {resolve_error, ResolutionError};
24
25 use build_reduced_graph;
26
27 use rustc::lint;
28 use rustc::middle::def::*;
29 use rustc::middle::def_id::DefId;
30 use rustc::middle::privacy::*;
31
32 use syntax::ast::{NodeId, Name};
33 use syntax::attr::AttrMetaMethods;
34 use syntax::codemap::Span;
35 use syntax::util::lev_distance::find_best_match_for_name;
36
37 use std::mem::replace;
38
39 /// Contains data for specific types of import directives.
40 #[derive(Copy, Clone,Debug)]
41 pub enum ImportDirectiveSubclass {
42     SingleImport(Name /* target */, Name /* source */),
43     GlobImport,
44 }
45
46 /// Whether an import can be shadowed by another import.
47 #[derive(Debug,PartialEq,Clone,Copy)]
48 pub enum Shadowable {
49     Always,
50     Never,
51 }
52
53 /// One import directive.
54 #[derive(Debug)]
55 pub struct ImportDirective {
56     pub module_path: Vec<Name>,
57     pub subclass: ImportDirectiveSubclass,
58     pub span: Span,
59     pub id: NodeId,
60     pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
61     pub shadowable: Shadowable,
62 }
63
64 impl ImportDirective {
65     pub fn new(module_path: Vec<Name>,
66                subclass: ImportDirectiveSubclass,
67                span: Span,
68                id: NodeId,
69                is_public: bool,
70                shadowable: Shadowable)
71                -> ImportDirective {
72         ImportDirective {
73             module_path: module_path,
74             subclass: subclass,
75             span: span,
76             id: id,
77             is_public: is_public,
78             shadowable: shadowable,
79         }
80     }
81 }
82
83 /// The item that an import resolves to.
84 #[derive(Clone,Debug)]
85 pub struct Target<'a> {
86     pub target_module: Module<'a>,
87     pub binding: NameBinding<'a>,
88     pub shadowable: Shadowable,
89 }
90
91 impl<'a> Target<'a> {
92     pub fn new(target_module: Module<'a>, binding: NameBinding<'a>, shadowable: Shadowable)
93                -> Self {
94         Target {
95             target_module: target_module,
96             binding: binding,
97             shadowable: shadowable,
98         }
99     }
100 }
101
102 #[derive(Debug)]
103 /// An ImportResolutionPerNamespace records what we know about an imported name.
104 /// More specifically, it records the number of unresolved `use` directives that import the name,
105 /// and for each namespace, it records the `use` directive importing the name in the namespace
106 /// and the `Target` to which the name in the namespace resolves (if applicable).
107 /// Different `use` directives may import the same name in different namespaces.
108 pub struct ImportResolutionPerNamespace<'a> {
109     // When outstanding_references reaches zero, outside modules can count on the targets being
110     // correct. Before then, all bets are off; future `use` directives could override the name.
111     // Since shadowing is forbidden, the only way outstanding_references > 1 in a legal program
112     // is if the name is imported by exactly two `use` directives, one of which resolves to a
113     // value and the other of which resolves to a type.
114     pub outstanding_references: usize,
115     pub type_ns: ImportResolution<'a>,
116     pub value_ns: ImportResolution<'a>,
117 }
118
119 /// Records what we know about an imported name in a namespace (see `ImportResolutionPerNamespace`).
120 #[derive(Clone,Debug)]
121 pub struct ImportResolution<'a> {
122     /// Whether the name in the namespace was imported with a `use` or a `pub use`.
123     pub is_public: bool,
124
125     /// Resolution of the name in the namespace
126     pub target: Option<Target<'a>>,
127
128     /// The source node of the `use` directive
129     pub id: NodeId,
130 }
131
132 impl<'a> ::std::ops::Index<Namespace> for ImportResolutionPerNamespace<'a> {
133     type Output = ImportResolution<'a>;
134     fn index(&self, ns: Namespace) -> &ImportResolution<'a> {
135         match ns { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
136     }
137 }
138
139 impl<'a> ::std::ops::IndexMut<Namespace> for ImportResolutionPerNamespace<'a> {
140     fn index_mut(&mut self, ns: Namespace) -> &mut ImportResolution<'a> {
141         match ns { TypeNS => &mut self.type_ns, ValueNS => &mut self.value_ns }
142     }
143 }
144
145 impl<'a> ImportResolutionPerNamespace<'a> {
146     pub fn new(id: NodeId, is_public: bool) -> Self {
147         let resolution = ImportResolution { id: id, is_public: is_public, target: None };
148         ImportResolutionPerNamespace {
149             outstanding_references: 0, type_ns: resolution.clone(), value_ns: resolution,
150         }
151     }
152
153     pub fn shadowable(&self, namespace: Namespace) -> Shadowable {
154         match self[namespace].target {
155             Some(ref target) => target.shadowable,
156             None => Shadowable::Always,
157         }
158     }
159 }
160
161 struct ImportResolvingError {
162     span: Span,
163     path: String,
164     help: String,
165 }
166
167 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
168     resolver: &'a mut Resolver<'b, 'tcx>,
169 }
170
171 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
172     // Import resolution
173     //
174     // This is a fixed-point algorithm. We resolve imports until our efforts
175     // are stymied by an unresolved import; then we bail out of the current
176     // module and continue. We terminate successfully once no more imports
177     // remain or unsuccessfully when no forward progress in resolving imports
178     // is made.
179
180     /// Resolves all imports for the crate. This method performs the fixed-
181     /// point iteration.
182     fn resolve_imports(&mut self) {
183         let mut i = 0;
184         let mut prev_unresolved_imports = 0;
185         loop {
186             debug!("(resolving imports) iteration {}, {} imports left",
187                    i,
188                    self.resolver.unresolved_imports);
189
190             let module_root = self.resolver.graph_root;
191             let errors = self.resolve_imports_for_module_subtree(module_root);
192
193             if self.resolver.unresolved_imports == 0 {
194                 debug!("(resolving imports) success");
195                 break;
196             }
197
198             if self.resolver.unresolved_imports == prev_unresolved_imports {
199                 // resolving failed
200                 if errors.len() > 0 {
201                     for e in errors {
202                         resolve_error(self.resolver,
203                                       e.span,
204                                       ResolutionError::UnresolvedImport(Some((&e.path, &e.help))));
205                     }
206                 } else {
207                     // Report unresolved imports only if no hard error was already reported
208                     // to avoid generating multiple errors on the same import.
209                     // Imports that are still indeterminate at this point are actually blocked
210                     // by errored imports, so there is no point reporting them.
211                     self.resolver.report_unresolved_imports(module_root);
212                 }
213                 break;
214             }
215
216             i += 1;
217             prev_unresolved_imports = self.resolver.unresolved_imports;
218         }
219     }
220
221     /// Attempts to resolve imports for the given module and all of its
222     /// submodules.
223     fn resolve_imports_for_module_subtree(&mut self,
224                                           module_: Module<'b>)
225                                           -> Vec<ImportResolvingError> {
226         let mut errors = Vec::new();
227         debug!("(resolving imports for module subtree) resolving {}",
228                module_to_string(&*module_));
229         let orig_module = replace(&mut self.resolver.current_module, module_);
230         errors.extend(self.resolve_imports_for_module(module_));
231         self.resolver.current_module = orig_module;
232
233         build_reduced_graph::populate_module_if_necessary(self.resolver, &module_);
234         for (_, child_node) in module_.children.borrow().iter() {
235             match child_node.type_ns.module() {
236                 None => {
237                     // Nothing to do.
238                 }
239                 Some(child_module) => {
240                     errors.extend(self.resolve_imports_for_module_subtree(child_module));
241                 }
242             }
243         }
244
245         for (_, child_module) in module_.anonymous_children.borrow().iter() {
246             errors.extend(self.resolve_imports_for_module_subtree(child_module));
247         }
248
249         errors
250     }
251
252     /// Attempts to resolve imports for the given module only.
253     fn resolve_imports_for_module(&mut self, module: Module<'b>) -> Vec<ImportResolvingError> {
254         let mut errors = Vec::new();
255
256         if module.all_imports_resolved() {
257             debug!("(resolving imports for module) all imports resolved for {}",
258                    module_to_string(&*module));
259             return errors;
260         }
261
262         let mut imports = module.imports.borrow_mut();
263         let import_count = imports.len();
264         let mut indeterminate_imports = Vec::new();
265         while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
266             let import_index = module.resolved_import_count.get();
267             match self.resolve_import_for_module(module, &imports[import_index]) {
268                 ResolveResult::Failed(err) => {
269                     let import_directive = &imports[import_index];
270                     let (span, help) = match err {
271                         Some((span, msg)) => (span, format!(". {}", msg)),
272                         None => (import_directive.span, String::new()),
273                     };
274                     errors.push(ImportResolvingError {
275                         span: span,
276                         path: import_path_to_string(&import_directive.module_path,
277                                                     import_directive.subclass),
278                         help: help,
279                     });
280                 }
281                 ResolveResult::Indeterminate => {}
282                 ResolveResult::Success(()) => {
283                     // count success
284                     module.resolved_import_count
285                           .set(module.resolved_import_count.get() + 1);
286                     continue;
287                 }
288             }
289             // This resolution was not successful, keep it for later
290             indeterminate_imports.push(imports.swap_remove(import_index));
291
292         }
293
294         imports.extend(indeterminate_imports);
295
296         errors
297     }
298
299     /// Attempts to resolve the given import. The return value indicates
300     /// failure if we're certain the name does not exist, indeterminate if we
301     /// don't know whether the name exists at the moment due to other
302     /// currently-unresolved imports, or success if we know the name exists.
303     /// If successful, the resolved bindings are written into the module.
304     fn resolve_import_for_module(&mut self,
305                                  module_: Module<'b>,
306                                  import_directive: &ImportDirective)
307                                  -> ResolveResult<()> {
308         let mut resolution_result = ResolveResult::Failed(None);
309         let module_path = &import_directive.module_path;
310
311         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
312                names_to_string(&module_path[..]),
313                module_to_string(&*module_));
314
315         // First, resolve the module path for the directive, if necessary.
316         let container = if module_path.is_empty() {
317             // Use the crate root.
318             Some((self.resolver.graph_root, LastMod(AllPublic)))
319         } else {
320             match self.resolver.resolve_module_path(module_,
321                                                     &module_path[..],
322                                                     UseLexicalScopeFlag::DontUseLexicalScope,
323                                                     import_directive.span) {
324                 ResolveResult::Failed(err) => {
325                     resolution_result = ResolveResult::Failed(err);
326                     None
327                 }
328                 ResolveResult::Indeterminate => {
329                     resolution_result = ResolveResult::Indeterminate;
330                     None
331                 }
332                 ResolveResult::Success(container) => Some(container),
333             }
334         };
335
336         match container {
337             None => {}
338             Some((containing_module, lp)) => {
339                 // We found the module that the target is contained
340                 // within. Attempt to resolve the import within it.
341
342                 match import_directive.subclass {
343                     SingleImport(target, source) => {
344                         resolution_result = self.resolve_single_import(&module_,
345                                                                        containing_module,
346                                                                        target,
347                                                                        source,
348                                                                        import_directive,
349                                                                        lp);
350                     }
351                     GlobImport => {
352                         resolution_result = self.resolve_glob_import(&module_,
353                                                                      containing_module,
354                                                                      import_directive,
355                                                                      lp);
356                     }
357                 }
358             }
359         }
360
361         // Decrement the count of unresolved imports.
362         match resolution_result {
363             ResolveResult::Success(()) => {
364                 assert!(self.resolver.unresolved_imports >= 1);
365                 self.resolver.unresolved_imports -= 1;
366             }
367             _ => {
368                 // Nothing to do here; just return the error.
369             }
370         }
371
372         // Decrement the count of unresolved globs if necessary. But only if
373         // the resolution result is a success -- other cases will
374         // be handled by the main loop.
375
376         if resolution_result.success() {
377             match import_directive.subclass {
378                 GlobImport => {
379                     module_.dec_glob_count();
380                     if import_directive.is_public {
381                         module_.dec_pub_glob_count();
382                     }
383                 }
384                 SingleImport(..) => {
385                     // Ignore.
386                 }
387             }
388             if import_directive.is_public {
389                 module_.dec_pub_count();
390             }
391         }
392
393         return resolution_result;
394     }
395
396     fn resolve_single_import(&mut self,
397                              module_: Module<'b>,
398                              target_module: Module<'b>,
399                              target: Name,
400                              source: Name,
401                              directive: &ImportDirective,
402                              lp: LastPrivate)
403                              -> ResolveResult<()> {
404         debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
405                 private {:?}",
406                target,
407                module_to_string(&*target_module),
408                source,
409                module_to_string(module_),
410                directive.id,
411                lp);
412
413         let lp = match lp {
414             LastMod(lp) => lp,
415             LastImport {..} => {
416                 self.resolver
417                     .session
418                     .span_bug(directive.span, "not expecting Import here, must be LastMod")
419             }
420         };
421
422         // We need to resolve both namespaces for this to succeed.
423
424         let mut value_result = UnknownResult;
425         let mut type_result = UnknownResult;
426         let mut lev_suggestion = "".to_owned();
427
428         // Search for direct children of the containing module.
429         build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
430
431         match target_module.children.borrow().get(&source) {
432             None => {
433                 let names = target_module.children.borrow();
434                 if let Some(name) = find_best_match_for_name(names.keys(),
435                                                              &source.as_str(),
436                                                              None) {
437                     lev_suggestion = format!(". Did you mean to use `{}`?", name);
438                 }
439             }
440             Some(ref child_name_bindings) => {
441                 // pub_err makes sure we don't give the same error twice.
442                 let mut pub_err = false;
443                 if child_name_bindings.value_ns.defined() {
444                     debug!("(resolving single import) found value binding");
445                     value_result = BoundResult(target_module,
446                                                child_name_bindings.value_ns.clone());
447                     if directive.is_public && !child_name_bindings.value_ns.is_public() {
448                         let msg = format!("`{}` is private, and cannot be reexported", source);
449                         let note_msg = format!("Consider marking `{}` as `pub` in the imported \
450                                                 module",
451                                                source);
452                         struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
453                             .span_note(directive.span, &note_msg)
454                             .emit();
455                         pub_err = true;
456                     }
457                     if directive.is_public && child_name_bindings.value_ns.
458                                               defined_with(DefModifiers::PRIVATE_VARIANT) {
459                         let msg = format!("variant `{}` is private, and cannot be reexported ( \
460                                            error E0364), consider declaring its enum as `pub`",
461                                            source);
462                         self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
463                                                        directive.id,
464                                                        directive.span,
465                                                        msg);
466                         pub_err = true;
467                     }
468                 }
469                 if child_name_bindings.type_ns.defined() {
470                     debug!("(resolving single import) found type binding");
471                     type_result = BoundResult(target_module,
472                                               child_name_bindings.type_ns.clone());
473                     if !pub_err && directive.is_public &&
474                        !child_name_bindings.type_ns.is_public() {
475                         let msg = format!("`{}` is private, and cannot be reexported", source);
476                         let note_msg = format!("Consider declaring module `{}` as a `pub mod`",
477                                                source);
478                         struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
479                             .span_note(directive.span, &note_msg)
480                             .emit();
481                     }
482                     if !pub_err && directive.is_public && child_name_bindings.type_ns.
483                                                     defined_with(DefModifiers::PRIVATE_VARIANT) {
484                         let msg = format!("variant `{}` is private, and cannot be reexported ( \
485                                            error E0365), consider declaring its enum as `pub`",
486                                            source);
487                         self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
488                                                        directive.id,
489                                                        directive.span,
490                                                        msg);
491                     }
492                 }
493             }
494         }
495
496         // Unless we managed to find a result in both namespaces (unlikely),
497         // search imports as well.
498         let mut value_used_reexport = false;
499         let mut type_used_reexport = false;
500         match (value_result.clone(), type_result.clone()) {
501             (BoundResult(..), BoundResult(..)) => {} // Continue.
502             _ => {
503                 // If there is an unresolved glob at this point in the
504                 // containing module, bail out. We don't know enough to be
505                 // able to resolve this import.
506
507                 if target_module.pub_glob_count.get() > 0 {
508                     debug!("(resolving single import) unresolved pub glob; bailing out");
509                     return ResolveResult::Indeterminate;
510                 }
511
512                 // Now search the exported imports within the containing module.
513                 match target_module.import_resolutions.borrow().get(&source) {
514                     None => {
515                         debug!("(resolving single import) no import");
516                         // The containing module definitely doesn't have an
517                         // exported import with the name in question. We can
518                         // therefore accurately report that the names are
519                         // unbound.
520
521                         if lev_suggestion.is_empty() {  // skip if we already have a suggestion
522                             let names = target_module.import_resolutions.borrow();
523                             if let Some(name) = find_best_match_for_name(names.keys(),
524                                                                          &source.as_str(),
525                                                                          None) {
526                                 lev_suggestion =
527                                     format!(". Did you mean to use the re-exported import `{}`?",
528                                             name);
529                             }
530                         }
531
532                         if value_result.is_unknown() {
533                             value_result = UnboundResult;
534                         }
535                         if type_result.is_unknown() {
536                             type_result = UnboundResult;
537                         }
538                     }
539                     Some(import_resolution) if import_resolution.outstanding_references == 0 => {
540
541                         fn get_binding<'a>(this: &mut Resolver,
542                                            import_resolution: &ImportResolutionPerNamespace<'a>,
543                                            namespace: Namespace,
544                                            source: Name)
545                                            -> NamespaceResult<'a> {
546
547                             // Import resolutions must be declared with "pub"
548                             // in order to be exported.
549                             if !import_resolution[namespace].is_public {
550                                 return UnboundResult;
551                             }
552
553                             match import_resolution[namespace].target.clone() {
554                                 None => {
555                                     return UnboundResult;
556                                 }
557                                 Some(Target {
558                                     target_module,
559                                     binding,
560                                     shadowable: _
561                                 }) => {
562                                     debug!("(resolving single import) found import in ns {:?}",
563                                            namespace);
564                                     let id = import_resolution[namespace].id;
565                                     // track used imports and extern crates as well
566                                     this.used_imports.insert((id, namespace));
567                                     this.record_import_use(id, source);
568                                     match target_module.def_id() {
569                                         Some(DefId{krate: kid, ..}) => {
570                                             this.used_crates.insert(kid);
571                                         }
572                                         _ => {}
573                                     }
574                                     return BoundResult(target_module, binding);
575                                 }
576                             }
577                         }
578
579                         // The name is an import which has been fully
580                         // resolved. We can, therefore, just follow it.
581                         if value_result.is_unknown() {
582                             value_result = get_binding(self.resolver,
583                                                        import_resolution,
584                                                        ValueNS,
585                                                        source);
586                             value_used_reexport = import_resolution.value_ns.is_public;
587                         }
588                         if type_result.is_unknown() {
589                             type_result = get_binding(self.resolver,
590                                                       import_resolution,
591                                                       TypeNS,
592                                                       source);
593                             type_used_reexport = import_resolution.type_ns.is_public;
594                         }
595
596                     }
597                     Some(_) => {
598                         // If target_module is the same module whose import we are resolving
599                         // and there it has an unresolved import with the same name as `source`,
600                         // then the user is actually trying to import an item that is declared
601                         // in the same scope
602                         //
603                         // e.g
604                         // use self::submodule;
605                         // pub mod submodule;
606                         //
607                         // In this case we continue as if we resolved the import and let the
608                         // check_for_conflicts_between_imports_and_items call below handle
609                         // the conflict
610                         match (module_.def_id(), target_module.def_id()) {
611                             (Some(id1), Some(id2)) if id1 == id2 => {
612                                 if value_result.is_unknown() {
613                                     value_result = UnboundResult;
614                                 }
615                                 if type_result.is_unknown() {
616                                     type_result = UnboundResult;
617                                 }
618                             }
619                             _ => {
620                                 // The import is unresolved. Bail out.
621                                 debug!("(resolving single import) unresolved import; bailing out");
622                                 return ResolveResult::Indeterminate;
623                             }
624                         }
625                     }
626                 }
627             }
628         }
629
630         let mut value_used_public = false;
631         let mut type_used_public = false;
632
633         // If we didn't find a result in the type namespace, search the
634         // external modules.
635         match type_result {
636             BoundResult(..) => {}
637             _ => {
638                 match target_module.external_module_children.borrow_mut().get(&source) {
639                     None => {} // Continue.
640                     Some(module) => {
641                         debug!("(resolving single import) found external module");
642                         // track the module as used.
643                         match module.def_id() {
644                             Some(DefId{krate: kid, ..}) => {
645                                 self.resolver.used_crates.insert(kid);
646                             }
647                             _ => {}
648                         }
649                         let name_binding = NameBinding::create_from_module(module);
650                         type_result = BoundResult(target_module, name_binding);
651                         type_used_public = true;
652                     }
653                 }
654             }
655         }
656
657         // We've successfully resolved the import. Write the results in.
658         let mut import_resolutions = module_.import_resolutions.borrow_mut();
659         let import_resolution = import_resolutions.get_mut(&target).unwrap();
660
661         {
662             let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
663                 let namespace_name = match namespace {
664                     TypeNS => "type",
665                     ValueNS => "value",
666                 };
667
668                 match *result {
669                     BoundResult(ref target_module, ref name_binding) => {
670                         debug!("(resolving single import) found {:?} target: {:?}",
671                                namespace_name,
672                                name_binding.def());
673                         self.check_for_conflicting_import(&import_resolution,
674                                                           directive.span,
675                                                           target,
676                                                           namespace);
677
678                         self.check_that_import_is_importable(&name_binding,
679                                                              directive.span,
680                                                              target);
681
682                         import_resolution[namespace] = ImportResolution {
683                             target: Some(Target::new(target_module,
684                                                      name_binding.clone(),
685                                                      directive.shadowable)),
686                             id: directive.id,
687                             is_public: directive.is_public
688                         };
689
690                         self.add_export(module_, target, &import_resolution[namespace]);
691                         *used_public = name_binding.is_public();
692                     }
693                     UnboundResult => {
694                         // Continue.
695                     }
696                     UnknownResult => {
697                         panic!("{:?} result should be known at this point", namespace_name);
698                     }
699                 }
700             };
701             check_and_write_import(ValueNS, &value_result, &mut value_used_public);
702             check_and_write_import(TypeNS, &type_result, &mut type_used_public);
703         }
704
705         self.check_for_conflicts_between_imports_and_items(module_,
706                                                            import_resolution,
707                                                            directive.span,
708                                                            target);
709
710         if value_result.is_unbound() && type_result.is_unbound() {
711             let msg = format!("There is no `{}` in `{}`{}",
712                               source,
713                               module_to_string(&target_module), lev_suggestion);
714             return ResolveResult::Failed(Some((directive.span, msg)));
715         }
716         let value_used_public = value_used_reexport || value_used_public;
717         let type_used_public = type_used_reexport || type_used_public;
718
719         assert!(import_resolution.outstanding_references >= 1);
720         import_resolution.outstanding_references -= 1;
721
722         // Record what this import resolves to for later uses in documentation,
723         // this may resolve to either a value or a type, but for documentation
724         // purposes it's good enough to just favor one over the other.
725         let value_def_and_priv = import_resolution.value_ns.target.as_ref().map(|target| {
726             let def = target.binding.def().unwrap();
727             (def,
728              if value_used_public {
729                 lp
730             } else {
731                 DependsOn(def.def_id())
732             })
733         });
734         let type_def_and_priv = import_resolution.type_ns.target.as_ref().map(|target| {
735             let def = target.binding.def().unwrap();
736             (def,
737              if type_used_public {
738                 lp
739             } else {
740                 DependsOn(def.def_id())
741             })
742         });
743
744         let import_lp = LastImport {
745             value_priv: value_def_and_priv.map(|(_, p)| p),
746             value_used: Used,
747             type_priv: type_def_and_priv.map(|(_, p)| p),
748             type_used: Used,
749         };
750
751         if let Some((def, _)) = value_def_and_priv {
752             self.resolver.def_map.borrow_mut().insert(directive.id,
753                                                       PathResolution {
754                                                           base_def: def,
755                                                           last_private: import_lp,
756                                                           depth: 0,
757                                                       });
758         }
759         if let Some((def, _)) = type_def_and_priv {
760             self.resolver.def_map.borrow_mut().insert(directive.id,
761                                                       PathResolution {
762                                                           base_def: def,
763                                                           last_private: import_lp,
764                                                           depth: 0,
765                                                       });
766         }
767
768         debug!("(resolving single import) successfully resolved import");
769         return ResolveResult::Success(());
770     }
771
772     // Resolves a glob import. Note that this function cannot fail; it either
773     // succeeds or bails out (as importing * from an empty module or a module
774     // that exports nothing is valid). target_module is the module we are
775     // actually importing, i.e., `foo` in `use foo::*`.
776     fn resolve_glob_import(&mut self,
777                            module_: Module<'b>,
778                            target_module: Module<'b>,
779                            import_directive: &ImportDirective,
780                            lp: LastPrivate)
781                            -> ResolveResult<()> {
782         let id = import_directive.id;
783         let is_public = import_directive.is_public;
784
785         // This function works in a highly imperative manner; it eagerly adds
786         // everything it can to the list of import resolutions of the module
787         // node.
788         debug!("(resolving glob import) resolving glob import {}", id);
789
790         // We must bail out if the node has unresolved imports of any kind
791         // (including globs).
792         if (*target_module).pub_count.get() > 0 {
793             debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
794             return ResolveResult::Indeterminate;
795         }
796
797         // Add all resolved imports from the containing module.
798         let import_resolutions = target_module.import_resolutions.borrow();
799
800         if module_.import_resolutions.borrow_state() != ::std::cell::BorrowState::Unused {
801             // In this case, target_module == module_
802             // This means we are trying to glob import a module into itself,
803             // and it is a no-go
804             debug!("(resolving glob imports) target module is current module; giving up");
805             return ResolveResult::Failed(Some((import_directive.span,
806                                                "Cannot glob-import a module into itself.".into())));
807         }
808
809         for (name, target_import_resolution) in import_resolutions.iter() {
810             debug!("(resolving glob import) writing module resolution {} into `{}`",
811                    *name,
812                    module_to_string(module_));
813
814             // Here we merge two import resolutions.
815             let mut import_resolutions = module_.import_resolutions.borrow_mut();
816             let mut dest_import_resolution = import_resolutions.entry(*name).or_insert_with(|| {
817                 ImportResolutionPerNamespace::new(id, is_public)
818             });
819
820             for &ns in [TypeNS, ValueNS].iter() {
821                 match target_import_resolution[ns].target {
822                     Some(ref target) if target_import_resolution[ns].is_public => {
823                         self.check_for_conflicting_import(&dest_import_resolution,
824                                                           import_directive.span,
825                                                           *name,
826                                                           ns);
827                         dest_import_resolution[ns] = ImportResolution {
828                             id: id, is_public: is_public, target: Some(target.clone())
829                         };
830                         self.add_export(module_, *name, &dest_import_resolution[ns]);
831                     }
832                     _ => {}
833                 }
834             }
835         }
836
837         // Add all children from the containing module.
838         build_reduced_graph::populate_module_if_necessary(self.resolver, &target_module);
839
840         for (&name, name_bindings) in target_module.children.borrow().iter() {
841             self.merge_import_resolution(module_,
842                                          target_module,
843                                          import_directive,
844                                          name,
845                                          name_bindings.clone());
846
847         }
848
849         // Record the destination of this import
850         if let Some(did) = target_module.def_id() {
851             self.resolver.def_map.borrow_mut().insert(id,
852                                                       PathResolution {
853                                                           base_def: Def::Mod(did),
854                                                           last_private: lp,
855                                                           depth: 0,
856                                                       });
857         }
858
859         debug!("(resolving glob import) successfully resolved import");
860         return ResolveResult::Success(());
861     }
862
863     fn merge_import_resolution(&mut self,
864                                module_: Module<'b>,
865                                containing_module: Module<'b>,
866                                import_directive: &ImportDirective,
867                                name: Name,
868                                name_bindings: NameBindings<'b>) {
869         let id = import_directive.id;
870         let is_public = import_directive.is_public;
871
872         let mut import_resolutions = module_.import_resolutions.borrow_mut();
873         let dest_import_resolution = import_resolutions.entry(name).or_insert_with(|| {
874             ImportResolutionPerNamespace::new(id, is_public)
875         });
876
877         debug!("(resolving glob import) writing resolution `{}` in `{}` to `{}`",
878                name,
879                module_to_string(&*containing_module),
880                module_to_string(module_));
881
882         // Merge the child item into the import resolution.
883         // pub_err makes sure we don't give the same error twice.
884         let mut pub_err = false;
885         {
886             let mut merge_child_item = |namespace| {
887                 if !pub_err && is_public &&
888                         name_bindings[namespace].defined_with(DefModifiers::PRIVATE_VARIANT) {
889                     let msg = format!("variant `{}` is private, and cannot be reexported (error \
890                                        E0364), consider declaring its enum as `pub`", name);
891                     self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
892                                                    import_directive.id,
893                                                    import_directive.span,
894                                                    msg);
895                     pub_err = true;
896                 }
897
898                 let modifier = DefModifiers::IMPORTABLE | DefModifiers::PUBLIC;
899                 if name_bindings[namespace].defined_with(modifier) {
900                     let namespace_name = match namespace {
901                         TypeNS => "type",
902                         ValueNS => "value",
903                     };
904                     debug!("(resolving glob import) ... for {} target", namespace_name);
905                     if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
906                         let msg = format!("a {} named `{}` has already been imported in this \
907                                            module",
908                                           namespace_name,
909                                           name);
910                         span_err!(self.resolver.session,
911                                   import_directive.span,
912                                   E0251,
913                                   "{}",
914                                   msg);
915                     } else {
916                         dest_import_resolution[namespace] = ImportResolution {
917                             target: Some(Target::new(containing_module,
918                                                      name_bindings[namespace].clone(),
919                                                      import_directive.shadowable)),
920                             id: id,
921                             is_public: is_public
922                         };
923                         self.add_export(module_, name, &dest_import_resolution[namespace]);
924                     }
925                 } else {
926                     // FIXME #30159: This is required for backwards compatability.
927                     dest_import_resolution[namespace].is_public |= is_public;
928                 }
929             };
930             merge_child_item(ValueNS);
931             merge_child_item(TypeNS);
932         }
933
934         self.check_for_conflicts_between_imports_and_items(module_,
935                                                            dest_import_resolution,
936                                                            import_directive.span,
937                                                            name);
938     }
939
940     fn add_export(&mut self, module: Module<'b>, name: Name, resolution: &ImportResolution<'b>) {
941         if !resolution.is_public { return }
942         let node_id = match module.def_id() {
943             Some(def_id) => self.resolver.ast_map.as_local_node_id(def_id).unwrap(),
944             None => return,
945         };
946         let export = match resolution.target.as_ref().unwrap().binding.def() {
947             Some(def) => Export { name: name, def_id: def.def_id() },
948             None => return,
949         };
950         self.resolver.export_map.entry(node_id).or_insert(Vec::new()).push(export);
951     }
952
953     /// Checks that imported names and items don't have the same name.
954     fn check_for_conflicting_import(&mut self,
955                                     import_resolution: &ImportResolutionPerNamespace,
956                                     import_span: Span,
957                                     name: Name,
958                                     namespace: Namespace) {
959         let target = &import_resolution[namespace].target;
960         debug!("check_for_conflicting_import: {}; target exists: {}",
961                name,
962                target.is_some());
963
964         match *target {
965             Some(ref target) if target.shadowable != Shadowable::Always => {
966                 let ns_word = match namespace {
967                     TypeNS => {
968                         match target.binding.module() {
969                             Some(ref module) if module.is_normal() => "module",
970                             Some(ref module) if module.is_trait() => "trait",
971                             _ => "type",
972                         }
973                     }
974                     ValueNS => "value",
975                 };
976                 let use_id = import_resolution[namespace].id;
977                 let item = self.resolver.ast_map.expect_item(use_id);
978                 let mut err = struct_span_err!(self.resolver.session,
979                                                import_span,
980                                                E0252,
981                                                "a {} named `{}` has already been imported \
982                                                 in this module",
983                                                ns_word,
984                                                name);
985                 span_note!(&mut err,
986                            item.span,
987                            "previous import of `{}` here",
988                            name);
989                 err.emit();
990             }
991             Some(_) | None => {}
992         }
993     }
994
995     /// Checks that an import is actually importable
996     fn check_that_import_is_importable(&mut self,
997                                        name_binding: &NameBinding,
998                                        import_span: Span,
999                                        name: Name) {
1000         if !name_binding.defined_with(DefModifiers::IMPORTABLE) {
1001             let msg = format!("`{}` is not directly importable", name);
1002             span_err!(self.resolver.session, import_span, E0253, "{}", &msg[..]);
1003         }
1004     }
1005
1006     /// Checks that imported names and items don't have the same name.
1007     fn check_for_conflicts_between_imports_and_items(&mut self,
1008                                                      module: Module<'b>,
1009                                                      import: &ImportResolutionPerNamespace<'b>,
1010                                                      import_span: Span,
1011                                                      name: Name) {
1012         // First, check for conflicts between imports and `extern crate`s.
1013         if module.external_module_children
1014                  .borrow()
1015                  .contains_key(&name) {
1016             match import.type_ns.target {
1017                 Some(ref target) if target.shadowable != Shadowable::Always => {
1018                     let msg = format!("import `{0}` conflicts with imported crate in this module \
1019                                        (maybe you meant `use {0}::*`?)",
1020                                       name);
1021                     span_err!(self.resolver.session, import_span, E0254, "{}", &msg[..]);
1022                 }
1023                 Some(_) | None => {}
1024             }
1025         }
1026
1027         // Check for item conflicts.
1028         let name_bindings = match module.children.borrow().get(&name) {
1029             None => {
1030                 // There can't be any conflicts.
1031                 return;
1032             }
1033             Some(ref name_bindings) => (*name_bindings).clone(),
1034         };
1035
1036         match import.value_ns.target {
1037             Some(ref target) if target.shadowable != Shadowable::Always => {
1038                 if let Some(ref value) = *name_bindings.value_ns.borrow() {
1039                     let mut err = struct_span_err!(self.resolver.session,
1040                                                    import_span,
1041                                                    E0255,
1042                                                    "import `{}` conflicts with \
1043                                                     value in this module",
1044                                                    name);
1045                     if let Some(span) = value.span {
1046                         err.span_note(span, "conflicting value here");
1047                     }
1048                     err.emit();
1049                 }
1050             }
1051             Some(_) | None => {}
1052         }
1053
1054         match import.type_ns.target {
1055             Some(ref target) if target.shadowable != Shadowable::Always => {
1056                 if let Some(ref ty) = *name_bindings.type_ns.borrow() {
1057                     let (what, note) = match ty.module() {
1058                         Some(ref module) if module.is_normal() =>
1059                             ("existing submodule", "note conflicting module here"),
1060                         Some(ref module) if module.is_trait() =>
1061                             ("trait in this module", "note conflicting trait here"),
1062                         _ => ("type in this module", "note conflicting type here"),
1063                     };
1064                     let mut err = struct_span_err!(self.resolver.session,
1065                                                    import_span,
1066                                                    E0256,
1067                                                    "import `{}` conflicts with {}",
1068                                                    name,
1069                                                    what);
1070                     if let Some(span) = ty.span {
1071                         err.span_note(span, note);
1072                     }
1073                     err.emit();
1074                 }
1075             }
1076             Some(_) | None => {}
1077         }
1078     }
1079 }
1080
1081 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
1082     if names.is_empty() {
1083         import_directive_subclass_to_string(subclass)
1084     } else {
1085         (format!("{}::{}",
1086                  names_to_string(names),
1087                  import_directive_subclass_to_string(subclass)))
1088             .to_string()
1089     }
1090 }
1091
1092 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
1093     match subclass {
1094         SingleImport(_, source) => source.to_string(),
1095         GlobImport => "*".to_string(),
1096     }
1097 }
1098
1099 pub fn resolve_imports(resolver: &mut Resolver) {
1100     let mut import_resolver = ImportResolver { resolver: resolver };
1101     import_resolver.resolve_imports();
1102 }