]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/mod.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[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::hygiene::MacroKind;
18 use rustc_span::source_map::Spanned;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::Span;
21 use rustc_target::spec::abi::Abi;
22 use std::collections::VecDeque;
23
24 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
25     match node {
26         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
27         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
28         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
29         Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. })
30         | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => {
31             Some(fn_decl)
32         }
33         _ => None,
34     }
35 }
36
37 pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
38     match &node {
39         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
40         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
41         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
42         _ => None,
43     }
44 }
45
46 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
47     match node {
48         Node::Item(Item {
49             kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
50             ..
51         })
52         | Node::TraitItem(TraitItem {
53             kind:
54                 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
55             ..
56         })
57         | Node::ImplItem(ImplItem {
58             kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
59             ..
60         })
61         | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
62
63         Node::AnonConst(constant) => Some(constant.body),
64
65         _ => None,
66     }
67 }
68
69 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
70     match associated_body(node) {
71         Some(b) => b.hir_id == hir_id,
72         None => false,
73     }
74 }
75
76 #[derive(Copy, Clone)]
77 pub struct Map<'hir> {
78     pub(super) tcx: TyCtxt<'hir>,
79 }
80
81 /// An iterator that walks up the ancestor tree of a given `HirId`.
82 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
83 pub struct ParentHirIterator<'hir> {
84     current_id: HirId,
85     map: Map<'hir>,
86 }
87
88 impl<'hir> Iterator for ParentHirIterator<'hir> {
89     type Item = (HirId, Node<'hir>);
90
91     fn next(&mut self) -> Option<Self::Item> {
92         if self.current_id == CRATE_HIR_ID {
93             return None;
94         }
95         loop {
96             // There are nodes that do not have entries, so we need to skip them.
97             let parent_id = self.map.get_parent_node(self.current_id);
98
99             if parent_id == self.current_id {
100                 self.current_id = CRATE_HIR_ID;
101                 return None;
102             }
103
104             self.current_id = parent_id;
105             if let Some(node) = self.map.find(parent_id) {
106                 return Some((parent_id, node));
107             }
108             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
109         }
110     }
111 }
112
113 /// An iterator that walks up the ancestor tree of a given `HirId`.
114 /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
115 pub struct ParentOwnerIterator<'hir> {
116     current_id: HirId,
117     map: Map<'hir>,
118 }
119
120 impl<'hir> Iterator for ParentOwnerIterator<'hir> {
121     type Item = (LocalDefId, OwnerNode<'hir>);
122
123     fn next(&mut self) -> Option<Self::Item> {
124         if self.current_id.local_id.index() != 0 {
125             self.current_id.local_id = ItemLocalId::new(0);
126             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
127                 return Some((self.current_id.owner, node.node));
128             }
129         }
130         if self.current_id == CRATE_HIR_ID {
131             return None;
132         }
133         loop {
134             // There are nodes that do not have entries, so we need to skip them.
135             let parent_id = self.map.def_key(self.current_id.owner).parent;
136
137             let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| {
138                 let def_id = LocalDefId { local_def_index };
139                 self.map.local_def_id_to_hir_id(def_id).owner
140             });
141             self.current_id = HirId::make_owner(parent_id);
142
143             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
144             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
145                 return Some((self.current_id.owner, node.node));
146             }
147         }
148     }
149 }
150
151 impl<'hir> Map<'hir> {
152     pub fn krate(self) -> &'hir Crate<'hir> {
153         self.tcx.hir_crate(())
154     }
155
156     pub fn root_module(self) -> &'hir Mod<'hir> {
157         match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) {
158             Some(OwnerNode::Crate(item)) => item,
159             _ => bug!(),
160         }
161     }
162
163     pub fn items(self) -> impl Iterator<Item = &'hir Item<'hir>> + 'hir {
164         let krate = self.krate();
165         krate.owners.iter().filter_map(|owner| match owner.as_owner()?.node() {
166             OwnerNode::Item(item) => Some(item),
167             _ => None,
168         })
169     }
170
171     pub fn def_key(self, def_id: LocalDefId) -> DefKey {
172         // Accessing the DefKey is ok, since it is part of DefPathHash.
173         self.tcx.untracked_resolutions.definitions.def_key(def_id)
174     }
175
176     pub fn def_path_from_hir_id(self, id: HirId) -> Option<DefPath> {
177         self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
178     }
179
180     pub fn def_path(self, def_id: LocalDefId) -> DefPath {
181         // Accessing the DefPath is ok, since it is part of DefPathHash.
182         self.tcx.untracked_resolutions.definitions.def_path(def_id)
183     }
184
185     #[inline]
186     pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
187         // Accessing the DefPathHash is ok, it is incr. comp. stable.
188         self.tcx.untracked_resolutions.definitions.def_path_hash(def_id)
189     }
190
191     #[inline]
192     pub fn local_def_id(self, hir_id: HirId) -> LocalDefId {
193         self.opt_local_def_id(hir_id).unwrap_or_else(|| {
194             bug!(
195                 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
196                 hir_id,
197                 self.find(hir_id)
198             )
199         })
200     }
201
202     #[inline]
203     pub fn opt_local_def_id(self, hir_id: HirId) -> Option<LocalDefId> {
204         if hir_id.local_id == ItemLocalId::new(0) {
205             Some(hir_id.owner)
206         } else {
207             self.tcx
208                 .hir_owner_nodes(hir_id.owner)
209                 .as_owner()?
210                 .local_id_to_def_id
211                 .get(&hir_id.local_id)
212                 .copied()
213         }
214     }
215
216     #[inline]
217     pub fn local_def_id_to_hir_id(self, def_id: LocalDefId) -> HirId {
218         self.tcx.local_def_id_to_hir_id(def_id)
219     }
220
221     pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> + 'hir {
222         // Create a dependency to the crate to be sure we reexcute this when the amount of
223         // definitions change.
224         self.tcx.ensure().hir_crate(());
225         self.tcx.untracked_resolutions.definitions.iter_local_def_id()
226     }
227
228     pub fn opt_def_kind(self, local_def_id: LocalDefId) -> Option<DefKind> {
229         let hir_id = self.local_def_id_to_hir_id(local_def_id);
230         let def_kind = match self.find(hir_id)? {
231             Node::Item(item) => match item.kind {
232                 ItemKind::Static(..) => DefKind::Static,
233                 ItemKind::Const(..) => DefKind::Const,
234                 ItemKind::Fn(..) => DefKind::Fn,
235                 ItemKind::Macro(..) => DefKind::Macro(MacroKind::Bang),
236                 ItemKind::Mod(..) => DefKind::Mod,
237                 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
238                 ItemKind::TyAlias(..) => DefKind::TyAlias,
239                 ItemKind::Enum(..) => DefKind::Enum,
240                 ItemKind::Struct(..) => DefKind::Struct,
241                 ItemKind::Union(..) => DefKind::Union,
242                 ItemKind::Trait(..) => DefKind::Trait,
243                 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
244                 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
245                 ItemKind::Use(..) => DefKind::Use,
246                 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
247                 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
248                 ItemKind::Impl { .. } => DefKind::Impl,
249             },
250             Node::ForeignItem(item) => match item.kind {
251                 ForeignItemKind::Fn(..) => DefKind::Fn,
252                 ForeignItemKind::Static(..) => DefKind::Static,
253                 ForeignItemKind::Type => DefKind::ForeignTy,
254             },
255             Node::TraitItem(item) => match item.kind {
256                 TraitItemKind::Const(..) => DefKind::AssocConst,
257                 TraitItemKind::Fn(..) => DefKind::AssocFn,
258                 TraitItemKind::Type(..) => DefKind::AssocTy,
259             },
260             Node::ImplItem(item) => match item.kind {
261                 ImplItemKind::Const(..) => DefKind::AssocConst,
262                 ImplItemKind::Fn(..) => DefKind::AssocFn,
263                 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
264             },
265             Node::Variant(_) => DefKind::Variant,
266             Node::Ctor(variant_data) => {
267                 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
268                 assert_ne!(variant_data.ctor_hir_id(), None);
269
270                 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
271                     Some(Node::Item(..)) => def::CtorOf::Struct,
272                     Some(Node::Variant(..)) => def::CtorOf::Variant,
273                     _ => unreachable!(),
274                 };
275                 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
276             }
277             Node::AnonConst(_) => {
278                 let inline = match self.find(self.get_parent_node(hir_id)) {
279                     Some(Node::Expr(&Expr {
280                         kind: ExprKind::ConstBlock(ref anon_const), ..
281                     })) if anon_const.hir_id == hir_id => true,
282                     _ => false,
283                 };
284                 if inline { DefKind::InlineConst } else { DefKind::AnonConst }
285             }
286             Node::Field(_) => DefKind::Field,
287             Node::Expr(expr) => match expr.kind {
288                 ExprKind::Closure(.., None) => DefKind::Closure,
289                 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
290                 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
291             },
292             Node::GenericParam(param) => match param.kind {
293                 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
294                 GenericParamKind::Type { .. } => DefKind::TyParam,
295                 GenericParamKind::Const { .. } => DefKind::ConstParam,
296             },
297             Node::Crate(_) => DefKind::Mod,
298             Node::Stmt(_)
299             | Node::PathSegment(_)
300             | Node::Ty(_)
301             | Node::Infer(_)
302             | Node::TraitRef(_)
303             | Node::Pat(_)
304             | Node::Binding(_)
305             | Node::Local(_)
306             | Node::Param(_)
307             | Node::Arm(_)
308             | Node::Lifetime(_)
309             | Node::Visibility(_)
310             | Node::Block(_) => return None,
311         };
312         Some(def_kind)
313     }
314
315     pub fn def_kind(self, local_def_id: LocalDefId) -> DefKind {
316         self.opt_def_kind(local_def_id)
317             .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
318     }
319
320     pub fn find_parent_node(self, id: HirId) -> Option<HirId> {
321         if id.local_id == ItemLocalId::from_u32(0) {
322             Some(self.tcx.hir_owner_parent(id.owner))
323         } else {
324             let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
325             let node = owner.nodes[id.local_id].as_ref()?;
326             let hir_id = HirId { owner: id.owner, local_id: node.parent };
327             Some(hir_id)
328         }
329     }
330
331     pub fn get_parent_node(self, hir_id: HirId) -> HirId {
332         self.find_parent_node(hir_id).unwrap()
333     }
334
335     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
336     pub fn find(self, id: HirId) -> Option<Node<'hir>> {
337         if id.local_id == ItemLocalId::from_u32(0) {
338             let owner = self.tcx.hir_owner(id.owner)?;
339             Some(owner.node.into())
340         } else {
341             let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
342             let node = owner.nodes[id.local_id].as_ref()?;
343             Some(node.node)
344         }
345     }
346
347     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
348     #[inline]
349     pub fn find_by_def_id(self, id: LocalDefId) -> Option<Node<'hir>> {
350         self.find(self.local_def_id_to_hir_id(id))
351     }
352
353     /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
354     pub fn get(self, id: HirId) -> Node<'hir> {
355         self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
356     }
357
358     /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
359     #[inline]
360     pub fn get_by_def_id(self, id: LocalDefId) -> Node<'hir> {
361         self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id))
362     }
363
364     pub fn get_if_local(self, id: DefId) -> Option<Node<'hir>> {
365         id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
366     }
367
368     pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> {
369         let node = self.tcx.hir_owner(id)?;
370         match node.node {
371             OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics),
372             OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics),
373             OwnerNode::Item(Item {
374                 kind:
375                     ItemKind::Fn(_, generics, _)
376                     | ItemKind::TyAlias(_, generics)
377                     | ItemKind::Enum(_, generics)
378                     | ItemKind::Struct(_, generics)
379                     | ItemKind::Union(_, generics)
380                     | ItemKind::Trait(_, _, generics, ..)
381                     | ItemKind::TraitAlias(generics, _)
382                     | ItemKind::Impl(Impl { generics, .. }),
383                 ..
384             }) => Some(generics),
385             _ => None,
386         }
387     }
388
389     pub fn item(self, id: ItemId) -> &'hir Item<'hir> {
390         self.tcx.hir_owner(id.def_id).unwrap().node.expect_item()
391     }
392
393     pub fn trait_item(self, id: TraitItemId) -> &'hir TraitItem<'hir> {
394         self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item()
395     }
396
397     pub fn impl_item(self, id: ImplItemId) -> &'hir ImplItem<'hir> {
398         self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item()
399     }
400
401     pub fn foreign_item(self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
402         self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item()
403     }
404
405     pub fn body(self, id: BodyId) -> &'hir Body<'hir> {
406         self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id]
407     }
408
409     pub fn fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
410         if let Some(node) = self.find(hir_id) {
411             fn_decl(node)
412         } else {
413             bug!("no node for hir_id `{}`", hir_id)
414         }
415     }
416
417     pub fn fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
418         if let Some(node) = self.find(hir_id) {
419             fn_sig(node)
420         } else {
421             bug!("no node for hir_id `{}`", hir_id)
422         }
423     }
424
425     pub fn enclosing_body_owner(self, hir_id: HirId) -> HirId {
426         for (parent, _) in self.parent_iter(hir_id) {
427             if let Some(body) = self.maybe_body_owned_by(parent) {
428                 return self.body_owner(body);
429             }
430         }
431
432         bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
433     }
434
435     /// Returns the `HirId` that corresponds to the definition of
436     /// which this is the body of, i.e., a `fn`, `const` or `static`
437     /// item (possibly associated), a closure, or a `hir::AnonConst`.
438     pub fn body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
439         let parent = self.get_parent_node(hir_id);
440         assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
441         parent
442     }
443
444     pub fn body_owner_def_id(self, id: BodyId) -> LocalDefId {
445         self.local_def_id(self.body_owner(id))
446     }
447
448     /// Given a `HirId`, returns the `BodyId` associated with it,
449     /// if the node is a body owner, otherwise returns `None`.
450     pub fn maybe_body_owned_by(self, hir_id: HirId) -> Option<BodyId> {
451         self.find(hir_id).map(associated_body).flatten()
452     }
453
454     /// Given a body owner's id, returns the `BodyId` associated with it.
455     pub fn body_owned_by(self, id: HirId) -> BodyId {
456         self.maybe_body_owned_by(id).unwrap_or_else(|| {
457             span_bug!(
458                 self.span(id),
459                 "body_owned_by: {} has no associated body",
460                 self.node_to_string(id)
461             );
462         })
463     }
464
465     pub fn body_param_names(self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
466         self.body(id).params.iter().map(|arg| match arg.pat.kind {
467             PatKind::Binding(_, _, ident, _) => ident,
468             _ => Ident::empty(),
469         })
470     }
471
472     /// Returns the `BodyOwnerKind` of this `LocalDefId`.
473     ///
474     /// Panics if `LocalDefId` does not have an associated body.
475     pub fn body_owner_kind(self, id: HirId) -> BodyOwnerKind {
476         match self.get(id) {
477             Node::Item(&Item { kind: ItemKind::Const(..), .. })
478             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
479             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
480             | Node::AnonConst(_) => BodyOwnerKind::Const,
481             Node::Ctor(..)
482             | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
483             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
484             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
485             Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
486             Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
487             node => bug!("{:#?} is not a body node", node),
488         }
489     }
490
491     /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
492     ///
493     /// Panics if `LocalDefId` does not have an associated body.
494     ///
495     /// This should only be used for determining the context of a body, a return
496     /// value of `Some` does not always suggest that the owner of the body is `const`,
497     /// just that it has to be checked as if it were.
498     pub fn body_const_context(self, did: LocalDefId) -> Option<ConstContext> {
499         let hir_id = self.local_def_id_to_hir_id(did);
500         let ccx = match self.body_owner_kind(hir_id) {
501             BodyOwnerKind::Const => ConstContext::Const,
502             BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
503
504             BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
505             BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
506             BodyOwnerKind::Fn
507                 if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) =>
508             {
509                 ConstContext::ConstFn
510             }
511             BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
512         };
513
514         Some(ccx)
515     }
516
517     /// Returns an iterator of the `DefId`s for all body-owners in this
518     /// crate. If you would prefer to iterate over the bodies
519     /// themselves, you can do `self.hir().krate().body_ids.iter()`.
520     pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + 'hir {
521         self.krate()
522             .owners
523             .iter_enumerated()
524             .flat_map(move |(owner, owner_info)| {
525                 let bodies = &owner_info.as_owner()?.nodes.bodies;
526                 Some(bodies.iter().map(move |&(local_id, _)| {
527                     let hir_id = HirId { owner, local_id };
528                     let body_id = BodyId { hir_id };
529                     self.body_owner_def_id(body_id)
530                 }))
531             })
532             .flatten()
533     }
534
535     pub fn par_body_owners<F: Fn(LocalDefId) + Sync + Send>(self, f: F) {
536         use rustc_data_structures::sync::{par_iter, ParallelIterator};
537         #[cfg(parallel_compiler)]
538         use rustc_rayon::iter::IndexedParallelIterator;
539
540         par_iter(&self.krate().owners.raw).enumerate().for_each(|(owner, owner_info)| {
541             let owner = LocalDefId::new(owner);
542             if let MaybeOwner::Owner(owner_info) = owner_info {
543                 par_iter(owner_info.nodes.bodies.range(..)).for_each(|(local_id, _)| {
544                     let hir_id = HirId { owner, local_id: *local_id };
545                     let body_id = BodyId { hir_id };
546                     f(self.body_owner_def_id(body_id))
547                 })
548             }
549         });
550     }
551
552     pub fn ty_param_owner(self, id: HirId) -> LocalDefId {
553         match self.get(id) {
554             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
555                 id.expect_owner()
556             }
557             Node::GenericParam(_) => self.get_parent_item(id),
558             _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
559         }
560     }
561
562     pub fn ty_param_name(self, id: HirId) -> Symbol {
563         match self.get(id) {
564             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
565                 kw::SelfUpper
566             }
567             Node::GenericParam(param) => param.name.ident().name,
568             _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
569         }
570     }
571
572     pub fn trait_impls(self, trait_did: DefId) -> &'hir [LocalDefId] {
573         self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
574     }
575
576     /// Gets the attributes on the crate. This is preferable to
577     /// invoking `krate.attrs` because it registers a tighter
578     /// dep-graph access.
579     pub fn krate_attrs(self) -> &'hir [ast::Attribute] {
580         self.attrs(CRATE_HIR_ID)
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 }