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