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