]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
Rename hir::map::Node to hir::map::NodeKind
[rust.git] / src / librustc / hir / map / mod.rs
1 // Copyright 2012-2015 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 use self::collector::NodeCollector;
12 pub use self::def_collector::{DefCollector, MacroInvocationData};
13 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
14                             DisambiguatedDefPathData, DefPathHash};
15
16 use dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
17
18 use hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId, DefIndexAddressSpace};
19
20 use middle::cstore::CrateStore;
21
22 use rustc_target::spec::abi::Abi;
23 use rustc_data_structures::svh::Svh;
24 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
25 use syntax::source_map::Spanned;
26 use syntax::ext::base::MacroKind;
27 use syntax_pos::{Span, DUMMY_SP};
28
29 use hir::*;
30 use hir::print::Nested;
31 use util::nodemap::FxHashMap;
32
33 use std::io;
34 use std::result::Result::Err;
35 use ty::TyCtxt;
36
37 pub mod blocks;
38 mod collector;
39 mod def_collector;
40 pub mod definitions;
41 mod hir_id_validator;
42
43
44 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
45 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
46
47 #[derive(Copy, Clone, Debug)]
48 pub enum NodeKind<'hir> {
49     Item(&'hir Item),
50     ForeignItem(&'hir ForeignItem),
51     TraitItem(&'hir TraitItem),
52     ImplItem(&'hir ImplItem),
53     Variant(&'hir Variant),
54     Field(&'hir StructField),
55     AnonConst(&'hir AnonConst),
56     Expr(&'hir Expr),
57     Stmt(&'hir Stmt),
58     Ty(&'hir Ty),
59     TraitRef(&'hir TraitRef),
60     Binding(&'hir Pat),
61     Pat(&'hir Pat),
62     Block(&'hir Block),
63     Local(&'hir Local),
64     MacroDef(&'hir MacroDef),
65
66     /// StructCtor represents a tuple struct.
67     StructCtor(&'hir VariantData),
68
69     Lifetime(&'hir Lifetime),
70     GenericParam(&'hir GenericParam),
71     Visibility(&'hir Visibility),
72 }
73
74 /// Represents an entry and its parent NodeID.
75 /// The odd layout is to bring down the total size.
76 #[derive(Copy, Debug)]
77 pub enum EntryKind<'hir> {
78     /// Placeholder for holes in the map.
79     NotPresent,
80
81     /// All the node types, with a parent ID.
82     Item(NodeId, DepNodeIndex, &'hir Item),
83     ForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
84     TraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
85     ImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
86     Variant(NodeId, DepNodeIndex, &'hir Variant),
87     Field(NodeId, DepNodeIndex, &'hir StructField),
88     AnonConst(NodeId, DepNodeIndex, &'hir AnonConst),
89     Expr(NodeId, DepNodeIndex, &'hir Expr),
90     Stmt(NodeId, DepNodeIndex, &'hir Stmt),
91     Ty(NodeId, DepNodeIndex, &'hir Ty),
92     TraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
93     Binding(NodeId, DepNodeIndex, &'hir Pat),
94     Pat(NodeId, DepNodeIndex, &'hir Pat),
95     Block(NodeId, DepNodeIndex, &'hir Block),
96     StructCtor(NodeId, DepNodeIndex, &'hir VariantData),
97     Lifetime(NodeId, DepNodeIndex, &'hir Lifetime),
98     GenericParam(NodeId, DepNodeIndex, &'hir GenericParam),
99     Visibility(NodeId, DepNodeIndex, &'hir Visibility),
100     Local(NodeId, DepNodeIndex, &'hir Local),
101     MacroDef(DepNodeIndex, &'hir MacroDef),
102
103     /// Roots for node trees. The DepNodeIndex is the dependency node of the
104     /// crate's root module.
105     RootCrate(DepNodeIndex),
106 }
107
108 impl<'hir> Clone for EntryKind<'hir> {
109     fn clone(&self) -> EntryKind<'hir> {
110         *self
111     }
112 }
113
114 impl<'hir> EntryKind<'hir> {
115     fn parent_node(self) -> Option<NodeId> {
116         Some(match self {
117             EntryKind::Item(id, _, _) => id,
118             EntryKind::ForeignItem(id, _, _) => id,
119             EntryKind::TraitItem(id, _, _) => id,
120             EntryKind::ImplItem(id, _, _) => id,
121             EntryKind::Variant(id, _, _) => id,
122             EntryKind::Field(id, _, _) => id,
123             EntryKind::AnonConst(id, _, _) => id,
124             EntryKind::Expr(id, _, _) => id,
125             EntryKind::Stmt(id, _, _) => id,
126             EntryKind::Ty(id, _, _) => id,
127             EntryKind::TraitRef(id, _, _) => id,
128             EntryKind::Binding(id, _, _) => id,
129             EntryKind::Pat(id, _, _) => id,
130             EntryKind::Block(id, _, _) => id,
131             EntryKind::StructCtor(id, _, _) => id,
132             EntryKind::Lifetime(id, _, _) => id,
133             EntryKind::GenericParam(id, _, _) => id,
134             EntryKind::Visibility(id, _, _) => id,
135             EntryKind::Local(id, _, _) => id,
136
137             EntryKind::NotPresent |
138             EntryKind::MacroDef(..) |
139             EntryKind::RootCrate(_) => return None,
140         })
141     }
142
143     fn to_node(self) -> Option<NodeKind<'hir>> {
144         Some(match self {
145             EntryKind::Item(_, _, n) => NodeKind::Item(n),
146             EntryKind::ForeignItem(_, _, n) => NodeKind::ForeignItem(n),
147             EntryKind::TraitItem(_, _, n) => NodeKind::TraitItem(n),
148             EntryKind::ImplItem(_, _, n) => NodeKind::ImplItem(n),
149             EntryKind::Variant(_, _, n) => NodeKind::Variant(n),
150             EntryKind::Field(_, _, n) => NodeKind::Field(n),
151             EntryKind::AnonConst(_, _, n) => NodeKind::AnonConst(n),
152             EntryKind::Expr(_, _, n) => NodeKind::Expr(n),
153             EntryKind::Stmt(_, _, n) => NodeKind::Stmt(n),
154             EntryKind::Ty(_, _, n) => NodeKind::Ty(n),
155             EntryKind::TraitRef(_, _, n) => NodeKind::TraitRef(n),
156             EntryKind::Binding(_, _, n) => NodeKind::Binding(n),
157             EntryKind::Pat(_, _, n) => NodeKind::Pat(n),
158             EntryKind::Block(_, _, n) => NodeKind::Block(n),
159             EntryKind::StructCtor(_, _, n) => NodeKind::StructCtor(n),
160             EntryKind::Lifetime(_, _, n) => NodeKind::Lifetime(n),
161             EntryKind::GenericParam(_, _, n) => NodeKind::GenericParam(n),
162             EntryKind::Visibility(_, _, n) => NodeKind::Visibility(n),
163             EntryKind::Local(_, _, n) => NodeKind::Local(n),
164             EntryKind::MacroDef(_, n) => NodeKind::MacroDef(n),
165
166             EntryKind::NotPresent |
167             EntryKind::RootCrate(_) => return None
168         })
169     }
170
171     fn fn_decl(&self) -> Option<&FnDecl> {
172         match self {
173             EntryKind::Item(_, _, ref item) => {
174                 match item.node {
175                     ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
176                     _ => None,
177                 }
178             }
179
180             EntryKind::TraitItem(_, _, ref item) => {
181                 match item.node {
182                     TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
183                     _ => None
184                 }
185             }
186
187             EntryKind::ImplItem(_, _, ref item) => {
188                 match item.node {
189                     ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
190                     _ => None,
191                 }
192             }
193
194             EntryKind::Expr(_, _, ref expr) => {
195                 match expr.node {
196                     ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
197                     _ => None,
198                 }
199             }
200
201             _ => None
202         }
203     }
204
205     fn associated_body(self) -> Option<BodyId> {
206         match self {
207             EntryKind::Item(_, _, item) => {
208                 match item.node {
209                     ItemKind::Const(_, body) |
210                     ItemKind::Static(.., body) |
211                     ItemKind::Fn(_, _, _, body) => Some(body),
212                     _ => None,
213                 }
214             }
215
216             EntryKind::TraitItem(_, _, item) => {
217                 match item.node {
218                     TraitItemKind::Const(_, Some(body)) |
219                     TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
220                     _ => None
221                 }
222             }
223
224             EntryKind::ImplItem(_, _, item) => {
225                 match item.node {
226                     ImplItemKind::Const(_, body) |
227                     ImplItemKind::Method(_, body) => Some(body),
228                     _ => None,
229                 }
230             }
231
232             EntryKind::AnonConst(_, _, constant) => Some(constant.body),
233
234             EntryKind::Expr(_, _, expr) => {
235                 match expr.node {
236                     ExprKind::Closure(.., body, _, _) => Some(body),
237                     _ => None,
238                 }
239             }
240
241             _ => None
242         }
243     }
244
245     fn is_body_owner(self, node_id: NodeId) -> bool {
246         match self.associated_body() {
247             Some(b) => b.node_id == node_id,
248             None => false,
249         }
250     }
251 }
252
253 /// Stores a crate and any number of inlined items from other crates.
254 pub struct Forest {
255     krate: Crate,
256     pub dep_graph: DepGraph,
257 }
258
259 impl Forest {
260     pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
261         Forest {
262             krate,
263             dep_graph: dep_graph.clone(),
264         }
265     }
266
267     pub fn krate<'hir>(&'hir self) -> &'hir Crate {
268         self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
269         &self.krate
270     }
271 }
272
273 /// Represents a mapping from NodeKind IDs to AST elements and their parent
274 /// NodeKind IDs
275 #[derive(Clone)]
276 pub struct Map<'hir> {
277     /// The backing storage for all the AST nodes.
278     pub forest: &'hir Forest,
279
280     /// Same as the dep_graph in forest, just available with one fewer
281     /// deref. This is a gratuitous micro-optimization.
282     pub dep_graph: DepGraph,
283
284     /// The SVH of the local crate.
285     pub crate_hash: Svh,
286
287     /// NodeIds are sequential integers from 0, so we can be
288     /// super-compact by storing them in a vector. Not everything with
289     /// a NodeId is in the map, but empirically the occupancy is about
290     /// 75-80%, so there's not too much overhead (certainly less than
291     /// a hashmap, since they (at the time of writing) have a maximum
292     /// of 75% occupancy).
293     ///
294     /// Also, indexing is pretty quick when you've got a vector and
295     /// plain old integers.
296     map: Vec<EntryKind<'hir>>,
297
298     definitions: &'hir Definitions,
299
300     /// The reverse mapping of `node_to_hir_id`.
301     hir_to_node_id: FxHashMap<HirId, NodeId>,
302 }
303
304 impl<'hir> Map<'hir> {
305     /// Registers a read in the dependency graph of the AST node with
306     /// the given `id`. This needs to be called each time a public
307     /// function returns the HIR for a node -- in other words, when it
308     /// "reveals" the content of a node to the caller (who might not
309     /// otherwise have had access to those contents, and hence needs a
310     /// read recorded). If the function just returns a DefId or
311     /// NodeId, no actual content was returned, so no read is needed.
312     pub fn read(&self, id: NodeId) {
313         let entry = self.map[id.as_usize()];
314         match entry {
315             EntryKind::Item(_, dep_node_index, _) |
316             EntryKind::TraitItem(_, dep_node_index, _) |
317             EntryKind::ImplItem(_, dep_node_index, _) |
318             EntryKind::Variant(_, dep_node_index, _) |
319             EntryKind::ForeignItem(_, dep_node_index, _) |
320             EntryKind::Field(_, dep_node_index, _) |
321             EntryKind::Stmt(_, dep_node_index, _) |
322             EntryKind::Ty(_, dep_node_index, _) |
323             EntryKind::TraitRef(_, dep_node_index, _) |
324             EntryKind::Binding(_, dep_node_index, _) |
325             EntryKind::Pat(_, dep_node_index, _) |
326             EntryKind::Block(_, dep_node_index, _) |
327             EntryKind::StructCtor(_, dep_node_index, _) |
328             EntryKind::Lifetime(_, dep_node_index, _) |
329             EntryKind::GenericParam(_, dep_node_index, _) |
330             EntryKind::Visibility(_, dep_node_index, _) |
331             EntryKind::AnonConst(_, dep_node_index, _) |
332             EntryKind::Expr(_, dep_node_index, _) |
333             EntryKind::Local(_, dep_node_index, _) |
334             EntryKind::MacroDef(dep_node_index, _) |
335             EntryKind::RootCrate(dep_node_index) => {
336                 self.dep_graph.read_index(dep_node_index);
337             }
338             EntryKind::NotPresent => {
339                 bug!("called HirMap::read() with invalid NodeId")
340             }
341         }
342     }
343
344     #[inline]
345     pub fn definitions(&self) -> &'hir Definitions {
346         self.definitions
347     }
348
349     pub fn def_key(&self, def_id: DefId) -> DefKey {
350         assert!(def_id.is_local());
351         self.definitions.def_key(def_id.index)
352     }
353
354     pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
355         self.opt_local_def_id(id).map(|def_id| {
356             self.def_path(def_id)
357         })
358     }
359
360     pub fn def_path(&self, def_id: DefId) -> DefPath {
361         assert!(def_id.is_local());
362         self.definitions.def_path(def_id.index)
363     }
364
365     #[inline]
366     pub fn local_def_id(&self, node: NodeId) -> DefId {
367         self.opt_local_def_id(node).unwrap_or_else(|| {
368             bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
369                  node, self.find_entry(node))
370         })
371     }
372
373     #[inline]
374     pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
375         self.definitions.opt_local_def_id(node)
376     }
377
378     #[inline]
379     pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
380         self.definitions.as_local_node_id(def_id)
381     }
382
383     #[inline]
384     pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
385         self.hir_to_node_id[&hir_id]
386     }
387
388     #[inline]
389     pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
390         self.definitions.node_to_hir_id(node_id)
391     }
392
393     #[inline]
394     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
395         self.definitions.def_index_to_hir_id(def_index)
396     }
397
398     #[inline]
399     pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
400         self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
401     }
402
403     #[inline]
404     pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
405         self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
406     }
407
408     #[inline]
409     pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
410         self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
411     }
412
413     pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
414         let node = if let Some(node) = self.find(node_id) {
415             node
416         } else {
417             return None
418         };
419
420         match node {
421             NodeKind::Item(item) => {
422                 let def_id = || {
423                     self.local_def_id(item.id)
424                 };
425
426                 match item.node {
427                     ItemKind::Static(_, m, _) => Some(Def::Static(def_id(),
428                                                             m == MutMutable)),
429                     ItemKind::Const(..) => Some(Def::Const(def_id())),
430                     ItemKind::Fn(..) => Some(Def::Fn(def_id())),
431                     ItemKind::Mod(..) => Some(Def::Mod(def_id())),
432                     ItemKind::Existential(..) => Some(Def::Existential(def_id())),
433                     ItemKind::Ty(..) => Some(Def::TyAlias(def_id())),
434                     ItemKind::Enum(..) => Some(Def::Enum(def_id())),
435                     ItemKind::Struct(..) => Some(Def::Struct(def_id())),
436                     ItemKind::Union(..) => Some(Def::Union(def_id())),
437                     ItemKind::Trait(..) => Some(Def::Trait(def_id())),
438                     ItemKind::TraitAlias(..) => {
439                         bug!("trait aliases are not yet implemented (see issue #41517)")
440                     },
441                     ItemKind::ExternCrate(_) |
442                     ItemKind::Use(..) |
443                     ItemKind::ForeignMod(..) |
444                     ItemKind::GlobalAsm(..) |
445                     ItemKind::Impl(..) => None,
446                 }
447             }
448             NodeKind::ForeignItem(item) => {
449                 let def_id = self.local_def_id(item.id);
450                 match item.node {
451                     ForeignItemKind::Fn(..) => Some(Def::Fn(def_id)),
452                     ForeignItemKind::Static(_, m) => Some(Def::Static(def_id, m)),
453                     ForeignItemKind::Type => Some(Def::ForeignTy(def_id)),
454                 }
455             }
456             NodeKind::TraitItem(item) => {
457                 let def_id = self.local_def_id(item.id);
458                 match item.node {
459                     TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
460                     TraitItemKind::Method(..) => Some(Def::Method(def_id)),
461                     TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
462                 }
463             }
464             NodeKind::ImplItem(item) => {
465                 let def_id = self.local_def_id(item.id);
466                 match item.node {
467                     ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
468                     ImplItemKind::Method(..) => Some(Def::Method(def_id)),
469                     ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
470                     ImplItemKind::Existential(..) => Some(Def::AssociatedExistential(def_id)),
471                 }
472             }
473             NodeKind::Variant(variant) => {
474                 let def_id = self.local_def_id(variant.node.data.id());
475                 Some(Def::Variant(def_id))
476             }
477             NodeKind::Field(_) |
478             NodeKind::AnonConst(_) |
479             NodeKind::Expr(_) |
480             NodeKind::Stmt(_) |
481             NodeKind::Ty(_) |
482             NodeKind::TraitRef(_) |
483             NodeKind::Pat(_) |
484             NodeKind::Binding(_) |
485             NodeKind::StructCtor(_) |
486             NodeKind::Lifetime(_) |
487             NodeKind::Visibility(_) |
488             NodeKind::Block(_) => None,
489             NodeKind::Local(local) => {
490                 Some(Def::Local(local.id))
491             }
492             NodeKind::MacroDef(macro_def) => {
493                 Some(Def::Macro(self.local_def_id(macro_def.id),
494                                 MacroKind::Bang))
495             }
496             NodeKind::GenericParam(param) => {
497                 Some(match param.kind {
498                     GenericParamKind::Lifetime { .. } => Def::Local(param.id),
499                     GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)),
500                 })
501             }
502         }
503     }
504
505     fn entry_count(&self) -> usize {
506         self.map.len()
507     }
508
509     fn find_entry(&self, id: NodeId) -> Option<EntryKind<'hir>> {
510         self.map.get(id.as_usize()).cloned()
511     }
512
513     pub fn krate(&self) -> &'hir Crate {
514         self.forest.krate()
515     }
516
517     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
518         self.read(id.node_id);
519
520         // NB: intentionally bypass `self.forest.krate()` so that we
521         // do not trigger a read of the whole krate here
522         self.forest.krate.trait_item(id)
523     }
524
525     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
526         self.read(id.node_id);
527
528         // NB: intentionally bypass `self.forest.krate()` so that we
529         // do not trigger a read of the whole krate here
530         self.forest.krate.impl_item(id)
531     }
532
533     pub fn body(&self, id: BodyId) -> &'hir Body {
534         self.read(id.node_id);
535
536         // NB: intentionally bypass `self.forest.krate()` so that we
537         // do not trigger a read of the whole krate here
538         self.forest.krate.body(id)
539     }
540
541     pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
542         if let Some(entry) = self.find_entry(node_id) {
543             entry.fn_decl().map(|fd| fd.clone())
544         } else {
545             bug!("no entry for node_id `{}`", node_id)
546         }
547     }
548
549     /// Returns the `NodeId` that corresponds to the definition of
550     /// which this is the body of, i.e. a `fn`, `const` or `static`
551     /// item (possibly associated), a closure, or a `hir::AnonConst`.
552     pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
553         let parent = self.get_parent_node(node_id);
554         assert!(self.map[parent.as_usize()].is_body_owner(node_id));
555         parent
556     }
557
558     pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
559         self.local_def_id(self.body_owner(id))
560     }
561
562     /// Given a node id, returns the `BodyId` associated with it,
563     /// if the node is a body owner, otherwise returns `None`.
564     pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
565         if let Some(entry) = self.find_entry(id) {
566             if self.dep_graph.is_fully_enabled() {
567                 let hir_id_owner = self.node_to_hir_id(id).owner;
568                 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
569                 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
570             }
571
572             entry.associated_body()
573         } else {
574             bug!("no entry for id `{}`", id)
575         }
576     }
577
578     /// Given a body owner's id, returns the `BodyId` associated with it.
579     pub fn body_owned_by(&self, id: NodeId) -> BodyId {
580         self.maybe_body_owned_by(id).unwrap_or_else(|| {
581             span_bug!(self.span(id), "body_owned_by: {} has no associated body",
582                       self.node_to_string(id));
583         })
584     }
585
586     pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
587         match self.get(id) {
588             NodeKind::Item(&Item { node: ItemKind::Const(..), .. }) |
589             NodeKind::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
590             NodeKind::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
591             NodeKind::AnonConst(_) => {
592                 BodyOwnerKind::Const
593             }
594             NodeKind::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
595                 BodyOwnerKind::Static(m)
596             }
597             // Default to function if it's not a constant or static.
598             _ => BodyOwnerKind::Fn
599         }
600     }
601
602     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
603         match self.get(id) {
604             NodeKind::Item(&Item { node: ItemKind::Trait(..), .. }) => id,
605             NodeKind::GenericParam(_) => self.get_parent_node(id),
606             _ => {
607                 bug!("ty_param_owner: {} not a type parameter",
608                     self.node_to_string(id))
609             }
610         }
611     }
612
613     pub fn ty_param_name(&self, id: NodeId) -> Name {
614         match self.get(id) {
615             NodeKind::Item(&Item { node: ItemKind::Trait(..), .. }) => {
616                 keywords::SelfType.name()
617             }
618             NodeKind::GenericParam(param) => param.name.ident().name,
619             _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
620         }
621     }
622
623     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
624         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
625
626         // NB: intentionally bypass `self.forest.krate()` so that we
627         // do not trigger a read of the whole krate here
628         self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
629     }
630
631     pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
632         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
633
634         // NB: intentionally bypass `self.forest.krate()` so that we
635         // do not trigger a read of the whole krate here
636         self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
637     }
638
639     pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
640         self.trait_auto_impl(trait_did).is_some()
641     }
642
643     /// Get the attributes on the krate. This is preferable to
644     /// invoking `krate.attrs` because it registers a tighter
645     /// dep-graph access.
646     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
647         let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
648
649         self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
650         &self.forest.krate.attrs
651     }
652
653     /// Retrieve the NodeKind corresponding to `id`, panicking if it cannot
654     /// be found.
655     pub fn get(&self, id: NodeId) -> NodeKind<'hir> {
656         match self.find(id) {
657             Some(node) => node, // read recorded by `find`
658             None => bug!("couldn't find node id {} in the AST map", id)
659         }
660     }
661
662     pub fn get_if_local(&self, id: DefId) -> Option<NodeKind<'hir>> {
663         self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
664     }
665
666     pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
667         self.get_if_local(id).and_then(|node| {
668             match node {
669                 NodeKind::ImplItem(ref impl_item) => Some(&impl_item.generics),
670                 NodeKind::TraitItem(ref trait_item) => Some(&trait_item.generics),
671                 NodeKind::Item(ref item) => {
672                     match item.node {
673                         ItemKind::Fn(_, _, ref generics, _) |
674                         ItemKind::Ty(_, ref generics) |
675                         ItemKind::Enum(_, ref generics) |
676                         ItemKind::Struct(_, ref generics) |
677                         ItemKind::Union(_, ref generics) |
678                         ItemKind::Trait(_, _, ref generics, ..) |
679                         ItemKind::TraitAlias(ref generics, _) |
680                         ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
681                         _ => None,
682                     }
683                 }
684                 _ => None,
685             }
686         })
687     }
688
689     pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
690         self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
691     }
692
693     /// Retrieve the NodeKind corresponding to `id`, returning None if
694     /// cannot be found.
695     pub fn find(&self, id: NodeId) -> Option<NodeKind<'hir>> {
696         let result = self.find_entry(id).and_then(|x| x.to_node());
697         if result.is_some() {
698             self.read(id);
699         }
700         result
701     }
702
703     /// Similar to get_parent, returns the parent node id or id if there is no
704     /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
705     /// present in the map -- so passing the return value of get_parent_node to
706     /// get may actually panic.
707     /// This function returns the immediate parent in the AST, whereas get_parent
708     /// returns the enclosing item. Note that this might not be the actual parent
709     /// node in the AST - some kinds of nodes are not in the map and these will
710     /// never appear as the parent_node. So you can always walk the parent_nodes
711     /// from a node to the root of the ast (unless you get the same id back here
712     /// that can happen if the id is not in the map itself or is just weird).
713     pub fn get_parent_node(&self, id: NodeId) -> NodeId {
714         if self.dep_graph.is_fully_enabled() {
715             let hir_id_owner = self.node_to_hir_id(id).owner;
716             let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
717             self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
718         }
719
720         self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
721     }
722
723     /// Check if the node is an argument. An argument is a local variable whose
724     /// immediate parent is an item or a closure.
725     pub fn is_argument(&self, id: NodeId) -> bool {
726         match self.find(id) {
727             Some(NodeKind::Binding(_)) => (),
728             _ => return false,
729         }
730         match self.find(self.get_parent_node(id)) {
731             Some(NodeKind::Item(_)) |
732             Some(NodeKind::TraitItem(_)) |
733             Some(NodeKind::ImplItem(_)) => true,
734             Some(NodeKind::Expr(e)) => {
735                 match e.node {
736                     ExprKind::Closure(..) => true,
737                     _ => false,
738                 }
739             }
740             _ => false,
741         }
742     }
743
744     /// If there is some error when walking the parents (e.g., a node does not
745     /// have a parent in the map or a node can't be found), then we return the
746     /// last good node id we found. Note that reaching the crate root (id == 0),
747     /// is not an error, since items in the crate module have the crate root as
748     /// parent.
749     fn walk_parent_nodes<F, F2>(&self,
750                                 start_id: NodeId,
751                                 found: F,
752                                 bail_early: F2)
753         -> Result<NodeId, NodeId>
754         where F: Fn(&NodeKind<'hir>) -> bool, F2: Fn(&NodeKind<'hir>) -> bool
755     {
756         let mut id = start_id;
757         loop {
758             let parent_node = self.get_parent_node(id);
759             if parent_node == CRATE_NODE_ID {
760                 return Ok(CRATE_NODE_ID);
761             }
762             if parent_node == id {
763                 return Err(id);
764             }
765
766             let node = self.find_entry(parent_node);
767             if node.is_none() {
768                 return Err(id);
769             }
770             let node = node.unwrap().to_node();
771             match node {
772                 Some(ref node) => {
773                     if found(node) {
774                         return Ok(parent_node);
775                     } else if bail_early(node) {
776                         return Err(parent_node);
777                     }
778                 }
779                 None => {
780                     return Err(parent_node);
781                 }
782             }
783             id = parent_node;
784         }
785     }
786
787     /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
788     /// `while` or `loop` before reaching it, as block tail returns are not
789     /// available in them.
790     ///
791     /// ```
792     /// fn foo(x: usize) -> bool {
793     ///     if x == 1 {
794     ///         true  // `get_return_block` gets passed the `id` corresponding
795     ///     } else {  // to this, it will return `foo`'s `NodeId`.
796     ///         false
797     ///     }
798     /// }
799     /// ```
800     ///
801     /// ```
802     /// fn foo(x: usize) -> bool {
803     ///     loop {
804     ///         true  // `get_return_block` gets passed the `id` corresponding
805     ///     }         // to this, it will return `None`.
806     ///     false
807     /// }
808     /// ```
809     pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
810         let match_fn = |node: &NodeKind| {
811             match *node {
812                 NodeKind::Item(_) |
813                 NodeKind::ForeignItem(_) |
814                 NodeKind::TraitItem(_) |
815                 NodeKind::ImplItem(_) => true,
816                 _ => false,
817             }
818         };
819         let match_non_returning_block = |node: &NodeKind| {
820             match *node {
821                 NodeKind::Expr(ref expr) => {
822                     match expr.node {
823                         ExprKind::While(..) | ExprKind::Loop(..) => true,
824                         _ => false,
825                     }
826                 }
827                 _ => false,
828             }
829         };
830
831         match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
832             Ok(id) => Some(id),
833             Err(_) => None,
834         }
835     }
836
837     /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
838     /// parent item is in this map. The "parent item" is the closest parent node
839     /// in the HIR which is recorded by the map and is an item, either an item
840     /// in a module, trait, or impl.
841     pub fn get_parent(&self, id: NodeId) -> NodeId {
842         match self.walk_parent_nodes(id, |node| match *node {
843             NodeKind::Item(_) |
844             NodeKind::ForeignItem(_) |
845             NodeKind::TraitItem(_) |
846             NodeKind::ImplItem(_) => true,
847             _ => false,
848         }, |_| false) {
849             Ok(id) => id,
850             Err(id) => id,
851         }
852     }
853
854     /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
855     /// module parent is in this map.
856     pub fn get_module_parent(&self, id: NodeId) -> DefId {
857         let id = match self.walk_parent_nodes(id, |node| match *node {
858             NodeKind::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
859             _ => false,
860         }, |_| false) {
861             Ok(id) => id,
862             Err(id) => id,
863         };
864         self.local_def_id(id)
865     }
866
867     /// Returns the nearest enclosing scope. A scope is an item or block.
868     /// FIXME it is not clear to me that all items qualify as scopes - statics
869     /// and associated types probably shouldn't, for example. Behavior in this
870     /// regard should be expected to be highly unstable.
871     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
872         match self.walk_parent_nodes(id, |node| match *node {
873             NodeKind::Item(_) |
874             NodeKind::ForeignItem(_) |
875             NodeKind::TraitItem(_) |
876             NodeKind::ImplItem(_) |
877             NodeKind::Block(_) => true,
878             _ => false,
879         }, |_| false) {
880             Ok(id) => Some(id),
881             Err(_) => None,
882         }
883     }
884
885     pub fn get_parent_did(&self, id: NodeId) -> DefId {
886         self.local_def_id(self.get_parent(id))
887     }
888
889     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
890         let parent = self.get_parent(id);
891         let abi = match self.find_entry(parent) {
892             Some(EntryKind::Item(_, _, i)) => {
893                 match i.node {
894                     ItemKind::ForeignMod(ref nm) => Some(nm.abi),
895                     _ => None
896                 }
897             }
898             _ => None
899         };
900         match abi {
901             Some(abi) => {
902                 self.read(id); // reveals some of the content of a node
903                 abi
904             }
905             None => bug!("expected foreign mod or inlined parent, found {}",
906                           self.node_to_string(parent))
907         }
908     }
909
910     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
911         match self.find(id) { // read recorded by `find`
912             Some(NodeKind::Item(item)) => item,
913             _ => bug!("expected item, found {}", self.node_to_string(id))
914         }
915     }
916
917     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
918         match self.find(id) {
919             Some(NodeKind::ImplItem(item)) => item,
920             _ => bug!("expected impl item, found {}", self.node_to_string(id))
921         }
922     }
923
924     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
925         match self.find(id) {
926             Some(NodeKind::TraitItem(item)) => item,
927             _ => bug!("expected trait item, found {}", self.node_to_string(id))
928         }
929     }
930
931     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
932         match self.find(id) {
933             Some(NodeKind::Item(i)) => {
934                 match i.node {
935                     ItemKind::Struct(ref struct_def, _) |
936                     ItemKind::Union(ref struct_def, _) => struct_def,
937                     _ => {
938                         bug!("struct ID bound to non-struct {}",
939                              self.node_to_string(id));
940                     }
941                 }
942             }
943             Some(NodeKind::StructCtor(data)) => data,
944             Some(NodeKind::Variant(variant)) => &variant.node.data,
945             _ => {
946                 bug!("expected struct or variant, found {}",
947                      self.node_to_string(id));
948             }
949         }
950     }
951
952     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
953         match self.find(id) {
954             Some(NodeKind::Variant(variant)) => variant,
955             _ => bug!("expected variant, found {}", self.node_to_string(id)),
956         }
957     }
958
959     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
960         match self.find(id) {
961             Some(NodeKind::ForeignItem(item)) => item,
962             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
963         }
964     }
965
966     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
967         match self.find(id) { // read recorded by find
968             Some(NodeKind::Expr(expr)) => expr,
969             _ => bug!("expected expr, found {}", self.node_to_string(id))
970         }
971     }
972
973     /// Returns the name associated with the given NodeId's AST.
974     pub fn name(&self, id: NodeId) -> Name {
975         match self.get(id) {
976             NodeKind::Item(i) => i.name,
977             NodeKind::ForeignItem(i) => i.name,
978             NodeKind::ImplItem(ii) => ii.ident.name,
979             NodeKind::TraitItem(ti) => ti.ident.name,
980             NodeKind::Variant(v) => v.node.name,
981             NodeKind::Field(f) => f.ident.name,
982             NodeKind::Lifetime(lt) => lt.name.ident().name,
983             NodeKind::GenericParam(param) => param.name.ident().name,
984             NodeKind::Binding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.name,
985             NodeKind::StructCtor(_) => self.name(self.get_parent(id)),
986             _ => bug!("no name for {}", self.node_to_string(id))
987         }
988     }
989
990     /// Given a node ID, get a list of attributes associated with the AST
991     /// corresponding to the NodeKind ID
992     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
993         self.read(id); // reveals attributes on the node
994         let attrs = match self.find(id) {
995             Some(NodeKind::Item(i)) => Some(&i.attrs[..]),
996             Some(NodeKind::ForeignItem(fi)) => Some(&fi.attrs[..]),
997             Some(NodeKind::TraitItem(ref ti)) => Some(&ti.attrs[..]),
998             Some(NodeKind::ImplItem(ref ii)) => Some(&ii.attrs[..]),
999             Some(NodeKind::Variant(ref v)) => Some(&v.node.attrs[..]),
1000             Some(NodeKind::Field(ref f)) => Some(&f.attrs[..]),
1001             Some(NodeKind::Expr(ref e)) => Some(&*e.attrs),
1002             Some(NodeKind::Stmt(ref s)) => Some(s.node.attrs()),
1003             Some(NodeKind::GenericParam(param)) => Some(&param.attrs[..]),
1004             // unit/tuple structs take the attributes straight from
1005             // the struct definition.
1006             Some(NodeKind::StructCtor(_)) => {
1007                 return self.attrs(self.get_parent(id));
1008             }
1009             _ => None
1010         };
1011         attrs.unwrap_or(&[])
1012     }
1013
1014     /// Returns an iterator that yields the node id's with paths that
1015     /// match `parts`.  (Requires `parts` is non-empty.)
1016     ///
1017     /// For example, if given `parts` equal to `["bar", "quux"]`, then
1018     /// the iterator will produce node id's for items with paths
1019     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1020     /// any other such items it can find in the map.
1021     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1022                                  -> NodesMatchingSuffix<'a, 'hir> {
1023         NodesMatchingSuffix {
1024             map: self,
1025             item_name: parts.last().unwrap(),
1026             in_which: &parts[..parts.len() - 1],
1027             idx: CRATE_NODE_ID,
1028         }
1029     }
1030
1031     pub fn span(&self, id: NodeId) -> Span {
1032         self.read(id); // reveals span from node
1033         match self.find_entry(id) {
1034             Some(EntryKind::Item(_, _, item)) => item.span,
1035             Some(EntryKind::ForeignItem(_, _, foreign_item)) => foreign_item.span,
1036             Some(EntryKind::TraitItem(_, _, trait_method)) => trait_method.span,
1037             Some(EntryKind::ImplItem(_, _, impl_item)) => impl_item.span,
1038             Some(EntryKind::Variant(_, _, variant)) => variant.span,
1039             Some(EntryKind::Field(_, _, field)) => field.span,
1040             Some(EntryKind::AnonConst(_, _, constant)) => self.body(constant.body).value.span,
1041             Some(EntryKind::Expr(_, _, expr)) => expr.span,
1042             Some(EntryKind::Stmt(_, _, stmt)) => stmt.span,
1043             Some(EntryKind::Ty(_, _, ty)) => ty.span,
1044             Some(EntryKind::TraitRef(_, _, tr)) => tr.path.span,
1045             Some(EntryKind::Binding(_, _, pat)) => pat.span,
1046             Some(EntryKind::Pat(_, _, pat)) => pat.span,
1047             Some(EntryKind::Block(_, _, block)) => block.span,
1048             Some(EntryKind::StructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1049             Some(EntryKind::Lifetime(_, _, lifetime)) => lifetime.span,
1050             Some(EntryKind::GenericParam(_, _, param)) => param.span,
1051             Some(EntryKind::Visibility(_, _, &Spanned {
1052                 node: VisibilityKind::Restricted { ref path, .. }, ..
1053             })) => path.span,
1054             Some(EntryKind::Visibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1055             Some(EntryKind::Local(_, _, local)) => local.span,
1056             Some(EntryKind::MacroDef(_, macro_def)) => macro_def.span,
1057
1058             Some(EntryKind::RootCrate(_)) => self.forest.krate.span,
1059             Some(EntryKind::NotPresent) | None => {
1060                 bug!("hir::map::Map::span: id not in map: {:?}", id)
1061             }
1062         }
1063     }
1064
1065     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1066         self.as_local_node_id(id).map(|id| self.span(id))
1067     }
1068
1069     pub fn node_to_string(&self, id: NodeId) -> String {
1070         node_id_to_string(self, id, true)
1071     }
1072
1073     pub fn node_to_user_string(&self, id: NodeId) -> String {
1074         node_id_to_string(self, id, false)
1075     }
1076
1077     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1078         print::to_string(self, |s| s.print_node(self.get(id)))
1079     }
1080 }
1081
1082 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1083     map: &'a Map<'hir>,
1084     item_name: &'a String,
1085     in_which: &'a [String],
1086     idx: NodeId,
1087 }
1088
1089 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1090     /// Returns true only if some suffix of the module path for parent
1091     /// matches `self.in_which`.
1092     ///
1093     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1094     /// returns true if parent's path ends with the suffix
1095     /// `x_0::x_1::...::x_k`.
1096     fn suffix_matches(&self, parent: NodeId) -> bool {
1097         let mut cursor = parent;
1098         for part in self.in_which.iter().rev() {
1099             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1100                 None => return false,
1101                 Some((node_id, name)) => (node_id, name),
1102             };
1103             if mod_name != &**part {
1104                 return false;
1105             }
1106             cursor = self.map.get_parent(mod_id);
1107         }
1108         return true;
1109
1110         // Finds the first mod in parent chain for `id`, along with
1111         // that mod's name.
1112         //
1113         // If `id` itself is a mod named `m` with parent `p`, then
1114         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
1115         // chain, then returns `None`.
1116         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1117             loop {
1118                 match map.find(id)? {
1119                     NodeKind::Item(item) if item_is_mod(&item) =>
1120                         return Some((id, item.name)),
1121                     _ => {}
1122                 }
1123                 let parent = map.get_parent(id);
1124                 if parent == id { return None }
1125                 id = parent;
1126             }
1127
1128             fn item_is_mod(item: &Item) -> bool {
1129                 match item.node {
1130                     ItemKind::Mod(_) => true,
1131                     _ => false,
1132                 }
1133             }
1134         }
1135     }
1136
1137     // We are looking at some node `n` with a given name and parent
1138     // id; do their names match what I am seeking?
1139     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1140         name == &**self.item_name && self.suffix_matches(parent_of_n)
1141     }
1142 }
1143
1144 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1145     type Item = NodeId;
1146
1147     fn next(&mut self) -> Option<NodeId> {
1148         loop {
1149             let idx = self.idx;
1150             if idx.as_usize() >= self.map.entry_count() {
1151                 return None;
1152             }
1153             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1154             let name = match self.map.find_entry(idx) {
1155                 Some(EntryKind::Item(_, _, n))       => n.name(),
1156                 Some(EntryKind::ForeignItem(_, _, n))=> n.name(),
1157                 Some(EntryKind::TraitItem(_, _, n))  => n.name(),
1158                 Some(EntryKind::ImplItem(_, _, n))   => n.name(),
1159                 Some(EntryKind::Variant(_, _, n))    => n.name(),
1160                 Some(EntryKind::Field(_, _, n))      => n.name(),
1161                 _ => continue,
1162             };
1163             if self.matches_names(self.map.get_parent(idx), name) {
1164                 return Some(idx)
1165             }
1166         }
1167     }
1168 }
1169
1170 trait Named {
1171     fn name(&self) -> Name;
1172 }
1173
1174 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1175
1176 impl Named for Item { fn name(&self) -> Name { self.name } }
1177 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1178 impl Named for VariantKind { fn name(&self) -> Name { self.name } }
1179 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1180 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1181 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1182
1183
1184 pub fn map_crate<'hir>(sess: &::session::Session,
1185                        cstore: &dyn CrateStore,
1186                        forest: &'hir mut Forest,
1187                        definitions: &'hir Definitions)
1188                        -> Map<'hir> {
1189     let (map, crate_hash) = {
1190         let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1191
1192         let mut collector = NodeCollector::root(&forest.krate,
1193                                                 &forest.dep_graph,
1194                                                 &definitions,
1195                                                 hcx);
1196         intravisit::walk_crate(&mut collector, &forest.krate);
1197
1198         let crate_disambiguator = sess.local_crate_disambiguator();
1199         let cmdline_args = sess.opts.dep_tracking_hash();
1200         collector.finalize_and_compute_crate_hash(crate_disambiguator,
1201                                                   cstore,
1202                                                   sess.source_map(),
1203                                                   cmdline_args)
1204     };
1205
1206     if log_enabled!(::log::Level::Debug) {
1207         // This only makes sense for ordered stores; note the
1208         // enumerate to count the number of entries.
1209         let (entries_less_1, _) = map.iter().filter(|&x| {
1210             match *x {
1211                 EntryKind::NotPresent => false,
1212                 _ => true
1213             }
1214         }).enumerate().last().expect("AST map was empty after folding?");
1215
1216         let entries = entries_less_1 + 1;
1217         let vector_length = map.len();
1218         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1219               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1220     }
1221
1222     // Build the reverse mapping of `node_to_hir_id`.
1223     let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1224         .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1225
1226     let map = Map {
1227         forest,
1228         dep_graph: forest.dep_graph.clone(),
1229         crate_hash,
1230         map,
1231         hir_to_node_id,
1232         definitions,
1233     };
1234
1235     hir_id_validator::check_crate(&map);
1236
1237     map
1238 }
1239
1240 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1241 /// except it avoids creating a dependency on the whole crate.
1242 impl<'hir> print::PpAnn for Map<'hir> {
1243     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1244         match nested {
1245             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1246             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1247             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1248             Nested::Body(id) => state.print_expr(&self.body(id).value),
1249             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1250         }
1251     }
1252 }
1253
1254 impl<'a> print::State<'a> {
1255     pub fn print_node(&mut self, node: NodeKind) -> io::Result<()> {
1256         match node {
1257             NodeKind::Item(a)         => self.print_item(&a),
1258             NodeKind::ForeignItem(a)  => self.print_foreign_item(&a),
1259             NodeKind::TraitItem(a)    => self.print_trait_item(a),
1260             NodeKind::ImplItem(a)     => self.print_impl_item(a),
1261             NodeKind::Variant(a)      => self.print_variant(&a),
1262             NodeKind::AnonConst(a)    => self.print_anon_const(&a),
1263             NodeKind::Expr(a)         => self.print_expr(&a),
1264             NodeKind::Stmt(a)         => self.print_stmt(&a),
1265             NodeKind::Ty(a)           => self.print_type(&a),
1266             NodeKind::TraitRef(a)     => self.print_trait_ref(&a),
1267             NodeKind::Binding(a)       |
1268             NodeKind::Pat(a)          => self.print_pat(&a),
1269             NodeKind::Block(a)        => {
1270                 use syntax::print::pprust::PrintState;
1271
1272                 // containing cbox, will be closed by print-block at }
1273                 self.cbox(print::indent_unit)?;
1274                 // head-ibox, will be closed by print-block after {
1275                 self.ibox(0)?;
1276                 self.print_block(&a)
1277             }
1278             NodeKind::Lifetime(a)     => self.print_lifetime(&a),
1279             NodeKind::Visibility(a)   => self.print_visibility(&a),
1280             NodeKind::GenericParam(_) => bug!("cannot print NodeKind::GenericParam"),
1281             NodeKind::Field(_)        => bug!("cannot print StructField"),
1282             // these cases do not carry enough information in the
1283             // hir_map to reconstruct their full structure for pretty
1284             // printing.
1285             NodeKind::StructCtor(_)   => bug!("cannot print isolated StructCtor"),
1286             NodeKind::Local(a)        => self.print_local_decl(&a),
1287             NodeKind::MacroDef(_)     => bug!("cannot print MacroDef"),
1288         }
1289     }
1290 }
1291
1292 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1293     let id_str = format!(" (id={})", id);
1294     let id_str = if include_id { &id_str[..] } else { "" };
1295
1296     let path_str = || {
1297         // This functionality is used for debugging, try to use TyCtxt to get
1298         // the user-friendly path, otherwise fall back to stringifying DefPath.
1299         ::ty::tls::with_opt(|tcx| {
1300             if let Some(tcx) = tcx {
1301                 tcx.node_path_str(id)
1302             } else if let Some(path) = map.def_path_from_id(id) {
1303                 path.data.into_iter().map(|elem| {
1304                     elem.data.to_string()
1305                 }).collect::<Vec<_>>().join("::")
1306             } else {
1307                 String::from("<missing path>")
1308             }
1309         })
1310     };
1311
1312     match map.find(id) {
1313         Some(NodeKind::Item(item)) => {
1314             let item_str = match item.node {
1315                 ItemKind::ExternCrate(..) => "extern crate",
1316                 ItemKind::Use(..) => "use",
1317                 ItemKind::Static(..) => "static",
1318                 ItemKind::Const(..) => "const",
1319                 ItemKind::Fn(..) => "fn",
1320                 ItemKind::Mod(..) => "mod",
1321                 ItemKind::ForeignMod(..) => "foreign mod",
1322                 ItemKind::GlobalAsm(..) => "global asm",
1323                 ItemKind::Ty(..) => "ty",
1324                 ItemKind::Existential(..) => "existential type",
1325                 ItemKind::Enum(..) => "enum",
1326                 ItemKind::Struct(..) => "struct",
1327                 ItemKind::Union(..) => "union",
1328                 ItemKind::Trait(..) => "trait",
1329                 ItemKind::TraitAlias(..) => "trait alias",
1330                 ItemKind::Impl(..) => "impl",
1331             };
1332             format!("{} {}{}", item_str, path_str(), id_str)
1333         }
1334         Some(NodeKind::ForeignItem(_)) => {
1335             format!("foreign item {}{}", path_str(), id_str)
1336         }
1337         Some(NodeKind::ImplItem(ii)) => {
1338             match ii.node {
1339                 ImplItemKind::Const(..) => {
1340                     format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1341                 }
1342                 ImplItemKind::Method(..) => {
1343                     format!("method {} in {}{}", ii.ident, path_str(), id_str)
1344                 }
1345                 ImplItemKind::Type(_) => {
1346                     format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1347                 }
1348                 ImplItemKind::Existential(_) => {
1349                     format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1350                 }
1351             }
1352         }
1353         Some(NodeKind::TraitItem(ti)) => {
1354             let kind = match ti.node {
1355                 TraitItemKind::Const(..) => "assoc constant",
1356                 TraitItemKind::Method(..) => "trait method",
1357                 TraitItemKind::Type(..) => "assoc type",
1358             };
1359
1360             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1361         }
1362         Some(NodeKind::Variant(ref variant)) => {
1363             format!("variant {} in {}{}",
1364                     variant.node.name,
1365                     path_str(), id_str)
1366         }
1367         Some(NodeKind::Field(ref field)) => {
1368             format!("field {} in {}{}",
1369                     field.ident,
1370                     path_str(), id_str)
1371         }
1372         Some(NodeKind::AnonConst(_)) => {
1373             format!("const {}{}", map.node_to_pretty_string(id), id_str)
1374         }
1375         Some(NodeKind::Expr(_)) => {
1376             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1377         }
1378         Some(NodeKind::Stmt(_)) => {
1379             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1380         }
1381         Some(NodeKind::Ty(_)) => {
1382             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1383         }
1384         Some(NodeKind::TraitRef(_)) => {
1385             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1386         }
1387         Some(NodeKind::Binding(_)) => {
1388             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1389         }
1390         Some(NodeKind::Pat(_)) => {
1391             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1392         }
1393         Some(NodeKind::Block(_)) => {
1394             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1395         }
1396         Some(NodeKind::Local(_)) => {
1397             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1398         }
1399         Some(NodeKind::StructCtor(_)) => {
1400             format!("struct_ctor {}{}", path_str(), id_str)
1401         }
1402         Some(NodeKind::Lifetime(_)) => {
1403             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1404         }
1405         Some(NodeKind::GenericParam(ref param)) => {
1406             format!("generic_param {:?}{}", param, id_str)
1407         }
1408         Some(NodeKind::Visibility(ref vis)) => {
1409             format!("visibility {:?}{}", vis, id_str)
1410         }
1411         Some(NodeKind::MacroDef(_)) => {
1412             format!("macro {}{}",  path_str(), id_str)
1413         }
1414         None => {
1415             format!("unknown node{}", id_str)
1416         }
1417     }
1418 }
1419
1420 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1421     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1422         tcx.hir.describe_def(node_id)
1423     } else {
1424         bug!("Calling local describe_def query provider for upstream DefId: {:?}",
1425              def_id)
1426     }
1427 }