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