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