build_reduced_graph.rs 27.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Reduced graph building
//!
//! Here we build the "reduced graph": the graph of the module tree without
//! any imports resolved.

T
Fallout  
Tamir Duberstein 已提交
16
use DefModifiers;
17 18
use resolve_imports::ImportDirective;
use resolve_imports::ImportDirectiveSubclass::{self, SingleImport, GlobImport};
19
use Module;
20
use Namespace::{self, TypeNS, ValueNS};
21
use {NameBinding, NameBindingKind};
22
use ParentLink::{ModuleParentLink, BlockParentLink};
23
use Resolver;
N
Nick Cameron 已提交
24
use {resolve_error, resolve_struct_error, ResolutionError};
25

26
use rustc::middle::cstore::{CrateStore, ChildItem, DlDef};
27
use rustc::middle::def::*;
28
use rustc::middle::def_id::{CRATE_DEF_INDEX, DefId};
29
use rustc::middle::ty::VariantKind;
30

31
use syntax::ast::{Name, NodeId};
32
use syntax::attr::AttrMetaMethods;
33
use syntax::parse::token::special_idents;
34
use syntax::codemap::{Span, DUMMY_SP};
35 36

use rustc_front::hir;
J
Jeffrey Seyfried 已提交
37
use rustc_front::hir::{Block, DeclItem};
38 39 40 41
use rustc_front::hir::{ForeignItem, ForeignItemFn, ForeignItemStatic};
use rustc_front::hir::{Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn};
use rustc_front::hir::{ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
42
use rustc_front::hir::{PathListIdent, PathListMod, StmtDecl};
43
use rustc_front::hir::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple};
44
use rustc_front::intravisit::{self, Visitor};
45

46
use std::ops::{Deref, DerefMut};
47

C
corentih 已提交
48 49
struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
    resolver: &'a mut Resolver<'b, 'tcx>,
50 51
}

52 53 54
impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
    type Target = Resolver<'b, 'tcx>;

55 56 57 58 59
    fn deref(&self) -> &Resolver<'b, 'tcx> {
        &*self.resolver
    }
}

60
impl<'a, 'b:'a, 'tcx:'b> DerefMut for GraphBuilder<'a, 'b, 'tcx> {
61 62 63 64 65
    fn deref_mut(&mut self) -> &mut Resolver<'b, 'tcx> {
        &mut *self.resolver
    }
}

66 67 68 69 70 71 72 73 74 75 76 77
trait ToNameBinding<'a> {
    fn to_name_binding(self) -> NameBinding<'a>;
}

impl<'a> ToNameBinding<'a> for (Module<'a>, Span) {
    fn to_name_binding(self) -> NameBinding<'a> {
        NameBinding::create_from_module(self.0, Some(self.1))
    }
}

impl<'a> ToNameBinding<'a> for (Def, Span, DefModifiers) {
    fn to_name_binding(self) -> NameBinding<'a> {
78 79
        let kind = NameBindingKind::Def(self.0);
        NameBinding { modifiers: self.2, kind: kind, span: Some(self.1) }
80 81 82
    }
}

83 84
impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> {
    /// Constructs the reduced graph for the entire crate.
85
    fn build_reduced_graph(self, krate: &hir::Crate) {
86
        let mut visitor = BuildReducedGraphVisitor {
87
            parent: self.graph_root,
88 89
            builder: self,
        };
90
        intravisit::walk_crate(&mut visitor, krate);
91 92
    }

93 94 95 96
    /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined.
    fn try_define<T>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T)
        where T: ToNameBinding<'b>
    {
97
        let _ = parent.try_define_child(name, ns, def.to_name_binding());
98
    }
99

100 101 102
    /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
    /// otherwise, reports an error.
    fn define<T: ToNameBinding<'b>>(&self, parent: Module<'b>, name: Name, ns: Namespace, def: T) {
103
        let binding = def.to_name_binding();
104 105
        if let Err(old_binding) = parent.try_define_child(name, ns, binding.clone()) {
            self.report_conflict(parent, name, ns, old_binding, &binding);
106 107 108 109
        }
    }

    fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
110 111 112 113
        fn is_item(statement: &hir::Stmt) -> bool {
            if let StmtDecl(ref declaration, _) = statement.node {
                if let DeclItem(_) = declaration.node {
                    return true;
114 115
                }
            }
116
            false
117 118
        }

