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