]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
dff6926d2d34a4bde6e20b7c975f36fad039559e
[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 = ImportDirectiveSubclass::single(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                             let subclass = ImportDirectiveSubclass::single(rename, name);
262                             self.build_import_directive(parent,
263                                                         module_path,
264                                                         subclass,
265                                                         source_item.span,
266                                                         source_item.node.id(),
267                                                         is_public,
268                                                         shadowable);
269                         }
270                     }
271                     ViewPathGlob(_) => {
272                         self.build_import_directive(parent,
273                                                     module_path,
274                                                     GlobImport,
275                                                     view_path.span,
276                                                     item.id,
277                                                     is_public,
278                                                     shadowable);
279                     }
280                 }
281                 parent
282             }
283
284             ItemExternCrate(_) => {
285                 // n.b. we don't need to look at the path option here, because cstore already
286                 // did
287                 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
288                     let def_id = DefId {
289                         krate: crate_id,
290                         index: CRATE_DEF_INDEX,
291                     };
292                     self.external_exports.insert(def_id);
293                     let parent_link = ModuleParentLink(parent, name);
294                     let def = Def::Mod(def_id);
295                     let module = self.new_extern_crate_module(parent_link, def, is_public, item.id);
296                     self.define(parent, name, TypeNS, (module, sp));
297
298                     if is_public {
299                         let export = Export { name: name, def_id: def_id };
300                         if let Some(def_id) = parent.def_id() {
301                             let node_id = self.resolver.ast_map.as_local_node_id(def_id).unwrap();
302                             self.export_map.entry(node_id).or_insert(Vec::new()).push(export);
303                         }
304                     }
305
306                     self.build_reduced_graph_for_external_crate(module);
307                 }
308                 parent
309             }
310
311             ItemMod(..) => {
312                 let parent_link = ModuleParentLink(parent, name);
313                 let def = Def::Mod(self.ast_map.local_def_id(item.id));
314                 let module = self.new_module(parent_link, Some(def), false, is_public);
315                 self.define(parent, name, TypeNS, (module, sp));
316                 parent.module_children.borrow_mut().insert(item.id, module);
317                 module
318             }
319
320             ItemForeignMod(..) => parent,
321
322             // These items live in the value namespace.
323             ItemStatic(_, m, _) => {
324                 let mutbl = m == hir::MutMutable;
325                 let def = Def::Static(self.ast_map.local_def_id(item.id), mutbl);
326                 self.define(parent, name, ValueNS, (def, sp, modifiers));
327                 parent
328             }
329             ItemConst(_, _) => {
330                 let def = Def::Const(self.ast_map.local_def_id(item.id));
331                 self.define(parent, name, ValueNS, (def, sp, modifiers));
332                 parent
333             }
334             ItemFn(_, _, _, _, _, _) => {
335                 let def = Def::Fn(self.ast_map.local_def_id(item.id));
336                 self.define(parent, name, ValueNS, (def, sp, modifiers));
337                 parent
338             }
339
340             // These items live in the type namespace.
341             ItemTy(..) => {
342                 let parent_link = ModuleParentLink(parent, name);
343                 let def = Def::TyAlias(self.ast_map.local_def_id(item.id));
344                 let module = self.new_module(parent_link, Some(def), false, is_public);
345                 self.define(parent, name, TypeNS, (module, sp));
346                 parent
347             }
348
349             ItemEnum(ref enum_definition, _) => {
350                 let parent_link = ModuleParentLink(parent, name);
351                 let def = Def::Enum(self.ast_map.local_def_id(item.id));
352                 let module = self.new_module(parent_link, Some(def), false, is_public);
353                 self.define(parent, name, TypeNS, (module, sp));
354
355                 let variant_modifiers = if is_public {
356                     DefModifiers::empty()
357                 } else {
358                     DefModifiers::PRIVATE_VARIANT
359                 };
360                 for variant in &(*enum_definition).variants {
361                     let item_def_id = self.ast_map.local_def_id(item.id);
362                     self.build_reduced_graph_for_variant(variant, item_def_id,
363                                                          module, variant_modifiers);
364                 }
365                 parent
366             }
367
368             // These items live in both the type and value namespaces.
369             ItemStruct(ref struct_def, _) => {
370                 // Define a name in the type namespace.
371                 let def = Def::Struct(self.ast_map.local_def_id(item.id));
372                 self.define(parent, name, TypeNS, (def, sp, modifiers));
373
374                 // If this is a newtype or unit-like struct, define a name
375                 // in the value namespace as well
376                 if !struct_def.is_struct() {
377                     let def = Def::Struct(self.ast_map.local_def_id(struct_def.id()));
378                     self.define(parent, name, ValueNS, (def, sp, modifiers));
379                 }
380
381                 // Record the def ID and fields of this struct.
382                 let field_names = struct_def.fields()
383                                             .iter()
384                                             .map(|f| f.name)
385                                             .collect();
386                 let item_def_id = self.ast_map.local_def_id(item.id);
387                 self.structs.insert(item_def_id, field_names);
388
389                 parent
390             }
391
392             ItemDefaultImpl(_, _) |
393             ItemImpl(..) => parent,
394
395             ItemTrait(_, _, _, ref items) => {
396                 let def_id = self.ast_map.local_def_id(item.id);
397
398                 // Add all the items within to a new module.
399                 let parent_link = ModuleParentLink(parent, name);
400                 let def = Def::Trait(def_id);
401                 let module_parent = self.new_module(parent_link, Some(def), false, is_public);
402                 self.define(parent, name, TypeNS, (module_parent, sp));
403
404                 // Add the names of all the items to the trait info.
405                 for item in items {
406                     let item_def_id = self.ast_map.local_def_id(item.id);
407                     let (def, ns) = match item.node {
408                         hir::ConstTraitItem(..) => (Def::AssociatedConst(item_def_id), ValueNS),
409                         hir::MethodTraitItem(..) => (Def::Method(item_def_id), ValueNS),
410                         hir::TypeTraitItem(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
411                     };
412
413                     let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
414                     self.define(module_parent, item.name, ns, (def, item.span, modifiers));
415
416                     self.trait_item_map.insert((item.name, def_id), item_def_id);
417                 }
418
419                 parent
420             }
421         }
422     }
423
424     // Constructs the reduced graph for one variant. Variants exist in the
425     // type and value namespaces.
426     fn build_reduced_graph_for_variant(&mut self,
427                                        variant: &Variant,
428                                        item_id: DefId,
429                                        parent: Module<'b>,
430                                        variant_modifiers: DefModifiers) {
431         let name = variant.node.name;
432         if variant.node.data.is_struct() {
433             // Not adding fields for variants as they are not accessed with a self receiver
434             let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
435             self.structs.insert(variant_def_id, Vec::new());
436         }
437
438         // Variants are always treated as importable to allow them to be glob used.
439         // All variants are defined in both type and value namespaces as future-proofing.
440         let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers;
441         let def = Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id()));
442
443         self.define(parent, name, ValueNS, (def, variant.span, modifiers));
444         self.define(parent, name, TypeNS, (def, variant.span, modifiers));
445     }
446
447     /// Constructs the reduced graph for one foreign item.
448     fn build_reduced_graph_for_foreign_item(&mut self,
449                                             foreign_item: &ForeignItem,
450                                             parent: Module<'b>) {
451         let name = foreign_item.name;
452         let is_public = foreign_item.vis == hir::Public;
453         let modifiers = if is_public {
454             DefModifiers::PUBLIC
455         } else {
456             DefModifiers::empty()
457         } | DefModifiers::IMPORTABLE;
458
459         let def = match foreign_item.node {
460             ForeignItemFn(..) => {
461                 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
462             }
463             ForeignItemStatic(_, m) => {
464                 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
465             }
466         };
467         self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
468     }
469
470     fn build_reduced_graph_for_block(&mut self, block: &Block, parent: Module<'b>) -> Module<'b> {
471         if self.block_needs_anonymous_module(block) {
472             let block_id = block.id;
473
474             debug!("(building reduced graph for block) creating a new anonymous module for block \
475                     {}",
476                    block_id);
477
478             let parent_link = BlockParentLink(parent, block_id);
479             let new_module = self.new_module(parent_link, None, false, false);
480             parent.module_children.borrow_mut().insert(block_id, new_module);
481             new_module
482         } else {
483             parent
484         }
485     }
486
487     fn handle_external_def(&mut self,
488                            def: Def,
489                            vis: Visibility,
490                            final_ident: &str,
491                            name: Name,
492                            new_parent: Module<'b>) {
493         debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
494                final_ident,
495                vis);
496         let is_public = vis == hir::Public || new_parent.is_trait();
497
498         let mut modifiers = DefModifiers::empty();
499         if is_public {
500             modifiers = modifiers | DefModifiers::PUBLIC;
501         }
502         if new_parent.is_normal() {
503             modifiers = modifiers | DefModifiers::IMPORTABLE;
504         }
505
506         let is_exported = is_public &&
507                           match new_parent.def_id() {
508             None => true,
509             Some(did) => self.external_exports.contains(&did),
510         };
511         if is_exported {
512             self.external_exports.insert(def.def_id());
513         }
514
515         match def {
516             Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => {
517                 debug!("(building reduced graph for external crate) building module {} {}",
518                        final_ident,
519                        is_public);
520                 let parent_link = ModuleParentLink(new_parent, name);
521                 let module = self.new_module(parent_link, Some(def), true, is_public);
522                 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
523             }
524             Def::Variant(_, variant_id) => {
525                 debug!("(building reduced graph for external crate) building variant {}",
526                        final_ident);
527                 // Variants are always treated as importable to allow them to be glob used.
528                 // All variants are defined in both type and value namespaces as future-proofing.
529                 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
530                 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
531                 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
532                 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
533                     // Not adding fields for variants as they are not accessed with a self receiver
534                     self.structs.insert(variant_id, Vec::new());
535                 }
536             }
537             Def::Fn(..) |
538             Def::Static(..) |
539             Def::Const(..) |
540             Def::AssociatedConst(..) |
541             Def::Method(..) => {
542                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
543                        final_ident);
544                 self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
545             }
546             Def::Trait(def_id) => {
547                 debug!("(building reduced graph for external crate) building type {}",
548                        final_ident);
549
550                 // If this is a trait, add all the trait item names to the trait
551                 // info.
552
553                 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
554                 for trait_item_def in &trait_item_def_ids {
555                     let trait_item_name =
556                         self.session.cstore.item_name(trait_item_def.def_id());
557
558                     debug!("(building reduced graph for external crate) ... adding trait item \
559                             '{}'",
560                            trait_item_name);
561
562                     self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
563
564                     if is_exported {
565                         self.external_exports.insert(trait_item_def.def_id());
566                     }
567                 }
568
569                 let parent_link = ModuleParentLink(new_parent, name);
570                 let module = self.new_module(parent_link, Some(def), true, is_public);
571                 self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP));
572             }
573             Def::AssociatedTy(..) => {
574                 debug!("(building reduced graph for external crate) building type {}",
575                        final_ident);
576                 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
577             }
578             Def::Struct(def_id)
579                 if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
580                 debug!("(building reduced graph for external crate) building type and value for \
581                         {}",
582                        final_ident);
583                 self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));
584                 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
585                     let def = Def::Struct(ctor_def_id);
586                     self.try_define(new_parent, name, ValueNS, (def, DUMMY_SP, modifiers));
587                 }
588
589                 // Record the def ID and fields of this struct.
590                 let fields = self.session.cstore.struct_field_names(def_id);
591                 self.structs.insert(def_id, fields);
592             }
593             Def::Struct(..) => {}
594             Def::Local(..) |
595             Def::PrimTy(..) |
596             Def::TyParam(..) |
597             Def::Upvar(..) |
598             Def::Label(..) |
599             Def::SelfTy(..) |
600             Def::Err => {
601                 panic!("didn't expect `{:?}`", def);
602             }
603         }
604     }
605
606     /// Builds the reduced graph for a single item in an external crate.
607     fn build_reduced_graph_for_external_crate_def(&mut self,
608                                                   root: Module<'b>,
609                                                   xcdef: ChildItem) {
610         match xcdef.def {
611             DlDef(def) => {
612                 // Add the new child item, if necessary.
613                 match def {
614                     Def::ForeignMod(def_id) => {
615                         // Foreign modules have no names. Recur and populate
616                         // eagerly.
617                         for child in self.session.cstore.item_children(def_id) {
618                             self.build_reduced_graph_for_external_crate_def(root, child)
619                         }
620                     }
621                     _ => {
622                         self.handle_external_def(def,
623                                                  xcdef.vis,
624                                                  &xcdef.name.as_str(),
625                                                  xcdef.name,
626                                                  root);
627                     }
628                 }
629             }
630             DlImpl(_) => {
631                 debug!("(building reduced graph for external crate) ignoring impl");
632             }
633             DlField => {
634                 debug!("(building reduced graph for external crate) ignoring field");
635             }
636         }
637     }
638
639     /// Builds the reduced graph rooted at the given external module.
640     fn populate_external_module(&mut self, module: Module<'b>) {
641         debug!("(populating external module) attempting to populate {}",
642                module_to_string(module));
643
644         let def_id = match module.def_id() {
645             None => {
646                 debug!("(populating external module) ... no def ID!");
647                 return;
648             }
649             Some(def_id) => def_id,
650         };
651
652         for child in self.session.cstore.item_children(def_id) {
653             debug!("(populating external module) ... found ident: {}",
654                    child.name);
655             self.build_reduced_graph_for_external_crate_def(module, child);
656         }
657         module.populated.set(true)
658     }
659
660     /// Ensures that the reduced graph rooted at the given external module
661     /// is built, building it if it is not.
662     fn populate_module_if_necessary(&mut self, module: Module<'b>) {
663         if !module.populated.get() {
664             self.populate_external_module(module)
665         }
666         assert!(module.populated.get())
667     }
668
669     /// Builds the reduced graph rooted at the 'use' directive for an external
670     /// crate.
671     fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
672         let root_cnum = root.def_id().unwrap().krate;
673         for child in self.session.cstore.crate_top_level_items(root_cnum) {
674             self.build_reduced_graph_for_external_crate_def(root, child);
675         }
676     }
677
678     /// Creates and adds an import directive to the given module.
679     fn build_import_directive(&mut self,
680                               module_: Module<'b>,
681                               module_path: Vec<Name>,
682                               subclass: ImportDirectiveSubclass,
683                               span: Span,
684                               id: NodeId,
685                               is_public: bool,
686                               shadowable: Shadowable) {
687         if is_public {
688             module_.inc_pub_count();
689         }
690
691         // Bump the reference count on the name. Or, if this is a glob, set
692         // the appropriate flag.
693
694         match subclass {
695             SingleImport { target, .. } => {
696                 module_.increment_outstanding_references_for(target, ValueNS);
697                 module_.increment_outstanding_references_for(target, TypeNS);
698             }
699             GlobImport => {
700                 // Set the glob flag. This tells us that we don't know the
701                 // module's exports ahead of time.
702
703                 module_.inc_glob_count();
704                 if is_public {
705                     module_.inc_pub_glob_count();
706                 }
707             }
708         }
709
710         let directive =
711             ImportDirective::new(module_path, subclass, span, id, is_public, shadowable);
712         let directive = self.resolver.arenas.alloc_import_directive(directive);
713         module_.unresolved_imports.borrow_mut().push(directive);
714         self.unresolved_imports += 1;
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 }