]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Auto merge of #31648 - jseyfried:fix_diagnostics, r=nrc
[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         for (_, child_module) in module_.module_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<'b>> {
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                         source_module: module,
277                         import_directive: import_directive.clone(),
278                         span: span,
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         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
310                names_to_string(&import_directive.module_path),
311                module_to_string(&module_));
312
313         self.resolver
314             .resolve_module_path(module_,
315                                  &import_directive.module_path,
316                                  UseLexicalScopeFlag::DontUseLexicalScope,
317                                  import_directive.span)
318             .and_then(|(containing_module, lp)| {
319                 // We found the module that the target is contained
320                 // within. Attempt to resolve the import within it.
321                 if let SingleImport(target, source) = import_directive.subclass {
322                     self.resolve_single_import(module_,
323                                                containing_module,
324                                                target,
325                                                source,
326                                                import_directive,
327                                                lp)
328                 } else {
329                     self.resolve_glob_import(module_, containing_module, import_directive, lp)
330                 }
331             })
332             .and_then(|()| {
333                 // Decrement the count of unresolved imports.
334                 assert!(self.resolver.unresolved_imports >= 1);
335                 self.resolver.unresolved_imports -= 1;
336
337                 if let GlobImport = import_directive.subclass {
338                     module_.dec_glob_count();
339                     if import_directive.is_public {
340                         module_.dec_pub_glob_count();
341                     }
342                 }
343                 if import_directive.is_public {
344                     module_.dec_pub_count();
345                 }
346                 Success(())
347             })
348     }
349
350     fn resolve_single_import(&mut self,
351                              module_: Module<'b>,
352                              target_module: Module<'b>,
353                              target: Name,
354                              source: Name,
355                              directive: &ImportDirective,
356                              lp: LastPrivate)
357                              -> ResolveResult<()> {
358         debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
359                 private {:?}",
360                target,
361                module_to_string(&target_module),
362                source,
363                module_to_string(module_),
364                directive.id,
365                lp);
366
367         let lp = match lp {
368             LastMod(lp) => lp,
369             LastImport {..} => {
370                 self.resolver
371                     .session
372                     .span_bug(directive.span, "not expecting Import here, must be LastMod")
373             }
374         };
375
376         // If this is a circular import, we temporarily count it as determined so that
377         // it fails (as opposed to being indeterminate) when nothing else can define it.
378         if target_module.def_id() == module_.def_id() && source == target {
379             module_.decrement_outstanding_references_for(target, ValueNS);
380             module_.decrement_outstanding_references_for(target, TypeNS);
381         }
382
383         // We need to resolve both namespaces for this to succeed.
384         let value_result =
385             self.resolver.resolve_name_in_module(target_module, source, ValueNS, false, true);
386         let type_result =
387             self.resolver.resolve_name_in_module(target_module, source, TypeNS, false, true);
388
389         if target_module.def_id() == module_.def_id() && source == target {
390             module_.increment_outstanding_references_for(target, ValueNS);
391             module_.increment_outstanding_references_for(target, TypeNS);
392         }
393
394         match (&value_result, &type_result) {
395             (&Indeterminate, _) | (_, &Indeterminate) => return Indeterminate,
396             (&Failed(_), &Failed(_)) => {
397                 let children = target_module.resolutions.borrow();
398                 let names = children.keys().map(|&(ref name, _)| name);
399                 let lev_suggestion = match find_best_match_for_name(names, &source.as_str(), None) {
400                     Some(name) => format!(". Did you mean to use `{}`?", name),
401                     None => "".to_owned(),
402                 };
403                 let msg = format!("There is no `{}` in `{}`{}",
404                                   source,
405                                   module_to_string(target_module), lev_suggestion);
406                 return Failed(Some((directive.span, msg)));
407             }
408             _ => (),
409         }
410
411         match (&value_result, &type_result) {
412             (&Success(name_binding), _) if !name_binding.is_import() &&
413                                            directive.is_public &&
414                                            !name_binding.is_public() => {
415                 let msg = format!("`{}` is private, and cannot be reexported", source);
416                 let note_msg = format!("Consider marking `{}` as `pub` in the imported module",
417                                         source);
418                 struct_span_err!(self.resolver.session, directive.span, E0364, "{}", &msg)
419                     .span_note(directive.span, &note_msg)
420                     .emit();
421             }
422
423             (_, &Success(name_binding)) if !name_binding.is_import() && directive.is_public => {
424                 if !name_binding.is_public() {
425                     let msg = format!("`{}` is private, and cannot be reexported", source);
426                     let note_msg =
427                         format!("Consider declaring type or module `{}` with `pub`", source);
428                     struct_span_err!(self.resolver.session, directive.span, E0365, "{}", &msg)
429                         .span_note(directive.span, &note_msg)
430                         .emit();
431                 } else if name_binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
432                     let msg = format!("variant `{}` is private, and cannot be reexported \
433                                        (error E0364), consider declaring its enum as `pub`",
434                                        source);
435                     self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
436                                                    directive.id,
437                                                    directive.span,
438                                                    msg);
439                 }
440             }
441
442             _ => {}
443         }
444
445         for &(ns, result) in &[(ValueNS, &value_result), (TypeNS, &type_result)] {
446             if let Success(binding) = *result {
447                 if !binding.defined_with(DefModifiers::IMPORTABLE) {
448                     let msg = format!("`{}` is not directly importable", target);
449                     span_err!(self.resolver.session, directive.span, E0253, "{}", &msg);
450                 }
451
452                 self.define(module_, target, ns, directive.import(binding));
453             }
454         }
455
456         // Record what this import resolves to for later uses in documentation,
457         // this may resolve to either a value or a type, but for documentation
458         // purposes it's good enough to just favor one over the other.
459         module_.decrement_outstanding_references_for(target, ValueNS);
460         module_.decrement_outstanding_references_for(target, TypeNS);
461
462         let def_and_priv = |binding: &NameBinding| {
463             let def = binding.def().unwrap();
464             let last_private = if binding.is_public() { lp } else { DependsOn(def.def_id()) };
465             (def, last_private)
466         };
467         let value_def_and_priv = value_result.success().map(&def_and_priv);
468         let type_def_and_priv = type_result.success().map(&def_and_priv);
469
470         let import_lp = LastImport {
471             value_priv: value_def_and_priv.map(|(_, p)| p),
472             value_used: Used,
473             type_priv: type_def_and_priv.map(|(_, p)| p),
474             type_used: Used,
475         };
476
477         let write_path_resolution = |(def, _)| {
478             let path_resolution =
479                 PathResolution { base_def: def, last_private: import_lp, depth: 0 };
480             self.resolver.def_map.borrow_mut().insert(directive.id, path_resolution);
481         };
482         value_def_and_priv.map(&write_path_resolution);
483         type_def_and_priv.map(&write_path_resolution);
484
485         debug!("(resolving single import) successfully resolved import");
486         return Success(());
487     }
488
489     // Resolves a glob import. Note that this function cannot fail; it either
490     // succeeds or bails out (as importing * from an empty module or a module
491     // that exports nothing is valid). target_module is the module we are
492     // actually importing, i.e., `foo` in `use foo::*`.
493     fn resolve_glob_import(&mut self,
494                            module_: Module<'b>,
495                            target_module: Module<'b>,
496                            directive: &ImportDirective,
497                            lp: LastPrivate)
498                            -> ResolveResult<()> {
499         // We must bail out if the node has unresolved imports of any kind (including globs).
500         if target_module.pub_count.get() > 0 {
501             debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
502             return Indeterminate;
503         }
504
505         if module_.def_id() == target_module.def_id() {
506             // This means we are trying to glob import a module into itself, and it is a no-go
507             let msg = "Cannot glob-import a module into itself.".into();
508             return Failed(Some((directive.span, msg)));
509         }
510
511         // Add all children from the containing module.
512         build_reduced_graph::populate_module_if_necessary(self.resolver, target_module);
513         target_module.for_each_child(|name, ns, binding| {
514             if !binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { return }
515             if binding.is_extern_crate() { return }
516             self.define(module_, name, ns, directive.import(binding));
517
518             if ns == TypeNS && directive.is_public &&
519                binding.defined_with(DefModifiers::PRIVATE_VARIANT) {
520                 let msg = format!("variant `{}` is private, and cannot be reexported (error \
521                                    E0364), consider declaring its enum as `pub`", name);
522                 self.resolver.session.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
523                                                directive.id,
524                                                directive.span,
525                                                msg);
526             }
527         });
528
529         // Record the destination of this import
530         if let Some(did) = target_module.def_id() {
531             self.resolver.def_map.borrow_mut().insert(directive.id,
532                                                       PathResolution {
533                                                           base_def: Def::Mod(did),
534                                                           last_private: lp,
535                                                           depth: 0,
536                                                       });
537         }
538
539         debug!("(resolving glob import) successfully resolved import");
540         return Success(());
541     }
542
543     fn define(&mut self,
544               parent: Module<'b>,
545               name: Name,
546               ns: Namespace,
547               binding: NameBinding<'b>) {
548         let binding = self.resolver.new_name_binding(binding);
549         if let Err(old_binding) = parent.try_define_child(name, ns, binding) {
550             self.report_conflict(name, ns, binding, old_binding);
551         } else if binding.is_public() { // Add to the export map
552             if let (Some(parent_def_id), Some(def)) = (parent.def_id(), binding.def()) {
553                 let parent_node_id = self.resolver.ast_map.as_local_node_id(parent_def_id).unwrap();
554                 let export = Export { name: name, def_id: def.def_id() };
555                 self.resolver.export_map.entry(parent_node_id).or_insert(Vec::new()).push(export);
556             }
557         }
558     }
559
560     fn report_conflict(&mut self,
561                        name: Name,
562                        ns: Namespace,
563                        binding: &'b NameBinding<'b>,
564                        old_binding: &'b NameBinding<'b>) {
565         if old_binding.is_extern_crate() {
566             let msg = format!("import `{0}` conflicts with imported crate \
567                                in this module (maybe you meant `use {0}::*`?)",
568                               name);
569             span_err!(self.resolver.session, binding.span.unwrap(), E0254, "{}", &msg);
570         } else if old_binding.is_import() {
571             let ns_word = match (ns, old_binding.module()) {
572                 (ValueNS, _) => "value",
573                 (TypeNS, Some(module)) if module.is_normal() => "module",
574                 (TypeNS, Some(module)) if module.is_trait() => "trait",
575                 (TypeNS, _) => "type",
576             };
577             let mut err = struct_span_err!(self.resolver.session,
578                                            binding.span.unwrap(),
579                                            E0252,
580                                            "a {} named `{}` has already been imported \
581                                             in this module",
582                                            ns_word,
583                                            name);
584             err.span_note(old_binding.span.unwrap(),
585                           &format!("previous import of `{}` here", name));
586             err.emit();
587         } else if ns == ValueNS { // Check for item conflicts in the value namespace
588             let mut err = struct_span_err!(self.resolver.session,
589                                            binding.span.unwrap(),
590                                            E0255,
591                                            "import `{}` conflicts with value in this module",
592                                            name);
593             err.span_note(old_binding.span.unwrap(), "conflicting value here");
594             err.emit();
595         } else { // Check for item conflicts in the type namespace
596             let (what, note) = match old_binding.module() {
597                 Some(ref module) if module.is_normal() =>
598                     ("existing submodule", "note conflicting module here"),
599                 Some(ref module) if module.is_trait() =>
600                     ("trait in this module", "note conflicting trait here"),
601                 _ => ("type in this module", "note conflicting type here"),
602             };
603             let mut err = struct_span_err!(self.resolver.session,
604                                            binding.span.unwrap(),
605                                            E0256,
606                                            "import `{}` conflicts with {}",
607                                            name,
608                                            what);
609             err.span_note(old_binding.span.unwrap(), note);
610             err.emit();
611         }
612     }
613 }
614
615 fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
616     if names.is_empty() {
617         import_directive_subclass_to_string(subclass)
618     } else {
619         (format!("{}::{}",
620                  names_to_string(names),
621                  import_directive_subclass_to_string(subclass)))
622             .to_string()
623     }
624 }
625
626 fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
627     match subclass {
628         SingleImport(_, source) => source.to_string(),
629         GlobImport => "*".to_string(),
630     }
631 }
632
633 pub fn resolve_imports(resolver: &mut Resolver) {
634     let mut import_resolver = ImportResolver { resolver: resolver };
635     import_resolver.resolve_imports();
636 }