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