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::{PathListIdent, PathListMod, StmtDecl};
45 use rustc_front::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
46 use rustc_front::hir::Visibility;
47 use rustc_front::intravisit::{self, Visitor};
49 use std::mem::replace;
50 use std::ops::{Deref, DerefMut};
52 struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
53 resolver: &'a mut Resolver<'b, 'tcx>,
56 impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
57 type Target = Resolver<'b, 'tcx>;
59 fn deref(&self) -> &Resolver<'b, 'tcx> {
64 impl<'a, 'b:'a, 'tcx:'b> DerefMut for GraphBuilder<'a, 'b, 'tcx> {
65 fn deref_mut(&mut self) -> &mut Resolver<'b, 'tcx> {
70 trait ToNameBinding<'a> {
71 fn to_name_binding(self) -> NameBinding<'a>;
74 impl<'a> ToNameBinding<'a> for (Module<'a>, Span) {
75 fn to_name_binding(self) -> NameBinding<'a> {
76 NameBinding::create_from_module(self.0, Some(self.1))
80 impl<'a> ToNameBinding<'a> for (Def, Span, DefModifiers) {
81 fn to_name_binding(self) -> NameBinding<'a> {
82 let kind = NameBindingKind::Def(self.0);
83 NameBinding { modifiers: self.2, kind: kind, span: Some(self.1) }
87 impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> {
88 /// Constructs the reduced graph for the entire crate.
89 fn build_reduced_graph(self, krate: &hir::Crate) {
90 let mut visitor = BuildReducedGraphVisitor {
91 parent: self.graph_root,
94 intravisit::walk_crate(&mut visitor, krate);
97 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined.
98 fn try_define<T>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T)
99 where T: ToNameBinding<'b>
101 let _ = parent.try_define_child(name, ns, self.new_name_binding(def.to_name_binding()));
104 /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
105 /// otherwise, reports an error.
106 fn define<T: ToNameBinding<'b>>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T) {
107 let binding = self.new_name_binding(def.to_name_binding());
108 let old_binding = match parent.try_define_child(name, ns, binding) {
110 Err(old_binding) => old_binding,
113 let span = binding.span.unwrap_or(DUMMY_SP);
114 if !old_binding.is_extern_crate() && !binding.is_extern_crate() {
115 // Record an error here by looking up the namespace that had the duplicate
116 let ns_str = match ns { TypeNS => "type or module", ValueNS => "value" };
117 let resolution_error = ResolutionError::DuplicateDefinition(ns_str, name);
118 let mut err = resolve_struct_error(self, span, resolution_error);
120 if let Some(sp) = old_binding.span {
121 let note = format!("first definition of {} `{}` here", ns_str, name);
122 err.span_note(sp, ¬e);
125 } else if old_binding.is_extern_crate() && binding.is_extern_crate() {
126 span_err!(self.session,
129 "an external crate named `{}` has already been imported into this module",
132 span_err!(self.session,
135 "the name `{}` conflicts with an external crate \
136 that has been imported into this module",
141 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
142 fn is_item(statement: &hir::Stmt) -> bool {
143 if let StmtDecl(ref declaration, _) = statement.node {
144 if let DeclItem(_) = declaration.node {
151 // If any statements are items, we need to create an anonymous module
152 block.stmts.iter().any(is_item)
155 /// Constructs the reduced graph for one item.
156 fn build_reduced_graph_for_item(&mut self, item: &Item, parent: Module<'b>) -> Module<'b> {
157 let name = item.name;
159 let is_public = item.vis == hir::Public;
160 let modifiers = if is_public {
163 DefModifiers::empty()
164 } | DefModifiers::IMPORTABLE;
167 ItemUse(ref view_path) => {
168 // Extract and intern the module part of the path. For
169 // globs and lists, the path is found directly in the AST;
170 // for simple paths we have to munge the path a little.
171 let module_path = match view_path.node {
172 ViewPathSimple(_, ref full_path) => {
178 .map(|seg| seg.identifier.name)
182 ViewPathGlob(ref module_ident_path) |
183 ViewPathList(ref module_ident_path, _) => {
184 module_ident_path.segments
186 .map(|seg| seg.identifier.name)
191 // Build up the import directives.
192 let shadowable = item.attrs.iter().any(|attr| {
193 attr.name() == special_idents::prelude_import.name.as_str()
195 let shadowable = if shadowable {
201 match view_path.node {
202 ViewPathSimple(binding, ref full_path) => {
203 let source_name = full_path.segments.last().unwrap().identifier.name;
204 if source_name.as_str() == "mod" || source_name.as_str() == "self" {
207 ResolutionError::SelfImportsOnlyAllowedWithin);
210 let subclass = ImportDirectiveSubclass::single(binding, source_name);
211 self.build_import_directive(parent,
219 ViewPathList(_, ref source_items) => {
220 // Make sure there's at most one `mod` import in the list.
221 let mod_spans = source_items.iter()
224 PathListMod { .. } => Some(item.span),
228 .collect::<Vec<Span>>();
229 if mod_spans.len() > 1 {
230 let mut e = resolve_struct_error(self,
232 ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
233 for other_span in mod_spans.iter().skip(1) {
234 e.span_note(*other_span, "another `self` import appears here");
239 for source_item in source_items {
240 let (module_path, name, rename) = match source_item.node {
241 PathListIdent { name, rename, .. } =>
242 (module_path.clone(), name, rename.unwrap_or(name)),
243 PathListMod { rename, .. } => {
244 let name = match module_path.last() {
251 SelfImportOnlyInImportListWithNonEmptyPrefix
256 let module_path = module_path.split_last().unwrap().1;
257 let rename = rename.unwrap_or(name);
258 (module_path.to_vec(), name, rename)
261 let subclass = ImportDirectiveSubclass::single(rename, name);
262 self.build_import_directive(parent,
266 source_item.node.id(),
272 self.build_import_directive(parent,
284 ItemExternCrate(_) => {
285 // n.b. we don't need to look at the path option here, because cstore already
287 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
290 index: CRATE_DEF_INDEX,
292 self.external_exports.insert(def_id);
293 let parent_link = ModuleParentLink(parent, name);
294 let def = Def::Mod(def_id);
295 let module = self.new_extern_crate_module(parent_link, def, is_public, item.id);
296 self.define(parent, name, TypeNS, (module, sp));
299 let export = Export { name: name, def_id: def_id };
300 if let Some(def_id) = parent.def_id() {
301 let node_id = self.resolver.ast_map.as_local_node_id(def_id).unwrap();
302 self.export_map.entry(node_id).or_insert(Vec::new()).push(export);
306 self.build_reduced_graph_for_external_crate(module);
312 let parent_link = ModuleParentLink(parent, name);
313 let def = Def::Mod(self.ast_map.local_def_id(item.id));
314 let module = self.new_module(parent_link, Some(def), false, is_public);
315 self.define(parent, name, TypeNS, (module, sp));
316 parent.module_children.borrow_mut().insert(item.id, module);
320 ItemForeignMod(..) => parent,
322 // These items live in the value namespace.
323 ItemStatic(_, m, _) => {
324 let mutbl = m == hir::MutMutable;
325 let def = Def::Static(self.ast_map.local_def_id(item.id), mutbl);
326 self.define(parent, name, ValueNS, (def, sp, modifiers));
330 let def = Def::Const(self.ast_map.local_def_id(item.id));
331 self.define(parent, name, ValueNS, (def, sp, modifiers));
334 ItemFn(_, _, _, _, _, _) => {
335 let def = Def::Fn(self.ast_map.local_def_id(item.id));
336 self.define(parent, name, ValueNS, (def, sp, modifiers));
340 // These items live in the type namespace.
342 let parent_link = ModuleParentLink(parent, name);
343 let def = Def::TyAlias(self.ast_map.local_def_id(item.id));
344 let module = self.new_module(parent_link, Some(def), false, is_public);
345 self.define(parent, name, TypeNS, (module, sp));
349 ItemEnum(ref enum_definition, _) => {
350 let parent_link = ModuleParentLink(parent, name);
351 let def = Def::Enum(self.ast_map.local_def_id(item.id));
352 let module = self.new_module(parent_link, Some(def), false, is_public);
353 self.define(parent, name, TypeNS, (module, sp));
355 let variant_modifiers = if is_public {
356 DefModifiers::empty()
358 DefModifiers::PRIVATE_VARIANT
360 for variant in &(*enum_definition).variants {
361 let item_def_id = self.ast_map.local_def_id(item.id);
362 self.build_reduced_graph_for_variant(variant, item_def_id,
363 module, variant_modifiers);
368 // These items live in both the type and value namespaces.
369 ItemStruct(ref struct_def, _) => {
370 // Define a name in the type namespace.
371 let def = Def::Struct(self.ast_map.local_def_id(item.id));
372 self.define(parent, name, TypeNS, (def, sp, modifiers));
374 // If this is a newtype or unit-like struct, define a name
375 // in the value namespace as well
376 if !struct_def.is_struct() {
377 let def = Def::Struct(self.ast_map.local_def_id(struct_def.id()));
378 self.define(parent, name, ValueNS, (def, sp, modifiers));
381 // Record the def ID and fields of this struct.
382 let field_names = struct_def.fields()
386 let item_def_id = self.ast_map.local_def_id(item.id);
387 self.structs.insert(item_def_id, field_names);
392 ItemDefaultImpl(_, _) |
393 ItemImpl(..) => parent,
395 ItemTrait(_, _, _, ref items) => {
396 let def_id = self.ast_map.local_def_id(item.id);
398 // Add all the items within to a new module.
399 let parent_link = ModuleParentLink(parent, name);
400 let def = Def::Trait(def_id);
401 let module_parent = self.new_module(parent_link, Some(def), false, is_public);
402 self.define(parent, name, TypeNS, (module_parent, sp));
404 // Add the names of all the items to the trait info.
406 let item_def_id = self.ast_map.local_def_id(item.id);
407 let (def, ns) = match item.node {
408 hir::ConstTraitItem(..) => (Def::AssociatedConst(item_def_id), ValueNS),
409 hir::MethodTraitItem(..) => (Def::Method(item_def_id), ValueNS),
410 hir::TypeTraitItem(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
413 let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
414 self.define(module_parent, item.name, ns, (def, item.span, modifiers));
416 self.trait_item_map.insert((item.name, def_id), item_def_id);
424 // Constructs the reduced graph for one variant. Variants exist in the
425 // type and value namespaces.
426 fn build_reduced_graph_for_variant(&mut self,
430 variant_modifiers: DefModifiers) {
431 let name = variant.node.name;
432 if variant.node.data.is_struct() {
433 // Not adding fields for variants as they are not accessed with a self receiver
434 let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
435 self.structs.insert(variant_def_id, Vec::new());
438 // Variants are always treated as importable to allow them to be glob used.
439 // All variants are defined in both type and value namespaces as future-proofing.
440 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers;
441 let def = Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id()));
443 self.define(parent, name, ValueNS, (def, variant.span, modifiers));
444 self.define(parent, name, TypeNS, (def, variant.span, modifiers));
447 /// Constructs the reduced graph for one foreign item.
448 fn build_reduced_graph_for_foreign_item(&mut self,
449 foreign_item: &ForeignItem,
450 parent: Module<'b>) {
451 let name = foreign_item.name;
452 let is_public = foreign_item.vis == hir::Public;
453 let modifiers = if is_public {
456 DefModifiers::empty()
457 } | DefModifiers::IMPORTABLE;
459 let def = match foreign_item.node {
460 ForeignItemFn(..) => {
461 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
463 ForeignItemStatic(_, m) => {
464 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
467 self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
470 fn build_reduced_graph_for_block(&mut self, block: &Block, parent: Module<'b>) -> Module<'b> {
471 if self.block_needs_anonymous_module(block) {
472 let block_id = block.id;
474 debug!("(building reduced graph for block) creating a new anonymous module for block \
478 let parent_link = BlockParentLink(parent, block_id);
479 let new_module = self.new_module(parent_link, None, false, false);
480 parent.module_children.borrow_mut().insert(block_id, new_module);
487 fn handle_external_def(&mut self,
492 new_parent: Module<'b>) {
493 debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
496 let is_public = vis == hir::Public || new_parent.is_trait();
498 let mut modifiers = DefModifiers::empty();
500 modifiers = modifiers | DefModifiers::PUBLIC;
502 if new_parent.is_normal() {
503 modifiers = modifiers | DefModifiers::IMPORTABLE;
506 let is_exported = is_public &&
507 match new_parent.def_id() {
509 Some(did) => self.external_exports.contains(&did),
512 self.external_exports.insert(def.def_id());
516 Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => {
517 debug!("(building reduced graph for external crate) building module {} {}",
520 let parent_link = ModuleParentLink(new_parent, name);
521 let module = self.new_module(parent_link, Some(def), true, is_public);
522 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
524 Def::Variant(_, variant_id) => {
525 debug!("(building reduced graph for external crate) building variant {}",
527 // Variants are always treated as importable to allow them to be glob used.
528 // All variants are defined in both type and value namespaces as future-proofing.
529 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
530 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
531 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
532 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
533 // Not adding fields for variants as they are not accessed with a self receiver
534 self.structs.insert(variant_id, Vec::new());
540 Def::AssociatedConst(..) |
542 debug!("(building reduced graph for external crate) building value (fn/static) {}",
544 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
546 Def::Trait(def_id) => {
547 debug!("(building reduced graph for external crate) building type {}",
550 // If this is a trait, add all the trait item names to the trait
553 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
554 for trait_item_def in &trait_item_def_ids {
555 let trait_item_name =
556 self.session.cstore.item_name(trait_item_def.def_id());
558 debug!("(building reduced graph for external crate) ... adding trait item \
562 self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
565 self.external_exports.insert(trait_item_def.def_id());
569 let parent_link = ModuleParentLink(new_parent, name);
570 let module = self.new_module(parent_link, Some(def), true, is_public);
571 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
573 Def::AssociatedTy(..) => {
574 debug!("(building reduced graph for external crate) building type {}",
576 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
579 if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
580 debug!("(building reduced graph for external crate) building type and value for \
583 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
584 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
585 let def = Def::Struct(ctor_def_id);
586 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
589 // Record the def ID and fields of this struct.
590 let fields = self.session.cstore.struct_field_names(def_id);
591 self.structs.insert(def_id, fields);
593 Def::Struct(..) => {}
601 panic!("didn't expect `{:?}`", def);
606 /// Builds the reduced graph for a single item in an external crate.
607 fn build_reduced_graph_for_external_crate_def(&mut self,
612 // Add the new child item, if necessary.
614 Def::ForeignMod(def_id) => {
615 // Foreign modules have no names. Recur and populate
617 for child in self.session.cstore.item_children(def_id) {
618 self.build_reduced_graph_for_external_crate_def(root, child)
622 self.handle_external_def(def,
624 &xcdef.name.as_str(),
631 debug!("(building reduced graph for external crate) ignoring impl");
634 debug!("(building reduced graph for external crate) ignoring field");
639 /// Builds the reduced graph rooted at the given external module.
640 fn populate_external_module(&mut self, module: Module<'b>) {
641 debug!("(populating external module) attempting to populate {}",
642 module_to_string(module));
644 let def_id = match module.def_id() {
646 debug!("(populating external module) ... no def ID!");
649 Some(def_id) => def_id,
652 for child in self.session.cstore.item_children(def_id) {
653 debug!("(populating external module) ... found ident: {}",
655 self.build_reduced_graph_for_external_crate_def(module, child);
657 module.populated.set(true)
660 /// Ensures that the reduced graph rooted at the given external module
661 /// is built, building it if it is not.
662 fn populate_module_if_necessary(&mut self, module: Module<'b>) {
663 if !module.populated.get() {
664 self.populate_external_module(module)
666 assert!(module.populated.get())
669 /// Builds the reduced graph rooted at the 'use' directive for an external
671 fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
672 let root_cnum = root.def_id().unwrap().krate;
673 for child in self.session.cstore.crate_top_level_items(root_cnum) {
674 self.build_reduced_graph_for_external_crate_def(root, child);
678 /// Creates and adds an import directive to the given module.
679 fn build_import_directive(&mut self,
681 module_path: Vec<Name>,
682 subclass: ImportDirectiveSubclass,
686 shadowable: Shadowable) {
688 module_.inc_pub_count();
691 // Bump the reference count on the name. Or, if this is a glob, set
692 // the appropriate flag.
695 SingleImport { target, .. } => {
696 module_.increment_outstanding_references_for(target, ValueNS);
697 module_.increment_outstanding_references_for(target, TypeNS);
700 // Set the glob flag. This tells us that we don't know the
701 // module's exports ahead of time.
703 module_.inc_glob_count();
705 module_.inc_pub_glob_count();
711 ImportDirective::new(module_path, subclass, span, id, is_public, shadowable);
712 let directive = self.resolver.arenas.alloc_import_directive(directive);
713 module_.unresolved_imports.borrow_mut().push(directive);
714 self.unresolved_imports += 1;
718 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
719 builder: GraphBuilder<'a, 'b, 'tcx>,
723 impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
724 fn visit_nested_item(&mut self, item: hir::ItemId) {
725 self.visit_item(self.builder.resolver.ast_map.expect_item(item.id))
728 fn visit_item(&mut self, item: &Item) {
729 let p = self.builder.build_reduced_graph_for_item(item, &self.parent);
730 let old_parent = replace(&mut self.parent, p);
731 intravisit::walk_item(self, item);
732 self.parent = old_parent;
735 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
736 self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
739 fn visit_block(&mut self, block: &Block) {
740 let np = self.builder.build_reduced_graph_for_block(block, &self.parent);
741 let old_parent = replace(&mut self.parent, np);
742 intravisit::walk_block(self, block);
743 self.parent = old_parent;
747 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
748 GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
751 pub fn populate_module_if_necessary<'a, 'tcx>(resolver: &mut Resolver<'a, 'tcx>,
752 module: Module<'a>) {
753 GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);