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