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