119 120
        // If any statements are items, we need to create an anonymous module
        block.stmts.iter().any(is_item)
121 122 123
    }

    /// Constructs the reduced graph for one item.
J
Jeffrey Seyfried 已提交
124 125
    fn build_reduced_graph_for_item(&mut self, item: &Item, parent_ref: &mut Module<'b>) {
        let parent = *parent_ref;
V
Vadim Petrochenkov 已提交
126
        let name = item.name;
127
        let sp = item.span;
128
        let is_public = item.vis == hir::Public;
T
Fallout  
Tamir Duberstein 已提交
129 130 131 132 133
        let modifiers = if is_public {
            DefModifiers::PUBLIC
        } else {
            DefModifiers::empty()
        } | DefModifiers::IMPORTABLE;
134 135

        match item.node {
136 137 138 139 140 141 142
            ItemUse(ref view_path) => {
                // Extract and intern the module part of the path. For
                // globs and lists, the path is found directly in the AST;
                // for simple paths we have to munge the path a little.
                let module_path = match view_path.node {
                    ViewPathSimple(_, ref full_path) => {
                        full_path.segments
C
corentih 已提交
143 144 145 146 147 148
                                 .split_last()
                                 .unwrap()
                                 .1
                                 .iter()
                                 .map(|seg| seg.identifier.name)
                                 .collect()
149 150 151 152 153
                    }

                    ViewPathGlob(ref module_ident_path) |
                    ViewPathList(ref module_ident_path, _) => {
                        module_ident_path.segments
C
corentih 已提交
154 155 156
                                         .iter()
                                         .map(|seg| seg.identifier.name)
                                         .collect()
157 158 159 160
                    }
                };

                // Build up the import directives.
161
                let is_prelude = item.attrs.iter().any(|attr| {
162
                    attr.name() == special_idents::prelude_import.name.as_str()
163 164 165 166
                });

                match view_path.node {
                    ViewPathSimple(binding, ref full_path) => {
C
corentih 已提交
167
                        let source_name = full_path.segments.last().unwrap().identifier.name;
168
                        if source_name.as_str() == "mod" || source_name.as_str() == "self" {
169
                            resolve_error(self,
170 171
                                          view_path.span,
                                          ResolutionError::SelfImportsOnlyAllowedWithin);
172 173
                        }

174
                        let subclass = ImportDirectiveSubclass::single(binding, source_name);
175
                        self.build_import_directive(parent,
176 177 178 179 180
                                                    module_path,
                                                    subclass,
                                                    view_path.span,
                                                    item.id,
                                                    is_public,
181
                                                    is_prelude);
182 183 184
                    }
                    ViewPathList(_, ref source_items) => {
                        // Make sure there's at most one `mod` import in the list.
C
corentih 已提交
185 186 187 188 189 190 191 192
                        let mod_spans = source_items.iter()
                                                    .filter_map(|item| {
                                                        match item.node {
                                                            PathListMod { .. } => Some(item.span),
                                                            _ => None,
                                                        }
                                                    })
                                                    .collect::<Vec<Span>>();
193
                        if mod_spans.len() > 1 {
N
Nick Cameron 已提交
194
                            let mut e = resolve_struct_error(self,
C
corentih 已提交
195 196
                                          mod_spans[0],
                                          ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
197
                            for other_span in mod_spans.iter().skip(1) {
N
Nick Cameron 已提交
198
                                e.span_note(*other_span, "another `self` import appears here");
199
                            }
N
Nick Cameron 已提交
200
                            e.emit();
201 202
                        }

203
                        for source_item in source_items {
204 205
                            let (module_path, name, rename) = match source_item.node {
                                PathListIdent { name, rename, .. } =>
206
                                    (module_path.clone(), name, rename.unwrap_or(name)),
207
                                PathListMod { rename, .. } => {
208 209 210
                                    let name = match module_path.last() {
                                        Some(name) => *name,
                                        None => {
211
                                            resolve_error(
212 213
                                                self,
                                                source_item.span,
214
                                                ResolutionError::
215
                                                SelfImportOnlyInImportListWithNonEmptyPrefix
216
                                            );
217 218 219
                                            continue;
                                        }
                                    };
S
Simonas Kazlauskas 已提交
220
                                    let module_path = module_path.split_last().unwrap().1;
221
                                    let rename = rename.unwrap_or(name);
222
                                    (module_path.to_vec(), name, rename)
223 224
                                }
                            };
225
                            let subclass = ImportDirectiveSubclass::single(rename, name);
226
                            self.build_import_directive(parent,
C
corentih 已提交
227
                                                        module_path,
228
                                                        subclass,
C
corentih 已提交
229 230 231
                                                        source_item.span,
                                                        source_item.node.id(),
                                                        is_public,
232
                                                        is_prelude);
233 234 235
                        }
                    }
                    ViewPathGlob(_) => {
236
                        self.build_import_directive(parent,
237 238 239 240 241
                                                    module_path,
                                                    GlobImport,
                                                    view_path.span,
                                                    item.id,
                                                    is_public,
242
                                                    is_prelude);
243 244 245 246 247
                    }
                }
            }

            ItemExternCrate(_) => {
C
corentih 已提交
248 249
                // n.b. we don't need to look at the path option here, because cstore already
                // did
A
Ariel Ben-Yehuda 已提交
250
                if let Some(crate_id) = self.session.cstore.extern_mod_stmt_cnum(item.id) {
C
corentih 已提交
251 252 253 254
                    let def_id = DefId {
                        krate: crate_id,
                        index: CRATE_DEF_INDEX,
                    };
255
                    let parent_link = ModuleParentLink(parent, name);
256
                    let def = Def::Mod(def_id);
257 258
                    let module = self.new_extern_crate_module(parent_link, def, is_public, item.id);
                    self.define(parent, name, TypeNS, (module, sp));
259

260
                    self.build_reduced_graph_for_external_crate(module);
261 262 263
                }
            }

264
            ItemMod(..) => {
265
                let parent_link = ModuleParentLink(parent, name);
266
                let def = Def::Mod(self.ast_map.local_def_id(item.id));
267
                let module = self.new_module(parent_link, Some(def), false, is_public);
268
                self.define(parent, name, TypeNS, (module, sp));
269
                parent.module_children.borrow_mut().insert(item.id, module);
J
Jeffrey Seyfried 已提交
270
                *parent_ref = module;
271 272
            }

J
Jeffrey Seyfried 已提交
273
            ItemForeignMod(..) => {}
274 275 276

            // These items live in the value namespace.
            ItemStatic(_, m, _) => {
277
                let mutbl = m == hir::MutMutable;
278 279
                let def = Def::Static(self.ast_map.local_def_id(item.id), mutbl);
                self.define(parent, name, ValueNS, (def, sp, modifiers));
280 281
            }
            ItemConst(_, _) => {
282 283
                let def = Def::Const(self.ast_map.local_def_id(item.id));
                self.define(parent, name, ValueNS, (def, sp, modifiers));
284
            }
285
            ItemFn(_, _, _, _, _, _) => {
286
                let def = Def::Fn(self.ast_map.local_def_id(item.id));
287
                self.define(parent, name, ValueNS, (def, sp, modifiers));
288 289 290 291
            }

            // These items live in the type namespace.
            ItemTy(..) => {
292
                let def = Def::TyAlias(self.ast_map.local_def_id(item.id));
293
                self.define(parent, name, TypeNS, (def, sp, modifiers));
294 295 296
            }

            ItemEnum(ref enum_definition, _) => {
297
                let parent_link = ModuleParentLink(parent, name);
298
                let def = Def::Enum(self.ast_map.local_def_id(item.id));
299
                let module = self.new_module(parent_link, Some(def), false, is_public);
300
                self.define(parent, name, TypeNS, (module, sp));
301

302 303 304 305 306
                let variant_modifiers = if is_public {
                    DefModifiers::empty()
                } else {
                    DefModifiers::PRIVATE_VARIANT
                };
307
                for variant in &(*enum_definition).variants {
308
                    let item_def_id = self.ast_map.local_def_id(item.id);
309
                    self.build_reduced_graph_for_variant(variant, item_def_id,
310
                                                         module, variant_modifiers);
311 312 313 314 315 316
                }
            }

            // These items live in both the type and value namespaces.
            ItemStruct(ref struct_def, _) => {
                // Define a name in the type namespace.
317 318
                let def = Def::Struct(self.ast_map.local_def_id(item.id));
                self.define(parent, name, TypeNS, (def, sp, modifiers));
319 320 321

                // If this is a newtype or unit-like struct, define a name
                // in the value namespace as well
322 323
                if !struct_def.is_struct() {
                    let def = Def::Struct(self.ast_map.local_def_id(struct_def.id()));
324
                    self.define(parent, name, ValueNS, (def, sp, modifiers));
325 326 327
                }

                // Record the def ID and fields of this struct.
328 329
                let field_names = struct_def.fields()
                                            .iter()
330
                                            .map(|f| f.name)
331
                                            .collect();
332
                let item_def_id = self.ast_map.local_def_id(item.id);
333
                self.structs.insert(item_def_id, field_names);
334 335
            }

J
Jeffrey Seyfried 已提交
336
            ItemDefaultImpl(_, _) | ItemImpl(..) => {}
337 338

            ItemTrait(_, _, _, ref items) => {
339 340
                let def_id = self.ast_map.local_def_id(item.id);

341
                // Add all the items within to a new module.
342
                let parent_link = ModuleParentLink(parent, name);
343
                let def = Def::Trait(def_id);
344
                let module_parent = self.new_module(parent_link, Some(def), false, is_public);
345
                self.define(parent, name, TypeNS, (module_parent, sp));
346 347

                // Add the names of all the items to the trait info.
348 349 350 351 352 353 354
                for item in items {
                    let item_def_id = self.ast_map.local_def_id(item.id);
                    let (def, ns) = match item.node {
                        hir::ConstTraitItem(..) => (Def::AssociatedConst(item_def_id), ValueNS),
                        hir::MethodTraitItem(..) => (Def::Method(item_def_id), ValueNS),
                        hir::TypeTraitItem(..) => (Def::AssociatedTy(def_id, item_def_id), TypeNS),
                    };
355

356
                    let modifiers = DefModifiers::PUBLIC; // NB: not DefModifiers::IMPORTABLE
357
                    self.define(module_parent, item.name, ns, (def, item.span, modifiers));
358 359

                    self.trait_item_map.insert((item.name, def_id), item_def_id);
360 361 362 363 364 365 366 367 368 369
                }
            }
        }
    }

    // Constructs the reduced graph for one variant. Variants exist in the
    // type and value namespaces.
    fn build_reduced_graph_for_variant(&mut self,
                                       variant: &Variant,
                                       item_id: DefId,
370
                                       parent: Module<'b>,
371
                                       variant_modifiers: DefModifiers) {
372
        let name = variant.node.name;
373
        if variant.node.data.is_struct() {
374
            // Not adding fields for variants as they are not accessed with a self receiver
375
            let variant_def_id = self.ast_map.local_def_id(variant.node.data.id());
376
            self.structs.insert(variant_def_id, Vec::new());
377
        }
378

379 380
        // Variants are always treated as importable to allow them to be glob used.
        // All variants are defined in both type and value namespaces as future-proofing.
381 382 383 384 385
        let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE | variant_modifiers;
        let def = Def::Variant(item_id, self.ast_map.local_def_id(variant.node.data.id()));

        self.define(parent, name, ValueNS, (def, variant.span, modifiers));
        self.define(parent, name, TypeNS, (def, variant.span, modifiers));
386 387 388
    }

    /// Constructs the reduced graph for one foreign item.
389 390
    fn build_reduced_graph_for_foreign_item(&mut self,
                                            foreign_item: &ForeignItem,
391
                                            parent: Module<'b>) {
V
Vadim Petrochenkov 已提交
392
        let name = foreign_item.name;
393
        let is_public = foreign_item.vis == hir::Public;
T
Fallout  
Tamir Duberstein 已提交
394 395 396 397 398
        let modifiers = if is_public {
            DefModifiers::PUBLIC
        } else {
            DefModifiers::empty()
        } | DefModifiers::IMPORTABLE;
399

400 401
        let def = match foreign_item.node {
            ForeignItemFn(..) => {
402
                Def::Fn(self.ast_map.local_def_id(foreign_item.id))
403 404
            }
            ForeignItemStatic(_, m) => {
405
                Def::Static(self.ast_map.local_def_id(foreign_item.id), m)
406
            }
407
        };
408
        self.define(parent, name, ValueNS, (def, foreign_item.span, modifiers));
409 410
    }

J
Jeffrey Seyfried 已提交
411
    fn build_reduced_graph_for_block(&mut self, block: &Block, parent: &mut Module<'b>) {
412 413 414
        if self.block_needs_anonymous_module(block) {
            let block_id = block.id;

C
corentih 已提交
415 416
            debug!("(building reduced graph for block) creating a new anonymous module for block \
                    {}",
417 418
                   block_id);

419 420
            let parent_link = BlockParentLink(parent, block_id);
            let new_module = self.new_module(parent_link, None, false, false);
421
            parent.module_children.borrow_mut().insert(block_id, new_module);
J
Jeffrey Seyfried 已提交
422
            *parent = new_module;
423 424 425
        }
    }

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    /// Builds the reduced graph for a single item in an external crate.
    fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'b>, xcdef: ChildItem) {
        let def = match xcdef.def {
            DlDef(def) => def,
            _ => return,
        };

        if let Def::ForeignMod(def_id) = def {
            // Foreign modules have no names. Recur and populate eagerly.
            for child in self.session.cstore.item_children(def_id) {
                self.build_reduced_graph_for_external_crate_def(parent, child);
            }
            return;
        }

        let name = xcdef.name;
        let is_public = xcdef.vis == hir::Public || parent.is_trait();
443 444 445 446 447

        let mut modifiers = DefModifiers::empty();
        if is_public {
            modifiers = modifiers | DefModifiers::PUBLIC;
        }
448
        if parent.is_normal() {
449 450 451
            modifiers = modifiers | DefModifiers::IMPORTABLE;
        }

452
        match def {
453
            Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) => {
454
                debug!("(building reduced graph for external crate) building module {} {}",
455
                       name,
456
                       is_public);
457
                let parent_link = ModuleParentLink(parent, name);
458
                let module = self.new_module(parent_link, Some(def), true, is_public);
459
                self.try_define(parent, name, TypeNS, (module, DUMMY_SP));
460
            }
461
            Def::Variant(_, variant_id) => {
462
                debug!("(building reduced graph for external crate) building variant {}", name);
463 464
                // Variants are always treated as importable to allow them to be glob used.
                // All variants are defined in both type and value namespaces as future-proofing.
C
corentih 已提交
465
                let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
466 467
                self.try_define(parent, name, TypeNS, (def, DUMMY_SP, modifiers));
                self.try_define(parent, name, ValueNS, (def, DUMMY_SP, modifiers));
468
                if self.session.cstore.variant_kind(variant_id) == Some(VariantKind::Struct) {
C
corentih 已提交
469 470 471 472
                    // Not adding fields for variants as they are not accessed with a self receiver
                    self.structs.insert(variant_id, Vec::new());
                }
            }
473 474 475 476 477
            Def::Fn(..) |
            Def::Static(..) |
            Def::Const(..) |
            Def::AssociatedConst(..) |
            Def::Method(..) => {
C
corentih 已提交
478
                debug!("(building reduced graph for external crate) building value (fn/static) {}",
479 480
                       name);
                self.try_define(parent, name, ValueNS, (def, DUMMY_SP, modifiers));
481
            }
482
            Def::Trait(def_id) => {
483
                debug!("(building reduced graph for external crate) building type {}", name);
C
corentih 已提交
484 485 486 487

                // If this is a trait, add all the trait item names to the trait
                // info.

488
                let trait_item_def_ids = self.session.cstore.trait_item_def_ids(def_id);
C
corentih 已提交
489
                for trait_item_def in &trait_item_def_ids {
490 491
                    let trait_item_name =
                        self.session.cstore.item_name(trait_item_def.def_id());
C
corentih 已提交
492 493 494 495 496 497 498

                    debug!("(building reduced graph for external crate) ... adding trait item \
                            '{}'",
                           trait_item_name);

                    self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
                }
499

500
                let parent_link = ModuleParentLink(parent, name);
501
                let module = self.new_module(parent_link, Some(def), true, is_public);
502
                self.try_define(parent, name, TypeNS, (module, DUMMY_SP));
C
corentih 已提交
503
            }
504
            Def::TyAlias(..) | Def::AssociatedTy(..) => {
505 506
                debug!("(building reduced graph for external crate) building type {}", name);
                self.try_define(parent, name, TypeNS, (def, DUMMY_SP, modifiers));
C
corentih 已提交
507
            }
508 509
            Def::Struct(def_id)
                if self.session.cstore.tuple_struct_definition_if_ctor(def_id).is_none() => {
510 511 512
                debug!("(building reduced graph for external crate) building type and value for {}",
                       name);
                self.try_define(parent, name, TypeNS, (def, DUMMY_SP, modifiers));
513
                if let Some(ctor_def_id) = self.session.cstore.struct_ctor_def_id(def_id) {
514
                    let def = Def::Struct(ctor_def_id);
515
                    self.try_define(parent, name, ValueNS, (def, DUMMY_SP, modifiers));
C
corentih 已提交
516 517 518
                }

                // Record the def ID and fields of this struct.
519
                let fields = self.session.cstore.struct_field_names(def_id);
C
corentih 已提交
520 521
                self.structs.insert(def_id, fields);
            }
522
            Def::Struct(..) => {}
523 524 525 526 527 528 529
            Def::Local(..) |
            Def::PrimTy(..) |
            Def::TyParam(..) |
            Def::Upvar(..) |
            Def::Label(..) |
            Def::SelfTy(..) |
            Def::Err => {
C
corentih 已提交
530 531
                panic!("didn't expect `{:?}`", def);
            }
532 533 534 535 536
        }
    }

    /// Ensures that the reduced graph rooted at the given external module
    /// is built, building it if it is not.
