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