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