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