rustc_middle/hir/
map.rs

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