]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Auto merge of #30859 - aliclark:musl-nx-issue, r=brson
[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 resolve_imports::{ImportResolution, ImportResolutionPerNamespace};
20 use Module;
21 use Namespace::{TypeNS, ValueNS};
22 use NameBindings;
23 use {names_to_string, module_to_string};
24 use ParentLink::{ModuleParentLink, BlockParentLink};
25 use Resolver;
26 use resolve_imports::Shadowable;
27 use {resolve_error, resolve_struct_error, ResolutionError};
28
29 use self::DuplicateCheckingMode::*;
30
31 use rustc::middle::cstore::{CrateStore, ChildItem, DlDef, DlField, DlImpl};
32 use rustc::middle::def::*;
33 use rustc::middle::def_id::{CRATE_DEF_INDEX, DefId};
34 use rustc::middle::ty::VariantKind;
35
36 use syntax::ast::{Name, NodeId};
37 use syntax::attr::AttrMetaMethods;
38 use syntax::parse::token::special_idents;
39 use syntax::codemap::{Span, DUMMY_SP};
40
41 use rustc_front::hir;
42 use rustc_front::hir::{Block, DeclItem};
43 use rustc_front::hir::{ForeignItem, ForeignItemFn, ForeignItemStatic};
44 use rustc_front::hir::{Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn};
45 use rustc_front::hir::{ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
46 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
47 use rustc_front::hir::{NamedField, PathListIdent, PathListMod};
48 use rustc_front::hir::StmtDecl;
49 use rustc_front::hir::UnnamedField;
50 use rustc_front::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
51 use rustc_front::hir::Visibility;
52 use rustc_front::intravisit::{self, Visitor};
53
54 use std::mem::replace;
55 use std::ops::{Deref, DerefMut};
56
57 // Specifies how duplicates should be handled when adding a child item if
58 // another item exists with the same name in some namespace.
59 #[derive(Copy, Clone, PartialEq)]
60 enum DuplicateCheckingMode {
61     ForbidDuplicateTypes,
62     ForbidDuplicateValues,
63     ForbidDuplicateTypesAndValues,
64     OverwriteDuplicates,
65 }
66
67 struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
68     resolver: &'a mut Resolver<'b, 'tcx>,
69 }
70
71 impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
72     type Target = Resolver<'b, 'tcx>;
73
74     fn deref(&self) -> &Resolver<'b, 'tcx> {
75         &*self.resolver
76     }
77 }
78
79 impl<'a, 'b:'a, 'tcx:'b> DerefMut for GraphBuilder<'a, 'b, 'tcx> {
80     fn deref_mut(&mut self) -> &mut Resolver<'b, 'tcx> {
81         &mut *self.resolver
82     }
83 }
84
85 impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> {
86     /// Constructs the reduced graph for the entire crate.
87     fn build_reduced_graph(self, krate: &hir::Crate) {
88         let mut visitor = BuildReducedGraphVisitor {
89             parent: self.graph_root,
90             builder: self,
91         };
92         intravisit::walk_crate(&mut visitor, krate);
93     }
94
95     /// Adds a new child item to the module definition of the parent node,
96     /// or if there is already a child, does duplicate checking on the child.
97     /// Returns the child's corresponding name bindings.
98     fn add_child(&self,
99                  name: Name,
100                  parent: Module<'b>,
101                  duplicate_checking_mode: DuplicateCheckingMode,
102                  // For printing errors
103                  sp: Span)
104                  -> NameBindings<'b> {
105         self.check_for_conflicts_between_external_crates_and_items(parent, name, sp);
106
107         // Add or reuse the child.
108         let child = parent.children.borrow().get(&name).cloned();
109         match child {
110             None => {
111                 let child = NameBindings::new();
112                 parent.children.borrow_mut().insert(name, child.clone());
113                 child
114             }
115             Some(child) => {
116                 // Enforce the duplicate checking mode:
117                 //
118                 // * If we're requesting duplicate type checking, check that
119                 //   the name isn't defined in the type namespace.
120                 //
121                 // * If we're requesting duplicate value checking, check that
122                 //   the name isn't defined in the value namespace.
123                 //
124                 // * If we're requesting duplicate type and value checking,
125                 //   check that the name isn't defined in either namespace.
126                 //
127                 // * If no duplicate checking was requested at all, do
128                 //   nothing.
129
130                 let ns = match duplicate_checking_mode {
131                     ForbidDuplicateTypes if child.type_ns.defined() => TypeNS,
132                     ForbidDuplicateValues if child.value_ns.defined() => ValueNS,
133                     ForbidDuplicateTypesAndValues if child.type_ns.defined() => TypeNS,
134                     ForbidDuplicateTypesAndValues if child.value_ns.defined() => ValueNS,
135                     _ => return child,
136                 };
137
138                 // Record an error here by looking up the namespace that had the duplicate
139                 let ns_str = match ns { TypeNS => "type or module", ValueNS => "value" };
140                 let mut err = resolve_struct_error(self,
141                                                    sp,
142                                                    ResolutionError::DuplicateDefinition(ns_str,
143                                                                                         name));
144
145                 if let Some(sp) = child[ns].span() {
146                     let note = format!("first definition of {} `{}` here", ns_str, name);
147                     err.span_note(sp, &note);
148                 }
149                 err.emit();
150                 child
151             }
152         }
153     }
154
155     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
156         // Check each statement.
157         for statement in &block.stmts {
158             match statement.node {
159                 StmtDecl(ref declaration, _) => {
160                     match declaration.node {
161                         DeclItem(_) => {
162                             return true;
163                         }
164                         _ => {
165                             // Keep searching.
166                         }
167                     }
168                 }
169                 _ => {
170                     // Keep searching.
171                 }
172             }
173         }
174
175         // If we found no items, we don't need to create
176         // an anonymous module.
177
178         return false;
179     }
180
181     /// Constructs the reduced graph for one item.
182     fn build_reduced_graph_for_item(&mut self, item: &Item, parent: Module<'b>) -> Module<'b> {
183         let name = item.name;
184         let sp = item.span;
185         let is_public = item.vis == hir::Public;
186         let modifiers = if is_public {
187             DefModifiers::PUBLIC
188         } else {
189             DefModifiers::empty()
190         } | DefModifiers::IMPORTABLE;
191
192         match item.node {
193             ItemUse(ref view_path) => {
194                 // Extract and intern the module part of the path. For
195                 // globs and lists, the path is found directly in the AST;
196                 // for simple paths we have to munge the path a little.
197                 let module_path = match view_path.node {
198                     ViewPathSimple(_, ref full_path) => {
199                         full_path.segments
200                                  .split_last()
201                                  .unwrap()
202                                  .1
203                                  .iter()
204                                  .map(|seg| seg.identifier.name)
205                                  .collect()
206                     }
207
208                     ViewPathGlob(ref module_ident_path) |
209                     ViewPathList(ref module_ident_path, _) => {
210                         module_ident_path.segments
211                                          .iter()
212                                          .map(|seg| seg.identifier.name)
213                                          .collect()
214                     }
215                 };
216
217                 // Build up the import directives.
218                 let shadowable = item.attrs.iter().any(|attr| {
219                     attr.name() == special_idents::prelude_import.name.as_str()
220                 });
221                 let shadowable = if shadowable {
222                     Shadowable::Always
223                 } else {
224                     Shadowable::Never
225                 };
226
227                 match view_path.node {
228                     ViewPathSimple(binding, ref full_path) => {
229                         let source_name = full_path.segments.last().unwrap().identifier.name;
230                         if source_name.as_str() == "mod" || source_name.as_str() == "self" {
231                             resolve_error(self,
232                                           view_path.span,
233                                           ResolutionError::SelfImportsOnlyAllowedWithin);
234                         }
235
236                         let subclass = SingleImport(binding, source_name);
237                         self.build_import_directive(parent,
238                                                     module_path,
239                                                     subclass,
240                                                     view_path.span,
241                                                     item.id,
242                                                     is_public,
243                                                     shadowable);
244                     }
245                     ViewPathList(_, ref source_items) => {
246                         // Make sure there's at most one `mod` import in the list.
247                         let mod_spans = source_items.iter()
248                                                     .filter_map(|item| {
249                                                         match item.node {
250                                                             PathListMod { .. } => Some(item.span),
251                                                             _ => None,
252                                                         }
253                                                     })
254                                                     .collect::<Vec<Span>>();
255                         if mod_spans.len() > 1 {
256                             let mut e = resolve_struct_error(self,
257                                           mod_spans[0],
258                                           ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
259                             for other_span in mod_spans.iter().skip(1) {
260                                 e.span_note(*other_span, "another `self` import appears here");
261                             }
262                             e.emit();
263                         }
264
265                         for source_item in source_items {
266                             let (module_path, name, rename) = match source_item.node {
267                                 PathListIdent { name, rename, .. } =>
268                                     (module_path.clone(), name, rename.unwrap_or(name)),
269                                 PathListMod { rename, .. } => {
270                                     let name = match module_path.last() {
271                                         Some(name) => *name,
272                                         None => {
273                                             resolve_error(
274                                                 self,
275                                                 source_item.span,
276                                                 ResolutionError::
277                                                 SelfImportOnlyInImportListWithNonEmptyPrefix
278                                             );
279                                             continue;
280                                         }
281                                     };
282                                     let module_path = module_path.split_last().unwrap().1;
283                                     let rename = rename.unwrap_or(name);
284                                     (module_path.to_vec(), name, rename)
285                                 }
286                             };
287                             self.build_import_directive(parent,
288                                                         module_path,
289                                                         SingleImport(rename, name),
290                                                         source_item.span,
291                                                         source_item.node.id(),
292                                                         is_public,
293                                                         shadowable);
294                         }
295                     }
296                     ViewPathGlob(_) => {
297                         self.build_import_directive(parent,
298                                                     module_path,
299                                                     GlobImport,
300                                                     view_path.span,
301                                                     item.id,
302                                                     is_public,
303                                                     shadowable);
304                     }
305                 }
306                 parent
307             }
308
309             ItemExternCrate(_) => {
310                 // n.b. we don't need to look at the path option here, because cstore already
311                 // did
312                 if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
313                     let def_id = DefId {
314                         krate: crate_id,
315                         index: CRATE_DEF_INDEX,
316                     };
317                     self.external_exports.insert(def_id);
318                     let parent_link = ModuleParentLink(parent, name);
319                     let def = Def::Mod(def_id);
320                     let external_module = self.new_module(parent_link, Some(def), false, true);
321
322                     debug!("(build reduced graph for item) found extern `{}`",
323                            module_to_string(&*external_module));
324                     self.check_for_conflicts_for_external_crate(parent, name, sp);
325                     parent.external_module_children
326                           .borrow_mut()
327                           .insert(name, external_module);
328                     self.build_reduced_graph_for_external_crate(&external_module);
329                 }
330                 parent
331             }
332
333             ItemMod(..) => {
334                 let name_bindings = self.add_child(name, parent, ForbidDuplicateTypes, sp);
335
336                 let parent_link = ModuleParentLink(parent, name);
337                 let def = Def::Mod(self.ast_map.local_def_id(item.id));
338                 let module = self.new_module(parent_link, Some(def), false, is_public);
339                 name_bindings.define_module(module.clone(), sp);
340                 module
341             }
342
343             ItemForeignMod(..) => parent,
344
345             // These items live in the value namespace.
346             ItemStatic(_, m, _) => {
347                 let name_bindings = self.add_child(name, parent, ForbidDuplicateValues, sp);
348                 let mutbl = m == hir::MutMutable;
349
350                 name_bindings.define_value(Def::Static(self.ast_map.local_def_id(item.id), mutbl),
351                                            sp,
352                                            modifiers);
353                 parent
354             }
355             ItemConst(_, _) => {
356                 self.add_child(name, parent, ForbidDuplicateValues, sp)
357                     .define_value(Def::Const(self.ast_map.local_def_id(item.id)), sp, modifiers);
358                 parent
359             }
360             ItemFn(_, _, _, _, _, _) => {
361                 let name_bindings = self.add_child(name, parent, ForbidDuplicateValues, sp);
362
363                 let def = Def::Fn(self.ast_map.local_def_id(item.id));
364                 name_bindings.define_value(def, sp, modifiers);
365                 parent
366             }
367
368             // These items live in the type namespace.
369             ItemTy(..) => {
370                 let name_bindings = self.add_child(name,
371                                                    parent,
372                                                    ForbidDuplicateTypes,
373                                                    sp);
374
375                 let parent_link = ModuleParentLink(parent, name);
376                 let def = Def::TyAlias(self.ast_map.local_def_id(item.id));
377                 let module = self.new_module(parent_link, Some(def), false, is_public);
378                 name_bindings.define_module(module, sp);
379                 parent
380             }
381
382             ItemEnum(ref enum_definition, _) => {
383                 let name_bindings = self.add_child(name,
384                                                    parent,
385                                                    ForbidDuplicateTypes,
386                                                    sp);
387
388                 let parent_link = ModuleParentLink(parent, name);
389                 let def = Def::Enum(self.ast_map.local_def_id(item.id));
390                 let module = self.new_module(parent_link, Some(def), false, is_public);
391                 name_bindings.define_module(module.clone(), sp);
392
393                 let variant_modifiers = if is_public {
394                     DefModifiers::empty()
395                 } else {
396                     DefModifiers::PRIVATE_VARIANT
397                 };
398                 for variant in &(*enum_definition).variants {
399                     let item_def_id = self.ast_map.local_def_id(item.id);
400                     self.build_reduced_graph_for_variant(variant, item_def_id,
401                                                          &module, variant_modifiers);
402                 }
403                 parent
404             }
405
406             // These items live in both the type and value namespaces.
407             ItemStruct(ref struct_def, _) => {
408                 // Adding to both Type and Value namespaces or just Type?
409                 let (forbid, ctor_id) = if struct_def.is_struct() {
410                     (ForbidDuplicateTypes, None)
411                 } else {
412                     (ForbidDuplicateTypesAndValues, Some(struct_def.id()))
413                 };
414
415                 let name_bindings = self.add_child(name, parent, forbid, sp);
416
417                 // Define a name in the type namespace.
418                 name_bindings.define_type(Def::Struct(self.ast_map.local_def_id(item.id)),
419                                           sp,
420                                           modifiers);
421
422                 // If this is a newtype or unit-like struct, define a name
423                 // in the value namespace as well
424                 if let Some(cid) = ctor_id {
425                     name_bindings.define_value(Def::Struct(self.ast_map.local_def_id(cid)),
426                                                sp,
427                                                modifiers);
428                 }
429
430                 // Record the def ID and fields of this struct.
431                 let named_fields = struct_def.fields()
432                                              .iter()
433                                              .filter_map(|f| {
434                                                  match f.node.kind {
435                                                      NamedField(name, _) => Some(name),
436                                                      UnnamedField(_) => None,
437                                                  }
438                                              })
439                                              .collect();
440                 let item_def_id = self.ast_map.local_def_id(item.id);
441                 self.structs.insert(item_def_id, named_fields);
442
443                 parent
444             }
445
446             ItemDefaultImpl(_, _) |
447             ItemImpl(..) => parent,
448
449             ItemTrait(_, _, _, ref items) => {
450                 let name_bindings = self.add_child(name,
451                                                    parent,
452                                                    ForbidDuplicateTypes,
453                                                    sp);
454
455                 let def_id = self.ast_map.local_def_id(item.id);
456
457                 // Add all the items within to a new module.
458                 let parent_link = ModuleParentLink(parent, name);
459                 let def = Def::Trait(def_id);
460                 let module_parent = self.new_module(parent_link, Some(def), false, is_public);
461                 name_bindings.define_module(module_parent.clone(), sp);
462
463                 // Add the names of all the items to the trait info.
464                 for trait_item in items {
465                     let name_bindings = self.add_child(trait_item.name,
466                                                        &module_parent,
467                                                        ForbidDuplicateTypesAndValues,
468                                                        trait_item.span);
469
470                     match trait_item.node {
471                         hir::ConstTraitItem(..) => {
472                             let def = Def::AssociatedConst(self.ast_map.
473                                                                 local_def_id(trait_item.id));
474                             // NB: not DefModifiers::IMPORTABLE
475                             name_bindings.define_value(def, trait_item.span, DefModifiers::PUBLIC);
476                         }
477                         hir::MethodTraitItem(..) => {
478                             let def = Def::Method(self.ast_map.local_def_id(trait_item.id));
479                             // NB: not DefModifiers::IMPORTABLE
480                             name_bindings.define_value(def, trait_item.span, DefModifiers::PUBLIC);
481                         }
482                         hir::TypeTraitItem(..) => {
483                             let def = Def::AssociatedTy(self.ast_map.local_def_id(item.id),
484                                                       self.ast_map.local_def_id(trait_item.id));
485                             // NB: not DefModifiers::IMPORTABLE
486                             name_bindings.define_type(def, trait_item.span, DefModifiers::PUBLIC);
487                         }
488                     }
489
490                     let trait_item_def_id = self.ast_map.local_def_id(trait_item.id);
491                     self.trait_item_map.insert((trait_item.name, def_id), trait_item_def_id);
492                 }
493
494                 parent
495             }
496         }
497     }
498
499     // Constructs the reduced graph for one variant. Variants exist in the
500     // type and value namespaces.
501     fn build_reduced_graph_for_variant(&mut self,
502                                        variant: &Variant,
503                                        item_id: DefId,
504                                        parent: Module<'b>,
505                                        variant_modifiers: DefModifiers) {
506         let name = variant.node.name;
507         if variant.node.data.is_struct() {
508             // Not adding fields for variants as they are not accessed with a self receiver
509             let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
510             self.structs.insert(variant_def_id, Vec::new());
511         }
512
513         // Variants are always treated as importable to allow them to be glob used.
514         // All variants are defined in both type and value namespaces as future-proofing.
515         let child = self.add_child(name, parent, ForbidDuplicateTypesAndValues, variant.span);
516         child.define_value(Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id())),
517                            variant.span,
518                            DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers);
519         child.define_type(Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id())),
520                           variant.span,
521                           DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers);
522     }
523
524     /// Constructs the reduced graph for one foreign item.
525     fn build_reduced_graph_for_foreign_item(&mut self,
526                                             foreign_item: &ForeignItem,
527                                             parent: Module<'b>) {
528         let name = foreign_item.name;
529         let is_public = foreign_item.vis == hir::Public;
530         let modifiers = if is_public {
531             DefModifiers::PUBLIC
532         } else {
533             DefModifiers::empty()
534         } | DefModifiers::IMPORTABLE;
535         let name_bindings = self.add_child(name, parent, ForbidDuplicateValues, foreign_item.span);
536
537         let def = match foreign_item.node {
538             ForeignItemFn(..) => {
539                 Def::Fn(self.ast_map.local_def_id(foreign_item.id))
540             }
541             ForeignItemStatic(_, m) => {
542                 Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
543             }
544         };
545         name_bindings.define_value(def, foreign_item.span, modifiers);
546     }
547
548     fn build_reduced_graph_for_block(&mut self, block: &Block, parent: Module<'b>) -> Module<'b> {
549         if self.block_needs_anonymous_module(block) {
550             let block_id = block.id;
551
552             debug!("(building reduced graph for block) creating a new anonymous module for block \
553                     {}",
554                    block_id);
555
556             let parent_link = BlockParentLink(parent, block_id);
557             let new_module = self.new_module(parent_link, None, false, false);
558             parent.anonymous_children.borrow_mut().insert(block_id, new_module);
559             new_module
560         } else {
561             parent
562         }
563     }
564
565     fn handle_external_def(&mut self,
566                            def: Def,
567                            vis: Visibility,
568                            child_name_bindings: &NameBindings<'b>,
569                            final_ident: &str,
570                            name: Name,
571                            new_parent: Module<'b>) {
572         debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
573                final_ident,
574                vis);
575         let is_public = vis == hir::Public;
576         let modifiers = if is_public {
577             DefModifiers::PUBLIC
578         } else {
579             DefModifiers::empty()
580         } | DefModifiers::IMPORTABLE;
581         let is_exported = is_public &&
582                           match new_parent.def_id() {
583             None => true,
584             Some(did) => self.external_exports.contains(&did),
585         };
586         if is_exported {
587             self.external_exports.insert(def.def_id());
588         }
589         let is_struct_ctor = if let Def::Struct(def_id) = def {
590             self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_some()
591         } else {
592             false
593         };
594
595         match def {
596             Def::Mod(_) |
597             Def::ForeignMod(_) |
598             Def::Struct(..) |
599             Def::Enum(..) |
600             Def::TyAlias(..) if !is_struct_ctor => {
601                 if let Some(module_def) = child_name_bindings.type_ns.module() {
602                     debug!("(building reduced graph for external crate) already created module");
603                     module_def.def.set(Some(def));
604                 } else {
605                     debug!("(building reduced graph for external crate) building module {} {}",
606                            final_ident,
607                            is_public);
608                     let parent_link = ModuleParentLink(new_parent, name);
609                     let module = self.new_module(parent_link, Some(def), true, is_public);
610                     child_name_bindings.define_module(module, DUMMY_SP);
611                 }
612             }
613             _ => {}
614         }
615
616         match def {
617             Def::Mod(_) | Def::ForeignMod(_) => {}
618             Def::Variant(_, variant_id) => {
619                 debug!("(building reduced graph for external crate) building variant {}",
620                        final_ident);
621                 // Variants are always treated as importable to allow them to be glob used.
622                 // All variants are defined in both type and value namespaces as future-proofing.
623                 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
624                 child_name_bindings.define_type(def, DUMMY_SP, modifiers);
625                 child_name_bindings.define_value(def, DUMMY_SP, modifiers);
626                 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
627                     // Not adding fields for variants as they are not accessed with a self receiver
628                     self.structs.insert(variant_id, Vec::new());
629                 }
630             }
631             Def::Fn(..) |
632             Def::Static(..) |
633             Def::Const(..) |
634             Def::AssociatedConst(..) |
635             Def::Method(..) => {
636                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
637                        final_ident);
638                 // impl methods have already been defined with the correct importability
639                 // modifier
640                 let mut modifiers = match *child_name_bindings.value_ns.borrow() {
641                     Some(ref def) => (modifiers & !DefModifiers::IMPORTABLE) |
642                                      (def.modifiers & DefModifiers::IMPORTABLE),
643                     None => modifiers,
644                 };
645                 if !new_parent.is_normal() {
646                     modifiers = modifiers & !DefModifiers::IMPORTABLE;
647                 }
648                 child_name_bindings.define_value(def, DUMMY_SP, modifiers);
649             }
650             Def::Trait(def_id) => {
651                 debug!("(building reduced graph for external crate) building type {}",
652                        final_ident);
653
654                 // If this is a trait, add all the trait item names to the trait
655                 // info.
656
657                 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
658                 for trait_item_def in &trait_item_def_ids {
659                     let trait_item_name =
660                         self.session.cstore.item_name(trait_item_def.def_id());
661
662                     debug!("(building reduced graph for external crate) ... adding trait item \
663                             '{}'",
664                            trait_item_name);
665
666                     self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
667
668                     if is_exported {
669                         self.external_exports.insert(trait_item_def.def_id());
670                     }
671                 }
672
673                 // Define a module if necessary.
674                 let parent_link = ModuleParentLink(new_parent, name);
675                 let module = self.new_module(parent_link, Some(def), true, is_public);
676                 child_name_bindings.define_module(module, DUMMY_SP);
677             }
678             Def::Enum(..) | Def::TyAlias(..) | Def::AssociatedTy(..) => {
679                 debug!("(building reduced graph for external crate) building type {}",
680                        final_ident);
681
682                 let modifiers = match new_parent.is_normal() {
683                     true => modifiers,
684                     _ => modifiers & !DefModifiers::IMPORTABLE,
685                 };
686
687                 if let Def::Enum(..) = def {
688                     child_name_bindings.type_ns.set_modifiers(modifiers);
689                 } else if let Def::TyAlias(..) = def {
690                     child_name_bindings.type_ns.set_modifiers(modifiers);
691                 } else {
692                     child_name_bindings.define_type(def, DUMMY_SP, modifiers);
693                 }
694             }
695             Def::Struct(..) if is_struct_ctor => {
696                 // Do nothing
697             }
698             Def::Struct(def_id) => {
699                 debug!("(building reduced graph for external crate) building type and value for \
700                         {}",
701                        final_ident);
702
703                 child_name_bindings.define_type(def, DUMMY_SP, modifiers);
704                 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
705                     child_name_bindings.define_value(Def::Struct(ctor_def_id), DUMMY_SP, modifiers);
706                 }
707
708                 // Record the def ID and fields of this struct.
709                 let fields = self.session.cstore.struct_field_names(def_id);
710                 self.structs.insert(def_id, fields);
711             }
712             Def::Local(..) |
713             Def::PrimTy(..) |
714             Def::TyParam(..) |
715             Def::Upvar(..) |
716             Def::Label(..) |
717             Def::SelfTy(..) |
718             Def::Err => {
719                 panic!("didn't expect `{:?}`", def);
720             }
721         }
722     }
723
724     /// Builds the reduced graph for a single item in an external crate.
725     fn build_reduced_graph_for_external_crate_def(&mut self,
726                                                   root: Module<'b>,
727                                                   xcdef: ChildItem) {
728         match xcdef.def {
729             DlDef(def) => {
730                 // Add the new child item, if necessary.
731                 match def {
732                     Def::ForeignMod(def_id) => {
733                         // Foreign modules have no names. Recur and populate
734                         // eagerly.
735                         for child in self.session.cstore.item_children(def_id) {
736                             self.build_reduced_graph_for_external_crate_def(root, child)
737                         }
738                     }
739                     _ => {
740                         let child_name_bindings = self.add_child(xcdef.name,
741                                                                  root,
742                                                                  OverwriteDuplicates,
743                                                                  DUMMY_SP);
744
745                         self.handle_external_def(def,
746                                                  xcdef.vis,
747                                                  &child_name_bindings,
748                                                  &xcdef.name.as_str(),
749                                                  xcdef.name,
750                                                  root);
751                     }
752                 }
753             }
754             DlImpl(_) => {
755                 debug!("(building reduced graph for external crate) ignoring impl");
756             }
757             DlField => {
758                 debug!("(building reduced graph for external crate) ignoring field");
759             }
760         }
761     }
762
763     /// Builds the reduced graph rooted at the given external module.
764     fn populate_external_module(&mut self, module: Module<'b>) {
765         debug!("(populating external module) attempting to populate {}",
766                module_to_string(module));
767
768         let def_id = match module.def_id() {
769             None => {
770                 debug!("(populating external module) ... no def ID!");
771                 return;
772             }
773             Some(def_id) => def_id,
774         };
775
776         for child in self.session.cstore.item_children(def_id) {
777             debug!("(populating external module) ... found ident: {}",
778                    child.name);
779             self.build_reduced_graph_for_external_crate_def(module, child);
780         }
781         module.populated.set(true)
782     }
783
784     /// Ensures that the reduced graph rooted at the given external module
785     /// is built, building it if it is not.
786     fn populate_module_if_necessary(&mut self, module: Module<'b>) {
787         if !module.populated.get() {
788             self.populate_external_module(module)
789         }
790         assert!(module.populated.get())
791     }
792
793     /// Builds the reduced graph rooted at the 'use' directive for an external
794     /// crate.
795     fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
796         let root_cnum = root.def_id().unwrap().krate;
797         for child in self.session.cstore.crate_top_level_items(root_cnum) {
798             self.build_reduced_graph_for_external_crate_def(root, child);
799         }
800     }
801
802     /// Creates and adds an import directive to the given module.
803     fn build_import_directive(&mut self,
804                               module_: Module<'b>,
805                               module_path: Vec<Name>,
806                               subclass: ImportDirectiveSubclass,
807                               span: Span,
808                               id: NodeId,
809                               is_public: bool,
810                               shadowable: Shadowable) {
811         module_.imports
812                .borrow_mut()
813                .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
814         self.unresolved_imports += 1;
815
816         if is_public {
817             module_.inc_pub_count();
818         }
819
820         // Bump the reference count on the name. Or, if this is a glob, set
821         // the appropriate flag.
822
823         match subclass {
824             SingleImport(target, _) => {
825                 debug!("(building import directive) building import directive: {}::{}",
826                        names_to_string(&module_.imports.borrow().last().unwrap().module_path),
827                        target);
828
829                 let mut import_resolutions = module_.import_resolutions.borrow_mut();
830                 match import_resolutions.get_mut(&target) {
831                     Some(resolution_per_ns) => {
832                         debug!("(building import directive) bumping reference");
833                         resolution_per_ns.outstanding_references += 1;
834
835                         // the source of this name is different now
836                         let resolution =
837                             ImportResolution { id: id, is_public: is_public, target: None };
838                         resolution_per_ns[TypeNS] = resolution.clone();
839                         resolution_per_ns[ValueNS] = resolution;
840                         return;
841                     }
842                     None => {}
843                 }
844                 debug!("(building import directive) creating new");
845                 let mut import_resolution_per_ns = ImportResolutionPerNamespace::new(id, is_public);
846                 import_resolution_per_ns.outstanding_references = 1;
847                 import_resolutions.insert(target, import_resolution_per_ns);
848             }
849             GlobImport => {
850                 // Set the glob flag. This tells us that we don't know the
851                 // module's exports ahead of time.
852
853                 module_.inc_glob_count();
854                 if is_public {
855                     module_.inc_pub_glob_count();
856                 }
857             }
858         }
859     }
860 }
861
862 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
863     builder: GraphBuilder<'a, 'b, 'tcx>,
864     parent: Module<'b>,
865 }
866
867 impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
868     fn visit_nested_item(&mut self, item: hir::ItemId) {
869         self.visit_item(self.builder.resolver.ast_map.expect_item(item.id))
870     }
871
872     fn visit_item(&mut self, item: &Item) {
873         let p = self.builder.build_reduced_graph_for_item(item, &self.parent);
874         let old_parent = replace(&mut self.parent, p);
875         intravisit::walk_item(self, item);
876         self.parent = old_parent;
877     }
878
879     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
880         self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
881     }
882
883     fn visit_block(&mut self, block: &Block) {
884         let np = self.builder.build_reduced_graph_for_block(block, &self.parent);
885         let old_parent = replace(&mut self.parent, np);
886         intravisit::walk_block(self, block);
887         self.parent = old_parent;
888     }
889 }
890
891 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
892     GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
893 }
894
895 pub fn populate_module_if_necessary<'a, 'tcx>(resolver: &mut Resolver<'a, 'tcx>,
896                                               module: Module<'a>) {
897     GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);
898 }