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