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