rustc_middle/hir/
map.rs

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