]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Fix a rebasing issue and addressed reviewer comment
[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         let child = self.add_child(name, parent, ForbidDuplicateTypesAndValues, variant.span);
514         // variants are always treated as importable to allow them to be glob
515         // used
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
622                 // glob used
623                 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
624                 if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
625                     child_name_bindings.define_type(def, DUMMY_SP, modifiers);
626                     // Not adding fields for variants as they are not accessed with a self receiver
627                     self.structs.insert(variant_id, Vec::new());
628                 } else {
629                     child_name_bindings.define_value(def, DUMMY_SP, modifiers);
630                 }
631             }
632             Def::Fn(..) |
633             Def::Static(..) |
634             Def::Const(..) |
635             Def::AssociatedConst(..) |
636             Def::Method(..) => {
637                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
638                        final_ident);
639                 // impl methods have already been defined with the correct importability
640                 // modifier
641                 let mut modifiers = match *child_name_bindings.value_ns.borrow() {
642                     Some(ref def) => (modifiers & !DefModifiers::IMPORTABLE) |
643                                      (def.modifiers & DefModifiers::IMPORTABLE),
644                     None => modifiers,
645                 };
646                 if !new_parent.is_normal() {
647                     modifiers = modifiers & !DefModifiers::IMPORTABLE;
648                 }
649                 child_name_bindings.define_value(def, DUMMY_SP, modifiers);
650             }
651             Def::Trait(def_id) => {
652                 debug!("(building reduced graph for external crate) building type {}",
653                        final_ident);
654
655                 // If this is a trait, add all the trait item names to the trait
656                 // info.
657
658                 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
659                 for trait_item_def in &trait_item_def_ids {
660                     let trait_item_name =
661                         self.session.cstore.item_name(trait_item_def.def_id());
662
663                     debug!("(building reduced graph for external crate) ... adding trait item \
664                             '{}'",
665                            trait_item_name);
666
667                     self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
668
669                     if is_exported {
670                         self.external_exports.insert(trait_item_def.def_id());
671                     }
672                 }
673
674                 // Define a module if necessary.
675                 let parent_link = ModuleParentLink(new_parent, name);
676                 let module = self.new_module(parent_link, Some(def), true, is_public);
677                 child_name_bindings.define_module(module, DUMMY_SP);
678             }
679             Def::Enum(..) | Def::TyAlias(..) | Def::AssociatedTy(..) => {
680                 debug!("(building reduced graph for external crate) building type {}",
681                        final_ident);
682
683                 let modifiers = match new_parent.is_normal() {
684                     true => modifiers,
685                     _ => modifiers & !DefModifiers::IMPORTABLE,
686                 };
687
688                 if let Def::Enum(..) = def {
689                     child_name_bindings.type_ns.set_modifiers(modifiers);
690                 } else if let Def::TyAlias(..) = def {
691                     child_name_bindings.type_ns.set_modifiers(modifiers);
692                 } else {
693                     child_name_bindings.define_type(def, DUMMY_SP, modifiers);
694                 }
695             }
696             Def::Struct(..) if is_struct_ctor => {
697                 // Do nothing
698             }
699             Def::Struct(def_id) => {
700                 debug!("(building reduced graph for external crate) building type and value for \
701                         {}",
702                        final_ident);
703
704                 child_name_bindings.define_type(def, DUMMY_SP, modifiers);
705                 if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
706                     child_name_bindings.define_value(Def::Struct(ctor_def_id), DUMMY_SP, modifiers);
707                 }
708
709                 // Record the def ID and fields of this struct.
710                 let fields = self.session.cstore.struct_field_names(def_id);
711                 self.structs.insert(def_id, fields);
712             }
713             Def::Local(..) |
714             Def::PrimTy(..) |
715             Def::TyParam(..) |
716             Def::Upvar(..) |
717             Def::Label(..) |
718             Def::SelfTy(..) |
719             Def::Err => {
720                 panic!("didn't expect `{:?}`", def);
721             }
722         }
723     }
724
725     /// Builds the reduced graph for a single item in an external crate.
726     fn build_reduced_graph_for_external_crate_def(&mut self,
727                                                   root: Module<'b>,
728                                                   xcdef: ChildItem) {
729         match xcdef.def {
730             DlDef(def) => {
731                 // Add the new child item, if necessary.
732                 match def {
733                     Def::ForeignMod(def_id) => {
734                         // Foreign modules have no names. Recur and populate
735                         // eagerly.
736                         for child in self.session.cstore.item_children(def_id) {
737                             self.build_reduced_graph_for_external_crate_def(root, child)
738                         }
739                     }
740                     _ => {
741                         let child_name_bindings = self.add_child(xcdef.name,
742                                                                  root,
743                                                                  OverwriteDuplicates,
744                                                                  DUMMY_SP);
745
746                         self.handle_external_def(def,
747                                                  xcdef.vis,
748                                                  &child_name_bindings,
749                                                  &xcdef.name.as_str(),
750                                                  xcdef.name,
751                                                  root);
752                     }
753                 }
754             }
755             DlImpl(_) => {
756                 debug!("(building reduced graph for external crate) ignoring impl");
757             }
758             DlField => {
759                 debug!("(building reduced graph for external crate) ignoring field");
760             }
761         }
762     }
763
764     /// Builds the reduced graph rooted at the given external module.
765     fn populate_external_module(&mut self, module: Module<'b>) {
766         debug!("(populating external module) attempting to populate {}",
767                module_to_string(module));
768
769         let def_id = match module.def_id() {
770             None => {
771                 debug!("(populating external module) ... no def ID!");
772                 return;
773             }
774             Some(def_id) => def_id,
775         };
776
777         for child in self.session.cstore.item_children(def_id) {
778             debug!("(populating external module) ... found ident: {}",
779                    child.name);
780             self.build_reduced_graph_for_external_crate_def(module, child);
781         }
782         module.populated.set(true)
783     }
784
785     /// Ensures that the reduced graph rooted at the given external module
786     /// is built, building it if it is not.
787     fn populate_module_if_necessary(&mut self, module: Module<'b>) {
788         if !module.populated.get() {
789             self.populate_external_module(module)
790         }
791         assert!(module.populated.get())
792     }
793
794     /// Builds the reduced graph rooted at the 'use' directive for an external
795     /// crate.
796     fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
797         let root_cnum = root.def_id().unwrap().krate;
798         for child in self.session.cstore.crate_top_level_items(root_cnum) {
799             self.build_reduced_graph_for_external_crate_def(root, child);
800         }
801     }
802
803     /// Creates and adds an import directive to the given module.
804     fn build_import_directive(&mut self,
805                               module_: Module<'b>,
806                               module_path: Vec<Name>,
807                               subclass: ImportDirectiveSubclass,
808                               span: Span,
809                               id: NodeId,
810                               is_public: bool,
811                               shadowable: Shadowable) {
812         module_.imports
813                .borrow_mut()
814                .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
815         self.unresolved_imports += 1;
816
817         if is_public {
818             module_.inc_pub_count();
819         }
820
821         // Bump the reference count on the name. Or, if this is a glob, set
822         // the appropriate flag.
823
824         match subclass {
825             SingleImport(target, _) => {
826                 debug!("(building import directive) building import directive: {}::{}",
827                        names_to_string(&module_.imports.borrow().last().unwrap().module_path),
828                        target);
829
830                 let mut import_resolutions = module_.import_resolutions.borrow_mut();
831                 match import_resolutions.get_mut(&target) {
832                     Some(resolution_per_ns) => {
833                         debug!("(building import directive) bumping reference");
834                         resolution_per_ns.outstanding_references += 1;
835
836                         // the source of this name is different now
837                         let resolution =
838                             ImportResolution { id: id, is_public: is_public, target: None };
839                         resolution_per_ns[TypeNS] = resolution.clone();
840                         resolution_per_ns[ValueNS] = resolution;
841                         return;
842                     }
843                     None => {}
844                 }
845                 debug!("(building import directive) creating new");
846                 let mut import_resolution_per_ns = ImportResolutionPerNamespace::new(id, is_public);
847                 import_resolution_per_ns.outstanding_references = 1;
848                 import_resolutions.insert(target, import_resolution_per_ns);
849             }
850             GlobImport => {
851                 // Set the glob flag. This tells us that we don't know the
852                 // module's exports ahead of time.
853
854                 module_.inc_glob_count();
855                 if is_public {
856                     module_.inc_pub_glob_count();
857                 }
858             }
859         }
860     }
861 }
862
863 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
864     builder: GraphBuilder<'a, 'b, 'tcx>,
865     parent: Module<'b>,
866 }
867
868 impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
869     fn visit_nested_item(&mut self, item: hir::ItemId) {
870         self.visit_item(self.builder.resolver.ast_map.expect_item(item.id))
871     }
872
873     fn visit_item(&mut self, item: &Item) {
874         let p = self.builder.build_reduced_graph_for_item(item, &self.parent);
875         let old_parent = replace(&mut self.parent, p);
876         intravisit::walk_item(self, item);
877         self.parent = old_parent;
878     }
879
880     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
881         self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
882     }
883
884     fn visit_block(&mut self, block: &Block) {
885         let np = self.builder.build_reduced_graph_for_block(block, &self.parent);
886         let old_parent = replace(&mut self.parent, np);
887         intravisit::walk_block(self, block);
888         self.parent = old_parent;
889     }
890 }
891
892 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
893     GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
894 }
895
896 pub fn populate_module_if_necessary<'a, 'tcx>(resolver: &mut Resolver<'a, 'tcx>,
897                                               module: Module<'a>) {
898     GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);
899 }