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