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