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