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