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 = SingleImport(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 self.build_import_directive(parent,
263 SingleImport(rename, name),
265 source_item.node.id(),
271 self.build_import_directive(parent,
283 ItemExternCrate(_) => {
284 // n.b. we don't need to look at the path option here, because cstore already
286 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
289 index: CRATE_DEF_INDEX,
291 self.external_exports.insert(def_id);
292 let parent_link = ModuleParentLink(parent, name);
293 let def = Def::Mod(def_id);
294 let local_def_id = self.ast_map.local_def_id(item.id);
295 let external_module =
296 self.new_extern_crate_module(parent_link, def, is_public, local_def_id);
297 self.define(parent, name, TypeNS, (external_module, sp));
300 let export = Export { name: name, def_id: def_id };
301 if let Some(def_id) = parent.def_id() {
302 let node_id = self.resolver.ast_map.as_local_node_id(def_id).unwrap();
303 self.export_map.entry(node_id).or_insert(Vec::new()).push(export);
307 self.build_reduced_graph_for_external_crate(external_module);
313 let parent_link = ModuleParentLink(parent, name);
314 let def = Def::Mod(self.ast_map.local_def_id(item.id));
315 let module = self.new_module(parent_link, Some(def), false, is_public);
316 self.define(parent, name, TypeNS, (module, sp));
317 parent.module_children.borrow_mut().insert(item.id, module);
321 ItemForeignMod(..) => parent,
323 // These items live in the value namespace.
324 ItemStatic(_, m, _) => {
325 let mutbl = m == hir::MutMutable;
326 let def = Def::Static(self.ast_map.local_def_id(item.id), mutbl);
327 self.define(parent, name, ValueNS, (def, sp, modifiers));
331 let def = Def::Const(self.ast_map.local_def_id(item.id));
332 self.define(parent, name, ValueNS, (def, sp, modifiers));
335 ItemFn(_, _, _, _, _, _) => {
336 let def = Def::Fn(self.ast_map.local_def_id(item.id));
337 self.define(parent, name, ValueNS, (def, sp, modifiers));
341 // These items live in the type namespace.
343 let parent_link = ModuleParentLink(parent, name);
344 let def = Def::TyAlias(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));
350 ItemEnum(ref enum_definition, _) => {
351 let parent_link = ModuleParentLink(parent, name);
352 let def = Def::Enum(self.ast_map.local_def_id(item.id));
353 let module = self.new_module(parent_link, Some(def), false, is_public);
354 self.define(parent, name, TypeNS, (module, sp));
356 let variant_modifiers = if is_public {
357 DefModifiers::empty()
359 DefModifiers::PRIVATE_VARIANT
361 for variant in &(*enum_definition).variants {
362 let item_def_id = self.ast_map.local_def_id(item.id);
363 self.build_reduced_graph_for_variant(variant, item_def_id,
364 module, variant_modifiers);
369 // These items live in both the type and value namespaces.
370 ItemStruct(ref struct_def, _) => {
371 // Define a name in the type namespace.
372 let def = Def::Struct(self.ast_map.local_def_id(item.id));
373 self.define(parent, name, TypeNS, (def, sp, modifiers));
375 // If this is a newtype or unit-like struct, define a name
376 // in the value namespace as well
377 if !struct_def.is_struct() {
378 let def = Def::Struct(self.ast_map.local_def_id(struct_def.id()));
379 self.define(parent, name, ValueNS, (def, sp, modifiers));
382 // Record the def ID and fields of this struct.
383 let named_fields = struct_def.fields()
385 .filter_map(|f| f.node.name)
387 let item_def_id = self.ast_map.local_def_id(item.id);
388 self.structs.insert(item_def_id, named_fields);
393 ItemDefaultImpl(_, _) |
394 ItemImpl(..) => parent,
396 ItemTrait(_, _, _, ref items) => {
397 let def_id = self.ast_map.local_def_id(item.id);
399 // Add all the items within to a new module.
400 let parent_link = ModuleParentLink(parent, name);
401 let def = Def::Trait(def_id);
402 let module_parent = self.new_module(parent_link, Some(def), false, is_public);
403 self.define(parent, name, TypeNS, (module_parent, sp));
405 // Add the names of all the items to the trait info.
407 let item_def_id = self.ast_map.local_def_id(item.id);
408 let (def, ns) = match item.node {
409 hir::ConstTraitItem(..) => (Def::AssociatedConst(item_def_id), ValueNS),
410 hir::MethodTraitItem(..) => (Def::Method(item_def_id), ValueNS),
411 hir::TypeTraitItem(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
414 let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
415 self.define(module_parent, item.name, ns, (def, item.span, modifiers));
417 self.trait_item_map.insert((item.name, def_id), item_def_id);
425 // Constructs the reduced graph for one variant. Variants exist in the
426 // type and value namespaces.
427 fn build_reduced_graph_for_variant(&mut self,
431 variant_modifiers: DefModifiers) {
432 let name = variant.node.name;
433 if variant.node.data.is_struct() {
434 // Not adding fields for variants as they are not accessed with a self receiver
435 let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
436 self.structs.insert(variant_def_id, Vec::new());
439 // Variants are always treated as importable to allow them to be glob used.
440 // All variants are defined in both type and value namespaces as future-proofing.
441 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers;
442 let def = Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id()));
444 self.define(parent, name, ValueNS, (def, variant.span, modifiers));
445 self.define(parent, name, TypeNS, (def, variant.span, modifiers));
448 /// Constructs the reduced graph for one foreign item.
449 fn build_reduced_graph_for_foreign_item(&mut self,
450 foreign_item: &ForeignItem,
451 parent: Module<'b>) {
452 let name = foreign_item.name;
453 let is_public = foreign_item.vis == hir::Public;
454 let modifiers = if is_public {
457 DefModifiers::empty()
458 } | DefModifiers::IMPORTABLE;
460 let def = match foreign_item.node {
461 ForeignItemFn(..) => {
462 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
464 ForeignItemStatic(_, m) => {
465 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
468 self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
471 fn build_reduced_graph_for_block(&mut self, block: &Block, parent: Module<'b>) -> Module<'b> {
472 if self.block_needs_anonymous_module(block) {
473 let block_id = block.id;
475 debug!("(building reduced graph for block) creating a new anonymous module for block \
479 let parent_link = BlockParentLink(parent, block_id);
480 let new_module = self.new_module(parent_link, None, false, false);
481 parent.module_children.borrow_mut().insert(block_id, new_module);
488 fn handle_external_def(&mut self,
493 new_parent: Module<'b>) {
494 debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
497 let is_public = vis == hir::Public;
499 let mut modifiers = DefModifiers::empty();
501 modifiers = modifiers | DefModifiers::PUBLIC;
503 if new_parent.is_normal() {
504 modifiers = modifiers | DefModifiers::IMPORTABLE;
507 let is_exported = is_public &&
508 match new_parent.def_id() {
510 Some(did) => self.external_exports.contains(&did),
513 self.external_exports.insert(def.def_id());
517 Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => {
518 debug!("(building reduced graph for external crate) building module {} {}",
521 let parent_link = ModuleParentLink(new_parent, name);
522 let module = self.new_module(parent_link, Some(def), true, is_public);
523 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
525 Def::Variant(_, variant_id) => {
526 debug!("(building reduced graph for external crate) building variant {}",
528 // Variants are always treated as importable to allow them to be glob used.
529 // All variants are defined in both type and value namespaces as future-proofing.
530 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
531 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
532 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
533 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
534 // Not adding fields for variants as they are not accessed with a self receiver
535 self.structs.insert(variant_id, Vec::new());
541 Def::AssociatedConst(..) |
543 debug!("(building reduced graph for external crate) building value (fn/static) {}",
545 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
547 Def::Trait(def_id) => {
548 debug!("(building reduced graph for external crate) building type {}",
551 // If this is a trait, add all the trait item names to the trait
554 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
555 for trait_item_def in &trait_item_def_ids {
556 let trait_item_name =
557 self.session.cstore.item_name(trait_item_def.def_id());
559 debug!("(building reduced graph for external crate) ... adding trait item \
563 self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
566 self.external_exports.insert(trait_item_def.def_id());
570 let parent_link = ModuleParentLink(new_parent, name);
571 let module = self.new_module(parent_link, Some(def), true, is_public);
572 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
574 Def::AssociatedTy(..) => {
575 debug!("(building reduced graph for external crate) building type {}",
577 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
580 if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
581 debug!("(building reduced graph for external crate) building type and value for \
584 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
585 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
586 let def = Def::Struct(ctor_def_id);
587 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
590 // Record the def ID and fields of this struct.
591 let fields = self.session.cstore.struct_field_names(def_id);
592 self.structs.insert(def_id, fields);
594 Def::Struct(..) => {}
602 panic!("didn't expect `{:?}`", def);
607 /// Builds the reduced graph for a single item in an external crate.
608 fn build_reduced_graph_for_external_crate_def(&mut self,
613 // Add the new child item, if necessary.
615 Def::ForeignMod(def_id) => {
616 // Foreign modules have no names. Recur and populate
618 for child in self.session.cstore.item_children(def_id) {
619 self.build_reduced_graph_for_external_crate_def(root, child)
623 self.handle_external_def(def,
625 &xcdef.name.as_str(),
632 debug!("(building reduced graph for external crate) ignoring impl");
635 debug!("(building reduced graph for external crate) ignoring field");
640 /// Builds the reduced graph rooted at the given external module.
641 fn populate_external_module(&mut self, module: Module<'b>) {
642 debug!("(populating external module) attempting to populate {}",
643 module_to_string(module));
645 let def_id = match module.def_id() {
647 debug!("(populating external module) ... no def ID!");
650 Some(def_id) => def_id,
653 for child in self.session.cstore.item_children(def_id) {
654 debug!("(populating external module) ... found ident: {}",
656 self.build_reduced_graph_for_external_crate_def(module, child);
658 module.populated.set(true)
661 /// Ensures that the reduced graph rooted at the given external module
662 /// is built, building it if it is not.
663 fn populate_module_if_necessary(&mut self, module: Module<'b>) {
664 if !module.populated.get() {
665 self.populate_external_module(module)
667 assert!(module.populated.get())
670 /// Builds the reduced graph rooted at the 'use' directive for an external
672 fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
673 let root_cnum = root.def_id().unwrap().krate;
674 for child in self.session.cstore.crate_top_level_items(root_cnum) {
675 self.build_reduced_graph_for_external_crate_def(root, child);
679 /// Creates and adds an import directive to the given module.
680 fn build_import_directive(&mut self,
682 module_path: Vec<Name>,
683 subclass: ImportDirectiveSubclass,
687 shadowable: Shadowable) {
688 module_.unresolved_imports
690 .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
691 self.unresolved_imports += 1;
694 module_.inc_pub_count();
697 // Bump the reference count on the name. Or, if this is a glob, set
698 // the appropriate flag.
701 SingleImport(target, _) => {
702 module_.increment_outstanding_references_for(target, ValueNS);
703 module_.increment_outstanding_references_for(target, TypeNS);
706 // Set the glob flag. This tells us that we don't know the
707 // module's exports ahead of time.
709 module_.inc_glob_count();
711 module_.inc_pub_glob_count();
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);