]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/mod.rs
Compute `ty_param_owner` using DefIdTree.
[rust.git] / compiler / rustc_middle / src / hir / map / mod.rs
1 use crate::hir::{ModuleItems, Owner};
2 use crate::ty::{DefIdTree, 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 re-execute 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(_, mt, _) => DefKind::Static(mt),
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(_, mt) => DefKind::Static(mt),
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, def_id: LocalDefId) -> BodyOwnerKind {
475         match self.tcx.def_kind(def_id) {
476             DefKind::Const | DefKind::AssocConst | DefKind::InlineConst | DefKind::AnonConst => {
477                 BodyOwnerKind::Const
478             }
479             DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn,
480             DefKind::Closure | DefKind::Generator => BodyOwnerKind::Closure,
481             DefKind::Static(mt) => BodyOwnerKind::Static(mt),
482             dk => bug!("{:?} is not a body node: {:?}", def_id, dk),
483         }
484     }
485
486     /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
487     ///
488     /// Panics if `LocalDefId` does not have an associated body.
489     ///
490     /// This should only be used for determining the context of a body, a return
491     /// value of `Some` does not always suggest that the owner of the body is `const`,
492     /// just that it has to be checked as if it were.
493     pub fn body_const_context(self, def_id: LocalDefId) -> Option<ConstContext> {
494         let ccx = match self.body_owner_kind(def_id) {
495             BodyOwnerKind::Const => ConstContext::Const,
496             BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
497
498             BodyOwnerKind::Fn if self.tcx.is_constructor(def_id.to_def_id()) => return None,
499             BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(def_id.to_def_id()) => {
500                 ConstContext::ConstFn
501             }
502             BodyOwnerKind::Fn
503                 if self.tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const) =>
504             {
505                 ConstContext::ConstFn
506             }
507             BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
508         };
509
510         Some(ccx)
511     }
512
513     /// Returns an iterator of the `DefId`s for all body-owners in this
514     /// crate. If you would prefer to iterate over the bodies
515     /// themselves, you can do `self.hir().krate().body_ids.iter()`.
516     pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + 'hir {
517         self.krate()
518             .owners
519             .iter_enumerated()
520             .flat_map(move |(owner, owner_info)| {
521                 let bodies = &owner_info.as_owner()?.nodes.bodies;
522                 Some(bodies.iter().map(move |&(local_id, _)| {
523                     let hir_id = HirId { owner, local_id };
524                     let body_id = BodyId { hir_id };
525                     self.body_owner_def_id(body_id)
526                 }))
527             })
528             .flatten()
529     }
530
531     pub fn par_body_owners<F: Fn(LocalDefId) + Sync + Send>(self, f: F) {
532         use rustc_data_structures::sync::{par_iter, ParallelIterator};
533         #[cfg(parallel_compiler)]
534         use rustc_rayon::iter::IndexedParallelIterator;
535
536         par_iter(&self.krate().owners.raw).enumerate().for_each(|(owner, owner_info)| {
537             let owner = LocalDefId::new(owner);
538             if let MaybeOwner::Owner(owner_info) = owner_info {
539                 par_iter(owner_info.nodes.bodies.range(..)).for_each(|(local_id, _)| {
540                     let hir_id = HirId { owner, local_id: *local_id };
541                     let body_id = BodyId { hir_id };
542                     f(self.body_owner_def_id(body_id))
543                 })
544             }
545         });
546     }
547
548     pub fn ty_param_owner(self, def_id: LocalDefId) -> LocalDefId {
549         let def_kind = self.tcx.def_kind(def_id);
550         match def_kind {
551             DefKind::Trait | DefKind::TraitAlias => def_id,
552             DefKind::TyParam | DefKind::ConstParam => self.tcx.local_parent(def_id).unwrap(),
553             _ => bug!("ty_param_owner: {:?} is a {:?} not a type parameter", def_id, def_kind),
554         }
555     }
556
557     pub fn ty_param_name(self, id: HirId) -> Symbol {
558         match self.get(id) {
559             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
560                 kw::SelfUpper
561             }
562             Node::GenericParam(param) => param.name.ident().name,
563             _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
564         }
565     }
566
567     pub fn trait_impls(self, trait_did: DefId) -> &'hir [LocalDefId] {
568         self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
569     }
570
571     /// Gets the attributes on the crate. This is preferable to
572     /// invoking `krate.attrs` because it registers a tighter
573     /// dep-graph access.
574     pub fn krate_attrs(self) -> &'hir [ast::Attribute] {
575         self.attrs(CRATE_HIR_ID)
576     }
577
578     pub fn rustc_coherence_is_core(self) -> bool {
579         self.krate_attrs().iter().any(|attr| attr.has_name(sym::rustc_coherence_is_core))
580     }
581
582     pub fn get_module(self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
583         let hir_id = HirId::make_owner(module);
584         match self.tcx.hir_owner(module).map(|o| o.node) {
585             Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
586                 (m, span, hir_id)
587             }
588             Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id),
589             node => panic!("not a module: {:?}", node),
590         }
591     }
592
593     /// Walks the contents of a crate. See also `Crate::visit_all_items`.
594     pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
595         let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID);
596         visitor.visit_mod(top_mod, span, hir_id);
597     }
598
599     /// Walks the attributes in a crate.
600     pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) {
601         let krate = self.krate();
602         for (owner, info) in krate.owners.iter_enumerated() {
603             if let MaybeOwner::Owner(info) = info {
604                 for (local_id, attrs) in info.attrs.map.iter() {
605                     let id = HirId { owner, local_id: *local_id };
606                     for a in *attrs {
607                         visitor.visit_attribute(id, a)
608                     }
609                 }
610             }
611         }
612     }
613
614     /// Visits all items in the crate in some deterministic (but
615     /// unspecified) order. If you just need to process every item,
616     /// but don't care about nesting, this method is the best choice.
617     ///
618     /// If you do care about nesting -- usually because your algorithm
619     /// follows lexical scoping rules -- then you want a different
620     /// approach. You should override `visit_nested_item` in your
621     /// visitor and then call `intravisit::walk_crate` instead.
622     pub fn visit_all_item_likes<V>(self, visitor: &mut V)
623     where
624         V: itemlikevisit::ItemLikeVisitor<'hir>,
625     {
626         let krate = self.krate();
627         for owner in krate.owners.iter().filter_map(|i| i.as_owner()) {
628             match owner.node() {
629                 OwnerNode::Item(item) => visitor.visit_item(item),
630                 OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
631                 OwnerNode::ImplItem(item) => visitor.visit_impl_item(item),
632                 OwnerNode::TraitItem(item) => visitor.visit_trait_item(item),
633                 OwnerNode::Crate(_) => {}
634             }
635         }
636     }
637
638     /// A parallel version of `visit_all_item_likes`.
639     pub fn par_visit_all_item_likes<V>(self, visitor: &V)
640     where
641         V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
642     {
643         let krate = self.krate();
644         par_for_each_in(&krate.owners.raw, |owner| match owner.map(OwnerInfo::node) {
645             MaybeOwner::Owner(OwnerNode::Item(item)) => visitor.visit_item(item),
646             MaybeOwner::Owner(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item),
647             MaybeOwner::Owner(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item),
648             MaybeOwner::Owner(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item),
649             MaybeOwner::Owner(OwnerNode::Crate(_))
650             | MaybeOwner::NonOwner(_)
651             | MaybeOwner::Phantom => {}
652         })
653     }
654
655     pub fn visit_item_likes_in_module<V>(self, module: LocalDefId, visitor: &mut V)
656     where
657         V: ItemLikeVisitor<'hir>,
658     {
659         let module = self.tcx.hir_module_items(module);
660
661         for id in module.items.iter() {
662             visitor.visit_item(self.item(*id));
663         }
664
665         for id in module.trait_items.iter() {
666             visitor.visit_trait_item(self.trait_item(*id));
667         }
668
669         for id in module.impl_items.iter() {
670             visitor.visit_impl_item(self.impl_item(*id));
671         }
672
673         for id in module.foreign_items.iter() {
674             visitor.visit_foreign_item(self.foreign_item(*id));
675         }
676     }
677
678     pub fn for_each_module(self, f: impl Fn(LocalDefId)) {
679         let mut queue = VecDeque::new();
680         queue.push_back(CRATE_DEF_ID);
681
682         while let Some(id) = queue.pop_front() {
683             f(id);
684             let items = self.tcx.hir_module_items(id);
685             queue.extend(items.submodules.iter().copied())
686         }
687     }
688
689     #[cfg(not(parallel_compiler))]
690     #[inline]
691     pub fn par_for_each_module(self, f: impl Fn(LocalDefId)) {
692         self.for_each_module(f)
693     }
694
695     #[cfg(parallel_compiler)]
696     pub fn par_for_each_module(self, f: impl Fn(LocalDefId) + Sync) {
697         use rustc_data_structures::sync::{par_iter, ParallelIterator};
698         par_iter_submodules(self.tcx, CRATE_DEF_ID, &f);
699
700         fn par_iter_submodules<F>(tcx: TyCtxt<'_>, module: LocalDefId, f: &F)
701         where
702             F: Fn(LocalDefId) + Sync,
703         {
704             (*f)(module);
705             let items = tcx.hir_module_items(module);
706             par_iter(&items.submodules[..]).for_each(|&sm| par_iter_submodules(tcx, sm, f));
707         }
708     }
709
710     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
711     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
712     pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> {
713         ParentHirIterator { current_id, map: self }
714     }
715
716     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
717     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
718     pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> {
719         ParentOwnerIterator { current_id, map: self }
720     }
721
722     /// Checks if the node is left-hand side of an assignment.
723     pub fn is_lhs(self, id: HirId) -> bool {
724         match self.find(self.get_parent_node(id)) {
725             Some(Node::Expr(expr)) => match expr.kind {
726                 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
727                 _ => false,
728             },
729             _ => false,
730         }
731     }
732
733     /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
734     /// Used exclusively for diagnostics, to avoid suggestion function calls.
735     pub fn is_inside_const_context(self, hir_id: HirId) -> bool {
736         self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
737     }
738
739     /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
740     /// `while` or `loop` before reaching it, as block tail returns are not
741     /// available in them.
742     ///
743     /// ```
744     /// fn foo(x: usize) -> bool {
745     ///     if x == 1 {
746     ///         true  // If `get_return_block` gets passed the `id` corresponding
747     ///     } else {  // to this, it will return `foo`'s `HirId`.
748     ///         false
749     ///     }
750     /// }
751     /// ```
752     ///
753     /// ```
754     /// fn foo(x: usize) -> bool {
755     ///     loop {
756     ///         true  // If `get_return_block` gets passed the `id` corresponding
757     ///     }         // to this, it will return `None`.
758     ///     false
759     /// }
760     /// ```
761     pub fn get_return_block(self, id: HirId) -> Option<HirId> {
762         let mut iter = self.parent_iter(id).peekable();
763         let mut ignore_tail = false;
764         if let Some(node) = self.find(id) {
765             if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
766                 // When dealing with `return` statements, we don't care about climbing only tail
767                 // expressions.
768                 ignore_tail = true;
769             }
770         }
771         while let Some((hir_id, node)) = iter.next() {
772             if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
773                 match next_node {
774                     Node::Block(Block { expr: None, .. }) => return None,
775                     // The current node is not the tail expression of its parent.
776                     Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
777                     _ => {}
778                 }
779             }
780             match node {
781                 Node::Item(_)
782                 | Node::ForeignItem(_)
783                 | Node::TraitItem(_)
784                 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
785                 | Node::ImplItem(_) => return Some(hir_id),
786                 // Ignore `return`s on the first iteration
787                 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
788                 | Node::Local(_) => {
789                     return None;
790                 }
791                 _ => {}
792             }
793         }
794         None
795     }
796
797     /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
798     /// parent item is in this map. The "parent item" is the closest parent node
799     /// in the HIR which is recorded by the map and is an item, either an item
800     /// in a module, trait, or impl.
801     pub fn get_parent_item(self, hir_id: HirId) -> LocalDefId {
802         if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() {
803             def_id
804         } else {
805             CRATE_DEF_ID
806         }
807     }
808
809     /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
810     /// module parent is in this map.
811     pub(super) fn get_module_parent_node(self, hir_id: HirId) -> LocalDefId {
812         for (def_id, node) in self.parent_owner_iter(hir_id) {
813             if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
814                 return def_id;
815             }
816         }
817         CRATE_DEF_ID
818     }
819
820     /// When on an if expression, a match arm tail expression or a match arm, give back
821     /// the enclosing `if` or `match` expression.
822     ///
823     /// Used by error reporting when there's a type error in an if or match arm caused by the
824     /// expression needing to be unit.
825     pub fn get_if_cause(self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
826         for (_, node) in self.parent_iter(hir_id) {
827             match node {
828                 Node::Item(_)
829                 | Node::ForeignItem(_)
830                 | Node::TraitItem(_)
831                 | Node::ImplItem(_)
832                 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
833                 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
834                     return Some(expr);
835                 }
836                 _ => {}
837             }
838         }
839         None
840     }
841
842     /// Returns the nearest enclosing scope. A scope is roughly an item or block.
843     pub fn get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
844         for (hir_id, node) in self.parent_iter(hir_id) {
845             if let Node::Item(Item {
846                 kind:
847                     ItemKind::Fn(..)
848                     | ItemKind::Const(..)
849                     | ItemKind::Static(..)
850                     | ItemKind::Mod(..)
851                     | ItemKind::Enum(..)
852                     | ItemKind::Struct(..)
853                     | ItemKind::Union(..)
854                     | ItemKind::Trait(..)
855                     | ItemKind::Impl { .. },
856                 ..
857             })
858             | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
859             | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
860             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
861             | Node::Block(_) = node
862             {
863                 return Some(hir_id);
864             }
865         }
866         None
867     }
868
869     /// Returns the defining scope for an opaque type definition.
870     pub fn get_defining_scope(self, id: HirId) -> HirId {
871         let mut scope = id;
872         loop {
873             scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
874             if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
875                 return scope;
876             }
877         }
878     }
879
880     pub fn get_foreign_abi(self, hir_id: HirId) -> Abi {
881         let parent = self.get_parent_item(hir_id);
882         if let Some(node) = self.tcx.hir_owner(parent) {
883             if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node.node
884             {
885                 return *abi;
886             }
887         }
888         bug!(
889             "expected foreign mod or inlined parent, found {}",
890             self.node_to_string(HirId::make_owner(parent))
891         )
892     }
893
894     pub fn expect_item(self, id: LocalDefId) -> &'hir Item<'hir> {
895         match self.tcx.hir_owner(id) {
896             Some(Owner { node: OwnerNode::Item(item), .. }) => item,
897             _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))),
898         }
899     }
900
901     pub fn expect_impl_item(self, id: LocalDefId) -> &'hir ImplItem<'hir> {
902         match self.tcx.hir_owner(id) {
903             Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item,
904             _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))),
905         }
906     }
907
908     pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> {
909         match self.tcx.hir_owner(id) {
910             Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item,
911             _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))),
912         }
913     }
914
915     pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> {
916         match self.find(id) {
917             Some(Node::Variant(variant)) => variant,
918             _ => bug!("expected variant, found {}", self.node_to_string(id)),
919         }
920     }
921
922     pub fn expect_foreign_item(self, id: LocalDefId) -> &'hir ForeignItem<'hir> {
923         match self.tcx.hir_owner(id) {
924             Some(Owner { node: OwnerNode::ForeignItem(item), .. }) => item,
925             _ => {
926                 bug!("expected foreign item, found {}", self.node_to_string(HirId::make_owner(id)))
927             }
928         }
929     }
930
931     pub fn expect_expr(self, id: HirId) -> &'hir Expr<'hir> {
932         match self.find(id) {
933             Some(Node::Expr(expr)) => expr,
934             _ => bug!("expected expr, found {}", self.node_to_string(id)),
935         }
936     }
937
938     pub fn opt_name(self, id: HirId) -> Option<Symbol> {
939         Some(match self.get(id) {
940             Node::Item(i) => i.ident.name,
941             Node::ForeignItem(fi) => fi.ident.name,
942             Node::ImplItem(ii) => ii.ident.name,
943             Node::TraitItem(ti) => ti.ident.name,
944             Node::Variant(v) => v.ident.name,
945             Node::Field(f) => f.ident.name,
946             Node::Lifetime(lt) => lt.name.ident().name,
947             Node::GenericParam(param) => param.name.ident().name,
948             Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
949             Node::Ctor(..) => self.name(HirId::make_owner(self.get_parent_item(id))),
950             _ => return None,
951         })
952     }
953
954     pub fn name(self, id: HirId) -> Symbol {
955         match self.opt_name(id) {
956             Some(name) => name,
957             None => bug!("no name for {}", self.node_to_string(id)),
958         }
959     }
960
961     /// Given a node ID, gets a list of attributes associated with the AST
962     /// corresponding to the node-ID.
963     pub fn attrs(self, id: HirId) -> &'hir [ast::Attribute] {
964         self.tcx.hir_attrs(id.owner).get(id.local_id)
965     }
966
967     /// Gets the span of the definition of the specified HIR node.
968     /// This is used by `tcx.get_span`
969     pub fn span(self, hir_id: HirId) -> Span {
970         self.opt_span(hir_id)
971             .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
972     }
973
974     pub fn opt_span(self, hir_id: HirId) -> Option<Span> {
975         let span = match self.find(hir_id)? {
976             Node::Param(param) => param.span,
977             Node::Item(item) => match &item.kind {
978                 ItemKind::Fn(sig, _, _) => sig.span,
979                 _ => item.span,
980             },
981             Node::ForeignItem(foreign_item) => foreign_item.span,
982             Node::TraitItem(trait_item) => match &trait_item.kind {
983                 TraitItemKind::Fn(sig, _) => sig.span,
984                 _ => trait_item.span,
985             },
986             Node::ImplItem(impl_item) => match &impl_item.kind {
987                 ImplItemKind::Fn(sig, _) => sig.span,
988                 _ => impl_item.span,
989             },
990             Node::Variant(variant) => variant.span,
991             Node::Field(field) => field.span,
992             Node::AnonConst(constant) => self.body(constant.body).value.span,
993             Node::Expr(expr) => expr.span,
994             Node::Stmt(stmt) => stmt.span,
995             Node::PathSegment(seg) => seg.ident.span,
996             Node::Ty(ty) => ty.span,
997             Node::TraitRef(tr) => tr.path.span,
998             Node::Binding(pat) => pat.span,
999             Node::Pat(pat) => pat.span,
1000             Node::Arm(arm) => arm.span,
1001             Node::Block(block) => block.span,
1002             Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
1003                 Node::Item(item) => item.span,
1004                 Node::Variant(variant) => variant.span,
1005                 _ => unreachable!(),
1006             },
1007             Node::Lifetime(lifetime) => lifetime.span,
1008             Node::GenericParam(param) => param.span,
1009             Node::Visibility(&Spanned {
1010                 node: VisibilityKind::Restricted { ref path, .. },
1011                 ..
1012             }) => path.span,
1013             Node::Infer(i) => i.span,
1014             Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
1015             Node::Local(local) => local.span,
1016             Node::Crate(item) => item.inner,
1017         };
1018         Some(span)
1019     }
1020
1021     /// Like `hir.span()`, but includes the body of function items
1022     /// (instead of just the function header)
1023     pub fn span_with_body(self, hir_id: HirId) -> Span {
1024         match self.find(hir_id) {
1025             Some(Node::TraitItem(item)) => item.span,
1026             Some(Node::ImplItem(impl_item)) => impl_item.span,
1027             Some(Node::Item(item)) => item.span,
1028             Some(_) => self.span(hir_id),
1029             _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
1030         }
1031     }
1032
1033     pub fn span_if_local(self, id: DefId) -> Option<Span> {
1034         id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
1035     }
1036
1037     pub fn res_span(self, res: Res) -> Option<Span> {
1038         match res {
1039             Res::Err => None,
1040             Res::Local(id) => Some(self.span(id)),
1041             res => self.span_if_local(res.opt_def_id()?),
1042         }
1043     }
1044
1045     /// Get a representation of this `id` for debugging purposes.
1046     /// NOTE: Do NOT use this in diagnostics!
1047     pub fn node_to_string(self, id: HirId) -> String {
1048         hir_id_to_string(self, id)
1049     }
1050
1051     /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
1052     /// called with the HirId for the `{ ... }` anon const
1053     pub fn opt_const_param_default_param_hir_id(self, anon_const: HirId) -> Option<HirId> {
1054         match self.get(self.get_parent_node(anon_const)) {
1055             Node::GenericParam(GenericParam {
1056                 hir_id: param_id,
1057                 kind: GenericParamKind::Const { .. },
1058                 ..
1059             }) => Some(*param_id),
1060             _ => None,
1061         }
1062     }
1063 }
1064
1065 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1066     fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
1067         (*self).find(hir_id)
1068     }
1069
1070     fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1071         (*self).body(id)
1072     }
1073
1074     fn item(&self, id: ItemId) -> &'hir Item<'hir> {
1075         (*self).item(id)
1076     }
1077
1078     fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1079         (*self).trait_item(id)
1080     }
1081
1082     fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1083         (*self).impl_item(id)
1084     }
1085
1086     fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
1087         (*self).foreign_item(id)
1088     }
1089 }
1090
1091 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
1092     debug_assert_eq!(crate_num, LOCAL_CRATE);
1093     let krate = tcx.hir_crate(());
1094     let hir_body_hash = krate.hir_hash;
1095
1096     let upstream_crates = upstream_crates(tcx);
1097
1098     // We hash the final, remapped names of all local source files so we
1099     // don't have to include the path prefix remapping commandline args.
1100     // If we included the full mapping in the SVH, we could only have
1101     // reproducible builds by compiling from the same directory. So we just
1102     // hash the result of the mapping instead of the mapping itself.
1103     let mut source_file_names: Vec<_> = tcx
1104         .sess
1105         .source_map()
1106         .files()
1107         .iter()
1108         .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1109         .map(|source_file| source_file.name_hash)
1110         .collect();
1111
1112     source_file_names.sort_unstable();
1113
1114     let mut hcx = tcx.create_stable_hashing_context();
1115     let mut stable_hasher = StableHasher::new();
1116     hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher);
1117     upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1118     source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1119     if tcx.sess.opts.debugging_opts.incremental_relative_spans {
1120         let definitions = &tcx.untracked_resolutions.definitions;
1121         let mut owner_spans: Vec<_> = krate
1122             .owners
1123             .iter_enumerated()
1124             .filter_map(|(def_id, info)| {
1125                 let _ = info.as_owner()?;
1126                 let def_path_hash = definitions.def_path_hash(def_id);
1127                 let span = definitions.def_span(def_id);
1128                 debug_assert_eq!(span.parent(), None);
1129                 Some((def_path_hash, span))
1130             })
1131             .collect();
1132         owner_spans.sort_unstable_by_key(|bn| bn.0);
1133         owner_spans.hash_stable(&mut hcx, &mut stable_hasher);
1134     }
1135     tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1136     tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1137
1138     let crate_hash: Fingerprint = stable_hasher.finish();
1139     Svh::new(crate_hash.to_smaller_hash())
1140 }
1141
1142 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1143     let mut upstream_crates: Vec<_> = tcx
1144         .crates(())
1145         .iter()
1146         .map(|&cnum| {
1147             let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum);
1148             let hash = tcx.crate_hash(cnum);
1149             (stable_crate_id, hash)
1150         })
1151         .collect();
1152     upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1153     upstream_crates
1154 }
1155
1156 fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
1157     let id_str = format!(" (hir_id={})", id);
1158
1159     let path_str = || {
1160         // This functionality is used for debugging, try to use `TyCtxt` to get
1161         // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1162         crate::ty::tls::with_opt(|tcx| {
1163             if let Some(tcx) = tcx {
1164                 let def_id = map.local_def_id(id);
1165                 tcx.def_path_str(def_id.to_def_id())
1166             } else if let Some(path) = map.def_path_from_hir_id(id) {
1167                 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1168             } else {
1169                 String::from("<missing path>")
1170             }
1171         })
1172     };
1173
1174     let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1175     let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1176
1177     match map.find(id) {
1178         Some(Node::Item(item)) => {
1179             let item_str = match item.kind {
1180                 ItemKind::ExternCrate(..) => "extern crate",
1181                 ItemKind::Use(..) => "use",
1182                 ItemKind::Static(..) => "static",
1183                 ItemKind::Const(..) => "const",
1184                 ItemKind::Fn(..) => "fn",
1185                 ItemKind::Macro(..) => "macro",
1186                 ItemKind::Mod(..) => "mod",
1187                 ItemKind::ForeignMod { .. } => "foreign mod",
1188                 ItemKind::GlobalAsm(..) => "global asm",
1189                 ItemKind::TyAlias(..) => "ty",
1190                 ItemKind::OpaqueTy(..) => "opaque type",
1191                 ItemKind::Enum(..) => "enum",
1192                 ItemKind::Struct(..) => "struct",
1193                 ItemKind::Union(..) => "union",
1194                 ItemKind::Trait(..) => "trait",
1195                 ItemKind::TraitAlias(..) => "trait alias",
1196                 ItemKind::Impl { .. } => "impl",
1197             };
1198             format!("{} {}{}", item_str, path_str(), id_str)
1199         }
1200         Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1201         Some(Node::ImplItem(ii)) => match ii.kind {
1202             ImplItemKind::Const(..) => {
1203                 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1204             }
1205             ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1206             ImplItemKind::TyAlias(_) => {
1207                 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1208             }
1209         },
1210         Some(Node::TraitItem(ti)) => {
1211             let kind = match ti.kind {
1212                 TraitItemKind::Const(..) => "assoc constant",
1213                 TraitItemKind::Fn(..) => "trait method",
1214                 TraitItemKind::Type(..) => "assoc type",
1215             };
1216
1217             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1218         }
1219         Some(Node::Variant(ref variant)) => {
1220             format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1221         }
1222         Some(Node::Field(ref field)) => {
1223             format!("field {} in {}{}", field.ident, path_str(), id_str)
1224         }
1225         Some(Node::AnonConst(_)) => node_str("const"),
1226         Some(Node::Expr(_)) => node_str("expr"),
1227         Some(Node::Stmt(_)) => node_str("stmt"),
1228         Some(Node::PathSegment(_)) => node_str("path segment"),
1229         Some(Node::Ty(_)) => node_str("type"),
1230         Some(Node::TraitRef(_)) => node_str("trait ref"),
1231         Some(Node::Binding(_)) => node_str("local"),
1232         Some(Node::Pat(_)) => node_str("pat"),
1233         Some(Node::Param(_)) => node_str("param"),
1234         Some(Node::Arm(_)) => node_str("arm"),
1235         Some(Node::Block(_)) => node_str("block"),
1236         Some(Node::Infer(_)) => node_str("infer"),
1237         Some(Node::Local(_)) => node_str("local"),
1238         Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1239         Some(Node::Lifetime(_)) => node_str("lifetime"),
1240         Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1241         Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1242         Some(Node::Crate(..)) => String::from("root_crate"),
1243         None => format!("unknown node{}", id_str),
1244     }
1245 }
1246
1247 pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems {
1248     let mut collector = ModuleCollector {
1249         tcx,
1250         submodules: Vec::default(),
1251         items: Vec::default(),
1252         trait_items: Vec::default(),
1253         impl_items: Vec::default(),
1254         foreign_items: Vec::default(),
1255     };
1256
1257     let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id);
1258     collector.visit_mod(hir_mod, span, hir_id);
1259
1260     let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } =
1261         collector;
1262     return ModuleItems {
1263         submodules: submodules.into_boxed_slice(),
1264         items: items.into_boxed_slice(),
1265         trait_items: trait_items.into_boxed_slice(),
1266         impl_items: impl_items.into_boxed_slice(),
1267         foreign_items: foreign_items.into_boxed_slice(),
1268     };
1269
1270     struct ModuleCollector<'tcx> {
1271         tcx: TyCtxt<'tcx>,
1272         submodules: Vec<LocalDefId>,
1273         items: Vec<ItemId>,
1274         trait_items: Vec<TraitItemId>,
1275         impl_items: Vec<ImplItemId>,
1276         foreign_items: Vec<ForeignItemId>,
1277     }
1278
1279     impl<'hir> Visitor<'hir> for ModuleCollector<'hir> {
1280         type NestedFilter = nested_filter::All;
1281
1282         fn nested_visit_map(&mut self) -> Self::Map {
1283             self.tcx.hir()
1284         }
1285
1286         fn visit_item(&mut self, item: &'hir Item<'hir>) {
1287             self.items.push(item.item_id());
1288             if let ItemKind::Mod(..) = item.kind {
1289                 // If this declares another module, do not recurse inside it.
1290                 self.submodules.push(item.def_id);
1291             } else {
1292                 intravisit::walk_item(self, item)
1293             }
1294         }
1295
1296         fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1297             self.trait_items.push(item.trait_item_id());
1298             intravisit::walk_trait_item(self, item)
1299         }
1300
1301         fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1302             self.impl_items.push(item.impl_item_id());
1303             intravisit::walk_impl_item(self, item)
1304         }
1305
1306         fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1307             self.foreign_items.push(item.foreign_item_id());
1308             intravisit::walk_foreign_item(self, item)
1309         }
1310     }
1311 }