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