]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/mod.rs
Rollup merge of #95251 - GrishaVar:hashes-u16-to-u8, r=dtolnay
[rust.git] / compiler / rustc_middle / src / hir / map / mod.rs
1 use crate::hir::{ModuleItems, Owner};
2 use crate::ty::TyCtxt;
3 use rustc_ast as ast;
4 use rustc_data_structures::fingerprint::Fingerprint;
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_data_structures::svh::Svh;
7 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
11 use rustc_hir::intravisit::{self, Visitor};
12 use rustc_hir::itemlikevisit::ItemLikeVisitor;
13 use rustc_hir::*;
14 use rustc_index::vec::Idx;
15 use rustc_middle::hir::nested_filter;
16 use rustc_span::def_id::StableCrateId;
17 use rustc_span::source_map::Spanned;
18 use rustc_span::symbol::{kw, sym, Ident, Symbol};
19 use rustc_span::Span;
20 use rustc_target::spec::abi::Abi;
21 use std::collections::VecDeque;
22
23 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
24     match node {
25         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
26         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
27         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
28         Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. })
29         | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => {
30             Some(fn_decl)
31         }
32         _ => None,
33     }
34 }
35
36 pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
37     match &node {
38         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
39         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
40         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
41         _ => None,
42     }
43 }
44
45 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
46     match node {
47         Node::Item(Item {
48             kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
49             ..
50         })
51         | Node::TraitItem(TraitItem {
52             kind:
53                 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
54             ..
55         })
56         | Node::ImplItem(ImplItem {
57             kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
58             ..
59         })
60         | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
61
62         Node::AnonConst(constant) => Some(constant.body),
63
64         _ => None,
65     }
66 }
67
68 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
69     match associated_body(node) {
70         Some(b) => b.hir_id == hir_id,
71         None => false,
72     }
73 }
74
75 #[derive(Copy, Clone)]
76 pub struct Map<'hir> {
77     pub(super) tcx: TyCtxt<'hir>,
78 }
79
80 /// An iterator that walks up the ancestor tree of a given `HirId`.
81 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
82 pub struct ParentHirIterator<'hir> {
83     current_id: HirId,
84     map: Map<'hir>,
85 }
86
87 impl<'hir> Iterator for ParentHirIterator<'hir> {
88     type Item = (HirId, Node<'hir>);
89
90     fn next(&mut self) -> Option<Self::Item> {
91         if self.current_id == CRATE_HIR_ID {
92             return None;
93         }
94         loop {
95             // There are nodes that do not have entries, so we need to skip them.
96             let parent_id = self.map.get_parent_node(self.current_id);
97
98             if parent_id == self.current_id {
99                 self.current_id = CRATE_HIR_ID;
100                 return None;
101             }
102
103             self.current_id = parent_id;
104             if let Some(node) = self.map.find(parent_id) {
105                 return Some((parent_id, node));
106             }
107             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
108         }
109     }
110 }
111
112 /// An iterator that walks up the ancestor tree of a given `HirId`.
113 /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
114 pub struct ParentOwnerIterator<'hir> {
115     current_id: HirId,
116     map: Map<'hir>,
117 }
118
119 impl<'hir> Iterator for ParentOwnerIterator<'hir> {
120     type Item = (LocalDefId, OwnerNode<'hir>);
121
122     fn next(&mut self) -> Option<Self::Item> {
123         if self.current_id.local_id.index() != 0 {
124             self.current_id.local_id = ItemLocalId::new(0);
125             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
126                 return Some((self.current_id.owner, node.node));
127             }
128         }
129         if self.current_id == CRATE_HIR_ID {
130             return None;
131         }
132         loop {
133             // There are nodes that do not have entries, so we need to skip them.
134             let parent_id = self.map.def_key(self.current_id.owner).parent;
135
136             let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| {
137                 let def_id = LocalDefId { local_def_index };
138                 self.map.local_def_id_to_hir_id(def_id).owner
139             });
140             self.current_id = HirId::make_owner(parent_id);
141
142             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
143             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
144                 return Some((self.current_id.owner, node.node));
145             }
146         }
147     }
148 }
149
150 impl<'hir> Map<'hir> {
151     pub fn krate(self) -> &'hir Crate<'hir> {
152         self.tcx.hir_crate(())
153     }
154
155     pub fn root_module(self) -> &'hir Mod<'hir> {
156         match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) {
157             Some(OwnerNode::Crate(item)) => item,
158             _ => bug!(),
159         }
160     }
161
162     pub fn items(self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
163         let krate = self.krate();
164         krate.owners.iter().filter_map(|owner| match owner.as_owner()?.node() {
165             OwnerNode::Item(item) => Some(item),
166             _ => None,
167         })
168     }
169
170     pub fn def_key(self, def_id: LocalDefId) -> DefKey {
171         // Accessing the DefKey is ok, since it is part of DefPathHash.
172         self.tcx.untracked_resolutions.definitions.def_key(def_id)
173     }
174
175     pub fn def_path_from_hir_id(self, id: HirId) -> Option<DefPath> {
176         self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
177     }
178
179     pub fn def_path(self, def_id: LocalDefId) -> DefPath {
180         // Accessing the DefPath is ok, since it is part of DefPathHash.
181         self.tcx.untracked_resolutions.definitions.def_path(def_id)
182     }
183
184     #[inline]
185     pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
186         // Accessing the DefPathHash is ok, it is incr. comp. stable.
187         self.tcx.untracked_resolutions.definitions.def_path_hash(def_id)
188     }
189
190     #[inline]
191     pub fn local_def_id(self, hir_id: HirId) -> LocalDefId {
192         self.opt_local_def_id(hir_id).unwrap_or_else(|| {
193             bug!(
194                 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
195                 hir_id,
196                 self.find(hir_id)
197             )
198         })
199     }
200
201     #[inline]
202     pub fn opt_local_def_id(self, hir_id: HirId) -> Option<LocalDefId> {
203         if hir_id.local_id == ItemLocalId::new(0) {
204             Some(hir_id.owner)
205         } else {
206             self.tcx
207                 .hir_owner_nodes(hir_id.owner)
208                 .as_owner()?
209                 .local_id_to_def_id
210                 .get(&hir_id.local_id)
211                 .copied()
212         }
213     }
214
215     #[inline]
216     pub fn local_def_id_to_hir_id(self, def_id: LocalDefId) -> HirId {
217         self.tcx.local_def_id_to_hir_id(def_id)
218     }
219
220     pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + 'hir {
221         // Create a dependency to the crate to be sure we reexcute this when the amount of
222         // definitions change.
223         self.tcx.ensure().hir_crate(());
224         self.tcx.untracked_resolutions.definitions.iter_local_def_id()
225     }
226
227     pub fn opt_def_kind(self, local_def_id: LocalDefId) -> Option<DefKind> {
228         let hir_id = self.local_def_id_to_hir_id(local_def_id);
229         let def_kind = match self.find(hir_id)? {
230             Node::Item(item) => match item.kind {
231                 ItemKind::Static(..) => DefKind::Static,
232                 ItemKind::Const(..) => DefKind::Const,
233                 ItemKind::Fn(..) => DefKind::Fn,
234                 ItemKind::Macro(_, macro_kind) => DefKind::Macro(macro_kind),
235                 ItemKind::Mod(..) => DefKind::Mod,
236                 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
237                 ItemKind::TyAlias(..) => DefKind::TyAlias,
238                 ItemKind::Enum(..) => DefKind::Enum,
239                 ItemKind::Struct(..) => DefKind::Struct,
240                 ItemKind::Union(..) => DefKind::Union,
241                 ItemKind::Trait(..) => DefKind::Trait,
242                 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
243                 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
244                 ItemKind::Use(..) => DefKind::Use,
245                 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
246                 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
247                 ItemKind::Impl { .. } => DefKind::Impl,
248             },
249             Node::ForeignItem(item) => match item.kind {
250                 ForeignItemKind::Fn(..) => DefKind::Fn,
251                 ForeignItemKind::Static(..) => DefKind::Static,
252                 ForeignItemKind::Type => DefKind::ForeignTy,
253             },
254             Node::TraitItem(item) => match item.kind {
255                 TraitItemKind::Const(..) => DefKind::AssocConst,
256                 TraitItemKind::Fn(..) => DefKind::AssocFn,
257                 TraitItemKind::Type(..) => DefKind::AssocTy,
258             },
259             Node::ImplItem(item) => match item.kind {
260                 ImplItemKind::Const(..) => DefKind::AssocConst,
261                 ImplItemKind::Fn(..) => DefKind::AssocFn,
262                 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
263             },
264             Node::Variant(_) => DefKind::Variant,
265             Node::Ctor(variant_data) => {
266                 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
267                 assert_ne!(variant_data.ctor_hir_id(), None);
268
269                 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
270                     Some(Node::Item(..)) => def::CtorOf::Struct,
271                     Some(Node::Variant(..)) => def::CtorOf::Variant,
272                     _ => unreachable!(),
273                 };
274                 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
275             }
276             Node::AnonConst(_) => {
277                 let inline = match self.find(self.get_parent_node(hir_id)) {
278                     Some(Node::Expr(&Expr {
279                         kind: ExprKind::ConstBlock(ref anon_const), ..
280                     })) if anon_const.hir_id == hir_id => true,
281                     _ => false,
282                 };
283                 if inline { DefKind::InlineConst } else { DefKind::AnonConst }
284             }
285             Node::Field(_) => DefKind::Field,
286             Node::Expr(expr) => match expr.kind {
287                 ExprKind::Closure(.., None) => DefKind::Closure,
288                 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
289                 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
290             },
291             Node::GenericParam(param) => match param.kind {
292                 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
293                 GenericParamKind::Type { .. } => DefKind::TyParam,
294                 GenericParamKind::Const { .. } => DefKind::ConstParam,
295             },
296             Node::Crate(_) => DefKind::Mod,
297             Node::Stmt(_)
298             | Node::PathSegment(_)
299             | Node::Ty(_)
300             | Node::Infer(_)
301             | Node::TraitRef(_)
302             | Node::Pat(_)
303             | Node::Binding(_)
304             | Node::Local(_)
305             | Node::Param(_)
306             | Node::Arm(_)
307             | Node::Lifetime(_)
308             | Node::Visibility(_)
309             | Node::Block(_) => return None,
310         };
311         Some(def_kind)
312     }
313
314     pub fn def_kind(self, local_def_id: LocalDefId) -> DefKind {
315         self.opt_def_kind(local_def_id)
316             .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
317     }
318
319     pub fn find_parent_node(self, id: HirId) -> Option<HirId> {
320         if id.local_id == ItemLocalId::from_u32(0) {
321             Some(self.tcx.hir_owner_parent(id.owner))
322         } else {
323             let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
324             let node = owner.nodes[id.local_id].as_ref()?;
325             let hir_id = HirId { owner: id.owner, local_id: node.parent };
326             Some(hir_id)
327         }
328     }
329
330     pub fn get_parent_node(self, hir_id: HirId) -> HirId {
331         self.find_parent_node(hir_id).unwrap()
332     }
333
334     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
335     pub fn find(self, id: HirId) -> Option<Node<'hir>> {
336         if id.local_id == ItemLocalId::from_u32(0) {
337             let owner = self.tcx.hir_owner(id.owner)?;
338             Some(owner.node.into())
339         } else {
340             let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
341             let node = owner.nodes[id.local_id].as_ref()?;
342             Some(node.node)
343         }
344     }
345
346     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
347     #[inline]
348     pub fn find_by_def_id(self, id: LocalDefId) -> Option<Node<'hir>> {
349         self.find(self.local_def_id_to_hir_id(id))
350     }
351
352     /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
353     pub fn get(self, id: HirId) -> Node<'hir> {
354         self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
355     }
356
357     /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
358     #[inline]
359     pub fn get_by_def_id(self, id: LocalDefId) -> Node<'hir> {
360         self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id))
361     }
362
363     pub fn get_if_local(self, id: DefId) -> Option<Node<'hir>> {
364         id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
365     }
366
367     pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> {
368         let node = self.tcx.hir_owner(id)?;
369         match node.node {
370             OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics),
371             OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics),
372             OwnerNode::Item(Item {
373                 kind:
374                     ItemKind::Fn(_, generics, _)
375                     | ItemKind::TyAlias(_, generics)
376                     | ItemKind::Enum(_, generics)
377                     | ItemKind::Struct(_, generics)
378                     | ItemKind::Union(_, generics)
379                     | ItemKind::Trait(_, _, generics, ..)
380                     | ItemKind::TraitAlias(generics, _)
381                     | ItemKind::Impl(Impl { generics, .. }),
382                 ..
383             }) => Some(generics),
384             _ => None,
385         }
386     }
387
388     pub fn item(self, id: ItemId) -> &'hir Item<'hir> {
389         self.tcx.hir_owner(id.def_id).unwrap().node.expect_item()
390     }
391
392     pub fn trait_item(self, id: TraitItemId) -> &'hir TraitItem<'hir> {
393         self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item()
394     }
395
396     pub fn impl_item(self, id: ImplItemId) -> &'hir ImplItem<'hir> {
397         self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item()
398     }
399
400     pub fn foreign_item(self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
401         self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item()
402     }
403
404     pub fn body(self, id: BodyId) -> &'hir Body<'hir> {
405         self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id]
406     }
407
408     pub fn fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
409         if let Some(node) = self.find(hir_id) {
410             fn_decl(node)
411         } else {
412             bug!("no node for hir_id `{}`", hir_id)
413         }
414     }
415
416     pub fn fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
417         if let Some(node) = self.find(hir_id) {
418             fn_sig(node)
419         } else {
420             bug!("no node for hir_id `{}`", hir_id)
421         }
422     }
423
424     pub fn enclosing_body_owner(self, hir_id: HirId) -> HirId {
425         for (parent, _) in self.parent_iter(hir_id) {
426             if let Some(body) = self.maybe_body_owned_by(parent) {
427                 return self.body_owner(body);
428             }
429         }
430
431         bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
432     }
433
434     /// Returns the `HirId` that corresponds to the definition of
435     /// which this is the body of, i.e., a `fn`, `const` or `static`
436     /// item (possibly associated), a closure, or a `hir::AnonConst`.
437     pub fn body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
438         let parent = self.get_parent_node(hir_id);
439         assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
440         parent
441     }
442
443     pub fn body_owner_def_id(self, id: BodyId) -> LocalDefId {
444         self.local_def_id(self.body_owner(id))
445     }
446
447     /// Given a `HirId`, returns the `BodyId` associated with it,
448     /// if the node is a body owner, otherwise returns `None`.
449     pub fn maybe_body_owned_by(self, hir_id: HirId) -> Option<BodyId> {
450         self.find(hir_id).map(associated_body).flatten()
451     }
452
453     /// Given a body owner's id, returns the `BodyId` associated with it.
454     pub fn body_owned_by(self, id: HirId) -> BodyId {
455         self.maybe_body_owned_by(id).unwrap_or_else(|| {
456             span_bug!(
457                 self.span(id),
458                 "body_owned_by: {} has no associated body",
459                 self.node_to_string(id)
460             );
461         })
462     }
463
464     pub fn body_param_names(self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
465         self.body(id).params.iter().map(|arg| match arg.pat.kind {
466             PatKind::Binding(_, _, ident, _) => ident,
467             _ => Ident::empty(),
468         })
469     }
470
471     /// Returns the `BodyOwnerKind` of this `LocalDefId`.
472     ///
473     /// Panics if `LocalDefId` does not have an associated body.
474     pub fn body_owner_kind(self, id: HirId) -> BodyOwnerKind {
475         match self.get(id) {
476             Node::Item(&Item { kind: ItemKind::Const(..), .. })
477             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
478             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
479             | Node::AnonConst(_) => BodyOwnerKind::Const,
480             Node::Ctor(..)
481             | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
482             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
483             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
484             Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
485             Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
486             node => bug!("{:#?} is not a body node", node),
487         }
488     }
489
490     /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
491     ///
492     /// Panics if `LocalDefId` does not have an associated body.
493     ///
494     /// This should only be used for determining the context of a body, a return
495     /// value of `Some` does not always suggest that the owner of the body is `const`,
496     /// just that it has to be checked as if it were.
497     pub fn body_const_context(self, did: LocalDefId) -> Option<ConstContext> {
498         let hir_id = self.local_def_id_to_hir_id(did);
499         let ccx = match self.body_owner_kind(hir_id) {
500             BodyOwnerKind::Const => ConstContext::Const,
501             BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
502
503             BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
504             BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
505             BodyOwnerKind::Fn
506                 if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) =>
507             {
508                 ConstContext::ConstFn
509             }
510             BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
511         };
512
513         Some(ccx)
514     }
515
516     /// Returns an iterator of the `DefId`s for all body-owners in this
517     /// crate. If you would prefer to iterate over the bodies
518     /// themselves, you can do `self.hir().krate().body_ids.iter()`.
519     pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + 'hir {
520         self.krate()
521             .owners
522             .iter_enumerated()
523             .flat_map(move |(owner, owner_info)| {
524                 let bodies = &owner_info.as_owner()?.nodes.bodies;
525                 Some(bodies.iter().map(move |&(local_id, _)| {
526                     let hir_id = HirId { owner, local_id };
527                     let body_id = BodyId { hir_id };
528                     self.body_owner_def_id(body_id)
529                 }))
530             })
531             .flatten()
532     }
533
534     pub fn par_body_owners<F: Fn(LocalDefId) + Sync + Send>(self, f: F) {
535         use rustc_data_structures::sync::{par_iter, ParallelIterator};
536         #[cfg(parallel_compiler)]
537         use rustc_rayon::iter::IndexedParallelIterator;
538
539         par_iter(&self.krate().owners.raw).enumerate().for_each(|(owner, owner_info)| {
540             let owner = LocalDefId::new(owner);
541             if let MaybeOwner::Owner(owner_info) = owner_info {
542                 par_iter(owner_info.nodes.bodies.range(..)).for_each(|(local_id, _)| {
543                     let hir_id = HirId { owner, local_id: *local_id };
544                     let body_id = BodyId { hir_id };
545                     f(self.body_owner_def_id(body_id))
546                 })
547             }
548         });
549     }
550
551     pub fn ty_param_owner(self, id: HirId) -> LocalDefId {
552         match self.get(id) {
553             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
554                 id.expect_owner()
555             }
556             Node::GenericParam(_) => self.get_parent_item(id),
557             _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
558         }
559     }
560
561     pub fn ty_param_name(self, id: HirId) -> Symbol {
562         match self.get(id) {
563             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
564                 kw::SelfUpper
565             }
566             Node::GenericParam(param) => param.name.ident().name,
567             _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
568         }
569     }
570
571     pub fn trait_impls(self, trait_did: DefId) -> &'hir [LocalDefId] {
572         self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
573     }
574
575     /// Gets the attributes on the crate. This is preferable to
576     /// invoking `krate.attrs` because it registers a tighter
577     /// dep-graph access.
578     pub fn krate_attrs(self) -> &'hir [ast::Attribute] {
579         self.attrs(CRATE_HIR_ID)
580     }
581
582     pub fn rustc_coherence_is_core(self) -> bool {
583         self.krate_attrs().iter().any(|attr| attr.has_name(sym::rustc_coherence_is_core))
584     }
585
586     pub fn get_module(self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
587         let hir_id = HirId::make_owner(module);
588         match self.tcx.hir_owner(module).map(|o| o.node) {
589             Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
590                 (m, span, hir_id)
591             }
592             Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id),
593             node => panic!("not a module: {:?}", node),
594         }
595     }
596
597     /// Walks the contents of a crate. See also `Crate::visit_all_items`.
598     pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
599         let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID);
600         visitor.visit_mod(top_mod, span, hir_id);
601     }
602
603     /// Walks the attributes in a crate.
604     pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) {
605         let krate = self.krate();
606         for (owner, info) in krate.owners.iter_enumerated() {
607             if let MaybeOwner::Owner(info) = info {
608                 for (local_id, attrs) in info.attrs.map.iter() {
609                     let id = HirId { owner, local_id: *local_id };
610                     for a in *attrs {
611                         visitor.visit_attribute(id, a)
612                     }
613                 }
614             }
615         }
616     }
617
618     /// Visits all items in the crate in some deterministic (but
619     /// unspecified) order. If you just need to process every item,
620     /// but don't care about nesting, this method is the best choice.
621     ///
622     /// If you do care about nesting -- usually because your algorithm
623     /// follows lexical scoping rules -- then you want a different
624     /// approach. You should override `visit_nested_item` in your
625     /// visitor and then call `intravisit::walk_crate` instead.
626     pub fn visit_all_item_likes<V>(self, visitor: &mut V)
627     where
628         V: itemlikevisit::ItemLikeVisitor<'hir>,
629     {
630         let krate = self.krate();
631         for owner in krate.owners.iter().filter_map(|i| i.as_owner()) {
632             match owner.node() {
633                 OwnerNode::Item(item) => visitor.visit_item(item),
634                 OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
635                 OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
636                 OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
637                 OwnerNode::Crate(_) => {}
638             }
639         }
640     }
641
642     /// A parallel version of `visit_all_item_likes`.
643     pub fn par_visit_all_item_likes<V>(self, visitor: &V)
644     where
645         V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
646     {
647         let krate = self.krate();
648         par_for_each_in(&krate.owners.raw, |owner| match owner.map(OwnerInfo::node) {
649             MaybeOwner::Owner(OwnerNode::Item(item)) => visitor.visit_item(item),
650             MaybeOwner::Owner(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
651             MaybeOwner::Owner(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
652             MaybeOwner::Owner(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
653             MaybeOwner::Owner(OwnerNode::Crate(_))
654             | MaybeOwner::NonOwner(_)
655             | MaybeOwner::Phantom => {}
656         })
657     }
658
659     pub fn visit_item_likes_in_module<V>(self, module: LocalDefId, visitor: &mut V)
660     where
661         V: ItemLikeVisitor<'hir>,
662     {
663         let module = self.tcx.hir_module_items(module);
664
665         for id in module.items.iter() {
666             visitor.visit_item(self.item(*id));
667         }
668
669         for id in module.trait_items.iter() {
670             visitor.visit_trait_item(self.trait_item(*id));
671         }
672
673         for id in module.impl_items.iter() {
674             visitor.visit_impl_item(self.impl_item(*id));
675         }
676
677         for id in module.foreign_items.iter() {
678             visitor.visit_foreign_item(self.foreign_item(*id));
679         }
680     }
681
682     pub fn for_each_module(self, f: impl Fn(LocalDefId)) {
683         let mut queue = VecDeque::new();
684         queue.push_back(CRATE_DEF_ID);
685
686         while let Some(id) = queue.pop_front() {
687             f(id);
688             let items = self.tcx.hir_module_items(id);
689             queue.extend(items.submodules.iter().copied())
690         }
691     }
692
693     #[cfg(not(parallel_compiler))]
694     #[inline]
695     pub fn par_for_each_module(self, f: impl Fn(LocalDefId)) {
696         self.for_each_module(f)
697     }
698
699     #[cfg(parallel_compiler)]
700     pub fn par_for_each_module(self, f: impl Fn(LocalDefId) + Sync) {
701         use rustc_data_structures::sync::{par_iter, ParallelIterator};
702         par_iter_submodules(self.tcx, CRATE_DEF_ID, &f);
703
704         fn par_iter_submodules<F>(tcx: TyCtxt<'_>, module: LocalDefId, f: &F)
705         where
706             F: Fn(LocalDefId) + Sync,
707         {
708             (*f)(module);
709             let items = tcx.hir_module_items(module);
710             par_iter(&items.submodules[..]).for_each(|&sm| par_iter_submodules(tcx, sm, f));
711         }
712     }
713
714     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
715     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
716     pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> {
717         ParentHirIterator { current_id, map: self }
718     }
719
720     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
721     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
722     pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> {
723         ParentOwnerIterator { current_id, map: self }
724     }
725
726     /// Checks if the node is left-hand side of an assignment.
727     pub fn is_lhs(self, id: HirId) -> bool {
728         match self.find(self.get_parent_node(id)) {
729             Some(Node::Expr(expr)) => match expr.kind {
730                 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
731                 _ => false,
732             },
733             _ => false,
734         }
735     }
736
737     /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
738     /// Used exclusively for diagnostics, to avoid suggestion function calls.
739     pub fn is_inside_const_context(self, hir_id: HirId) -> bool {
740         self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
741     }
742
743     /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
744     /// `while` or `loop` before reaching it, as block tail returns are not
745     /// available in them.
746     ///
747     /// ```
748     /// fn foo(x: usize) -> bool {
749     ///     if x == 1 {
750     ///         true  // If `get_return_block` gets passed the `id` corresponding
751     ///     } else {  // to this, it will return `foo`'s `HirId`.
752     ///         false
753     ///     }
754     /// }
755     /// ```
756     ///
757     /// ```
758     /// fn foo(x: usize) -> bool {
759     ///     loop {
760     ///         true  // If `get_return_block` gets passed the `id` corresponding
761     ///     }         // to this, it will return `None`.
762     ///     false
763     /// }
764     /// ```
765     pub fn get_return_block(self, id: HirId) -> Option<HirId> {
766         let mut iter = self.parent_iter(id).peekable();
767         let mut ignore_tail = false;
768         if let Some(node) = self.find(id) {
769             if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
770                 // When dealing with `return` statements, we don't care about climbing only tail
771                 // expressions.
772                 ignore_tail = true;
773             }
774         }
775         while let Some((hir_id, node)) = iter.next() {
776             if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
777                 match next_node {
778                     Node::Block(Block { expr: None, .. }) => return None,
779                     // The current node is not the tail expression of its parent.
780                     Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
781                     _ => {}
782                 }
783             }
784             match node {
785                 Node::Item(_)
786                 | Node::ForeignItem(_)
787                 | Node::TraitItem(_)
788                 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
789                 | Node::ImplItem(_) => return Some(hir_id),
790                 // Ignore `return`s on the first iteration
791                 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
792                 | Node::Local(_) => {
793                     return None;
794                 }
795                 _ => {}
796             }
797         }
798         None
799     }
800
801     /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
802     /// parent item is in this map. The "parent item" is the closest parent node
803     /// in the HIR which is recorded by the map and is an item, either an item
804     /// in a module, trait, or impl.
805     pub fn get_parent_item(self, hir_id: HirId) -> LocalDefId {
806         if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() {
807             def_id
808         } else {
809             CRATE_DEF_ID
810         }
811     }
812
813     /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
814     /// module parent is in this map.
815     pub(super) fn get_module_parent_node(self, hir_id: HirId) -> LocalDefId {
816         for (def_id, node) in self.parent_owner_iter(hir_id) {
817             if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
818                 return def_id;
819             }
820         }
821         CRATE_DEF_ID
822     }
823
824     /// When on an if expression, a match arm tail expression or a match arm, give back
825     /// the enclosing `if` or `match` expression.
826     ///
827     /// Used by error reporting when there's a type error in an if or match arm caused by the
828     /// expression needing to be unit.
829     pub fn get_if_cause(self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
830         for (_, node) in self.parent_iter(hir_id) {
831             match node {
832                 Node::Item(_)
833                 | Node::ForeignItem(_)
834                 | Node::TraitItem(_)
835                 | Node::ImplItem(_)
836                 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
837                 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
838                     return Some(expr);
839                 }
840                 _ => {}
841             }
842         }
843         None
844     }
845
846     /// Returns the nearest enclosing scope. A scope is roughly an item or block.
847     pub fn get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
848         for (hir_id, node) in self.parent_iter(hir_id) {
849             if let Node::Item(Item {
850                 kind:
851                     ItemKind::Fn(..)
852                     | ItemKind::Const(..)
853                     | ItemKind::Static(..)
854                     | ItemKind::Mod(..)
855                     | ItemKind::Enum(..)
856                     | ItemKind::Struct(..)
857                     | ItemKind::Union(..)
858                     | ItemKind::Trait(..)
859                     | ItemKind::Impl { .. },
860                 ..
861             })
862             | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
863             | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
864             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
865             | Node::Block(_) = node
866             {
867                 return Some(hir_id);
868             }
869         }
870         None
871     }
872
873     /// Returns the defining scope for an opaque type definition.
874     pub fn get_defining_scope(self, id: HirId) -> HirId {
875         let mut scope = id;
876         loop {
877             scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
878             if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
879                 return scope;
880             }
881         }
882     }
883
884     pub fn get_foreign_abi(self, hir_id: HirId) -> Abi {
885         let parent = self.get_parent_item(hir_id);
886         if let Some(node) = self.tcx.hir_owner(parent) {
887             if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node.node
888             {
889                 return *abi;
890             }
891         }
892         bug!(
893             "expected foreign mod or inlined parent, found {}",
894             self.node_to_string(HirId::make_owner(parent))
895         )
896     }
897
898     pub fn expect_item(self, id: LocalDefId) -> &'hir Item<'hir> {
899         match self.tcx.hir_owner(id) {
900             Some(Owner { node: OwnerNode::Item(item), .. }) => item,
901             _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))),
902         }
903     }
904
905     pub fn expect_impl_item(self, id: LocalDefId) -> &'hir ImplItem<'hir> {
906         match self.tcx.hir_owner(id) {
907             Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item,
908             _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))),
909         }
910     }
911
912     pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> {
913         match self.tcx.hir_owner(id) {
914             Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item,
915             _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))),
916         }
917     }
918
919     pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> {
920         match self.find(id) {
921             Some(Node::Variant(variant)) => variant,
922             _ => bug!("expected variant, found {}", self.node_to_string(id)),
923         }
924     }
925
926     pub fn expect_foreign_item(self, id: LocalDefId) -> &'hir ForeignItem<'hir> {
927         match self.tcx.hir_owner(id) {
928             Some(Owner { node: OwnerNode::ForeignItem(item), .. }) => item,
929             _ => {
930                 bug!("expected foreign item, found {}", self.node_to_string(HirId::make_owner(id)))
931             }
932         }
933     }
934
935     pub fn expect_expr(self, id: HirId) -> &'hir Expr<'hir> {
936         match self.find(id) {
937             Some(Node::Expr(expr)) => expr,
938             _ => bug!("expected expr, found {}", self.node_to_string(id)),
939         }
940     }
941
942     pub fn opt_name(self, id: HirId) -> Option<Symbol> {
943         Some(match self.get(id) {
944             Node::Item(i) => i.ident.name,
945             Node::ForeignItem(fi) => fi.ident.name,
946             Node::ImplItem(ii) => ii.ident.name,
947             Node::TraitItem(ti) => ti.ident.name,
948             Node::Variant(v) => v.ident.name,
949             Node::Field(f) => f.ident.name,
950             Node::Lifetime(lt) => lt.name.ident().name,
951             Node::GenericParam(param) => param.name.ident().name,
952             Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
953             Node::Ctor(..) => self.name(HirId::make_owner(self.get_parent_item(id))),
954             _ => return None,
955         })
956     }
957
958     pub fn name(self, id: HirId) -> Symbol {
959         match self.opt_name(id) {
960             Some(name) => name,
961             None => bug!("no name for {}", self.node_to_string(id)),
962         }
963     }
964
965     /// Given a node ID, gets a list of attributes associated with the AST
966     /// corresponding to the node-ID.
967     pub fn attrs(self, id: HirId) -> &'hir [ast::Attribute] {
968         self.tcx.hir_attrs(id.owner).get(id.local_id)
969     }
970
971     /// Gets the span of the definition of the specified HIR node.
972     /// This is used by `tcx.get_span`
973     pub fn span(self, hir_id: HirId) -> Span {
974         self.opt_span(hir_id)
975             .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
976     }
977
978     pub fn opt_span(self, hir_id: HirId) -> Option<Span> {
979         let span = match self.find(hir_id)? {
980             Node::Param(param) => param.span,
981             Node::Item(item) => match &item.kind {
982                 ItemKind::Fn(sig, _, _) => sig.span,
983                 _ => item.span,
984             },
985             Node::ForeignItem(foreign_item) => foreign_item.span,
986             Node::TraitItem(trait_item) => match &trait_item.kind {
987                 TraitItemKind::Fn(sig, _) => sig.span,
988                 _ => trait_item.span,
989             },
990             Node::ImplItem(impl_item) => match &impl_item.kind {
991                 ImplItemKind::Fn(sig, _) => sig.span,
992                 _ => impl_item.span,
993             },
994             Node::Variant(variant) => variant.span,
995             Node::Field(field) => field.span,
996             Node::AnonConst(constant) => self.body(constant.body).value.span,
997             Node::Expr(expr) => expr.span,
998             Node::Stmt(stmt) => stmt.span,
999             Node::PathSegment(seg) => seg.ident.span,
1000             Node::Ty(ty) => ty.span,
1001             Node::TraitRef(tr) => tr.path.span,
1002             Node::Binding(pat) => pat.span,
1003             Node::Pat(pat) => pat.span,
1004             Node::Arm(arm) => arm.span,
1005             Node::Block(block) => block.span,
1006             Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
1007                 Node::Item(item) => item.span,
1008                 Node::Variant(variant) => variant.span,
1009                 _ => unreachable!(),
1010             },
1011             Node::Lifetime(lifetime) => lifetime.span,
1012             Node::GenericParam(param) => param.span,
1013             Node::Visibility(&Spanned {
1014                 node: VisibilityKind::Restricted { ref path, .. },
1015                 ..
1016             }) => path.span,
1017             Node::Infer(i) => i.span,
1018             Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
1019             Node::Local(local) => local.span,
1020             Node::Crate(item) => item.inner,
1021         };
1022         Some(span)
1023     }
1024
1025     /// Like `hir.span()`, but includes the body of function items
1026     /// (instead of just the function header)
1027     pub fn span_with_body(self, hir_id: HirId) -> Span {
1028         match self.find(hir_id) {
1029             Some(Node::TraitItem(item)) => item.span,
1030             Some(Node::ImplItem(impl_item)) => impl_item.span,
1031             Some(Node::Item(item)) => item.span,
1032             Some(_) => self.span(hir_id),
1033             _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
1034         }
1035     }
1036
1037     pub fn span_if_local(self, id: DefId) -> Option<Span> {
1038         id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
1039     }
1040
1041     pub fn res_span(self, res: Res) -> Option<Span> {
1042         match res {
1043             Res::Err => None,
1044             Res::Local(id) => Some(self.span(id)),
1045             res => self.span_if_local(res.opt_def_id()?),
1046         }
1047     }
1048
1049     /// Get a representation of this `id` for debugging purposes.
1050     /// NOTE: Do NOT use this in diagnostics!
1051     pub fn node_to_string(self, id: HirId) -> String {
1052         hir_id_to_string(self, id)
1053     }
1054
1055     /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
1056     /// called with the HirId for the `{ ... }` anon const
1057     pub fn opt_const_param_default_param_hir_id(self, anon_const: HirId) -> Option<HirId> {
1058         match self.get(self.get_parent_node(anon_const)) {
1059             Node::GenericParam(GenericParam {
1060                 hir_id: param_id,
1061                 kind: GenericParamKind::Const { .. },
1062                 ..
1063             }) => Some(*param_id),
1064             _ => None,
1065         }
1066     }
1067 }
1068
1069 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1070     fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
1071         (*self).find(hir_id)
1072     }
1073
1074     fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1075         (*self).body(id)
1076     }
1077
1078     fn item(&self, id: ItemId) -> &'hir Item<'hir> {
1079         (*self).item(id)
1080     }
1081
1082     fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1083         (*self).trait_item(id)
1084     }
1085
1086     fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1087         (*self).impl_item(id)
1088     }
1089
1090     fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
1091         (*self).foreign_item(id)
1092     }
1093 }
1094
1095 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
1096     debug_assert_eq!(crate_num, LOCAL_CRATE);
1097     let krate = tcx.hir_crate(());
1098     let hir_body_hash = krate.hir_hash;
1099
1100     let upstream_crates = upstream_crates(tcx);
1101
1102     // We hash the final, remapped names of all local source files so we
1103     // don't have to include the path prefix remapping commandline args.
1104     // If we included the full mapping in the SVH, we could only have
1105     // reproducible builds by compiling from the same directory. So we just
1106     // hash the result of the mapping instead of the mapping itself.
1107     let mut source_file_names: Vec<_> = tcx
1108         .sess
1109         .source_map()
1110         .files()
1111         .iter()
1112         .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1113         .map(|source_file| source_file.name_hash)
1114         .collect();
1115
1116     source_file_names.sort_unstable();
1117
1118     let mut hcx = tcx.create_stable_hashing_context();
1119     let mut stable_hasher = StableHasher::new();
1120     hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher);
1121     upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1122     source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1123     if tcx.sess.opts.debugging_opts.incremental_relative_spans {
1124         let definitions = &tcx.untracked_resolutions.definitions;
1125         let mut owner_spans: Vec<_> = krate
1126             .owners
1127             .iter_enumerated()
1128             .filter_map(|(def_id, info)| {
1129                 let _ = info.as_owner()?;
1130                 let def_path_hash = definitions.def_path_hash(def_id);
1131                 let span = definitions.def_span(def_id);
1132                 debug_assert_eq!(span.parent(), None);
1133                 Some((def_path_hash, span))
1134             })
1135             .collect();
1136         owner_spans.sort_unstable_by_key(|bn| bn.0);
1137         owner_spans.hash_stable(&mut hcx, &mut stable_hasher);
1138     }
1139     tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1140     tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1141
1142     let crate_hash: Fingerprint = stable_hasher.finish();
1143     Svh::new(crate_hash.to_smaller_hash())
1144 }
1145
1146 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1147     let mut upstream_crates: Vec<_> = tcx
1148         .crates(())
1149         .iter()
1150         .map(|&cnum| {
1151             let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum);
1152             let hash = tcx.crate_hash(cnum);
1153             (stable_crate_id, hash)
1154         })
1155         .collect();
1156     upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1157     upstream_crates
1158 }
1159
1160 fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
1161     let id_str = format!(" (hir_id={})", id);
1162
1163     let path_str = || {
1164         // This functionality is used for debugging, try to use `TyCtxt` to get
1165         // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1166         crate::ty::tls::with_opt(|tcx| {
1167             if let Some(tcx) = tcx {
1168                 let def_id = map.local_def_id(id);
1169                 tcx.def_path_str(def_id.to_def_id())
1170             } else if let Some(path) = map.def_path_from_hir_id(id) {
1171                 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1172             } else {
1173                 String::from("<missing path>")
1174             }
1175         })
1176     };
1177
1178     let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1179     let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1180
1181     match map.find(id) {
1182         Some(Node::Item(item)) => {
1183             let item_str = match item.kind {
1184                 ItemKind::ExternCrate(..) => "extern crate",
1185                 ItemKind::Use(..) => "use",
1186                 ItemKind::Static(..) => "static",
1187                 ItemKind::Const(..) => "const",
1188                 ItemKind::Fn(..) => "fn",
1189                 ItemKind::Macro(..) => "macro",
1190                 ItemKind::Mod(..) => "mod",
1191                 ItemKind::ForeignMod { .. } => "foreign mod",
1192                 ItemKind::GlobalAsm(..) => "global asm",
1193                 ItemKind::TyAlias(..) => "ty",
1194                 ItemKind::OpaqueTy(..) => "opaque type",
1195                 ItemKind::Enum(..) => "enum",
1196                 ItemKind::Struct(..) => "struct",
1197                 ItemKind::Union(..) => "union",
1198                 ItemKind::Trait(..) => "trait",
1199                 ItemKind::TraitAlias(..) => "trait alias",
1200                 ItemKind::Impl { .. } => "impl",
1201             };
1202             format!("{} {}{}", item_str, path_str(), id_str)
1203         }
1204         Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1205         Some(Node::ImplItem(ii)) => match ii.kind {
1206             ImplItemKind::Const(..) => {
1207                 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1208             }
1209             ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1210             ImplItemKind::TyAlias(_) => {
1211                 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1212             }
1213         },
1214         Some(Node::TraitItem(ti)) => {
1215             let kind = match ti.kind {
1216                 TraitItemKind::Const(..) => "assoc constant",
1217                 TraitItemKind::Fn(..) => "trait method",
1218                 TraitItemKind::Type(..) => "assoc type",
1219             };
1220
1221             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1222         }
1223         Some(Node::Variant(ref variant)) => {
1224             format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1225         }
1226         Some(Node::Field(ref field)) => {
1227             format!("field {} in {}{}", field.ident, path_str(), id_str)
1228         }
1229         Some(Node::AnonConst(_)) => node_str("const"),
1230         Some(Node::Expr(_)) => node_str("expr"),
1231         Some(Node::Stmt(_)) => node_str("stmt"),
1232         Some(Node::PathSegment(_)) => node_str("path segment"),
1233         Some(Node::Ty(_)) => node_str("type"),
1234         Some(Node::TraitRef(_)) => node_str("trait ref"),
1235         Some(Node::Binding(_)) => node_str("local"),
1236         Some(Node::Pat(_)) => node_str("pat"),
1237         Some(Node::Param(_)) => node_str("param"),
1238         Some(Node::Arm(_)) => node_str("arm"),
1239         Some(Node::Block(_)) => node_str("block"),
1240         Some(Node::Infer(_)) => node_str("infer"),
1241         Some(Node::Local(_)) => node_str("local"),
1242         Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1243         Some(Node::Lifetime(_)) => node_str("lifetime"),
1244         Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1245         Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1246         Some(Node::Crate(..)) => String::from("root_crate"),
1247         None => format!("unknown node{}", id_str),
1248     }
1249 }
1250
1251 pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems {
1252     let mut collector = ModuleCollector {
1253         tcx,
1254         submodules: Vec::default(),
1255         items: Vec::default(),
1256         trait_items: Vec::default(),
1257         impl_items: Vec::default(),
1258         foreign_items: Vec::default(),
1259     };
1260
1261     let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id);
1262     collector.visit_mod(hir_mod, span, hir_id);
1263
1264     let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } =
1265         collector;
1266     return ModuleItems {
1267         submodules: submodules.into_boxed_slice(),
1268         items: items.into_boxed_slice(),
1269         trait_items: trait_items.into_boxed_slice(),
1270         impl_items: impl_items.into_boxed_slice(),
1271         foreign_items: foreign_items.into_boxed_slice(),
1272     };
1273
1274     struct ModuleCollector<'tcx> {
1275         tcx: TyCtxt<'tcx>,
1276         submodules: Vec<LocalDefId>,
1277         items: Vec<ItemId>,
1278         trait_items: Vec<TraitItemId>,
1279         impl_items: Vec<ImplItemId>,
1280         foreign_items: Vec<ForeignItemId>,
1281     }
1282
1283     impl<'hir> Visitor<'hir> for ModuleCollector<'hir> {
1284         type NestedFilter = nested_filter::All;
1285
1286         fn nested_visit_map(&mut self) -> Self::Map {
1287             self.tcx.hir()
1288         }
1289
1290         fn visit_item(&mut self, item: &'hir Item<'hir>) {
1291             self.items.push(item.item_id());
1292             if let ItemKind::Mod(..) = item.kind {
1293                 // If this declares another module, do not recurse inside it.
1294                 self.submodules.push(item.def_id);
1295             } else {
1296                 intravisit::walk_item(self, item)
1297             }
1298         }
1299
1300         fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1301             self.trait_items.push(item.trait_item_id());
1302             intravisit::walk_trait_item(self, item)
1303         }
1304
1305         fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1306             self.impl_items.push(item.impl_item_id());
1307             intravisit::walk_impl_item(self, item)
1308         }
1309
1310         fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1311             self.foreign_items.push(item.foreign_item_id());
1312             intravisit::walk_foreign_item(self, item)
1313         }
1314     }
1315 }