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