]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Fix regression from #31461 and fix the test that was supposed to catch it.
[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::privacy::*;
29
30 use syntax::ast::{NodeId, Name};
31 use syntax::attr::AttrMetaMethods;
32 use syntax::codemap::Span;
33 use syntax::util::lev_distance::find_best_match_for_name;
34
35 use std::mem::replace;
36
37 /// Contains data for specific types of import directives.
38 #[derive(Copy, Clone,Debug)]
39 pub enum ImportDirectiveSubclass {
40     SingleImport(Name /* target */, Name /* source */),
41     GlobImport,
42 }
43
44 /// Whether an import can be shadowed by another import.
45 #[derive(Debug,PartialEq,Clone,Copy)]
46 pub enum Shadowable {
47     Always,
48     Never,
49 }
50
51 /// One import directive.
52 #[derive(Debug,Clone)]
53 pub struct ImportDirective {
54     pub module_path: Vec<Name>,
55     pub subclass: ImportDirectiveSubclass,
56     pub span: Span,
57     pub id: NodeId,
58     pub is_public: bool, // see note in ImportResolutionPerNamespace about how to use this
59     pub shadowable: Shadowable,
60 }
61
62 impl ImportDirective {
63     pub fn new(module_path: Vec<Name>,
64                subclass: ImportDirectiveSubclass,
65                span: Span,
66                id: NodeId,
67                is_public: bool,
68                shadowable: Shadowable)
69                -> ImportDirective {
70         ImportDirective {
71             module_path: module_path,
72             subclass: subclass,
73             span: span,
74             id: id,
75             is_public: is_public,
76             shadowable: shadowable,
77         }
78     }
79
80     // Given the binding to which this directive resolves in a particular namespace,
81     // this returns the binding for the name this directive defines in that namespace.
82     fn import<'a>(&self, binding: &'a NameBinding<'a>) -> NameBinding<'a> {
83         let mut modifiers = match self.is_public {
84             true => DefModifiers::PUBLIC | DefModifiers::IMPORTABLE,
85             false => DefModifiers::empty(),
86         };
87         if let GlobImport = self.subclass {
88             modifiers = modifiers | DefModifiers::GLOB_IMPORTED;
89         }
90         if self.shadowable == Shadowable::Always {
91             modifiers = modifiers | DefModifiers::PRELUDE;
92         }
93
94         NameBinding {
95             kind: NameBindingKind::Import { binding: binding, id: self.id },
96             span: Some(self.span),
97             modifiers: modifiers,
98         }
99     }
100 }
101
102 #[derive(Clone, Default)]
103 /// Records information about the resolution of a name in a module.
104 pub struct NameResolution<'a> {
105     /// The number of unresolved single imports that could define the name.
106     pub outstanding_references: usize,
107     /// The least shadowable known binding for this name, or None if there are no known bindings.
108     pub binding: Option<&'a NameBinding<'a>>,
109 }
110
111 impl<'a> NameResolution<'a> {
112     pub fn result(&self, outstanding_globs: usize) -> ResolveResult<&'a NameBinding<'a>> {
113         // If no unresolved imports (single or glob) can define the name, self.binding is final.
114         if self.outstanding_references == 0 && outstanding_globs == 0 {
115             return self.binding.map(Success).unwrap_or(Failed(None));
116         }
117
118         if let Some(binding) = self.binding {
119             // Single imports will never be shadowable by other single or glob imports.
120             if !binding.defined_with(DefModifiers::GLOB_IMPORTED) { return Success(binding); }
121             // Non-PRELUDE glob imports will never be shadowable by other glob imports.
122             if self.outstanding_references == 0 && !binding.defined_with(DefModifiers::PRELUDE) {
123                 return Success(binding);
124             }
125         }
126
127         Indeterminate
128     }
129
130     // Define the name or return the existing binding if there is a collision.
131     pub fn try_define(&mut self, binding: &'a NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> {
132         let is_prelude = |binding: &NameBinding| binding.defined_with(DefModifiers::PRELUDE);
133         let old_binding = match self.binding {
134             Some(_) if is_prelude(binding) => return Ok(()),
135             Some(old_binding) if !is_prelude(old_binding) => old_binding,
136             _ => { self.binding = Some(binding); return Ok(()); }
137         };
138
139         // FIXME #31337: We currently allow items to shadow glob-imported re-exports.
140         if !old_binding.is_import() && binding.defined_with(DefModifiers::GLOB_IMPORTED) {
141             if let NameBindingKind::Import { binding, .. } = binding.kind {
142                 if binding.is_import() { return Ok(()); }
143             }
144         }
145
146         Err(old_binding)
147     }
148 }
149
150 struct ImportResolvingError<'a> {
151     /// Module where the error happened
152     source_module: Module<'a>,
153     import_directive: ImportDirective,
154     span: Span,
155     help: String,
156 }
157
158 struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
159     resolver: &'a mut Resolver<'b, 'tcx>,
160 }
161
162 impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
163     // Import resolution
164     //
165     // This is a fixed-point algorithm. We resolve imports until our efforts
166     // are stymied by an unresolved import; then we bail out of the current
167     // module and continue. We terminate successfully once no more imports
168     // remain or unsuccessfully when no forward progress in resolving imports
169     // is made.
170
171     /// Resolves all imports for the crate. This method performs the fixed-
172     /// point iteration.
173     fn resolve_imports(&mut self) {
174         let mut i = 0;
175         let mut prev_unresolved_imports = 0;
176         loop {
177             debug!("(resolving imports) iteration {}, {} imports left",
178                    i,
179                    self.resolver.unresolved_imports);
180
181             let module_root = self.resolver.graph_root;
182             let errors = self.resolve_imports_for_module_subtree(module_root);
183
184             if self.resolver.unresolved_imports == 0 {
185                 debug!("(resolving imports) success");
186                 break;
187             }
188
189             if self.resolver.unresolved_imports == prev_unresolved_imports {
190                 // resolving failed
191                 if errors.len() > 0 {
192                     for e in errors {
193                         self.import_resolving_error(e)
194                     }
195                 } else {
196                     // Report unresolved imports only if no hard error was already reported
197                     // to avoid generating multiple errors on the same import.
198                     // Imports that are still indeterminate at this point are actually blocked
199                     // by errored imports, so there is no point reporting them.
200                     self.resolver.report_unresolved_imports(module_root);
201                 }
202                 break;
203             }
204
205             i += 1;
206             prev_unresolved_imports = self.resolver.unresolved_imports;
207         }
208     }
209
210     /// Resolves an `ImportResolvingError` into the correct enum discriminant
211     /// and passes that on to `resolve_error`.
212     fn import_resolving_error(&self, e: ImportResolvingError<'b>) {
213         // If it's a single failed import then create a "fake" import
214         // resolution for it so that later resolve stages won't complain.
215         if let SingleImport(target, _) = e.import_directive.subclass {
216             let dummy_binding = self.resolver.new_name_binding(NameBinding {
217                 modifiers: DefModifiers::PRELUDE,
218                 kind: NameBindingKind::Def(Def::Err),
219                 span: None,
220             });
221
222             let _ = e.source_module.try_define_child(target, ValueNS, dummy_binding);
223             let _ = e.source_module.try_define_child(target, TypeNS, dummy_binding);
224         }
225
226         let path = import_path_to_string(&e.import_directive.module_path,
227                                          e.import_directive.subclass);
228
229         resolve_error(self.resolver,
230                       e.span,
231                       ResolutionError::UnresolvedImport(Some((&path, &e.help))));
232     }
233
234     /// Attempts to resolve imports for the given module and all of its
235     /// submodules.
236     fn resolve_imports_for_module_subtree(&mut self,
237                                           module_: Module<'b>)
238                                           -> Vec<ImportResolvingError<'b>> {
239         let mut errors = Vec::new();
240         debug!("(resolving imports for module subtree) resolving {}",
241                module_to_string(&*module_));
242         let orig_module = replace(&mut self.resolver.current_module, module_);
243         errors.extend(self.resolve_imports_for_module(module_));
244         self.resolver.current_module = orig_module;
245
246         build_reduced_graph::populate_module_if_necessary(self.resolver, module_);
247         module_.for_each_local_child(|_, _, child_node| {
248             match child_node.module() {
249                 None => {
250                     // Nothing to do.
251                 }
252                 Some(child_module) => {
253                     errors.extend(self.resolve_imports_for_module_subtree(child_module));
254                 }
255             }
256         });
257
258         for (_, child_module) in module_.anonymous_children.borrow().iter() {
259             errors.extend(self.resolve_imports_for_module_subtree(child_module));
260         }
261
262         errors
263     }
264
265     /// Attempts to resolve imports for the given module only.
266     fn resolve_imports_for_module(&mut self, module: Module<'b>) -> Vec<ImportResolvingError<'b>> {
267         let mut errors = Vec::new();
268
269         if module.all_imports_resolved() {
270             debug!("(resolving imports for module) all imports resolved for {}",
271                    module_to_string(&*module));
272             return errors;
273         }
274
275         let mut imports = module.imports.borrow_mut();
276         let import_count = imports.len();
277         let mut indeterminate_imports = Vec::new();
278         while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
279             let import_index = module.resolved_import_count.get();
280             match self.resolve_import_for_module(module, &imports[import_index]) {
281                 ResolveResult::Failed(err) => {
282                     let import_directive = &imports[import_index];
283                     let (span, help) = match err {
284                         Some((span, msg)) => (span, format!(". {}", msg)),
285                         None => (import_directive.span, String::new()),
286                     };
287                     errors.push(ImportResolvingError {
288                         source_module: module,
289                         import_directive: import_directive.clone(),
290                         span: span,
291                         help: help,
292                     });
293                 }
294                 ResolveResult::Indeterminate => {}
295                 ResolveResult::Success(()) => {
296                     // count success
297                     module.resolved_import_count
298                           .set(module.resolved_import_count.get() + 1);
299                     continue;
300                 }
301             }
302             // This resolution was not successful, keep it for later
303             indeterminate_imports.push(imports.swap_remove(import_index));
304
305         }
306
307         imports.extend(indeterminate_imports);
308
309         errors
310     }
311
312     /// Attempts to resolve the given import. The return value indicates
313     /// failure if we're certain the name does not exist, indeterminate if we
314     /// don't know whether the name exists at the moment due to other
315     /// currently-unresolved imports, or success if we know the name exists.
316     /// If successful, the resolved bindings are written into the module.
317     fn resolve_import_for_module(&mut self,
318                                  module_: Module<'b>,
319                                  import_directive: &ImportDirective)
320                                  -> ResolveResult<()> {
321         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
322                names_to_string(&import_directive.module_path),
323                module_to_string(&*module_));
324
325         self.resolver
326             .resolve_module_path(module_,
327                                  &import_directive.module_path,
328                                  UseLexicalScopeFlag::DontUseLexicalScope,
329                                  import_directive.span)
330             .and_then(|(containing_module, lp)| {
331                 // We found the module that the target is contained
332                 // within. Attempt to resolve the import within it.
333                 if let SingleImport(target, source) = import_directive.subclass {
334                     self.resolve_single_import(module_,
335                                                containing_module,
336                                                target,
337                                                source,
338                                                import_directive,
339                                                lp)
340                 } else {
341                     self.resolve_glob_import(module_, containing_module, import_directive, lp)
342                 }
343             })
344             .and_then(|()| {
345                 // Decrement the count of unresolved imports.
346                 assert!(self.resolver.unresolved_imports >= 1);
347                 self.resolver.unresolved_imports -= 1;
348
349                 if let GlobImport = import_directive.subclass {
350                     module_.dec_glob_count();
351                     if import_directive.is_public {
352                         module_.dec_pub_glob_count();
353                     }
354                 }
355                 if import_directive.is_public {
356                     module_.dec_pub_count();
357                 }
358                 Success(())
359             })
360     }
361
362     fn resolve_single_import(&mut self,
363                              module_: Module<'b>,
364                              target_module: Module<'b>,
365                              target: Name,
366                              source: Name,
367                              directive: &ImportDirective,
368                              lp: LastPrivate)
369                              -> ResolveResult<()> {
370         debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
371                 private {:?}",
372                target,
373                module_to_string(&*target_module),
374                source,
375                module_to_string(module_),
376                directive.id,
377                lp);
378
379         let lp = match lp {
380             LastMod(lp) => lp,
381             LastImport {..} => {
382                 self.resolver
383                     .session
384                     .span_bug(directive.span, "not expecting Import here, must be LastMod")
385             }
386         };
387
388         // If this is a circular import, we temporarily count it as determined so that
389         // it fails (as opposed to being indeterminate) when nothing else can define it.
390         if target_module.def_id() == module_.def_id() && source == target {
391             module_.decrement_outstanding_references_for(target, ValueNS);
392             module_.decrement_outstanding_references_for(target, TypeNS);
393         }
394
395         // We need to resolve both namespaces for this to succeed.
396         let value_result =
397             self.resolver.resolve_name_in_module(target_module, source, ValueNS, false, true);
398         let type_result =
399             self.resolver.resolve_name_in_module(target_module, source, TypeNS, false, true);
400
401         if target_module.def_id() == module_.def_id() && source == target {
402             module_.increment_outstanding_references_for(target, ValueNS);
403             module_.increment_outstanding_references_for(target, TypeNS);
404         }
405
406         match (&value_result, &type_result) {
407             (&Success(name_binding), _) if !name_binding.is_import() &&
408                                            directive.is_public &&
409                                            !name_binding.is_public() => {
410                 let msg = format!("`{}` is private, and cannot be reexported", source);
411                 let note_msg = format!("Consider marking `{}` as `pub` in the imported module",
412                                         source);
413                 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
414                     .span_note(directive.span, &note_msg)
415                     .emit();
416             }
417
418             (_, &Success(name_binding)) if !name_binding.is_import() && directive.is_public => {
419                 if !name_binding.is_public() {
420                     let msg = format!("`{}` is private, and cannot be reexported", source);
421                     let note_msg =
422                         format!("Consider declaring type or module `{}` with `pub`", source);
423                     struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
424                         .span_note(directive.span, &note_msg)
425                         .emit();
426                 } else if name_binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
427                     let msg = format!("variant `{}` is private, and cannot be reexported \
428                                        (error E0364), consider declaring its enum as `pub`",
429                                        source);
430                     self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
431                                                    directive.id,
432                                                    directive.span,
433                                                    msg);
434                 }
435             }
436
437             _ => {}
438         }
439
440         match (&value_result, &type_result) {
441             (&Indeterminate, _) | (_, &Indeterminate) => return Indeterminate,
442             (&Failed(_), &Failed(_)) => {
443                 let children = target_module.children.borrow();
444                 let names = children.keys().map(|&(ref name, _)| name);
445                 let lev_suggestion = match find_best_match_for_name(names, &source.as_str(), None) {
446                     Some(name) => format!(". Did you mean to use `{}`?", name),
447                     None => "".to_owned(),
448                 };
449                 let msg = format!("There is no `{}` in `{}`{}",
450                                   source,
451                                   module_to_string(target_module), lev_suggestion);
452                 return Failed(Some((directive.span, msg)));
453             }
454             _ => (),
455         }
456
457         for &(ns, result) in &[(ValueNS, &value_result), (TypeNS, &type_result)] {
458             if let Success(binding) = *result {
459                 if !binding.defined_with(DefModifiers::IMPORTABLE) {
460                     let msg = format!("`{}` is not directly importable", target);
461                     span_err!(self.resolver.session, directive.span, E0253, "{}", &msg);
462                 }
463
464                 self.define(module_, target, ns, directive.import(binding));
465             }
466         }
467
468         // Record what this import resolves to for later uses in documentation,
469         // this may resolve to either a value or a type, but for documentation
470         // purposes it's good enough to just favor one over the other.
471         module_.decrement_outstanding_references_for(target, ValueNS);
472         module_.decrement_outstanding_references_for(target, TypeNS);
473
474         let def_and_priv = |binding: &NameBinding| {
475             let def = binding.def().unwrap();
476             let last_private = if binding.is_public() { lp } else { DependsOn(def.def_id()) };
477             (def, last_private)
478         };
479         let value_def_and_priv = value_result.success().map(&def_and_priv);
480         let type_def_and_priv = type_result.success().map(&def_and_priv);
481
482         let import_lp = LastImport {
483             value_priv: value_def_and_priv.map(|(_, p)| p),
484             value_used: Used,
485             type_priv: type_def_and_priv.map(|(_, p)| p),
486             type_used: Used,
487         };
488
489         let write_path_resolution = |(def, _)| {
490             let path_resolution =
491                 PathResolution { base_def: def, last_private: import_lp, depth: 0 };
492             self.resolver.def_map.borrow_mut().insert(directive.id, path_resolution);
493         };
494         value_def_and_priv.map(&write_path_resolution);
495         type_def_and_priv.map(&write_path_resolution);
496
497         debug!("(resolving single import) successfully resolved import");
498         return Success(());
499     }
500
501     // Resolves a glob import. Note that this function cannot fail; it either
502     // succeeds or bails out (as importing * from an empty module or a module
503     // that exports nothing is valid). target_module is the module we are
504     // actually importing, i.e., `foo` in `use foo::*`.
505     fn resolve_glob_import(&mut self,
506                            module_: Module<'b>,
507                            target_module: Module<'b>,
508                            directive: &ImportDirective,
509                            lp: LastPrivate)
510                            -> ResolveResult<()> {
511         // We must bail out if the node has unresolved imports of any kind (including globs).
512         if target_module.pub_count.get() > 0 {
513             debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
514             return Indeterminate;
515         }
516
517         if module_.def_id() == target_module.def_id() {
518             // This means we are trying to glob import a module into itself, and it is a no-go
519             let msg = "Cannot glob-import a module into itself.".into();
520             return Failed(Some((directive.span, msg)));
521         }
522
523         // Add all children from the containing module.
524         build_reduced_graph::populate_module_if_necessary(self.resolver, target_module);
525         target_module.for_each_child(|name, ns, binding| {
526             if !binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { return }
527             if binding.is_extern_crate() { return }
528             self.define(module_, name, ns, directive.import(binding));
529
530             if ns == TypeNS && directive.is_public &&
531                binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
532                 let msg = format!("variant `{}` is private, and cannot be reexported (error \
533                                    E0364), consider declaring its enum as `pub`", name);
534                 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
535                                                directive.id,
536                                                directive.span,
537                                                msg);
538             }
539         });
540
541         // Record the destination of this import
542         if let Some(did) = target_module.def_id() {
543             self.resolver.def_map.borrow_mut().insert(directive.id,
544                                                       PathResolution {
545                                                           base_def: Def::Mod(did),
546                                                           last_private: lp,
547                                                           depth: 0,
548                                                       });
549         }
550
551         debug!("(resolving glob import) successfully resolved import");
552         return Success(());
553     }
554
555     fn define(&mut self,
556               parent: Module<'b>,
557               name: Name,
558               ns: Namespace,
559               binding: NameBinding<'b>) {
560         let binding = self.resolver.new_name_binding(binding);
561         if let Err(old_binding) = parent.try_define_child(name, ns, binding) {
562             self.report_conflict(name, ns, binding, old_binding);
563         } else if binding.is_public() { // Add to the export map
564             if let (Some(parent_def_id), Some(def)) = (parent.def_id(), binding.def()) {
565                 let parent_node_id = self.resolver.ast_map.as_local_node_id(parent_def_id).unwrap();
566                 let export = Export { name: name, def_id: def.def_id() };
567                 self.resolver.export_map.entry(parent_node_id).or_insert(Vec::new()).push(export);
568             }
569         }
570     }
571
572     fn report_conflict(&mut self,
573                        name: Name,
574                        ns: Namespace,
575                        binding: &'b NameBinding<'b>,
576                        old_binding: &'b NameBinding<'b>) {
577         if old_binding.is_extern_crate() {
578             let msg = format!("import `{0}` conflicts with imported crate \
579                                in this module (maybe you meant `use {0}::*`?)",
580                               name);
581             span_err!(self.resolver.session, binding.span.unwrap(), E0254, "{}", &msg);
582         } else if old_binding.is_import() {
583             let ns_word = match (ns, old_binding.module()) {
584                 (ValueNS, _) => "value",
585                 (TypeNS, Some(module)) if module.is_normal() => "module",
586                 (TypeNS, Some(module)) if module.is_trait() => "trait",
587                 (TypeNS, _) => "type",
588             };
589             let mut err = struct_span_err!(self.resolver.session,
590                                            binding.span.unwrap(),
591                                            E0252,
592                                            "a {} named `{}` has already been imported \
593                                             in this module",
594                                            ns_word,
595                                            name);
596             err.span_note(old_binding.span.unwrap(),
597                           &format!("previous import of `{}` here", name));
598             err.emit();
599         } else if ns == ValueNS { // Check for item conflicts in the value namespace
600             let mut err = struct_span_err!(self.resolver.session,
601                                            binding.span.unwrap(),
602                                            E0255,
603                                            "import `{}` conflicts with value in this module",
604                                            name);
605             err.span_note(old_binding.span.unwrap(), "conflicting value here");
606             err.emit();
607         } else { // Check for item conflicts in the type namespace
608             let (what, note) = match old_binding.module() {
609                 Some(ref module) if module.is_normal() =>
610                     ("existing submodule", "note conflicting module here"),
611                 Some(ref module) if module.is_trait() =>
612                     ("trait in this module", "note conflicting trait here"),
613                 _ => ("type in this module", "note conflicting type here"),
614             };
615             let mut err = struct_span_err!(self.resolver.session,
616                                            binding.span.unwrap(),
617                                            E0256,
618                                            "import `{}` conflicts with {}",
619                                            name,
620                                            what);
621             err.span_note(old_binding.span.unwrap(), note);
622             err.emit();
623         }
624     }
625 }
626
627 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
628     if names.is_empty() {
629         import_directive_subclass_to_string(subclass)
630     } else {
631         (format!("{}::{}",
632                  names_to_string(names),
633                  import_directive_subclass_to_string(subclass)))
634             .to_string()
635     }
636 }
637
638 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
639     match subclass {
640         SingleImport(_, source) => source.to_string(),
641         GlobImport => "*".to_string(),
642     }
643 }
644
645 pub fn resolve_imports(resolver: &mut Resolver) {
646     let mut import_resolver = ImportResolver { resolver: resolver };
647     import_resolver.resolve_imports();
648 }