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