537
    fn populate_module_if_necessary(&mut self, module: Module<'b>) {
538 539 540
        if module.populated.get() { return }
        for child in self.session.cstore.item_children(module.def_id().unwrap()) {
            self.build_reduced_graph_for_external_crate_def(module, child);
541
        }
542
        module.populated.set(true)
543 544 545 546
    }

    /// Builds the reduced graph rooted at the 'use' directive for an external
    /// crate.
547
    fn build_reduced_graph_for_external_crate(&mut self, root: Module<'b>) {
548 549 550 551
        let root_cnum = root.def_id().unwrap().krate;
        for child in self.session.cstore.crate_top_level_items(root_cnum) {
            self.build_reduced_graph_for_external_crate_def(root, child);
        }
552 553 554 555
    }

    /// Creates and adds an import directive to the given module.
    fn build_import_directive(&mut self,
556
                              module_: Module<'b>,
557 558 559 560 561
                              module_path: Vec<Name>,
                              subclass: ImportDirectiveSubclass,
                              span: Span,
                              id: NodeId,
                              is_public: bool,
562
                              is_prelude: bool) {
563 564 565 566
        // Bump the reference count on the name. Or, if this is a glob, set
        // the appropriate flag.

        match subclass {
567
            SingleImport { target, .. } => {
568 569
                module_.increment_outstanding_references_for(target, ValueNS, is_public);
                module_.increment_outstanding_references_for(target, TypeNS, is_public);
570
            }
571
            GlobImport if !is_prelude => {
572 573
                // Set the glob flag. This tells us that we don't know the
                // module's exports ahead of time.
574
                module_.inc_glob_count(is_public)
575
            }
576 577 578
            // Prelude imports are not included in the glob counts since they do not get added to
            // `resolved_globs` -- they are handled separately in `resolve_imports`.
            GlobImport => {}
579
        }
580

581
        let directive =
582
            ImportDirective::new(module_path, subclass, span, id, is_public, is_prelude);
583
        module_.add_import_directive(directive);
584
        self.unresolved_imports += 1;
585 586 587
    }
}

