]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
77e6dd73b4cc56d117c15c11b1818484e7ca1890
[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 DefModifiers;
17 use resolve_imports::ImportDirective;
18 use resolve_imports::ImportDirectiveSubclass::{self, SingleImport, GlobImport};
19 use Module;
20 use Namespace::{self, TypeNS, ValueNS};
21 use {NameBinding, NameBindingKind};
22 use module_to_string;
23 use ParentLink::{ModuleParentLink, BlockParentLink};
24 use Resolver;
25 use resolve_imports::Shadowable;
26 use {resolve_error, resolve_struct_error, ResolutionError};
27
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;
32
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};
37
38 use rustc_front::hir;
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};
48
49 use std::mem::replace;
50 use std::ops::{Deref, DerefMut};
51
52 struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
53     resolver: &'a mut Resolver<'b, 'tcx>,
54 }
55
56 impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
57     type Target = Resolver<'b, 'tcx>;
58
59     fn deref(&self) -> &Resolver<'b, 'tcx> {
60         &*self.resolver
61     }
62 }
63
64 impl<'a, 'b:'a, 'tcx:'b> DerefMut for GraphBuilder<'a, 'b, 'tcx> {
65     fn deref_mut(&mut self) -> &mut Resolver<'b, 'tcx> {
66         &mut *self.resolver
67     }
68 }
69
70 trait ToNameBinding<'a> {
71     fn to_name_binding(self) -> NameBinding<'a>;
72 }
73
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))
77     }
78 }
79
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) }
84     }
85 }
86
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,
92             builder: self,
93         };
94         intravisit::walk_crate(&mut visitor, krate);
95     }
96
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>
100     {
101         let _ = parent.try_define_child(name, ns, self.new_name_binding(def.to_name_binding()));
102     }
103
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) {
109             Ok(()) => return,
110             Err(old_binding) => old_binding,
111         };
112
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);
119
120             if let Some(sp) = old_binding.span {
121                 let note = format!("first definition of {} `{}` here", ns_str, name);
122                 err.span_note(sp, &note);
123             }
124             err.emit();
125         } else if old_binding.is_extern_crate() && binding.is_extern_crate() {
126             span_err!(self.session,
127                       span,
128                       E0259,
129                       "an external crate named `{}` has already been imported into this module",
130                       name);
131         } else {
132             span_err!(self.session,
133                       span,
134                       E0260,
135                       "the name `{}` conflicts with an external crate \
136                       that has been imported into this module",
137                       name);
138         }
139     }
140
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 {
145                     return true;
146                 }
147             }
148             false
149         }
150
151         // If any statements are items, we need to create an anonymous module
152         block.stmts.iter().any(is_item)
153     }
154
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;
158         let sp = item.span;
159         let is_public = item.vis == hir::Public;
160         let modifiers = if is_public {
161             DefModifiers::PUBLIC
162         } else {
163             DefModifiers::empty()
164         } | DefModifiers::IMPORTABLE;
165
166         match item.node {
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) => {
173                         full_path.segments
174                                  .split_last()
175                                  .unwrap()
176                                  .1
177                                  .iter()
178                                  .map(|seg| seg.identifier.name)
179                                  .collect()
180                     }
181
182                     ViewPathGlob(ref module_ident_path) |
183                     ViewPathList(ref module_ident_path, _) => {
184                         module_ident_path.segments
185                                          .iter()
186                                          .map(|seg| seg.identifier.name)
187                                          .collect()
188                     }
189                 };
190
191                 // Build up the import directives.
192                 let shadowable = item.attrs.iter().any(|attr| {
193                     attr.name() == special_idents::prelude_import.name.as_str()
194                 });
195                 let shadowable = if shadowable {
196                     Shadowable::Always
197                 } else {
198                     Shadowable::Never
199                 };
200
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" {
205                             resolve_error(self,
206                                           view_path.span,
207                                           ResolutionError::SelfImportsOnlyAllowedWithin);
208                         }
209
210                         let subclass = SingleImport(binding, source_name);
211                         self.build_import_directive(parent,
212                                                     module_path,
213                                                     subclass,
214                                                     view_path.span,
215                                                     item.id,
216                                                     is_public,
217                                                     shadowable);
218                     }
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()
222                                                     .filter_map(|item| {
223                                                         match item.node {
224                                                             PathListMod { .. } => Some(item.span),
225                                                             _ => None,
226                                                         }
227                                                     })
228                                                     .collect::<Vec<Span>>();
229                         if mod_spans.len() > 1 {
230                             let mut e = resolve_struct_error(self,
231                                           mod_spans[0],
232                                           ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
233                             for other_span in mod_spans.iter().skip(1) {
234                                 e.span_note(*other_span, "another `self` import appears here");
235                             }
236                             e.emit();
237                         }
238
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() {
245                                         Some(name) => *name,
246                                         None => {
247                                             resolve_error(
248                                                 self,
249                                                 source_item.span,
250                                                 ResolutionError::
251                                                 SelfImportOnlyInImportListWithNonEmptyPrefix
252                                             );
253                                             continue;
254                                         }
255                                     };
256                                     let module_path = module_path.split_last().unwrap().1;
257                                     let rename = rename.unwrap_or(name);
258                                     (module_path.to_vec(), name, rename)
259                                 }
260                             };
261                             self.build_import_directive(parent,
262                                                         module_path,
263                                                         SingleImport(rename, name),
264                                                         source_item.span,
265                                                         source_item.node.id(),
266                                                         is_public,
267                                                         shadowable);
268                         }
269                     }
270                     ViewPathGlob(_) => {
271                         self.build_import_directive(parent,
272                                                     module_path,
273                                                     GlobImport,
274                                                     view_path.span,
275                                                     item.id,
276                                                     is_public,
277                                                     shadowable);
278                     }
279                 }
280                 parent
281             }
282
283             ItemExternCrate(_) => {
284                 // n.b. we don't need to look at the path option here, because cstore already
285                 // did
286                 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
287                     let def_id = DefId {
288                         krate: crate_id,
289                         index: CRATE_DEF_INDEX,
290                     };
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));
298
299                     if is_public {
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);
304                         }
305                     }
306
307                     self.build_reduced_graph_for_external_crate(external_module);
308                 }
309                 parent
310             }
311
312             ItemMod(..) => {
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);
318                 module
319             }
320
321             ItemForeignMod(..) => parent,
322
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));
328                 parent
329             }
330             ItemConst(_, _) => {
331                 let def = Def::Const(self.ast_map.local_def_id(item.id));
332                 self.define(parent, name, ValueNS, (def, sp, modifiers));
333                 parent
334             }
335             ItemFn(_, _, _, _, _, _) => {
336                 let def = Def::Fn(self.ast_map.local_def_id(item.id));
337                 self.define(parent, name, ValueNS, (def, sp, modifiers));
338                 parent
339             }
340
341             // These items live in the type namespace.
342             ItemTy(..) => {
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));
347                 parent
348             }
349
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));
355
356                 let variant_modifiers = if is_public {
357                     DefModifiers::empty()
358                 } else {
359                     DefModifiers::PRIVATE_VARIANT
360                 };
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);
365                 }
366                 parent
367             }
368
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));
374
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));
380                 }
381
382                 // Record the def ID and fields of this struct.
383                 let named_fields = struct_def.fields()
384                                              .iter()
385                                              .filter_map(|f| f.node.name)
386                                              .collect();
387                 let item_def_id = self.ast_map.local_def_id(item.id);
388                 self.structs.insert(item_def_id, named_fields);
389
390                 parent
391             }
392
393             ItemDefaultImpl(_, _) |
394             ItemImpl(..) => parent,
395
396             ItemTrait(_, _, _, ref items) => {
397                 let def_id = self.ast_map.local_def_id(item.id);
398
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));
404
405                 // Add the names of all the items to the trait info.
406                 for item in items {
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),
412                     };
413
414                     let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
415                     self.define(module_parent, item.name, ns, (def, item.span, modifiers));
416
417                     self.trait_item_map.insert((item.name, def_id), item_def_id);
418                 }
419
420                 parent
421             }
422         }
423     }
424
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,
428                                        variant: &Variant,
429                                        item_id: DefId,
430                                        parent: Module<'b>,
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());
437         }
438
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()));
443
444         self.define(parent, name, ValueNS, (def, variant.span, modifiers));
445         self.define(parent, name, TypeNS, (def, variant.span, modifiers));
446     }
447
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 {
455             DefModifiers::PUBLIC
456         } else {
457             DefModifiers::empty()
458         } | DefModifiers::IMPORTABLE;
459
460         let def = match foreign_item.node {
461             ForeignItemFn(..) => {
462                 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
463             }
464             ForeignItemStatic(_, m) => {
465                 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
466             }
467         };
468         self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
469     }
470
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;
474
475             debug!("(building reduced graph for block) creating a new anonymous module for block \
476                     {}",
477                    block_id);
478
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);
482             new_module
483         } else {
484             parent
485         }
486     }
487
488     fn handle_external_def(&mut self,
489                            def: Def,
490                            vis: Visibility,
491                            final_ident: &str,
492                            name: Name,
493                            new_parent: Module<'b>) {
494         debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
495                final_ident,
496                vis);
497         let is_public = vis == hir::Public;
498
499         let mut modifiers = DefModifiers::empty();
500         if is_public {
501             modifiers = modifiers | DefModifiers::PUBLIC;
502         }
503         if new_parent.is_normal() {
504             modifiers = modifiers | DefModifiers::IMPORTABLE;
505         }
506
507         let is_exported = is_public &&
508                           match new_parent.def_id() {
509             None => true,
510             Some(did) => self.external_exports.contains(&did),
511         };
512         if is_exported {
513             self.external_exports.insert(def.def_id());
514         }
515
516         match def {
517             Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => {
518                 debug!("(building reduced graph for external crate) building module {} {}",
519                        final_ident,
520                        is_public);
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));
524             }
525             Def::Variant(_, variant_id) => {
526                 debug!("(building reduced graph for external crate) building variant {}",
527                        final_ident);
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());
536                 }
537             }
538             Def::Fn(..) |
539             Def::Static(..) |
540             Def::Const(..) |
541             Def::AssociatedConst(..) |
542             Def::Method(..) => {
543                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
544                        final_ident);
545                 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
546             }
547             Def::Trait(def_id) => {
548                 debug!("(building reduced graph for external crate) building type {}",
549                        final_ident);
550
551                 // If this is a trait, add all the trait item names to the trait
552                 // info.
553
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());
558
559                     debug!("(building reduced graph for external crate) ... adding trait item \
560                             '{}'",
561                            trait_item_name);
562
563                     self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
564
565                     if is_exported {
566                         self.external_exports.insert(trait_item_def.def_id());
567                     }
568                 }
569
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));
573             }
574             Def::AssociatedTy(..) => {
575                 debug!("(building reduced graph for external crate) building type {}",
576                        final_ident);
577                 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
578             }
579             Def::Struct(def_id)
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 \
582                         {}",
583                        final_ident);
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));
588                 }
589
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);
593             }
594             Def::Struct(..) => {}
595             Def::Local(..) |
596             Def::PrimTy(..) |
597             Def::TyParam(..) |
598             Def::Upvar(..) |
599             Def::Label(..) |
600             Def::SelfTy(..) |
601             Def::Err => {
602                 panic!("didn't expect `{:?}`", def);
603             }
604         }
605     }
606
607     /// Builds the reduced graph for a single item in an external crate.
608     fn build_reduced_graph_for_external_crate_def(&mut self,
609                                                   root: Module<'b>,
610                                                   xcdef: ChildItem) {
611         match xcdef.def {
612             DlDef(def) => {
613                 // Add the new child item, if necessary.
614                 match def {
615                     Def::ForeignMod(def_id) => {
616                         // Foreign modules have no names. Recur and populate
617                         // eagerly.
618                         for child in self.session.cstore.item_children(def_id) {
619                             self.build_reduced_graph_for_external_crate_def(root, child)
620                         }
621                     }
622                     _ => {
623                         self.handle_external_def(def,
624                                                  xcdef.vis,
625                                                  &xcdef.name.as_str(),
626                                                  xcdef.name,
627                                                  root);
628                     }
629                 }
630             }
631             DlImpl(_) => {
632                 debug!("(building reduced graph for external crate) ignoring impl");
633             }
634             DlField => {
635                 debug!("(building reduced graph for external crate) ignoring field");
636             }
637         }
638     }
639
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));
644
645         let def_id = match module.def_id() {
646             None => {
647                 debug!("(populating external module) ... no def ID!");
648                 return;
649             }
650             Some(def_id) => def_id,
651         };
652
653         for child in self.session.cstore.item_children(def_id) {
654             debug!("(populating external module) ... found ident: {}",
655                    child.name);
656             self.build_reduced_graph_for_external_crate_def(module, child);
657         }
658         module.populated.set(true)
659     }
660
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)
666         }
667         assert!(module.populated.get())
668     }
669
670     /// Builds the reduced graph rooted at the 'use' directive for an external
671     /// crate.
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);
676         }
677     }
678
679     /// Creates and adds an import directive to the given module.
680     fn build_import_directive(&mut self,
681                               module_: Module<'b>,
682                               module_path: Vec<Name>,
683                               subclass: ImportDirectiveSubclass,
684                               span: Span,
685                               id: NodeId,
686                               is_public: bool,
687                               shadowable: Shadowable) {
688         module_.unresolved_imports
689                .borrow_mut()
690                .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
691         self.unresolved_imports += 1;
692
693         if is_public {
694             module_.inc_pub_count();
695         }
696
697         // Bump the reference count on the name. Or, if this is a glob, set
698         // the appropriate flag.
699
700         match subclass {
701             SingleImport(target, _) => {
702                 module_.increment_outstanding_references_for(target, ValueNS);
703                 module_.increment_outstanding_references_for(target, TypeNS);
704             }
705             GlobImport => {
706                 // Set the glob flag. This tells us that we don't know the
707                 // module's exports ahead of time.
708
709                 module_.inc_glob_count();
710                 if is_public {
711                     module_.inc_pub_glob_count();
712                 }
713             }
714         }
715     }
716 }
717
718 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
719     builder: GraphBuilder<'a, 'b, 'tcx>,
720     parent: Module<'b>,
721 }
722
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))
726     }
727
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;
733     }
734
735     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
736         self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
737     }
738
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;
744     }
745 }
746
747 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
748     GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
749 }
750
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);
754 }