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