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