]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Replace the field `imports` in Module with `unresolved_imports` and refactor away...
[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::{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};
50
51 use std::mem::replace;
52 use std::ops::{Deref, DerefMut};
53
54 struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
55     resolver: &'a mut Resolver<'b, 'tcx>,
56 }
57
58 impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
59     type Target = Resolver<'b, 'tcx>;
60
61     fn deref(&self) -> &Resolver<'b, 'tcx> {
62         &*self.resolver
63     }
64 }
65
66 impl<'a, 'b:'a, 'tcx:'b> DerefMut for GraphBuilder<'a, 'b, 'tcx> {
67     fn deref_mut(&mut self) -> &mut Resolver<'b, 'tcx> {
68         &mut *self.resolver
69     }
70 }
71
72 trait ToNameBinding<'a> {
73     fn to_name_binding(self) -> NameBinding<'a>;
74 }
75
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))
79     }
80 }
81
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) }
86     }
87 }
88
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,
94             builder: self,
95         };
96         intravisit::walk_crate(&mut visitor, krate);
97     }
98
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>
102     {
103         let _ = parent.try_define_child(name, ns, self.new_name_binding(def.to_name_binding()));
104     }
105
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) {
111             Ok(()) => return,
112             Err(old_binding) => old_binding,
113         };
114
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);
121
122             if let Some(sp) = old_binding.span {
123                 let note = format!("first definition of {} `{}` here", ns_str, name);
124                 err.span_note(sp, &note);
125             }
126             err.emit();
127         } else if old_binding.is_extern_crate() && binding.is_extern_crate() {
128             span_err!(self.session,
129                       span,
130                       E0259,
131                       "an external crate named `{}` has already been imported into this module",
132                       name);
133         } else {
134             span_err!(self.session,
135                       span,
136                       E0260,
137                       "the name `{}` conflicts with an external crate \
138                       that has been imported into this module",
139                       name);
140         }
141     }
142
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 {
147                     return true;
148                 }
149             }
150             false
151         }
152
153         // If any statements are items, we need to create an anonymous module
154         block.stmts.iter().any(is_item)
155     }
156
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;
160         let sp = item.span;
161         let is_public = item.vis == hir::Public;
162         let modifiers = if is_public {
163             DefModifiers::PUBLIC
164         } else {
165             DefModifiers::empty()
166         } | DefModifiers::IMPORTABLE;
167
168         match item.node {
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) => {
175                         full_path.segments
176                                  .split_last()
177                                  .unwrap()
178                                  .1
179                                  .iter()
180                                  .map(|seg| seg.identifier.name)
181                                  .collect()
182                     }
183
184                     ViewPathGlob(ref module_ident_path) |
185                     ViewPathList(ref module_ident_path, _) => {
186                         module_ident_path.segments
187                                          .iter()
188                                          .map(|seg| seg.identifier.name)
189                                          .collect()
190                     }
191                 };
192
193                 // Build up the import directives.
194                 let shadowable = item.attrs.iter().any(|attr| {
195                     attr.name() == special_idents::prelude_import.name.as_str()
196                 });
197                 let shadowable = if shadowable {
198                     Shadowable::Always
199                 } else {
200                     Shadowable::Never
201                 };
202
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" {
207                             resolve_error(self,
208                                           view_path.span,
209                                           ResolutionError::SelfImportsOnlyAllowedWithin);
210                         }
211
212                         let subclass = SingleImport(binding, source_name);
213                         self.build_import_directive(parent,
214                                                     module_path,
215                                                     subclass,
216                                                     view_path.span,
217                                                     item.id,
218                                                     is_public,
219                                                     shadowable);
220                     }
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()
224                                                     .filter_map(|item| {
225                                                         match item.node {
226                                                             PathListMod { .. } => Some(item.span),
227                                                             _ => None,
228                                                         }
229                                                     })
230                                                     .collect::<Vec<Span>>();
231                         if mod_spans.len() > 1 {
232                             let mut e = resolve_struct_error(self,
233                                           mod_spans[0],
234                                           ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
235                             for other_span in mod_spans.iter().skip(1) {
236                                 e.span_note(*other_span, "another `self` import appears here");
237                             }
238                             e.emit();
239                         }
240
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() {
247                                         Some(name) => *name,
248                                         None => {
249                                             resolve_error(
250                                                 self,
251                                                 source_item.span,
252                                                 ResolutionError::
253                                                 SelfImportOnlyInImportListWithNonEmptyPrefix
254                                             );
255                                             continue;
256                                         }
257                                     };
258                                     let module_path = module_path.split_last().unwrap().1;
259                                     let rename = rename.unwrap_or(name);
260                                     (module_path.to_vec(), name, rename)
261                                 }
262                             };
263                             self.build_import_directive(parent,
264                                                         module_path,
265                                                         SingleImport(rename, name),
266                                                         source_item.span,
267                                                         source_item.node.id(),
268                                                         is_public,
269                                                         shadowable);
270                         }
271                     }
272                     ViewPathGlob(_) => {
273                         self.build_import_directive(parent,
274                                                     module_path,
275                                                     GlobImport,
276                                                     view_path.span,
277                                                     item.id,
278                                                     is_public,
279                                                     shadowable);
280                     }
281                 }
282                 parent
283             }
284
285             ItemExternCrate(_) => {
286                 // n.b. we don't need to look at the path option here, because cstore already
287                 // did
288                 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
289                     let def_id = DefId {
290                         krate: crate_id,
291                         index: CRATE_DEF_INDEX,
292                     };
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));
298
299                     self.build_reduced_graph_for_external_crate(external_module);
300                 }
301                 parent
302             }
303
304             ItemMod(..) => {
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);
310                 module
311             }
312
313             ItemForeignMod(..) => parent,
314
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));
320                 parent
321             }
322             ItemConst(_, _) => {
323                 let def = Def::Const(self.ast_map.local_def_id(item.id));
324                 self.define(parent, name, ValueNS, (def, sp, modifiers));
325                 parent
326             }
327             ItemFn(_, _, _, _, _, _) => {
328                 let def = Def::Fn(self.ast_map.local_def_id(item.id));
329                 self.define(parent, name, ValueNS, (def, sp, modifiers));
330                 parent
331             }
332
333             // These items live in the type namespace.
334             ItemTy(..) => {
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));
339                 parent
340             }
341
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));
347
348                 let variant_modifiers = if is_public {
349                     DefModifiers::empty()
350                 } else {
351                     DefModifiers::PRIVATE_VARIANT
352                 };
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);
357                 }
358                 parent
359             }
360
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));
366
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));
372                 }
373
374                 // Record the def ID and fields of this struct.
375                 let named_fields = struct_def.fields()
376                                              .iter()
377                                              .filter_map(|f| {
378                                                  match f.node.kind {
379                                                      NamedField(name, _) => Some(name),
380                                                      UnnamedField(_) => None,
381                                                  }
382                                              })
383                                              .collect();
384                 let item_def_id = self.ast_map.local_def_id(item.id);
385                 self.structs.insert(item_def_id, named_fields);
386
387                 parent
388             }
389
390             ItemDefaultImpl(_, _) |
391             ItemImpl(..) => parent,
392
393             ItemTrait(_, _, _, ref items) => {
394                 let def_id = self.ast_map.local_def_id(item.id);
395
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));
401
402                 // Add the names of all the items to the trait info.
403                 for item in items {
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),
409                     };
410
411                     let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
412                     self.define(module_parent, item.name, ns, (def, item.span, modifiers));
413
414                     self.trait_item_map.insert((item.name, def_id), item_def_id);
415                 }
416
417                 parent
418             }
419         }
420     }
421
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,
425                                        variant: &Variant,
426                                        item_id: DefId,
427                                        parent: Module<'b>,
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());
434         }
435
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()));
440
441         self.define(parent, name, ValueNS, (def, variant.span, modifiers));
442         self.define(parent, name, TypeNS, (def, variant.span, modifiers));
443     }
444
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 {
452             DefModifiers::PUBLIC
453         } else {
454             DefModifiers::empty()
455         } | DefModifiers::IMPORTABLE;
456
457         let def = match foreign_item.node {
458             ForeignItemFn(..) => {
459                 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
460             }
461             ForeignItemStatic(_, m) => {
462                 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
463             }
464         };
465         self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
466     }
467
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;
471
472             debug!("(building reduced graph for block) creating a new anonymous module for block \
473                     {}",
474                    block_id);
475
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);
479             new_module
480         } else {
481             parent
482         }
483     }
484
485     fn handle_external_def(&mut self,
486                            def: Def,
487                            vis: Visibility,
488                            final_ident: &str,
489                            name: Name,
490                            new_parent: Module<'b>) {
491         debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
492                final_ident,
493                vis);
494         let is_public = vis == hir::Public;
495
496         let mut modifiers = DefModifiers::empty();
497         if is_public {
498             modifiers = modifiers | DefModifiers::PUBLIC;
499         }
500         if new_parent.is_normal() {
501             modifiers = modifiers | DefModifiers::IMPORTABLE;
502         }
503
504         let is_exported = is_public &&
505                           match new_parent.def_id() {
506             None => true,
507             Some(did) => self.external_exports.contains(&did),
508         };
509         if is_exported {
510             self.external_exports.insert(def.def_id());
511         }
512
513         match def {
514             Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => {
515                 debug!("(building reduced graph for external crate) building module {} {}",
516                        final_ident,
517                        is_public);
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));
521             }
522             Def::Variant(_, variant_id) => {
523                 debug!("(building reduced graph for external crate) building variant {}",
524                        final_ident);
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());
533                 }
534             }
535             Def::Fn(..) |
536             Def::Static(..) |
537             Def::Const(..) |
538             Def::AssociatedConst(..) |
539             Def::Method(..) => {
540                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
541                        final_ident);
542                 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
543             }
544             Def::Trait(def_id) => {
545                 debug!("(building reduced graph for external crate) building type {}",
546                        final_ident);
547
548                 // If this is a trait, add all the trait item names to the trait
549                 // info.
550
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());
555
556                     debug!("(building reduced graph for external crate) ... adding trait item \
557                             '{}'",
558                            trait_item_name);
559
560                     self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
561
562                     if is_exported {
563                         self.external_exports.insert(trait_item_def.def_id());
564                     }
565                 }
566
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));
570             }
571             Def::AssociatedTy(..) => {
572                 debug!("(building reduced graph for external crate) building type {}",
573                        final_ident);
574                 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
575             }
576             Def::Struct(def_id)
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 \
579                         {}",
580                        final_ident);
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));
585                 }
586
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);
590             }
591             Def::Struct(..) => {}
592             Def::Local(..) |
593             Def::PrimTy(..) |
594             Def::TyParam(..) |
595             Def::Upvar(..) |
596             Def::Label(..) |
597             Def::SelfTy(..) |
598             Def::Err => {
599                 panic!("didn't expect `{:?}`", def);
600             }
601         }
602     }
603
604     /// Builds the reduced graph for a single item in an external crate.
605     fn build_reduced_graph_for_external_crate_def(&mut self,
606                                                   root: Module<'b>,
607                                                   xcdef: ChildItem) {
608         match xcdef.def {
609             DlDef(def) => {
610                 // Add the new child item, if necessary.
611                 match def {
612                     Def::ForeignMod(def_id) => {
613                         // Foreign modules have no names. Recur and populate
614                         // eagerly.
615                         for child in self.session.cstore.item_children(def_id) {
616                             self.build_reduced_graph_for_external_crate_def(root, child)
617                         }
618                     }
619                     _ => {
620                         self.handle_external_def(def,
621                                                  xcdef.vis,
622                                                  &xcdef.name.as_str(),
623                                                  xcdef.name,
624                                                  root);
625                     }
626                 }
627             }
628             DlImpl(_) => {
629                 debug!("(building reduced graph for external crate) ignoring impl");
630             }
631             DlField => {
632                 debug!("(building reduced graph for external crate) ignoring field");
633             }
634         }
635     }
636
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));
641
642         let def_id = match module.def_id() {
643             None => {
644                 debug!("(populating external module) ... no def ID!");
645                 return;
646             }
647             Some(def_id) => def_id,
648         };
649
650         for child in self.session.cstore.item_children(def_id) {
651             debug!("(populating external module) ... found ident: {}",
652                    child.name);
653             self.build_reduced_graph_for_external_crate_def(module, child);
654         }
655         module.populated.set(true)
656     }
657
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)
663         }
664         assert!(module.populated.get())
665     }
666
667     /// Builds the reduced graph rooted at the 'use' directive for an external
668     /// crate.
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);
673         }
674     }
675
676     /// Creates and adds an import directive to the given module.
677     fn build_import_directive(&mut self,
678                               module_: Module<'b>,
679                               module_path: Vec<Name>,
680                               subclass: ImportDirectiveSubclass,
681                               span: Span,
682                               id: NodeId,
683                               is_public: bool,
684                               shadowable: Shadowable) {
685         module_.unresolved_imports
686                .borrow_mut()
687                .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
688         self.unresolved_imports += 1;
689
690         if is_public {
691             module_.inc_pub_count();
692         }
693
694         // Bump the reference count on the name. Or, if this is a glob, set
695         // the appropriate flag.
696
697         match subclass {
698             SingleImport(target, _) => {
699                 module_.increment_outstanding_references_for(target, ValueNS);
700                 module_.increment_outstanding_references_for(target, TypeNS);
701             }
702             GlobImport => {
703                 // Set the glob flag. This tells us that we don't know the
704                 // module's exports ahead of time.
705
706                 module_.inc_glob_count();
707                 if is_public {
708                     module_.inc_pub_glob_count();
709                 }
710             }
711         }
712     }
713 }
714
715 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
716     builder: GraphBuilder<'a, 'b, 'tcx>,
717     parent: Module<'b>,
718 }
719
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))
723     }
724
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;
730     }
731
732     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
733         self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
734     }
735
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;
741     }
742 }
743
744 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
745     GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
746 }
747
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);
751 }