]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
Rollup merge of #67873 - Dylan-DPC:feature/change-remove-to-partial, r=Amanieu
[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 rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::svh::Svh;
16 use rustc_index::vec::IndexVec;
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::source_map::Spanned;
19 use rustc_span::symbol::kw;
20 use rustc_span::{Span, DUMMY_SP};
21 use rustc_target::spec::abi::Abi;
22 use syntax::ast::{self, Name, NodeId};
23
24 pub mod blocks;
25 mod collector;
26 pub mod definitions;
27 mod hir_id_validator;
28
29 /// Represents an entry and its parent `HirId`.
30 #[derive(Copy, Clone, Debug)]
31 pub struct Entry<'hir> {
32     parent: HirId,
33     dep_node: DepNodeIndex,
34     node: Node<'hir>,
35 }
36
37 impl<'hir> Entry<'hir> {
38     fn parent_node(self) -> Option<HirId> {
39         match self.node {
40             Node::Crate | Node::MacroDef(_) => None,
41             _ => Some(self.parent),
42         }
43     }
44
45     fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
46         match self.node {
47             Node::Item(ref item) => match item.kind {
48                 ItemKind::Fn(ref sig, _, _) => Some(&sig.decl),
49                 _ => None,
50             },
51
52             Node::TraitItem(ref item) => match item.kind {
53                 TraitItemKind::Method(ref sig, _) => Some(&sig.decl),
54                 _ => None,
55             },
56
57             Node::ImplItem(ref item) => match item.kind {
58                 ImplItemKind::Method(ref sig, _) => Some(&sig.decl),
59                 _ => None,
60             },
61
62             Node::Expr(ref expr) => match expr.kind {
63                 ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
64                 _ => None,
65             },
66
67             _ => None,
68         }
69     }
70
71     fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
72         match &self.node {
73             Node::Item(item) => match &item.kind {
74                 ItemKind::Fn(sig, _, _) => Some(sig),
75                 _ => None,
76             },
77
78             Node::TraitItem(item) => match &item.kind {
79                 TraitItemKind::Method(sig, _) => Some(sig),
80                 _ => None,
81             },
82
83             Node::ImplItem(item) => match &item.kind {
84                 ImplItemKind::Method(sig, _) => Some(sig),
85                 _ => None,
86             },
87
88             _ => None,
89         }
90     }
91
92     fn associated_body(self) -> Option<BodyId> {
93         match self.node {
94             Node::Item(item) => match item.kind {
95                 ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body) => {
96                     Some(body)
97                 }
98                 _ => None,
99             },
100
101             Node::TraitItem(item) => match item.kind {
102                 TraitItemKind::Const(_, Some(body))
103                 | TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
104                 _ => None,
105             },
106
107             Node::ImplItem(item) => match item.kind {
108                 ImplItemKind::Const(_, body) | ImplItemKind::Method(_, body) => Some(body),
109                 _ => None,
110             },
111
112             Node::AnonConst(constant) => Some(constant.body),
113
114             Node::Expr(expr) => match expr.kind {
115                 ExprKind::Closure(.., body, _, _) => Some(body),
116                 _ => None,
117             },
118
119             _ => None,
120         }
121     }
122
123     fn is_body_owner(self, hir_id: HirId) -> bool {
124         match self.associated_body() {
125             Some(b) => b.hir_id == hir_id,
126             None => false,
127         }
128     }
129 }
130
131 /// Stores a crate and any number of inlined items from other crates.
132 pub struct Forest<'hir> {
133     krate: Crate<'hir>,
134     pub dep_graph: DepGraph,
135 }
136
137 impl Forest<'hir> {
138     pub fn new(krate: Crate<'hir>, dep_graph: &DepGraph) -> Forest<'hir> {
139         Forest { krate, dep_graph: dep_graph.clone() }
140     }
141
142     pub fn krate(&self) -> &Crate<'hir> {
143         self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
144         &self.krate
145     }
146
147     /// This is used internally in the dependency tracking system.
148     /// Use the `krate` method to ensure your dependency on the
149     /// crate is tracked.
150     pub fn untracked_krate(&self) -> &Crate<'hir> {
151         &self.krate
152     }
153 }
154
155 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
156 /// but it is implemented as 2 layers of arrays.
157 /// - first we have `A = IndexVec<DefIndex, B>` mapping `DefIndex`s to an inner value
158 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
159 pub(super) type HirEntryMap<'hir> = IndexVec<DefIndex, IndexVec<ItemLocalId, Option<Entry<'hir>>>>;
160
161 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
162 #[derive(Clone)]
163 pub struct Map<'hir> {
164     /// The backing storage for all the AST nodes.
165     pub forest: &'hir Forest<'hir>,
166
167     /// Same as the dep_graph in forest, just available with one fewer
168     /// deref. This is a gratuitous micro-optimization.
169     pub dep_graph: DepGraph,
170
171     /// The SVH of the local crate.
172     pub crate_hash: Svh,
173
174     map: HirEntryMap<'hir>,
175
176     definitions: Definitions,
177
178     /// The reverse mapping of `node_to_hir_id`.
179     hir_to_node_id: FxHashMap<HirId, NodeId>,
180 }
181
182 struct ParentHirIterator<'map, 'hir> {
183     current_id: HirId,
184     map: &'map Map<'hir>,
185 }
186
187 impl<'map, 'hir> ParentHirIterator<'map, 'hir> {
188     fn new(current_id: HirId, map: &'map Map<'hir>) -> ParentHirIterator<'map, 'hir> {
189         ParentHirIterator { current_id, map }
190     }
191 }
192
193 impl<'map, 'hir> Iterator for ParentHirIterator<'map, 'hir> {
194     type Item = (HirId, Node<'hir>);
195
196     fn next(&mut self) -> Option<Self::Item> {
197         if self.current_id == CRATE_HIR_ID {
198             return None;
199         }
200         loop {
201             // There are nodes that do not have entries, so we need to skip them.
202             let parent_id = self.map.get_parent_node(self.current_id);
203
204             if parent_id == self.current_id {
205                 self.current_id = CRATE_HIR_ID;
206                 return None;
207             }
208
209             self.current_id = parent_id;
210             if let Some(entry) = self.map.find_entry(parent_id) {
211                 return Some((parent_id, entry.node));
212             }
213             // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
214         }
215     }
216 }
217
218 impl<'hir> Map<'hir> {
219     #[inline]
220     fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
221         let local_map = self.map.get(id.owner)?;
222         local_map.get(id.local_id)?.as_ref()
223     }
224
225     /// Registers a read in the dependency graph of the AST node with
226     /// the given `id`. This needs to be called each time a public
227     /// function returns the HIR for a node -- in other words, when it
228     /// "reveals" the content of a node to the caller (who might not
229     /// otherwise have had access to those contents, and hence needs a
230     /// read recorded). If the function just returns a DefId or
231     /// HirId, no actual content was returned, so no read is needed.
232     pub fn read(&self, hir_id: HirId) {
233         if let Some(entry) = self.lookup(hir_id) {
234             self.dep_graph.read_index(entry.dep_node);
235         } else {
236             bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
237         }
238     }
239
240     #[inline]
241     pub fn definitions(&self) -> &Definitions {
242         &self.definitions
243     }
244
245     pub fn def_key(&self, def_id: DefId) -> DefKey {
246         assert!(def_id.is_local());
247         self.definitions.def_key(def_id.index)
248     }
249
250     pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
251         self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
252     }
253
254     pub fn def_path(&self, def_id: DefId) -> DefPath {
255         assert!(def_id.is_local());
256         self.definitions.def_path(def_id.index)
257     }
258
259     #[inline]
260     pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
261         self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
262             let hir_id = self.node_to_hir_id(node);
263             bug!(
264                 "local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
265                 node,
266                 self.find_entry(hir_id)
267             )
268         })
269     }
270
271     #[inline]
272     pub fn local_def_id(&self, hir_id: HirId) -> DefId {
273         self.opt_local_def_id(hir_id).unwrap_or_else(|| {
274             bug!(
275                 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
276                 hir_id,
277                 self.find_entry(hir_id)
278             )
279         })
280     }
281
282     #[inline]
283     pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
284         let node_id = self.hir_to_node_id(hir_id);
285         self.definitions.opt_local_def_id(node_id)
286     }
287
288     #[inline]
289     pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
290         self.definitions.opt_local_def_id(node)
291     }
292
293     #[inline]
294     pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
295         self.definitions.as_local_node_id(def_id)
296     }
297
298     #[inline]
299     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
300         self.definitions.as_local_hir_id(def_id)
301     }
302
303     #[inline]
304     pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
305         self.hir_to_node_id[&hir_id]
306     }
307
308     #[inline]
309     pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
310         self.definitions.node_to_hir_id(node_id)
311     }
312
313     #[inline]
314     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
315         self.definitions.def_index_to_hir_id(def_index)
316     }
317
318     #[inline]
319     pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
320         self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
321     }
322
323     pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
324         let node = if let Some(node) = self.find(hir_id) { node } else { return None };
325
326         Some(match node {
327             Node::Item(item) => match item.kind {
328                 ItemKind::Static(..) => DefKind::Static,
329                 ItemKind::Const(..) => DefKind::Const,
330                 ItemKind::Fn(..) => DefKind::Fn,
331                 ItemKind::Mod(..) => DefKind::Mod,
332                 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
333                 ItemKind::TyAlias(..) => DefKind::TyAlias,
334                 ItemKind::Enum(..) => DefKind::Enum,
335                 ItemKind::Struct(..) => DefKind::Struct,
336                 ItemKind::Union(..) => DefKind::Union,
337                 ItemKind::Trait(..) => DefKind::Trait,
338                 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
339                 ItemKind::ExternCrate(_)
340                 | ItemKind::Use(..)
341                 | ItemKind::ForeignMod(..)
342                 | ItemKind::GlobalAsm(..)
343                 | ItemKind::Impl(..) => return None,
344             },
345             Node::ForeignItem(item) => match item.kind {
346                 ForeignItemKind::Fn(..) => DefKind::Fn,
347                 ForeignItemKind::Static(..) => DefKind::Static,
348                 ForeignItemKind::Type => DefKind::ForeignTy,
349             },
350             Node::TraitItem(item) => match item.kind {
351                 TraitItemKind::Const(..) => DefKind::AssocConst,
352                 TraitItemKind::Method(..) => DefKind::Method,
353                 TraitItemKind::Type(..) => DefKind::AssocTy,
354             },
355             Node::ImplItem(item) => match item.kind {
356                 ImplItemKind::Const(..) => DefKind::AssocConst,
357                 ImplItemKind::Method(..) => DefKind::Method,
358                 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
359                 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
360             },
361             Node::Variant(_) => DefKind::Variant,
362             Node::Ctor(variant_data) => {
363                 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
364                 if variant_data.ctor_hir_id().is_none() {
365                     return None;
366                 }
367                 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
368                     Some(Node::Item(..)) => def::CtorOf::Struct,
369                     Some(Node::Variant(..)) => def::CtorOf::Variant,
370                     _ => unreachable!(),
371                 };
372                 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
373             }
374             Node::AnonConst(_)
375             | Node::Field(_)
376             | Node::Expr(_)
377             | Node::Stmt(_)
378             | Node::PathSegment(_)
379             | Node::Ty(_)
380             | Node::TraitRef(_)
381             | Node::Pat(_)
382             | Node::Binding(_)
383             | Node::Local(_)
384             | Node::Param(_)
385             | Node::Arm(_)
386             | Node::Lifetime(_)
387             | Node::Visibility(_)
388             | Node::Block(_)
389             | Node::Crate => return None,
390             Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
391             Node::GenericParam(param) => match param.kind {
392                 GenericParamKind::Lifetime { .. } => return None,
393                 GenericParamKind::Type { .. } => DefKind::TyParam,
394                 GenericParamKind::Const { .. } => DefKind::ConstParam,
395             },
396         })
397     }
398
399     fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
400         self.lookup(id).cloned()
401     }
402
403     pub fn krate(&self) -> &'hir Crate<'hir> {
404         self.forest.krate()
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 pub struct NodesMatchingSuffix<'a> {
1088     map: &'a Map<'a>,
1089     item_name: &'a String,
1090     in_which: &'a [String],
1091 }
1092
1093 impl<'a> NodesMatchingSuffix<'a> {
1094     /// Returns `true` only if some suffix of the module path for parent
1095     /// matches `self.in_which`.
1096     ///
1097     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1098     /// returns true if parent's path ends with the suffix
1099     /// `x_0::x_1::...::x_k`.
1100     fn suffix_matches(&self, parent: HirId) -> bool {
1101         let mut cursor = parent;
1102         for part in self.in_which.iter().rev() {
1103             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1104                 None => return false,
1105                 Some((node_id, name)) => (node_id, name),
1106             };
1107             if mod_name.as_str() != *part {
1108                 return false;
1109             }
1110             cursor = self.map.get_parent_item(mod_id);
1111         }
1112         return true;
1113
1114         // Finds the first mod in parent chain for `id`, along with
1115         // that mod's name.
1116         //
1117         // If `id` itself is a mod named `m` with parent `p`, then
1118         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
1119         // chain, then returns `None`.
1120         fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1121             loop {
1122                 if let Node::Item(item) = map.find(id)? {
1123                     if item_is_mod(&item) {
1124                         return Some((id, item.ident.name));
1125                     }
1126                 }
1127                 let parent = map.get_parent_item(id);
1128                 if parent == id {
1129                     return None;
1130                 }
1131                 id = parent;
1132             }
1133
1134             fn item_is_mod(item: &Item<'_>) -> bool {
1135                 match item.kind {
1136                     ItemKind::Mod(_) => true,
1137                     _ => false,
1138                 }
1139             }
1140         }
1141     }
1142
1143     // We are looking at some node `n` with a given name and parent
1144     // id; do their names match what I am seeking?
1145     fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1146         name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1147     }
1148
1149     fn matches_suffix(&self, hir: HirId) -> bool {
1150         let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1151             Some(Node::Item(n)) => n.name(),
1152             Some(Node::ForeignItem(n)) => n.name(),
1153             Some(Node::TraitItem(n)) => n.name(),
1154             Some(Node::ImplItem(n)) => n.name(),
1155             Some(Node::Variant(n)) => n.name(),
1156             Some(Node::Field(n)) => n.name(),
1157             _ => return false,
1158         };
1159         self.matches_names(self.map.get_parent_item(hir), name)
1160     }
1161 }
1162
1163 trait Named {
1164     fn name(&self) -> Name;
1165 }
1166
1167 impl<T: Named> Named for Spanned<T> {
1168     fn name(&self) -> Name {
1169         self.node.name()
1170     }
1171 }
1172
1173 impl Named for Item<'_> {
1174     fn name(&self) -> Name {
1175         self.ident.name
1176     }
1177 }
1178 impl Named for ForeignItem<'_> {
1179     fn name(&self) -> Name {
1180         self.ident.name
1181     }
1182 }
1183 impl Named for Variant<'_> {
1184     fn name(&self) -> Name {
1185         self.ident.name
1186     }
1187 }
1188 impl Named for StructField<'_> {
1189     fn name(&self) -> Name {
1190         self.ident.name
1191     }
1192 }
1193 impl Named for TraitItem<'_> {
1194     fn name(&self) -> Name {
1195         self.ident.name
1196     }
1197 }
1198 impl Named for ImplItem<'_> {
1199     fn name(&self) -> Name {
1200         self.ident.name
1201     }
1202 }
1203
1204 pub fn map_crate<'hir>(
1205     sess: &rustc_session::Session,
1206     cstore: &CrateStoreDyn,
1207     forest: &'hir Forest<'hir>,
1208     definitions: Definitions,
1209 ) -> Map<'hir> {
1210     let _prof_timer = sess.prof.generic_activity("build_hir_map");
1211
1212     // Build the reverse mapping of `node_to_hir_id`.
1213     let hir_to_node_id = definitions
1214         .node_to_hir_id
1215         .iter_enumerated()
1216         .map(|(node_id, &hir_id)| (hir_id, node_id))
1217         .collect();
1218
1219     let (map, crate_hash) = {
1220         let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, &definitions, cstore);
1221
1222         let mut collector = NodeCollector::root(
1223             sess,
1224             &forest.krate,
1225             &forest.dep_graph,
1226             &definitions,
1227             &hir_to_node_id,
1228             hcx,
1229         );
1230         intravisit::walk_crate(&mut collector, &forest.krate);
1231
1232         let crate_disambiguator = sess.local_crate_disambiguator();
1233         let cmdline_args = sess.opts.dep_tracking_hash();
1234         collector.finalize_and_compute_crate_hash(crate_disambiguator, cstore, cmdline_args)
1235     };
1236
1237     let map = Map {
1238         forest,
1239         dep_graph: forest.dep_graph.clone(),
1240         crate_hash,
1241         map,
1242         hir_to_node_id,
1243         definitions,
1244     };
1245
1246     sess.time("validate HIR map", || {
1247         hir_id_validator::check_crate(&map);
1248     });
1249
1250     map
1251 }
1252
1253 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1254 /// except it avoids creating a dependency on the whole crate.
1255 impl<'hir> print::PpAnn for Map<'hir> {
1256     fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1257         match nested {
1258             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1259             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1260             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1261             Nested::Body(id) => state.print_expr(&self.body(id).value),
1262             Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1263         }
1264     }
1265 }
1266
1267 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1268     let id_str = format!(" (hir_id={})", id);
1269     let id_str = if include_id { &id_str[..] } else { "" };
1270
1271     let path_str = || {
1272         // This functionality is used for debugging, try to use `TyCtxt` to get
1273         // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1274         crate::ty::tls::with_opt(|tcx| {
1275             if let Some(tcx) = tcx {
1276                 let def_id = map.local_def_id(id);
1277                 tcx.def_path_str(def_id)
1278             } else if let Some(path) = map.def_path_from_hir_id(id) {
1279                 path.data
1280                     .into_iter()
1281                     .map(|elem| elem.data.to_string())
1282                     .collect::<Vec<_>>()
1283                     .join("::")
1284             } else {
1285                 String::from("<missing path>")
1286             }
1287         })
1288     };
1289
1290     match map.find(id) {
1291         Some(Node::Item(item)) => {
1292             let item_str = match item.kind {
1293                 ItemKind::ExternCrate(..) => "extern crate",
1294                 ItemKind::Use(..) => "use",
1295                 ItemKind::Static(..) => "static",
1296                 ItemKind::Const(..) => "const",
1297                 ItemKind::Fn(..) => "fn",
1298                 ItemKind::Mod(..) => "mod",
1299                 ItemKind::ForeignMod(..) => "foreign mod",
1300                 ItemKind::GlobalAsm(..) => "global asm",
1301                 ItemKind::TyAlias(..) => "ty",
1302                 ItemKind::OpaqueTy(..) => "opaque type",
1303                 ItemKind::Enum(..) => "enum",
1304                 ItemKind::Struct(..) => "struct",
1305                 ItemKind::Union(..) => "union",
1306                 ItemKind::Trait(..) => "trait",
1307                 ItemKind::TraitAlias(..) => "trait alias",
1308                 ItemKind::Impl(..) => "impl",
1309             };
1310             format!("{} {}{}", item_str, path_str(), id_str)
1311         }
1312         Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1313         Some(Node::ImplItem(ii)) => match ii.kind {
1314             ImplItemKind::Const(..) => {
1315                 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1316             }
1317             ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1318             ImplItemKind::TyAlias(_) => {
1319                 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1320             }
1321             ImplItemKind::OpaqueTy(_) => {
1322                 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1323             }
1324         },
1325         Some(Node::TraitItem(ti)) => {
1326             let kind = match ti.kind {
1327                 TraitItemKind::Const(..) => "assoc constant",
1328                 TraitItemKind::Method(..) => "trait method",
1329                 TraitItemKind::Type(..) => "assoc type",
1330             };
1331
1332             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1333         }
1334         Some(Node::Variant(ref variant)) => {
1335             format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1336         }
1337         Some(Node::Field(ref field)) => {
1338             format!("field {} in {}{}", field.ident, path_str(), id_str)
1339         }
1340         Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1341         Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1342         Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1343         Some(Node::PathSegment(_)) => {
1344             format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1345         }
1346         Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1347         Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1348         Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1349         Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1350         Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1351         Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1352         Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1353         Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1354         Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1355         Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1356         Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1357         Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1358         Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1359         Some(Node::Crate) => String::from("root_crate"),
1360         None => format!("unknown node{}", id_str),
1361     }
1362 }
1363
1364 pub fn provide(providers: &mut Providers<'_>) {
1365     providers.def_kind = |tcx, def_id| {
1366         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1367             tcx.hir().def_kind(hir_id)
1368         } else {
1369             bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);
1370         }
1371     };
1372 }