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