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