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