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