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