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