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