]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Remove unused imports
[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::{self, ModuleParentLink, BlockParentLink};
25 use Resolver;
26 use resolve_imports::Shadowable;
27 use {resolve_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
35 use syntax::ast::{Name, NodeId};
36 use syntax::attr::AttrMetaMethods;
37 use syntax::parse::token::special_idents;
38 use syntax::codemap::{Span, DUMMY_SP};
39
40 use rustc_front::hir;
41 use rustc_front::hir::{Block, DeclItem};
42 use rustc_front::hir::{ForeignItem, ForeignItemFn, ForeignItemStatic};
43 use rustc_front::hir::{Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn};
44 use rustc_front::hir::{ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
45 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
46 use rustc_front::hir::{NamedField, PathListIdent, PathListMod};
47 use rustc_front::hir::StmtDecl;
48 use rustc_front::hir::UnnamedField;
49 use rustc_front::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
50 use rustc_front::hir::Visibility;
51 use rustc_front::intravisit::{self, Visitor};
52
53 use std::mem::replace;
54 use std::ops::{Deref, DerefMut};
55 use std::rc::Rc;
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.clone(),
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: &Rc<Module>,
101                  duplicate_checking_mode: DuplicateCheckingMode,
102                  // For printing errors
103                  sp: Span)
104                  -> NameBindings {
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                 resolve_error(self, sp, ResolutionError::DuplicateDefinition(ns_str, name));
141
142                 if let Some(sp) = child[ns].span() {
143                     let note = format!("first definition of {} `{}` here", ns_str, name);
144                     self.session.span_note(sp, &note);
145                 }
146                 child
147             }
148         }
149     }
150
151     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
152         // Check each statement.
153         for statement in &block.stmts {
154             match statement.node {
155                 StmtDecl(ref declaration, _) => {
156                     match declaration.node {
157                         DeclItem(_) => {
158                             return true;
159                         }
160                         _ => {
161                             // Keep searching.
162                         }
163                     }
164                 }
165                 _ => {
166                     // Keep searching.
167                 }
168             }
169         }
170
171         // If we found no items, we don't need to create
172         // an anonymous module.
173
174         return false;
175     }
176
177     fn get_parent_link(&mut self, parent: &Rc<Module>, name: Name) -> ParentLink {
178         ModuleParentLink(Rc::downgrade(parent), name)
179     }
180
181     /// Constructs the reduced graph for one item.
182     fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) -> Rc<Module> {
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                             resolve_error(self,
257                                           mod_spans[0],
258                                           ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
259                             for other_span in mod_spans.iter().skip(1) {
260                                 self.session
261                                     .span_note(*other_span, "another `self` import appears here");
262                             }
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.clone()
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(Rc::downgrade(parent), name);
319                     let def = DefMod(def_id);
320                     let external_module = Module::new(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_between_external_crates(&**parent, name, sp);
325                     parent.external_module_children
326                           .borrow_mut()
327                           .insert(name, external_module.clone());
328                     self.build_reduced_graph_for_external_crate(&external_module);
329                 }
330                 parent.clone()
331             }
332
333             ItemMod(..) => {
334                 let name_bindings = self.add_child(name, parent, ForbidDuplicateTypes, sp);
335
336                 let parent_link = self.get_parent_link(parent, name);
337                 let def = DefMod(self.ast_map.local_def_id(item.id));
338                 let module = Module::new(parent_link, Some(def), false, is_public);
339                 name_bindings.define_module(module.clone(), sp);
340                 module
341             }
342
343             ItemForeignMod(..) => parent.clone(),
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(DefStatic(self.ast_map.local_def_id(item.id), mutbl),
351                                            sp,
352                                            modifiers);
353                 parent.clone()
354             }
355             ItemConst(_, _) => {
356                 self.add_child(name, parent, ForbidDuplicateValues, sp)
357                     .define_value(DefConst(self.ast_map.local_def_id(item.id)), sp, modifiers);
358                 parent.clone()
359             }
360             ItemFn(_, _, _, _, _, _) => {
361                 let name_bindings = self.add_child(name, parent, ForbidDuplicateValues, sp);
362
363                 let def = DefFn(self.ast_map.local_def_id(item.id), false);
364                 name_bindings.define_value(def, sp, modifiers);
365                 parent.clone()
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 = self.get_parent_link(parent, name);
376                 let def = DefTy(self.ast_map.local_def_id(item.id), false);
377                 let module = Module::new(parent_link, Some(def), false, is_public);
378                 name_bindings.define_module(module, sp);
379                 parent.clone()
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 = self.get_parent_link(parent, name);
389                 let def = DefTy(self.ast_map.local_def_id(item.id), true);
390                 let module = Module::new(parent_link, Some(def), false, is_public);
391                 name_bindings.define_module(module.clone(), sp);
392
393                 for variant in &(*enum_definition).variants {
394                     let item_def_id = self.ast_map.local_def_id(item.id);
395                     self.build_reduced_graph_for_variant(variant, item_def_id, &module);
396                 }
397                 parent.clone()
398             }
399
400             // These items live in both the type and value namespaces.
401             ItemStruct(ref struct_def, _) => {
402                 // Adding to both Type and Value namespaces or just Type?
403                 let (forbid, ctor_id) = if struct_def.is_struct() {
404                     (ForbidDuplicateTypes, None)
405                 } else {
406                     (ForbidDuplicateTypesAndValues, Some(struct_def.id()))
407                 };
408
409                 let name_bindings = self.add_child(name, parent, forbid, sp);
410
411                 // Define a name in the type namespace.
412                 name_bindings.define_type(DefTy(self.ast_map.local_def_id(item.id), false),
413                                           sp,
414                                           modifiers);
415
416                 // If this is a newtype or unit-like struct, define a name
417                 // in the value namespace as well
418                 if let Some(cid) = ctor_id {
419                     name_bindings.define_value(DefStruct(self.ast_map.local_def_id(cid)),
420                                                sp,
421                                                modifiers);
422                 }
423
424                 // Record the def ID and fields of this struct.
425                 let named_fields = struct_def.fields()
426                                              .iter()
427                                              .filter_map(|f| {
428                                                  match f.node.kind {
429                                                      NamedField(name, _) => Some(name),
430                                                      UnnamedField(_) => None,
431                                                  }
432                                              })
433                                              .collect();
434                 let item_def_id = self.ast_map.local_def_id(item.id);
435                 self.structs.insert(item_def_id, named_fields);
436
437                 parent.clone()
438             }
439
440             ItemDefaultImpl(_, _) |
441             ItemImpl(..) => parent.clone(),
442
443             ItemTrait(_, _, _, ref items) => {
444                 let name_bindings = self.add_child(name,
445                                                    parent,
446                                                    ForbidDuplicateTypes,
447                                                    sp);
448
449                 let def_id = self.ast_map.local_def_id(item.id);
450
451                 // Add all the items within to a new module.
452                 let parent_link = self.get_parent_link(parent, name);
453                 let def = DefTrait(def_id);
454                 let module_parent = Module::new(parent_link, Some(def), false, is_public);
455                 name_bindings.define_module(module_parent.clone(), sp);
456
457                 // Add the names of all the items to the trait info.
458                 for trait_item in items {
459                     let name_bindings = self.add_child(trait_item.name,
460                                                        &module_parent,
461                                                        ForbidDuplicateTypesAndValues,
462                                                        trait_item.span);
463
464                     match trait_item.node {
465                         hir::ConstTraitItem(..) => {
466                             let def = DefAssociatedConst(self.ast_map.local_def_id(trait_item.id));
467                             // NB: not DefModifiers::IMPORTABLE
468                             name_bindings.define_value(def, trait_item.span, DefModifiers::PUBLIC);
469                         }
470                         hir::MethodTraitItem(..) => {
471                             let def = DefMethod(self.ast_map.local_def_id(trait_item.id));
472                             // NB: not DefModifiers::IMPORTABLE
473                             name_bindings.define_value(def, trait_item.span, DefModifiers::PUBLIC);
474                         }
475                         hir::TypeTraitItem(..) => {
476                             let def = DefAssociatedTy(self.ast_map.local_def_id(item.id),
477                                                       self.ast_map.local_def_id(trait_item.id));
478                             // NB: not DefModifiers::IMPORTABLE
479                             name_bindings.define_type(def, trait_item.span, DefModifiers::PUBLIC);
480                         }
481                     }
482
483                     let trait_item_def_id = self.ast_map.local_def_id(trait_item.id);
484                     self.trait_item_map.insert((trait_item.name, def_id), trait_item_def_id);
485                 }
486
487                 parent.clone()
488             }
489         }
490     }
491
492     // Constructs the reduced graph for one variant. Variants exist in the
493     // type and value namespaces.
494     fn build_reduced_graph_for_variant(&mut self,
495                                        variant: &Variant,
496                                        item_id: DefId,
497                                        parent: &Rc<Module>) {
498         let name = variant.node.name;
499         let is_exported = if variant.node.data.is_struct() {
500             // Not adding fields for variants as they are not accessed with a self receiver
501             let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
502             self.structs.insert(variant_def_id, Vec::new());
503             true
504         } else {
505             false
506         };
507
508         let child = self.add_child(name, parent, ForbidDuplicateTypesAndValues, variant.span);
509         // variants are always treated as importable to allow them to be glob
510         // used
511         child.define_value(DefVariant(item_id,
512                                       self.ast_map.local_def_id(variant.node.data.id()),
513                                       is_exported),
514                            variant.span,
515                            DefModifiers::PUBLIC | DefModifiers::IMPORTABLE);
516         child.define_type(DefVariant(item_id,
517                                      self.ast_map.local_def_id(variant.node.data.id()),
518                                      is_exported),
519                           variant.span,
520                           DefModifiers::PUBLIC | DefModifiers::IMPORTABLE);
521     }
522
523     /// Constructs the reduced graph for one foreign item.
524     fn build_reduced_graph_for_foreign_item(&mut self,
525                                             foreign_item: &ForeignItem,
526                                             parent: &Rc<Module>) {
527         let name = foreign_item.name;
528         let is_public = foreign_item.vis == hir::Public;
529         let modifiers = if is_public {
530             DefModifiers::PUBLIC
531         } else {
532             DefModifiers::empty()
533         } | DefModifiers::IMPORTABLE;
534         let name_bindings = self.add_child(name, parent, ForbidDuplicateValues, foreign_item.span);
535
536         let def = match foreign_item.node {
537             ForeignItemFn(..) => {
538                 DefFn(self.ast_map.local_def_id(foreign_item.id), false)
539             }
540             ForeignItemStatic(_, m) => {
541                 DefStatic(self.ast_map.local_def_id(foreign_item.id), m)
542             }
543         };
544         name_bindings.define_value(def, foreign_item.span, modifiers);
545     }
546
547     fn build_reduced_graph_for_block(&mut self, block: &Block, parent: &Rc<Module>) -> Rc<Module> {
548         if self.block_needs_anonymous_module(block) {
549             let block_id = block.id;
550
551             debug!("(building reduced graph for block) creating a new anonymous module for block \
552                     {}",
553                    block_id);
554
555             let parent_link = BlockParentLink(Rc::downgrade(parent), block_id);
556             let new_module = Module::new(parent_link, None, false, false);
557             parent.anonymous_children.borrow_mut().insert(block_id, new_module.clone());
558             new_module
559         } else {
560             parent.clone()
561         }
562     }
563
564     fn handle_external_def(&mut self,
565                            def: Def,
566                            vis: Visibility,
567                            child_name_bindings: &NameBindings,
568                            final_ident: &str,
569                            name: Name,
570                            new_parent: &Rc<Module>) {
571         debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
572                final_ident,
573                vis);
574         let is_public = vis == hir::Public;
575         let modifiers = if is_public {
576             DefModifiers::PUBLIC
577         } else {
578             DefModifiers::empty()
579         } | DefModifiers::IMPORTABLE;
580         let is_exported = is_public &&
581                           match new_parent.def_id() {
582             None => true,
583             Some(did) => self.external_exports.contains(&did),
584         };
585         if is_exported {
586             self.external_exports.insert(def.def_id());
587         }
588
589         match def {
590             DefMod(_) |
591             DefForeignMod(_) |
592             DefStruct(_) |
593             DefTy(..) => {
594                 if let Some(module_def) = child_name_bindings.type_ns.module() {
595                     debug!("(building reduced graph for external crate) already created module");
596                     module_def.def.set(Some(def));
597                 } else {
598                     debug!("(building reduced graph for external crate) building module {} {}",
599                            final_ident,
600                            is_public);
601                     let parent_link = self.get_parent_link(new_parent, name);
602                     let module = Module::new(parent_link, Some(def), true, is_public);
603                     child_name_bindings.define_module(module, DUMMY_SP);
604                 }
605             }
606             _ => {}
607         }
608
609         match def {
610             DefMod(_) | DefForeignMod(_) => {}
611             DefVariant(_, variant_id, is_struct) => {
612                 debug!("(building reduced graph for external crate) building variant {}",
613                        final_ident);
614                 // variants are always treated as importable to allow them to be
615                 // glob used
616                 let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
617                 if is_struct {
618                     child_name_bindings.define_type(def, DUMMY_SP, modifiers);
619                     // Not adding fields for variants as they are not accessed with a self receiver
620                     self.structs.insert(variant_id, Vec::new());
621                 } else {
622                     child_name_bindings.define_value(def, DUMMY_SP, modifiers);
623                 }
624             }
625             DefFn(ctor_id, true) => {
626                 child_name_bindings.define_value(
627                 self.session.cstore.tuple_struct_definition_if_ctor(ctor_id)
628                     .map_or(def, |_| DefStruct(ctor_id)), DUMMY_SP, modifiers);
629             }
630             DefFn(..) |
631             DefStatic(..) |
632             DefConst(..) |
633             DefAssociatedConst(..) |
634             DefMethod(..) => {
635                 debug!("(building reduced graph for external crate) building value (fn/static) {}",
636                        final_ident);
637                 // impl methods have already been defined with the correct importability
638                 // modifier
639                 let mut modifiers = match *child_name_bindings.value_ns.borrow() {
640                     Some(ref def) => (modifiers & !DefModifiers::IMPORTABLE) |
641                                      (def.modifiers & DefModifiers::IMPORTABLE),
642                     None => modifiers,
643                 };
644                 if !new_parent.is_normal() {
645                     modifiers = modifiers & !DefModifiers::IMPORTABLE;
646                 }
647                 child_name_bindings.define_value(def, DUMMY_SP, modifiers);
648             }
649             DefTrait(def_id) => {
650                 debug!("(building reduced graph for external crate) building type {}",
651                        final_ident);
652
653                 // If this is a trait, add all the trait item names to the trait
654                 // info.
655
656                 let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
657                 for trait_item_def in &trait_item_def_ids {
658                     let trait_item_name =
659                         self.session.cstore.item_name(trait_item_def.def_id());
660
661                     debug!("(building reduced graph for external crate) ... adding trait item \
662                             '{}'",
663                            trait_item_name);
664
665                     self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
666
667                     if is_exported {
668                         self.external_exports.insert(trait_item_def.def_id());
669                     }
670                 }
671
672                 // Define a module if necessary.
673                 let parent_link = self.get_parent_link(new_parent, name);
674                 let module = Module::new(parent_link, Some(def), true, is_public);
675                 child_name_bindings.define_module(module, DUMMY_SP);
676             }
677             DefTy(..) | DefAssociatedTy(..) => {
678                 debug!("(building reduced graph for external crate) building type {}",
679                        final_ident);
680
681                 let modifiers = match new_parent.is_normal() {
682                     true => modifiers,
683                     _ => modifiers & !DefModifiers::IMPORTABLE,
684                 };
685
686                 if let DefTy(..) = def {
687                     child_name_bindings.type_ns.set_modifiers(modifiers);
688                 } else {
689                     child_name_bindings.define_type(def, DUMMY_SP, modifiers);
690                 }
691             }
692             DefStruct(def_id) => {
693                 debug!("(building reduced graph for external crate) building type and value for \
694                         {}",
695                        final_ident);
696                 child_name_bindings.define_type(def, DUMMY_SP, modifiers);
697                 let fields = self.session.cstore.struct_field_names(def_id);
698
699                 if fields.is_empty() {
700                     child_name_bindings.define_value(def, DUMMY_SP, modifiers);
701                 }
702
703                 // Record the def ID and fields of this struct.
704                 self.structs.insert(def_id, fields);
705             }
706             DefLocal(..) |
707             DefPrimTy(..) |
708             DefTyParam(..) |
709             DefUse(..) |
710             DefUpvar(..) |
711             DefLabel(..) |
712             DefSelfTy(..) |
713             DefErr => {
714                 panic!("didn't expect `{:?}`", def);
715             }
716         }
717     }
718
719     /// Builds the reduced graph for a single item in an external crate.
720     fn build_reduced_graph_for_external_crate_def(&mut self,
721                                                   root: &Rc<Module>,
722                                                   xcdef: ChildItem) {
723         match xcdef.def {
724             DlDef(def) => {
725                 // Add the new child item, if necessary.
726                 match def {
727                     DefForeignMod(def_id) => {
728                         // Foreign modules have no names. Recur and populate
729                         // eagerly.
730                         for child in self.session.cstore.item_children(def_id) {
731                             self.build_reduced_graph_for_external_crate_def(root, child)
732                         }
733                     }
734                     _ => {
735                         let child_name_bindings = self.add_child(xcdef.name,
736                                                                  root,
737                                                                  OverwriteDuplicates,
738                                                                  DUMMY_SP);
739
740                         self.handle_external_def(def,
741                                                  xcdef.vis,
742                                                  &child_name_bindings,
743                                                  &xcdef.name.as_str(),
744                                                  xcdef.name,
745                                                  root);
746                     }
747                 }
748             }
749             DlImpl(_) => {
750                 debug!("(building reduced graph for external crate) ignoring impl");
751             }
752             DlField => {
753                 debug!("(building reduced graph for external crate) ignoring field");
754             }
755         }
756     }
757
758     /// Builds the reduced graph rooted at the given external module.
759     fn populate_external_module(&mut self, module: &Rc<Module>) {
760         debug!("(populating external module) attempting to populate {}",
761                module_to_string(&**module));
762
763         let def_id = match module.def_id() {
764             None => {
765                 debug!("(populating external module) ... no def ID!");
766                 return;
767             }
768             Some(def_id) => def_id,
769         };
770
771         for child in self.session.cstore.item_children(def_id) {
772             debug!("(populating external module) ... found ident: {}",
773                    child.name);
774             self.build_reduced_graph_for_external_crate_def(module, child);
775         }
776         module.populated.set(true)
777     }
778
779     /// Ensures that the reduced graph rooted at the given external module
780     /// is built, building it if it is not.
781     fn populate_module_if_necessary(&mut self, module: &Rc<Module>) {
782         if !module.populated.get() {
783             self.populate_external_module(module)
784         }
785         assert!(module.populated.get())
786     }
787
788     /// Builds the reduced graph rooted at the 'use' directive for an external
789     /// crate.
790     fn build_reduced_graph_for_external_crate(&mut self, root: &Rc<Module>) {
791         let root_cnum = root.def_id().unwrap().krate;
792         for child in self.session.cstore.crate_top_level_items(root_cnum) {
793             self.build_reduced_graph_for_external_crate_def(root, child);
794         }
795     }
796
797     /// Creates and adds an import directive to the given module.
798     fn build_import_directive(&mut self,
799                               module_: &Module,
800                               module_path: Vec<Name>,
801                               subclass: ImportDirectiveSubclass,
802                               span: Span,
803                               id: NodeId,
804                               is_public: bool,
805                               shadowable: Shadowable) {
806         module_.imports
807                .borrow_mut()
808                .push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
809         self.unresolved_imports += 1;
810
811         if is_public {
812             module_.inc_pub_count();
813         }
814
815         // Bump the reference count on the name. Or, if this is a glob, set
816         // the appropriate flag.
817
818         match subclass {
819             SingleImport(target, _) => {
820                 debug!("(building import directive) building import directive: {}::{}",
821                        names_to_string(&module_.imports.borrow().last().unwrap().module_path),
822                        target);
823
824                 let mut import_resolutions = module_.import_resolutions.borrow_mut();
825                 match import_resolutions.get_mut(&target) {
826                     Some(resolution_per_ns) => {
827                         debug!("(building import directive) bumping reference");
828                         resolution_per_ns.outstanding_references += 1;
829
830                         // the source of this name is different now
831                         let resolution =
832                             ImportResolution { id: id, is_public: is_public, target: None };
833                         resolution_per_ns[TypeNS] = resolution.clone();
834                         resolution_per_ns[ValueNS] = resolution;
835                         return;
836                     }
837                     None => {}
838                 }
839                 debug!("(building import directive) creating new");
840                 let mut import_resolution_per_ns = ImportResolutionPerNamespace::new(id, is_public);
841                 import_resolution_per_ns.outstanding_references = 1;
842                 import_resolutions.insert(target, import_resolution_per_ns);
843             }
844             GlobImport => {
845                 // Set the glob flag. This tells us that we don't know the
846                 // module's exports ahead of time.
847
848                 module_.inc_glob_count();
849                 if is_public {
850                     module_.inc_pub_glob_count();
851                 }
852             }
853         }
854     }
855 }
856
857 struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
858     builder: GraphBuilder<'a, 'b, 'tcx>,
859     parent: Rc<Module>,
860 }
861
862 impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
863     fn visit_nested_item(&mut self, item: hir::ItemId) {
864         self.visit_item(self.builder.resolver.ast_map.expect_item(item.id))
865     }
866
867     fn visit_item(&mut self, item: &Item) {
868         let p = self.builder.build_reduced_graph_for_item(item, &self.parent);
869         let old_parent = replace(&mut self.parent, p);
870         intravisit::walk_item(self, item);
871         self.parent = old_parent;
872     }
873
874     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
875         self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
876     }
877
878     fn visit_block(&mut self, block: &Block) {
879         let np = self.builder.build_reduced_graph_for_block(block, &self.parent);
880         let old_parent = replace(&mut self.parent, np);
881         intravisit::walk_block(self, block);
882         self.parent = old_parent;
883     }
884 }
885
886 pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
887     GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
888 }
889
890 pub fn populate_module_if_necessary(resolver: &mut Resolver, module: &Rc<Module>) {
891     GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);
892 }