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.
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.
11 //! Reduced graph building
13 //! Here we build the "reduced graph": the graph of the module tree without
14 //! any imports resolved.
17 use resolve_imports::ImportDirective;
18 use resolve_imports::ImportDirectiveSubclass::{self, SingleImport, GlobImport};
20 use Namespace::{self, TypeNS, ValueNS};
21 use {NameBinding, NameBindingKind};
23 use ParentLink::{ModuleParentLink, BlockParentLink};
25 use resolve_imports::Shadowable;
26 use {resolve_error, resolve_struct_error, ResolutionError};
28 use rustc::middle::cstore::{CrateStore, ChildItem, DlDef, DlField, DlImpl};
29 use rustc::middle::def::*;
30 use rustc::middle::def_id::{CRATE_DEF_INDEX, DefId};
31 use rustc::middle::ty::VariantKind;
33 use syntax::ast::{Name, NodeId};
34 use syntax::attr::AttrMetaMethods;
35 use syntax::parse::token::special_idents;
36 use syntax::codemap::{Span, DUMMY_SP};
39 use rustc_front::hir::{Block, DeclItem};
40 use rustc_front::hir::{ForeignItem, ForeignItemFn, ForeignItemStatic};
41 use rustc_front::hir::{Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn};
42 use rustc_front::hir::{ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
43 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
44 use rustc_front::hir::{NamedField, PathListIdent, PathListMod};
45 use rustc_front::hir::StmtDecl;
46 use rustc_front::hir::UnnamedField;
47 use rustc_front::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
48 use rustc_front::hir::Visibility;
49 use rustc_front::intravisit::{self, Visitor};
51 use std::mem::replace;
52 use std::ops::{Deref, DerefMut};
54 struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
55 resolver: &'a mut Resolver<'b, 'tcx>,
58 impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
59 type Target = Resolver<'b, 'tcx>;
61 fn deref(&self) -> &Resolver<'b, 'tcx> {
66 impl<'a, 'b:'a, 'tcx:'b> DerefMut for GraphBuilder<'a, 'b, 'tcx> {
67 fn deref_mut(&mut self) -> &mut Resolver<'b, 'tcx> {
72 trait ToNameBinding<'a> {
73 fn to_name_binding(self) -> NameBinding<'a>;
76 impl<'a> ToNameBinding<'a> for (Module<'a>, Span) {
77 fn to_name_binding(self) -> NameBinding<'a> {
78 NameBinding::create_from_module(self.0, Some(self.1))
82 impl<'a> ToNameBinding<'a> for (Def, Span, DefModifiers) {
83 fn to_name_binding(self) -> NameBinding<'a> {
84 let kind = NameBindingKind::Def(self.0);
85 NameBinding { modifiers: self.2, kind: kind, span: Some(self.1) }
89 impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> {
90 /// Constructs the reduced graph for the entire crate.
91 fn build_reduced_graph(self, krate: &hir::Crate) {
92 let mut visitor = BuildReducedGraphVisitor {
93 parent: self.graph_root,
96 intravisit::walk_crate(&mut visitor, krate);
99 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined.
100 fn try_define<T>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T)
101 where T: ToNameBinding<'b>
103 let _ = parent.try_define_child(name, ns, self.new_name_binding(def.to_name_binding()));
106 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
107 /// otherwise, reports an error.
108 fn define<T: ToNameBinding<'b>>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T) {
109 let binding = self.new_name_binding(def.to_name_binding());
110 let old_binding = match parent.try_define_child(name, ns, binding) {
112 Err(old_binding) => old_binding,
115 let span = binding.span.unwrap_or(DUMMY_SP);
116 if !old_binding.is_extern_crate() && !binding.is_extern_crate() {
117 // Record an error here by looking up the namespace that had the duplicate
118 let ns_str = match ns { TypeNS => "type or module", ValueNS => "value" };
119 let resolution_error = ResolutionError::DuplicateDefinition(ns_str, name);
120 let mut err = resolve_struct_error(self, span, resolution_error);
122 if let Some(sp) = old_binding.span {
123 let note = format!("first definition of {} `{}` here", ns_str, name);
124 err.span_note(sp, ¬e);
127 } else if old_binding.is_extern_crate() && binding.is_extern_crate() {
128 span_err!(self.session,
131 "an external crate named `{}` has already been imported into this module",
134 span_err!(self.session,
137 "the name `{}` conflicts with an external crate \
138 that has been imported into this module",
143 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
144 fn is_item(statement: &hir::Stmt) -> bool {
145 if let StmtDecl(ref declaration, _) = statement.node {
146 if let DeclItem(_) = declaration.node {
153 // If any statements are items, we need to create an anonymous module
154 block.stmts.iter().any(is_item)
157 /// Constructs the reduced graph for one item.
158 fn build_reduced_graph_for_item(&mut self, item: &Item, parent: Module<'b>) -> Module<'b> {
159 let name = item.name;
161 let is_public = item.vis == hir::Public;
162 let modifiers = if is_public {
165 DefModifiers::empty()
166 } | DefModifiers::IMPORTABLE;
169 ItemUse(ref view_path) => {
170 // Extract and intern the module part of the path. For
171 // globs and lists, the path is found directly in the AST;
172 // for simple paths we have to munge the path a little.
173 let module_path = match view_path.node {
174 ViewPathSimple(_, ref full_path) => {
180 .map(|seg| seg.identifier.name)
184 ViewPathGlob(ref module_ident_path) |
185 ViewPathList(ref module_ident_path, _) => {
186 module_ident_path.segments
188 .map(|seg| seg.identifier.name)
193 // Build up the import directives.
194 let shadowable = item.attrs.iter().any(|attr| {
195 attr.name() == special_idents::prelude_import.name.as_str()
197 let shadowable = if shadowable {
203 match view_path.node {
204 ViewPathSimple(binding, ref full_path) => {
205 let source_name = full_path.segments.last().unwrap().identifier.name;
206 if source_name.as_str() == "mod" || source_name.as_str() == "self" {
209 ResolutionError::SelfImportsOnlyAllowedWithin);
212 let subclass = SingleImport(binding, source_name);
213 self.build_import_directive(parent,
221 ViewPathList(_, ref source_items) => {
222 // Make sure there's at most one `mod` import in the list.
223 let mod_spans = source_items.iter()
226 PathListMod { .. } => Some(item.span),
230 .collect::<Vec<Span>>();
231 if mod_spans.len() > 1 {
232 let mut e = resolve_struct_error(self,
234 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
235 for other_span in mod_spans.iter().skip(1) {
236 e.span_note(*other_span, "another `self` import appears here");
241 for source_item in source_items {
242 let (module_path, name, rename) = match source_item.node {
243 PathListIdent { name, rename, .. } =>
244 (module_path.clone(), name, rename.unwrap_or(name)),
245 PathListMod { rename, .. } => {
246 let name = match module_path.last() {
253 SelfImportOnlyInImportListWithNonEmptyPrefix
258 let module_path = module_path.split_last().unwrap().1;
259 let rename = rename.unwrap_or(name);
260 (module_path.to_vec(), name, rename)
263 self.build_import_directive(parent,
265 SingleImport(rename, name),
267 source_item.node.id(),
273 self.build_import_directive(parent,
285 ItemExternCrate(_) => {
286 // n.b. we don't need to look at the path option here, because cstore already
288 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
291 index: CRATE_DEF_INDEX,
293 self.external_exports.insert(def_id);
294 let parent_link = ModuleParentLink(parent, name);
295 let def = Def::Mod(def_id);
296 let external_module = self.new_extern_crate_module(parent_link, def);
297 self.define(parent, name, TypeNS, (external_module, sp));
299 self.build_reduced_graph_for_external_crate(external_module);
305 let parent_link = ModuleParentLink(parent, name);
306 let def = Def::Mod(self.ast_map.local_def_id(item.id));
307 let module = self.new_module(parent_link, Some(def), false, is_public);
308 self.define(parent, name, TypeNS, (module, sp));
309 parent.module_children.borrow_mut().insert(item.id, module);
313 ItemForeignMod(..) => parent,
315 // These items live in the value namespace.
316 ItemStatic(_, m, _) => {
317 let mutbl = m == hir::MutMutable;
318 let def = Def::Static(self.ast_map.local_def_id(item.id), mutbl);
319 self.define(parent, name, ValueNS, (def, sp, modifiers));
323 let def = Def::Const(self.ast_map.local_def_id(item.id));
324 self.define(parent, name, ValueNS, (def, sp, modifiers));
327 ItemFn(_, _, _, _, _, _) => {
328 let def = Def::Fn(self.ast_map.local_def_id(item.id));
329 self.define(parent, name, ValueNS, (def, sp, modifiers));
333 // These items live in the type namespace.
335 let parent_link = ModuleParentLink(parent, name);
336 let def = Def::TyAlias(self.ast_map.local_def_id(item.id));
337 let module = self.new_module(parent_link, Some(def), false, is_public);
338 self.define(parent, name, TypeNS, (module, sp));
342 ItemEnum(ref enum_definition, _) => {
343 let parent_link = ModuleParentLink(parent, name);
344 let def = Def::Enum(self.ast_map.local_def_id(item.id));
345 let module = self.new_module(parent_link, Some(def), false, is_public);
346 self.define(parent, name, TypeNS, (module, sp));
348 let variant_modifiers = if is_public {
349 DefModifiers::empty()
351 DefModifiers::PRIVATE_VARIANT
353 for variant in &(*enum_definition).variants {
354 let item_def_id = self.ast_map.local_def_id(item.id);
355 self.build_reduced_graph_for_variant(variant, item_def_id,
356 module, variant_modifiers);
361 // These items live in both the type and value namespaces.
362 ItemStruct(ref struct_def, _) => {
363 // Define a name in the type namespace.
364 let def = Def::Struct(self.ast_map.local_def_id(item.id));
365 self.define(parent, name, TypeNS, (def, sp, modifiers));
367 // If this is a newtype or unit-like struct, define a name
368 // in the value namespace as well
369 if !struct_def.is_struct() {
370 let def = Def::Struct(self.ast_map.local_def_id(struct_def.id()));
371 self.define(parent, name, ValueNS, (def, sp, modifiers));
374 // Record the def ID and fields of this struct.
375 let named_fields = struct_def.fields()
379 NamedField(name, _) => Some(name),
380 UnnamedField(_) => None,
384 let item_def_id = self.ast_map.local_def_id(item.id);
385 self.structs.insert(item_def_id, named_fields);
390 ItemDefaultImpl(_, _) |
391 ItemImpl(..) => parent,
393 ItemTrait(_, _, _, ref items) => {
394 let def_id = self.ast_map.local_def_id(item.id);
396 // Add all the items within to a new module.
397 let parent_link = ModuleParentLink(parent, name);
398 let def = Def::Trait(def_id);
399 let module_parent = self.new_module(parent_link, Some(def), false, is_public);
400 self.define(parent, name, TypeNS, (module_parent, sp));
402 // Add the names of all the items to the trait info.
404 let item_def_id = self.ast_map.local_def_id(item.id);
405 let (def, ns) = match item.node {
406 hir::ConstTraitItem(..) => (Def::AssociatedConst(item_def_id), ValueNS),
407 hir::MethodTraitItem(..) => (Def::Method(item_def_id), ValueNS),
408 hir::TypeTraitItem(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
411 let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
412 self.define(module_parent, item.name, ns, (def, item.span, modifiers));
414 self.trait_item_map.insert((item.name, def_id), item_def_id);
422 // Constructs the reduced graph for one variant. Variants exist in the
423 // type and value namespaces.
424 fn build_reduced_graph_for_variant(&mut self,
428 variant_modifiers: DefModifiers) {
429 let name = variant.node.name;
430 if variant.node.data.is_struct() {
431 // Not adding fields for variants as they are not accessed with a self receiver
432 let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
433 self.structs.insert(variant_def_id, Vec::new());
436 // Variants are always treated as importable to allow them to be glob used.
437 // All variants are defined in both type and value namespaces as future-proofing.
438 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers;
439 let def = Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id()));
441 self.define(parent, name, ValueNS, (def, variant.span, modifiers));
442 self.define(parent, name, TypeNS, (def, variant.span, modifiers));
445 /// Constructs the reduced graph for one foreign item.
446 fn build_reduced_graph_for_foreign_item(&mut self,
447 foreign_item: &ForeignItem,
448 parent: Module<'b>) {
449 let name = foreign_item.name;
450 let is_public = foreign_item.vis == hir::Public;
451 let modifiers = if is_public {
454 DefModifiers::empty()
455 } | DefModifiers::IMPORTABLE;
457 let def = match foreign_item.node {
458 ForeignItemFn(..) => {
459 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
461 ForeignItemStatic(_, m) => {
462 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
465 self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
468 fn build_reduced_graph_for_block(&mut self, block: &Block, parent: Module<'b>) -> Module<'b> {
469 if self.block_needs_anonymous_module(block) {
470 let block_id = block.id;
472 debug!("(building reduced graph for block) creating a new anonymous module for block \
476 let parent_link = BlockParentLink(parent, block_id);
477 let new_module = self.new_module(parent_link, None, false, false);
478 parent.module_children.borrow_mut().insert(block_id, new_module);
485 fn handle_external_def(&mut self,
490 new_parent: Module<'b>) {
491 debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
494 let is_public = vis == hir::Public;
496 let mut modifiers = DefModifiers::empty();
498 modifiers = modifiers | DefModifiers::PUBLIC;
500 if new_parent.is_normal() {
501 modifiers = modifiers | DefModifiers::IMPORTABLE;
504 let is_exported = is_public &&
505 match new_parent.def_id() {
507 Some(did) => self.external_exports.contains(&did),
510 self.external_exports.insert(def.def_id());
514 Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => {
515 debug!("(building reduced graph for external crate) building module {} {}",
518 let parent_link = ModuleParentLink(new_parent, name);
519 let module = self.new_module(parent_link, Some(def), true, is_public);
520 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
522 Def::Variant(_, variant_id) => {
523 debug!("(building reduced graph for external crate) building variant {}",
525 // Variants are always treated as importable to allow them to be glob used.
526 // All variants are defined in both type and value namespaces as future-proofing.
527 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
528 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
529 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
530 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
531 // Not adding fields for variants as they are not accessed with a self receiver
532 self.structs.insert(variant_id, Vec::new());
538 Def::AssociatedConst(..) |
540 debug!("(building reduced graph for external crate) building value (fn/static) {}",
542 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
544 Def::Trait(def_id) => {
545 debug!("(building reduced graph for external crate) building type {}",
548 // If this is a trait, add all the trait item names to the trait
551 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
552 for trait_item_def in &trait_item_def_ids {
553 let trait_item_name =
554 self.session.cstore.item_name(trait_item_def.def_id());
556 debug!("(building reduced graph for external crate) ... adding trait item \
560 self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
563 self.external_exports.insert(trait_item_def.def_id());
567 let parent_link = ModuleParentLink(new_parent, name);
568 let module = self.new_module(parent_link, Some(def), true, is_public);
569 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
571 Def::AssociatedTy(..) => {
572 debug!("(building reduced graph for external crate) building type {}",
574 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
577 if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
578 debug!("(building reduced graph for external crate) building type and value for \
581 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
582 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
583 let def = Def::Struct(ctor_def_id);
584 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
587 // Record the def ID and fields of this struct.
588 let fields = self.session.cstore.struct_field_names(def_id);
589 self.structs.insert(def_id, fields);
591 Def::Struct(..) => {}
599 panic!("didn't expect `{:?}`", def);
604 /// Builds the reduced graph for a single item in an external crate.
605 fn build_reduced_graph_for_external_crate_def(&mut self,
610 // Add the new child item, if necessary.
612 Def::ForeignMod(def_id) => {
613 // Foreign modules have no names. Recur and populate
615 for child in self.session.cstore.item_children(def_id) {
616 self.build_reduced_graph_for_external_crate_def(root, child)
620 self.handle_external_def(def,
622 &xcdef.name.as_str(),
629 debug!("(building reduced graph for external crate) ignoring impl");
632 debug!("(building reduced graph for external crate) ignoring field");
637 /// Builds the reduced graph rooted at the given external module.
638 fn populate_external_module(&mut self, module: Module<'b>) {
639 debug!("(populating external module) attempting to populate {}",
640 module_to_string(module));
642 let def_id = match module.def_id() {
644 debug!("(populating external module) ... no def ID!");
647 Some(def_id) => def_id,
650 for child in self.session.cstore.item_children(def_id) {
651 debug!("(populating external module) ... found ident: {}",
653 self.build_reduced_graph_for_external_crate_def(module, child);
655 module.populated.set(true)
658 /// Ensures that the reduced graph rooted at the given external module
659 /// is built, building it if it is not.
660 fn populate_module_if_necessary(&mut self, module: Module<'b>) {
661 if !module.populated.get() {
662 self.populate_external_module(module)
664 assert!(module.populated.get())
667 /// Builds the reduced graph rooted at the 'use' directive for an external
669 fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
670 let root_cnum = root.def_id().unwrap().krate;
671 for child in self.session.cstore.crate_top_level_items(root_cnum) {
672 self.build_reduced_graph_for_external_crate_def(root, child);
676 /// Creates and adds an import directive to the given module.
677 fn build_import_directive(&mut self,
679 module_path: Vec<Name>,
680 subclass: ImportDirectiveSubclass,
684 shadowable: Shadowable) {
685 module_.unresolved_imports
687 .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
688 self.unresolved_imports += 1;
691 module_.inc_pub_count();
694 // Bump the reference count on the name. Or, if this is a glob, set
695 // the appropriate flag.
698 SingleImport(target, _) => {
699 module_.increment_outstanding_references_for(target, ValueNS);
700 module_.increment_outstanding_references_for(target, TypeNS);
703 // Set the glob flag. This tells us that we don't know the
704 // module's exports ahead of time.
706 module_.inc_glob_count();
708 module_.inc_pub_glob_count();
715 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
716 builder: GraphBuilder<'a, 'b, 'tcx>,
720 impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
721 fn visit_nested_item(&mut self, item: hir::ItemId) {
722 self.visit_item(self.builder.resolver.ast_map.expect_item(item.id))
725 fn visit_item(&mut self, item: &Item) {
726 let p = self.builder.build_reduced_graph_for_item(item, &self.parent);
727 let old_parent = replace(&mut self.parent, p);
728 intravisit::walk_item(self, item);
729 self.parent = old_parent;
732 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
733 self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
736 fn visit_block(&mut self, block: &Block) {
737 let np = self.builder.build_reduced_graph_for_block(block, &self.parent);
738 let old_parent = replace(&mut self.parent, np);
739 intravisit::walk_block(self, block);
740 self.parent = old_parent;
744 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
745 GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
748 pub fn populate_module_if_necessary<'a, 'tcx>(resolver: &mut Resolver<'a, 'tcx>,
749 module: Module<'a>) {
750 GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);