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