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