C
corentih 已提交
588
struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
589
    builder: GraphBuilder<'a, 'b, 'tcx>,
590
    parent: Module<'b>,
591 592 593
}

impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
594 595 596 597
    fn visit_nested_item(&mut self, item: hir::ItemId) {
        self.visit_item(self.builder.resolver.ast_map.expect_item(item.id))
    }

598
    fn visit_item(&mut self, item: &Item) {
J
Jeffrey Seyfried 已提交
599 600
        let old_parent = self.parent;
        self.builder.build_reduced_graph_for_item(item, &mut self.parent);
601
        intravisit::walk_item(self, item);
602 603 604 605
        self.parent = old_parent;
    }

    fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
606
        self.builder.build_reduced_graph_for_foreign_item(foreign_item, &self.parent);
607 608 609
    }

    fn visit_block(&mut self, block: &Block) {
J
Jeffrey Seyfried 已提交
610 611
        let old_parent = self.parent;
        self.builder.build_reduced_graph_for_block(block, &mut self.parent);
612
        intravisit::walk_block(self, block);
613 614 615 616
        self.parent = old_parent;
    }
}

617
pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
C
corentih 已提交
618
    GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
619 620
}

621 622
pub fn populate_module_if_necessary<'a, 'tcx>(resolver: &mut Resolver<'a, 'tcx>,
                                              module: Module<'a>) {
C
corentih 已提交
623
    GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);
624
}