]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Rollup merge of #36147 - mikhail-m1:master, r=jonathandturner
[rust.git] / src / librustc_resolve / build_reduced_graph.rs
1 // Copyright 2012-2014 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 //! Reduced graph building
12 //!
13 //! Here we build the "reduced graph": the graph of the module tree without
14 //! any imports resolved.
15
16 use resolve_imports::ImportDirectiveSubclass::{self, GlobImport};
17 use Module;
18 use Namespace::{self, TypeNS, ValueNS};
19 use {NameBinding, NameBindingKind, ToNameBinding};
20 use ParentLink::{ModuleParentLink, BlockParentLink};
21 use Resolver;
22 use {resolve_error, resolve_struct_error, ResolutionError};
23
24 use rustc::middle::cstore::{ChildItem, DlDef};
25 use rustc::hir::def::*;
26 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
27 use rustc::ty::{self, VariantKind};
28
29 use syntax::ast::Name;
30 use syntax::attr;
31 use syntax::parse::token;
32
33 use syntax::ast::{Block, Crate};
34 use syntax::ast::{ForeignItem, ForeignItemKind, Item, ItemKind};
35 use syntax::ast::{Mutability, StmtKind, TraitItemKind};
36 use syntax::ast::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
37 use syntax::parse::token::keywords;
38 use syntax::visit::{self, Visitor};
39
40 use syntax_pos::{Span, DUMMY_SP};
41
42 impl<'a> ToNameBinding<'a> for (Module<'a>, Span, ty::Visibility) {
43     fn to_name_binding(self) -> NameBinding<'a> {
44         NameBinding { kind: NameBindingKind::Module(self.0), span: self.1, vis: self.2 }
45     }
46 }
47
48 impl<'a> ToNameBinding<'a> for (Def, Span, ty::Visibility) {
49     fn to_name_binding(self) -> NameBinding<'a> {
50         NameBinding { kind: NameBindingKind::Def(self.0), span: self.1, vis: self.2 }
51     }
52 }
53
54 impl<'b> Resolver<'b> {
55     /// Constructs the reduced graph for the entire crate.
56     pub fn build_reduced_graph(&mut self, krate: &Crate) {
57         let no_implicit_prelude = attr::contains_name(&krate.attrs, "no_implicit_prelude");
58         self.graph_root.no_implicit_prelude.set(no_implicit_prelude);
59         visit::walk_crate(&mut BuildReducedGraphVisitor { resolver: self }, krate);
60     }
61
62     /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
63     /// otherwise, reports an error.
64     fn define<T>(&mut self, parent: Module<'b>, name: Name, ns: Namespace, def: T)
65         where T: ToNameBinding<'b>,
66     {
67         let binding = def.to_name_binding();
68         if let Err(old_binding) = self.try_define(parent, name, ns, binding.clone()) {
69             self.report_conflict(parent, name, ns, old_binding, &binding);
70         }
71     }
72
73     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
74         // If any statements are items, we need to create an anonymous module
75         block.stmts.iter().any(|statement| match statement.node {
76             StmtKind::Item(_) => true,
77             _ => false,
78         })
79     }
80
81     /// Constructs the reduced graph for one item.
82     fn build_reduced_graph_for_item(&mut self, item: &Item) {
83         let parent = self.current_module;
84         let parent_vis = self.current_vis;
85         let name = item.ident.name;
86         let sp = item.span;
87         let vis = self.resolve_visibility(&item.vis);
88
89         match item.node {
90             ItemKind::Use(ref view_path) => {
91                 // Extract and intern the module part of the path. For
92                 // globs and lists, the path is found directly in the AST;
93                 // for simple paths we have to munge the path a little.
94                 let module_path: Vec<Name> = match view_path.node {
95                     ViewPathSimple(_, ref full_path) => {
96                         full_path.segments
97                                  .split_last()
98                                  .unwrap()
99                                  .1
100                                  .iter()
101                                  .map(|seg| seg.identifier.name)
102                                  .collect()
103                     }
104
105                     ViewPathGlob(ref module_ident_path) |
106                     ViewPathList(ref module_ident_path, _) => {
107                         module_ident_path.segments
108                                          .iter()
109                                          .map(|seg| seg.identifier.name)
110                                          .collect()
111                     }
112                 };
113
114                 // Build up the import directives.
115                 let is_prelude = attr::contains_name(&item.attrs, "prelude_import");
116
117                 match view_path.node {
118                     ViewPathSimple(binding, ref full_path) => {
119                         let source_name = full_path.segments.last().unwrap().identifier.name;
120                         if source_name.as_str() == "mod" || source_name.as_str() == "self" {
121                             resolve_error(self,
122                                           view_path.span,
123                                           ResolutionError::SelfImportsOnlyAllowedWithin);
124                         }
125
126                         let subclass = ImportDirectiveSubclass::single(binding.name, source_name);
127                         let span = view_path.span;
128                         self.add_import_directive(module_path, subclass, span, item.id, vis);
129                     }
130                     ViewPathList(_, ref source_items) => {
131                         // Make sure there's at most one `mod` import in the list.
132                         let mod_spans = source_items.iter().filter_map(|item| {
133                             if item.node.name.name == keywords::SelfValue.name() {
134                                 Some(item.span)
135                             } else {
136                                 None
137                             }
138                         }).collect::<Vec<Span>>();
139
140                         if mod_spans.len() > 1 {
141                             let mut e = resolve_struct_error(self,
142                                           mod_spans[0],
143                                           ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
144                             for other_span in mod_spans.iter().skip(1) {
145                                 e.span_note(*other_span, "another `self` import appears here");
146                             }
147                             e.emit();
148                         }
149
150                         for source_item in source_items {
151                             let node = source_item.node;
152                             let (module_path, name, rename) = {
153                                 if node.name.name != keywords::SelfValue.name() {
154                                     let rename = node.rename.unwrap_or(node.name).name;
155                                     (module_path.clone(), node.name.name, rename)
156                                 } else {
157                                     let name = match module_path.last() {
158                                         Some(name) => *name,
159                                         None => {
160                                             resolve_error(
161                                                 self,
162                                                 source_item.span,
163                                                 ResolutionError::
164                                                 SelfImportOnlyInImportListWithNonEmptyPrefix
165                                             );
166                                             continue;
167                                         }
168                                     };
169                                     let module_path = module_path.split_last().unwrap().1;
170                                     let rename = node.rename.map(|i| i.name).unwrap_or(name);
171                                     (module_path.to_vec(), name, rename)
172                                 }
173                             };
174                             let subclass = ImportDirectiveSubclass::single(rename, name);
175                             let (span, id) = (source_item.span, source_item.node.id);
176                             self.add_import_directive(module_path, subclass, span, id, vis);
177                         }
178                     }
179                     ViewPathGlob(_) => {
180                         let subclass = GlobImport { is_prelude: is_prelude };
181                         let span = view_path.span;
182                         self.add_import_directive(module_path, subclass, span, item.id, vis);
183                     }
184                 }
185             }
186
187             ItemKind::ExternCrate(_) => {
188                 // n.b. we don't need to look at the path option here, because cstore already
189                 // did
190                 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
191                     let def_id = DefId {
192                         krate: crate_id,
193                         index: CRATE_DEF_INDEX,
194                     };
195                     let parent_link = ModuleParentLink(parent, name);
196                     let def = Def::Mod(def_id);
197                     let module = self.new_extern_crate_module(parent_link, def, item.id);
198                     self.define(parent, name, TypeNS, (module, sp, vis));
199
200                     self.build_reduced_graph_for_external_crate(module);
201                 }
202             }
203
204             ItemKind::Mod(..) => {
205                 let parent_link = ModuleParentLink(parent, name);
206                 let def = Def::Mod(self.definitions.local_def_id(item.id));
207                 let module = self.new_module(parent_link, Some(def), false);
208                 module.no_implicit_prelude.set({
209                     parent.no_implicit_prelude.get() ||
210                         attr::contains_name(&item.attrs, "no_implicit_prelude")
211                 });
212                 self.define(parent, name, TypeNS, (module, sp, vis));
213                 self.module_map.insert(item.id, module);
214
215                 // Descend into the module.
216                 self.current_module = module;
217                 self.current_vis = ty::Visibility::Restricted(item.id);
218             }
219
220             ItemKind::ForeignMod(..) => {}
221
222             // These items live in the value namespace.
223             ItemKind::Static(_, m, _) => {
224                 let mutbl = m == Mutability::Mutable;
225                 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
226                 self.define(parent, name, ValueNS, (def, sp, vis));
227             }
228             ItemKind::Const(_, _) => {
229                 let def = Def::Const(self.definitions.local_def_id(item.id));
230                 self.define(parent, name, ValueNS, (def, sp, vis));
231             }
232             ItemKind::Fn(_, _, _, _, _, _) => {
233                 let def = Def::Fn(self.definitions.local_def_id(item.id));
234                 self.define(parent, name, ValueNS, (def, sp, vis));
235             }
236
237             // These items live in the type namespace.
238             ItemKind::Ty(..) => {
239                 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
240                 self.define(parent, name, TypeNS, (def, sp, vis));
241             }
242
243             ItemKind::Enum(ref enum_definition, _) => {
244                 let parent_link = ModuleParentLink(parent, name);
245                 let def = Def::Enum(self.definitions.local_def_id(item.id));
246                 let module = self.new_module(parent_link, Some(def), false);
247                 self.define(parent, name, TypeNS, (module, sp, vis));
248
249                 for variant in &(*enum_definition).variants {
250                     let item_def_id = self.definitions.local_def_id(item.id);
251                     self.build_reduced_graph_for_variant(variant, item_def_id, module, vis);
252                 }
253             }
254
255             // These items live in both the type and value namespaces.
256             ItemKind::Struct(ref struct_def, _) => {
257                 // Define a name in the type namespace.
258                 let def = Def::Struct(self.definitions.local_def_id(item.id));
259                 self.define(parent, name, TypeNS, (def, sp, vis));
260
261                 // If this is a newtype or unit-like struct, define a name
262                 // in the value namespace as well
263                 if !struct_def.is_struct() {
264                     let def = Def::Struct(self.definitions.local_def_id(struct_def.id()));
265                     self.define(parent, name, ValueNS, (def, sp, vis));
266                 }
267
268                 // Record the def ID and fields of this struct.
269                 let field_names = struct_def.fields().iter().enumerate().map(|(index, field)| {
270                     self.resolve_visibility(&field.vis);
271                     field.ident.map(|ident| ident.name)
272                                .unwrap_or_else(|| token::intern(&index.to_string()))
273                 }).collect();
274                 let item_def_id = self.definitions.local_def_id(item.id);
275                 self.structs.insert(item_def_id, field_names);
276             }
277
278             ItemKind::Union(..) => panic!("`union` is not yet implemented"),
279
280             ItemKind::DefaultImpl(_, _) | ItemKind::Impl(..) => {}
281
282             ItemKind::Trait(_, _, _, ref items) => {
283                 let def_id = self.definitions.local_def_id(item.id);
284
285                 // Add all the items within to a new module.
286                 let parent_link = ModuleParentLink(parent, name);
287                 let def = Def::Trait(def_id);
288                 let module_parent = self.new_module(parent_link, Some(def), false);
289                 self.define(parent, name, TypeNS, (module_parent, sp, vis));
290
291                 // Add the names of all the items to the trait info.
292                 for item in items {
293                     let item_def_id = self.definitions.local_def_id(item.id);
294                     let mut is_static_method = false;
295                     let (def, ns) = match item.node {
296                         TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
297                         TraitItemKind::Method(ref sig, _) => {
298                             is_static_method = !sig.decl.has_self();
299                             (Def::Method(item_def_id), ValueNS)
300                         }
301                         TraitItemKind::Type(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
302                         TraitItemKind::Macro(_) => panic!("unexpanded macro in resolve!"),
303                     };
304
305                     self.define(module_parent, item.ident.name, ns, (def, item.span, vis));
306
307                     self.trait_item_map.insert((item.ident.name, def_id), is_static_method);
308                 }
309             }
310             ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
311         }
312
313         visit::walk_item(&mut BuildReducedGraphVisitor { resolver: self }, item);
314         self.current_module = parent;
315         self.current_vis = parent_vis;
316     }
317
318     // Constructs the reduced graph for one variant. Variants exist in the
319     // type and value namespaces.
320     fn build_reduced_graph_for_variant(&mut self,
321                                        variant: &Variant,
322                                        item_id: DefId,
323                                        parent: Module<'b>,
324                                        vis: ty::Visibility) {
325         let name = variant.node.name.name;
326         if variant.node.data.is_struct() {
327             // Not adding fields for variants as they are not accessed with a self receiver
328             let variant_def_id = self.definitions.local_def_id(variant.node.data.id());
329             self.structs.insert(variant_def_id, Vec::new());
330         }
331
332         // Variants are always treated as importable to allow them to be glob used.
333         // All variants are defined in both type and value namespaces as future-proofing.
334         let def = Def::Variant(item_id, self.definitions.local_def_id(variant.node.data.id()));
335         self.define(parent, name, ValueNS, (def, variant.span, vis));
336         self.define(parent, name, TypeNS, (def, variant.span, vis));
337     }
338
339     /// Constructs the reduced graph for one foreign item.
340     fn build_reduced_graph_for_foreign_item(&mut self, foreign_item: &ForeignItem) {
341         let parent = self.current_module;
342         let name = foreign_item.ident.name;
343
344         let def = match foreign_item.node {
345             ForeignItemKind::Fn(..) => {
346                 Def::Fn(self.definitions.local_def_id(foreign_item.id))
347             }
348             ForeignItemKind::Static(_, m) => {
349                 Def::Static(self.definitions.local_def_id(foreign_item.id), m)
350             }
351         };
352         let vis = self.resolve_visibility(&foreign_item.vis);
353         self.define(parent, name, ValueNS, (def, foreign_item.span, vis));
354     }
355
356     fn build_reduced_graph_for_block(&mut self, block: &Block) {
357         let parent = self.current_module;
358         if self.block_needs_anonymous_module(block) {
359             let block_id = block.id;
360
361             debug!("(building reduced graph for block) creating a new anonymous module for block \
362                     {}",
363                    block_id);
364
365             let parent_link = BlockParentLink(parent, block_id);
366             let new_module = self.new_module(parent_link, None, false);
367             self.module_map.insert(block_id, new_module);
368             self.current_module = new_module; // Descend into the block.
369         }
370
371         visit::walk_block(&mut BuildReducedGraphVisitor { resolver: self }, block);
372         self.current_module = parent;
373     }
374
375     /// Builds the reduced graph for a single item in an external crate.
376     fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'b>, xcdef: ChildItem) {
377         let def = match xcdef.def {
378             DlDef(def) => def,
379             _ => return,
380         };
381
382         if let Def::ForeignMod(def_id) = def {
383             // Foreign modules have no names. Recur and populate eagerly.
384             for child in self.session.cstore.item_children(def_id) {
385                 self.build_reduced_graph_for_external_crate_def(parent, child);
386             }
387             return;
388         }
389
390         let name = xcdef.name;
391         let vis = if parent.is_trait() { ty::Visibility::Public } else { xcdef.vis };
392
393         match def {
394             Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) => {
395                 debug!("(building reduced graph for external crate) building module {} {:?}",
396                        name, vis);
397                 let parent_link = ModuleParentLink(parent, name);
398                 let module = self.new_module(parent_link, Some(def), true);
399                 let _ = self.try_define(parent, name, TypeNS, (module, DUMMY_SP, vis));
400             }
401             Def::Variant(_, variant_id) => {
402                 debug!("(building reduced graph for external crate) building variant {}", name);
403                 // Variants are always treated as importable to allow them to be glob used.
404                 // All variants are defined in both type and value namespaces as future-proofing.
405                 let _ = self.try_define(parent, name, TypeNS, (def, DUMMY_SP, vis));
406                 let _ = self.try_define(parent, name, ValueNS, (def, DUMMY_SP, vis));
407                 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
408                     // Not adding fields for variants as they are not accessed with a self receiver
409                     self.structs.insert(variant_id, Vec::new());
410                 }
411             }
412             Def::Fn(..) |
413             Def::Static(..) |
414             Def::Const(..) |
415             Def::AssociatedConst(..) |
416             Def::Method(..) => {
417                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
418                        name);
419                 let _ = self.try_define(parent, name, ValueNS, (def, DUMMY_SP, vis));
420             }
421             Def::Trait(def_id) => {
422                 debug!("(building reduced graph for external crate) building type {}", name);
423
424                 // If this is a trait, add all the trait item names to the trait
425                 // info.
426
427                 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
428                 for trait_item_def in &trait_item_def_ids {
429                     let trait_item_name =
430                         self.session.cstore.item_name(trait_item_def.def_id());
431
432                     debug!("(building reduced graph for external crate) ... adding trait item \
433                             '{}'",
434                            trait_item_name);
435
436                     self.trait_item_map.insert((trait_item_name, def_id), false);
437                 }
438
439                 let parent_link = ModuleParentLink(parent, name);
440                 let module = self.new_module(parent_link, Some(def), true);
441                 let _ = self.try_define(parent, name, TypeNS, (module, DUMMY_SP, vis));
442             }
443             Def::TyAlias(..) | Def::AssociatedTy(..) => {
444                 debug!("(building reduced graph for external crate) building type {}", name);
445                 let _ = self.try_define(parent, name, TypeNS, (def, DUMMY_SP, vis));
446             }
447             Def::Struct(def_id)
448                 if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
449                 debug!("(building reduced graph for external crate) building type and value for {}",
450                        name);
451                 let _ = self.try_define(parent, name, TypeNS, (def, DUMMY_SP, vis));
452                 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
453                     let def = Def::Struct(ctor_def_id);
454                     let _ = self.try_define(parent, name, ValueNS, (def, DUMMY_SP, vis));
455                 }
456
457                 // Record the def ID and fields of this struct.
458                 let fields = self.session.cstore.struct_field_names(def_id);
459                 self.structs.insert(def_id, fields);
460             }
461             Def::Struct(..) => {}
462             Def::Local(..) |
463             Def::PrimTy(..) |
464             Def::TyParam(..) |
465             Def::Upvar(..) |
466             Def::Label(..) |
467             Def::SelfTy(..) |
468             Def::Err => {
469                 bug!("didn't expect `{:?}`", def);
470             }
471         }
472     }
473
474     /// Builds the reduced graph rooted at the 'use' directive for an external
475     /// crate.
476     fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
477         let root_cnum = root.def_id().unwrap().krate;
478         for child in self.session.cstore.crate_top_level_items(root_cnum) {
479             self.build_reduced_graph_for_external_crate_def(root, child);
480         }
481     }
482
483     /// Ensures that the reduced graph rooted at the given external module
484     /// is built, building it if it is not.
485     pub fn populate_module_if_necessary(&mut self, module: Module<'b>) {
486         if module.populated.get() { return }
487         for child in self.session.cstore.item_children(module.def_id().unwrap()) {
488             self.build_reduced_graph_for_external_crate_def(module, child);
489         }
490         module.populated.set(true)
491     }
492 }
493
494 struct BuildReducedGraphVisitor<'a, 'b: 'a> {
495     resolver: &'a mut Resolver<'b>,
496 }
497
498 impl<'a, 'b> Visitor for BuildReducedGraphVisitor<'a, 'b> {
499     fn visit_item(&mut self, item: &Item) {
500         self.resolver.build_reduced_graph_for_item(item);
501     }
502
503     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
504         self.resolver.build_reduced_graph_for_foreign_item(foreign_item);
505     }
506
507     fn visit_block(&mut self, block: &Block) {
508         self.resolver.build_reduced_graph_for_block(block);
509     }
510 }