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