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