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