Skip to main content

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