rustc_middle/hir/
map.rs

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