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