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