Skip to main content

rustc_middle/hir/
mod.rs

1//! HIR datatypes. See the [rustc dev guide] for more info.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
4
5pub mod map;
6pub mod nested_filter;
7pub mod place;
8
9use std::sync::Arc;
10
11use rustc_ast::{self as ast};
12use rustc_data_structures::fingerprint::Fingerprint;
13use rustc_data_structures::fx::FxIndexSet;
14use rustc_data_structures::sorted_map::SortedMap;
15use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
16use rustc_data_structures::steal::Steal;
17use rustc_data_structures::sync::{DynSend, DynSync, try_par_for_each_in};
18use rustc_hir::def::{DefKind, Res};
19use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
20use rustc_hir::lints::DelayedLint;
21use rustc_hir::*;
22use rustc_index::IndexVec;
23use rustc_macros::{Decodable, Encodable, HashStable};
24use rustc_span::{ErrorGuaranteed, ExpnId, Span};
25
26use crate::query::Providers;
27use crate::ty::{ResolverAstLowering, TyCtxt};
28
29/// The top-level data structure that stores the entire contents of
30/// the crate currently being compiled.
31///
32/// For more details, see the [rustc dev guide].
33///
34/// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
35#[derive(#[automatically_derived]
impl<'hir> ::core::fmt::Debug for Crate<'hir> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "Crate",
            "owners", &self.owners, "delayed_ids", &self.delayed_ids,
            "delayed_resolver", &self.delayed_resolver, "opt_hir_hash",
            &&self.opt_hir_hash)
    }
}Debug)]
36pub struct Crate<'hir> {
37    // This field is private by intention, access it through `owner` method.
38    owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
39    // Ids of delayed AST owners which are lowered through `lower_delayed_owner` query.
40    pub delayed_ids: FxIndexSet<LocalDefId>,
41    // The resolver and AST crate which are set in the end of the `hir_crate` query
42    // and then stolen and dropped in `force_delayed_owners_lowering`.
43    pub delayed_resolver: Steal<(ResolverAstLowering<'hir>, Arc<ast::Crate>)>,
44    // Only present when incr. comp. is enabled.
45    pub opt_hir_hash: Option<Fingerprint>,
46}
47
48impl<'hir> Crate<'hir> {
49    pub fn new(
50        owners: IndexVec<LocalDefId, MaybeOwner<'hir>>,
51        delayed_ids: FxIndexSet<LocalDefId>,
52        delayed_resolver: Steal<(ResolverAstLowering<'hir>, Arc<ast::Crate>)>,
53        opt_hir_hash: Option<Fingerprint>,
54    ) -> Crate<'hir> {
55        Crate { owners, delayed_ids, delayed_resolver, opt_hir_hash }
56    }
57
58    /// Serves as an entry point for getting `MaybeOwner`. As owner can either be in
59    /// `owners` of `hir_crate` or it can be delayed AST owner (i.e., delegations)
60    /// we need to firstly check in `hir_crate` and then delayed AST owners.
61    /// This method can be invoked when not all delayed AST owners are lowered.
62    pub fn owner(&self, tcx: TyCtxt<'hir>, def_id: LocalDefId) -> MaybeOwner<'hir> {
63        // Delayed LocalDefId can be in `self.owners` if there exists non-delayed LocalDefId
64        // which is greater than delayed LocalDefId, we use IndexVec for owners,
65        // so we will call ensure_contains_elem which will grow it.
66        if let Some(owner) = self.owners.get(def_id)
67            && (self.delayed_ids.is_empty() || !#[allow(non_exhaustive_omitted_patterns)] match owner {
    MaybeOwner::Phantom => true,
    _ => false,
}matches!(owner, MaybeOwner::Phantom))
68        {
69            return *owner;
70        }
71
72        if self.delayed_ids.contains(&def_id) {
73            tcx.ensure_done().lower_delayed_owner(def_id);
74        }
75
76        tcx.delayed_owner(def_id)
77    }
78}
79
80impl<HirCtx: HashStableContext> HashStable<HirCtx> for Crate<'_> {
81    fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) {
82        let Crate { opt_hir_hash, .. } = self;
83        opt_hir_hash.unwrap().hash_stable(hcx, hasher)
84    }
85}
86
87/// Gather the LocalDefId for each item-like within a module, including items contained within
88/// bodies. The Ids are in visitor order. This is used to partition a pass between modules.
89#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleItems {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["add_root", "submodules", "free_items", "trait_items",
                        "impl_items", "foreign_items", "opaques", "body_owners",
                        "nested_bodies", "delayed_lint_items", "eiis"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.add_root, &self.submodules, &self.free_items,
                        &self.trait_items, &self.impl_items, &self.foreign_items,
                        &self.opaques, &self.body_owners, &self.nested_bodies,
                        &self.delayed_lint_items, &&self.eiis];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "ModuleItems",
            names, values)
    }
}Debug, const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for ModuleItems {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    ModuleItems {
                        add_root: ref __binding_0,
                        submodules: ref __binding_1,
                        free_items: ref __binding_2,
                        trait_items: ref __binding_3,
                        impl_items: ref __binding_4,
                        foreign_items: ref __binding_5,
                        opaques: ref __binding_6,
                        body_owners: ref __binding_7,
                        nested_bodies: ref __binding_8,
                        delayed_lint_items: ref __binding_9,
                        eiis: ref __binding_10 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                        { __binding_2.hash_stable(__hcx, __hasher); }
                        { __binding_3.hash_stable(__hcx, __hasher); }
                        { __binding_4.hash_stable(__hcx, __hasher); }
                        { __binding_5.hash_stable(__hcx, __hasher); }
                        { __binding_6.hash_stable(__hcx, __hasher); }
                        { __binding_7.hash_stable(__hcx, __hasher); }
                        { __binding_8.hash_stable(__hcx, __hasher); }
                        { __binding_9.hash_stable(__hcx, __hasher); }
                        { __binding_10.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for ModuleItems {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    ModuleItems {
                        add_root: ref __binding_0,
                        submodules: ref __binding_1,
                        free_items: ref __binding_2,
                        trait_items: ref __binding_3,
                        impl_items: ref __binding_4,
                        foreign_items: ref __binding_5,
                        opaques: ref __binding_6,
                        body_owners: ref __binding_7,
                        nested_bodies: ref __binding_8,
                        delayed_lint_items: ref __binding_9,
                        eiis: ref __binding_10 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_4,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_5,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_6,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_7,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_8,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_9,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_10,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for ModuleItems {
            fn decode(__decoder: &mut __D) -> Self {
                ModuleItems {
                    add_root: ::rustc_serialize::Decodable::decode(__decoder),
                    submodules: ::rustc_serialize::Decodable::decode(__decoder),
                    free_items: ::rustc_serialize::Decodable::decode(__decoder),
                    trait_items: ::rustc_serialize::Decodable::decode(__decoder),
                    impl_items: ::rustc_serialize::Decodable::decode(__decoder),
                    foreign_items: ::rustc_serialize::Decodable::decode(__decoder),
                    opaques: ::rustc_serialize::Decodable::decode(__decoder),
                    body_owners: ::rustc_serialize::Decodable::decode(__decoder),
                    nested_bodies: ::rustc_serialize::Decodable::decode(__decoder),
                    delayed_lint_items: ::rustc_serialize::Decodable::decode(__decoder),
                    eiis: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
90pub struct ModuleItems {
91    /// Whether this represents the whole crate, in which case we need to add `CRATE_OWNER_ID` to
92    /// the iterators if we want to account for the crate root.
93    add_root: bool,
94    submodules: Box<[OwnerId]>,
95    free_items: Box<[ItemId]>,
96    trait_items: Box<[TraitItemId]>,
97    impl_items: Box<[ImplItemId]>,
98    foreign_items: Box<[ForeignItemId]>,
99    opaques: Box<[LocalDefId]>,
100    body_owners: Box<[LocalDefId]>,
101    nested_bodies: Box<[LocalDefId]>,
102    // only filled with hir_crate_items, not with hir_module_items
103    delayed_lint_items: Box<[OwnerId]>,
104
105    /// Statics and functions with an `EiiImpls` or `EiiExternTarget` attribute
106    eiis: Box<[LocalDefId]>,
107}
108
109impl ModuleItems {
110    /// Returns all non-associated locally defined items in all modules.
111    ///
112    /// Note that this does *not* include associated items of `impl` blocks! It also does not
113    /// include foreign items. If you want to e.g. get all functions, use `definitions()` below.
114    ///
115    /// However, this does include the `impl` blocks themselves.
116    pub fn free_items(&self) -> impl Iterator<Item = ItemId> {
117        self.free_items.iter().copied()
118    }
119
120    pub fn trait_items(&self) -> impl Iterator<Item = TraitItemId> {
121        self.trait_items.iter().copied()
122    }
123
124    pub fn delayed_lint_items(&self) -> impl Iterator<Item = OwnerId> {
125        self.delayed_lint_items.iter().copied()
126    }
127
128    pub fn eiis(&self) -> impl Iterator<Item = LocalDefId> {
129        self.eiis.iter().copied()
130    }
131
132    /// Returns all items that are associated with some `impl` block (both inherent and trait impl
133    /// blocks).
134    pub fn impl_items(&self) -> impl Iterator<Item = ImplItemId> {
135        self.impl_items.iter().copied()
136    }
137
138    pub fn foreign_items(&self) -> impl Iterator<Item = ForeignItemId> {
139        self.foreign_items.iter().copied()
140    }
141
142    pub fn owners(&self) -> impl Iterator<Item = OwnerId> {
143        self.add_root
144            .then_some(CRATE_OWNER_ID)
145            .into_iter()
146            .chain(self.free_items.iter().map(|id| id.owner_id))
147            .chain(self.trait_items.iter().map(|id| id.owner_id))
148            .chain(self.impl_items.iter().map(|id| id.owner_id))
149            .chain(self.foreign_items.iter().map(|id| id.owner_id))
150    }
151
152    pub fn opaques(&self) -> impl Iterator<Item = LocalDefId> {
153        self.opaques.iter().copied()
154    }
155
156    /// Closures and inline consts
157    pub fn nested_bodies(&self) -> impl Iterator<Item = LocalDefId> {
158        self.nested_bodies.iter().copied()
159    }
160
161    pub fn definitions(&self) -> impl Iterator<Item = LocalDefId> {
162        self.owners().map(|id| id.def_id)
163    }
164
165    /// Closures and inline consts
166    pub fn par_nested_bodies(
167        &self,
168        f: impl Fn(LocalDefId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
169    ) -> Result<(), ErrorGuaranteed> {
170        try_par_for_each_in(&self.nested_bodies[..], |&&id| f(id))
171    }
172
173    pub fn par_items(
174        &self,
175        f: impl Fn(ItemId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
176    ) -> Result<(), ErrorGuaranteed> {
177        try_par_for_each_in(&self.free_items[..], |&&id| f(id))
178    }
179
180    pub fn par_trait_items(
181        &self,
182        f: impl Fn(TraitItemId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
183    ) -> Result<(), ErrorGuaranteed> {
184        try_par_for_each_in(&self.trait_items[..], |&&id| f(id))
185    }
186
187    pub fn par_impl_items(
188        &self,
189        f: impl Fn(ImplItemId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
190    ) -> Result<(), ErrorGuaranteed> {
191        try_par_for_each_in(&self.impl_items[..], |&&id| f(id))
192    }
193
194    pub fn par_foreign_items(
195        &self,
196        f: impl Fn(ForeignItemId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
197    ) -> Result<(), ErrorGuaranteed> {
198        try_par_for_each_in(&self.foreign_items[..], |&&id| f(id))
199    }
200
201    pub fn par_opaques(
202        &self,
203        f: impl Fn(LocalDefId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
204    ) -> Result<(), ErrorGuaranteed> {
205        try_par_for_each_in(&self.opaques[..], |&&id| f(id))
206    }
207}
208
209impl<'tcx> TyCtxt<'tcx> {
210    pub fn parent_module(self, id: HirId) -> LocalModDefId {
211        if !id.is_owner() && self.def_kind(id.owner) == DefKind::Mod {
212            LocalModDefId::new_unchecked(id.owner.def_id)
213        } else {
214            self.parent_module_from_def_id(id.owner.def_id)
215        }
216    }
217
218    pub fn parent_module_from_def_id(self, mut id: LocalDefId) -> LocalModDefId {
219        while let Some(parent) = self.opt_local_parent(id) {
220            id = parent;
221            if self.def_kind(id) == DefKind::Mod {
222                break;
223            }
224        }
225        LocalModDefId::new_unchecked(id)
226    }
227
228    /// Returns `true` if this is a foreign item (i.e., linked via `extern { ... }`).
229    pub fn is_foreign_item(self, def_id: impl Into<DefId>) -> bool {
230        self.opt_parent(def_id.into())
231            .is_some_and(|parent| #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(parent) {
    DefKind::ForeignMod => true,
    _ => false,
}matches!(self.def_kind(parent), DefKind::ForeignMod))
232    }
233
234    pub fn hash_owner_nodes(
235        self,
236        node: OwnerNode<'_>,
237        bodies: &SortedMap<ItemLocalId, &Body<'_>>,
238        attrs: &SortedMap<ItemLocalId, &[Attribute]>,
239        delayed_lints: &[DelayedLint],
240        define_opaque: Option<&[(Span, LocalDefId)]>,
241    ) -> Hashes {
242        if !self.needs_crate_hash() {
243            return Hashes {
244                opt_hash_including_bodies: None,
245                attrs_hash: None,
246                delayed_lints_hash: None,
247            };
248        }
249
250        self.with_stable_hashing_context(|mut hcx| {
251            let mut stable_hasher = StableHasher::new();
252            node.hash_stable(&mut hcx, &mut stable_hasher);
253            // Bodies are stored out of line, so we need to pull them explicitly in the hash.
254            bodies.hash_stable(&mut hcx, &mut stable_hasher);
255            let h1 = stable_hasher.finish();
256
257            let mut stable_hasher = StableHasher::new();
258            attrs.hash_stable(&mut hcx, &mut stable_hasher);
259
260            // Hash the defined opaque types, which are not present in the attrs.
261            define_opaque.hash_stable(&mut hcx, &mut stable_hasher);
262
263            let h2 = stable_hasher.finish();
264
265            // hash lints emitted during ast lowering
266            let mut stable_hasher = StableHasher::new();
267            delayed_lints.hash_stable(&mut hcx, &mut stable_hasher);
268            let h3 = stable_hasher.finish();
269
270            Hashes {
271                opt_hash_including_bodies: Some(h1),
272                attrs_hash: Some(h2),
273                delayed_lints_hash: Some(h3),
274            }
275        })
276    }
277
278    pub fn qpath_is_lang_item(self, qpath: QPath<'_>, lang_item: LangItem) -> bool {
279        self.qpath_lang_item(qpath) == Some(lang_item)
280    }
281
282    /// This does not use typeck results since this is intended to be used with generated code.
283    pub fn qpath_lang_item(self, qpath: QPath<'_>) -> Option<LangItem> {
284        if let QPath::Resolved(_, path) = qpath
285            && let Res::Def(_, def_id) = path.res
286        {
287            return self.lang_items().from_def_id(def_id);
288        }
289        None
290    }
291
292    /// Whether this expression constitutes a read of value of the type that
293    /// it evaluates to.
294    ///
295    /// This is used to determine if we should consider the block to diverge
296    /// if the expression evaluates to `!`, and if we should insert a `NeverToAny`
297    /// coercion for values of type `!`.
298    ///
299    /// This function generally returns `false` if the expression is a place
300    /// expression and the *parent* expression is the scrutinee of a match or
301    /// the pointee of an `&` addr-of expression, since both of those parent
302    /// expressions take a *place* and not a value.
303    pub fn expr_guaranteed_to_constitute_read_for_never(self, expr: &Expr<'_>) -> bool {
304        // We only care about place exprs. Anything else returns an immediate
305        // which would constitute a read. We don't care about distinguishing
306        // "syntactic" place exprs since if the base of a field projection is
307        // not a place then it would've been UB to read from it anyways since
308        // that constitutes a read.
309        if !expr.is_syntactic_place_expr() {
310            return true;
311        }
312
313        let parent_node = self.parent_hir_node(expr.hir_id);
314        match parent_node {
315            Node::Expr(parent_expr) => {
316                match parent_expr.kind {
317                    // Addr-of, field projections, and LHS of assignment don't constitute reads.
318                    // Assignment does call `drop_in_place`, though, but its safety
319                    // requirements are not the same.
320                    ExprKind::AddrOf(..) | ExprKind::Field(..) => false,
321
322                    // Place-preserving expressions only constitute reads if their
323                    // parent expression constitutes a read.
324                    ExprKind::Type(..) | ExprKind::UnsafeBinderCast(..) => {
325                        self.expr_guaranteed_to_constitute_read_for_never(parent_expr)
326                    }
327
328                    ExprKind::Assign(lhs, _, _) => {
329                        // Only the LHS does not constitute a read
330                        expr.hir_id != lhs.hir_id
331                    }
332
333                    // See note on `PatKind::Or` in `Pat::is_guaranteed_to_constitute_read_for_never`
334                    // for why this is `all`.
335                    ExprKind::Match(scrutinee, arms, _) => {
336                        match (&scrutinee.hir_id, &expr.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::None);
        }
    }
};assert_eq!(scrutinee.hir_id, expr.hir_id);
337                        arms.iter().all(|arm| arm.pat.is_guaranteed_to_constitute_read_for_never())
338                    }
339                    ExprKind::Let(LetExpr { init, pat, .. }) => {
340                        match (&init.hir_id, &expr.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::None);
        }
    }
};assert_eq!(init.hir_id, expr.hir_id);
341                        pat.is_guaranteed_to_constitute_read_for_never()
342                    }
343
344                    // Any expression child of these expressions constitute reads.
345                    ExprKind::Array(_)
346                    | ExprKind::Call(_, _)
347                    | ExprKind::Use(_, _)
348                    | ExprKind::MethodCall(_, _, _, _)
349                    | ExprKind::Tup(_)
350                    | ExprKind::Binary(_, _, _)
351                    | ExprKind::Unary(_, _)
352                    | ExprKind::Cast(_, _)
353                    | ExprKind::DropTemps(_)
354                    | ExprKind::If(_, _, _)
355                    | ExprKind::Closure(_)
356                    | ExprKind::Block(_, _)
357                    | ExprKind::AssignOp(_, _, _)
358                    | ExprKind::Index(_, _, _)
359                    | ExprKind::Break(_, _)
360                    | ExprKind::Ret(_)
361                    | ExprKind::Become(_)
362                    | ExprKind::InlineAsm(_)
363                    | ExprKind::Struct(_, _, _)
364                    | ExprKind::Repeat(_, _)
365                    | ExprKind::Yield(_, _) => true,
366
367                    // These expressions have no (direct) sub-exprs.
368                    ExprKind::ConstBlock(_)
369                    | ExprKind::Loop(_, _, _, _)
370                    | ExprKind::Lit(_)
371                    | ExprKind::Path(_)
372                    | ExprKind::Continue(_)
373                    | ExprKind::OffsetOf(_, _)
374                    | ExprKind::Err(_) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("no sub-expr expected for {0:?}", expr.kind)));
}unreachable!("no sub-expr expected for {:?}", expr.kind),
375                }
376            }
377
378            // If we have a subpattern that performs a read, we want to consider this
379            // to diverge for compatibility to support something like `let x: () = *never_ptr;`.
380            Node::LetStmt(LetStmt { init: Some(target), pat, .. }) => {
381                match (&target.hir_id, &expr.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::None);
        }
    }
};assert_eq!(target.hir_id, expr.hir_id);
382                pat.is_guaranteed_to_constitute_read_for_never()
383            }
384
385            // These nodes (if they have a sub-expr) do constitute a read.
386            Node::Block(_)
387            | Node::Arm(_)
388            | Node::ExprField(_)
389            | Node::AnonConst(_)
390            | Node::ConstBlock(_)
391            | Node::ConstArg(_)
392            | Node::Stmt(_)
393            | Node::Item(Item { kind: ItemKind::Const(..) | ItemKind::Static(..), .. })
394            | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. })
395            | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => true,
396
397            Node::TyPat(_) | Node::Pat(_) => {
398                self.dcx().span_delayed_bug(expr.span, "place expr not allowed in pattern");
399                true
400            }
401
402            // These nodes do not have direct sub-exprs.
403            Node::Param(_)
404            | Node::Item(_)
405            | Node::ForeignItem(_)
406            | Node::TraitItem(_)
407            | Node::ImplItem(_)
408            | Node::Variant(_)
409            | Node::Field(_)
410            | Node::PathSegment(_)
411            | Node::Ty(_)
412            | Node::AssocItemConstraint(_)
413            | Node::TraitRef(_)
414            | Node::PatField(_)
415            | Node::PatExpr(_)
416            | Node::LetStmt(_)
417            | Node::Synthetic
418            | Node::Err(_)
419            | Node::Ctor(_)
420            | Node::Lifetime(_)
421            | Node::GenericParam(_)
422            | Node::Crate(_)
423            | Node::Infer(_)
424            | Node::WherePredicate(_)
425            | Node::PreciseCapturingNonLifetimeArg(_)
426            | Node::ConstArgExprField(_)
427            | Node::OpaqueTy(_) => {
428                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("no sub-expr expected for {0:?}", parent_node)));
}unreachable!("no sub-expr expected for {parent_node:?}")
429            }
430        }
431    }
432
433    #[inline]
434    fn hir_owner_parent_impl(self, owner_id: OwnerId) -> HirId {
435        self.opt_local_parent(owner_id.def_id).map_or(CRATE_HIR_ID, |parent_def_id| {
436            let parent_owner_id = self.local_def_id_to_hir_id(parent_def_id).owner;
437            HirId {
438                owner: parent_owner_id,
439                local_id: self
440                    .hir_crate(())
441                    .owner(self, parent_owner_id.def_id)
442                    .unwrap()
443                    .parenting
444                    .get(&owner_id.def_id)
445                    .copied()
446                    .unwrap_or(ItemLocalId::ZERO),
447            }
448        })
449    }
450
451    /// Optimization of `hir_owner_parent` query as an inlined function
452    /// in case of non-incremental build. The query itself renamed to `hir_owner_parent_q`.
453    #[inline]
454    pub fn hir_owner_parent(self, owner_id: OwnerId) -> HirId {
455        if self.dep_graph.is_fully_enabled() {
456            self.hir_owner_parent_q(owner_id)
457        } else {
458            self.hir_owner_parent_impl(owner_id)
459        }
460    }
461}
462
463/// Hashes computed by [`TyCtxt::hash_owner_nodes`] if necessary.
464#[derive(#[automatically_derived]
impl ::core::clone::Clone for Hashes {
    #[inline]
    fn clone(&self) -> Hashes {
        let _: ::core::clone::AssertParamIsClone<Option<Fingerprint>>;
        let _: ::core::clone::AssertParamIsClone<Option<Fingerprint>>;
        let _: ::core::clone::AssertParamIsClone<Option<Fingerprint>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Hashes { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Hashes {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Hashes",
            "opt_hash_including_bodies", &self.opt_hash_including_bodies,
            "attrs_hash", &self.attrs_hash, "delayed_lints_hash",
            &&self.delayed_lints_hash)
    }
}Debug)]
465pub struct Hashes {
466    pub opt_hash_including_bodies: Option<Fingerprint>,
467    pub attrs_hash: Option<Fingerprint>,
468    pub delayed_lints_hash: Option<Fingerprint>,
469}
470
471pub fn provide(providers: &mut Providers) {
472    providers.hir_crate_items = map::hir_crate_items;
473    providers.crate_hash = map::crate_hash;
474    providers.hir_module_items = map::hir_module_items;
475    providers.local_def_id_to_hir_id = |tcx, def_id| match tcx.hir_crate(()).owner(tcx, def_id) {
476        MaybeOwner::Owner(_) => HirId::make_owner(def_id),
477        MaybeOwner::NonOwner(hir_id) => hir_id,
478        MaybeOwner::Phantom => crate::util::bug::bug_fmt(format_args!("No HirId for {0:?}", def_id))bug!("No HirId for {:?}", def_id),
479    };
480    providers.opt_hir_owner_nodes =
481        |tcx, id| tcx.hir_crate(()).owner(tcx, id).as_owner().map(|i| &i.nodes);
482    providers.hir_owner_parent_q = |tcx, owner_id| tcx.hir_owner_parent_impl(owner_id);
483    providers.hir_attr_map = |tcx, id| {
484        tcx.hir_crate(()).owner(tcx, id.def_id).as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs)
485    };
486    providers.opt_ast_lowering_delayed_lints =
487        |tcx, id| tcx.hir_crate(()).owner(tcx, id.def_id).as_owner().map(|o| &o.delayed_lints);
488    providers.def_span = |tcx, def_id| tcx.hir_span(tcx.local_def_id_to_hir_id(def_id));
489    providers.def_ident_span = |tcx, def_id| {
490        let hir_id = tcx.local_def_id_to_hir_id(def_id);
491        tcx.hir_opt_ident_span(hir_id)
492    };
493    providers.ty_span = |tcx, def_id| {
494        let node = tcx.hir_node_by_def_id(def_id);
495        match node.ty() {
496            Some(ty) => ty.span,
497            None => crate::util::bug::bug_fmt(format_args!("{0:?} doesn\'t have a type: {1:#?}",
        def_id, node))bug!("{def_id:?} doesn't have a type: {node:#?}"),
498        }
499    };
500    providers.fn_arg_idents = |tcx, def_id| {
501        let node = tcx.hir_node_by_def_id(def_id);
502        if let Some(body_id) = node.body_id() {
503            tcx.arena.alloc_from_iter(tcx.hir_body_param_idents(body_id))
504        } else if let Node::TraitItem(&TraitItem {
505            kind: TraitItemKind::Fn(_, TraitFn::Required(idents)),
506            ..
507        })
508        | Node::ForeignItem(&ForeignItem {
509            kind: ForeignItemKind::Fn(_, idents, _),
510            ..
511        }) = node
512        {
513            idents
514        } else {
515            crate::util::bug::span_bug_fmt(tcx.hir_span(tcx.local_def_id_to_hir_id(def_id)),
    format_args!("fn_arg_idents: unexpected item {0:?}", def_id));span_bug!(
516                tcx.hir_span(tcx.local_def_id_to_hir_id(def_id)),
517                "fn_arg_idents: unexpected item {:?}",
518                def_id
519            );
520        }
521    };
522    providers.all_local_trait_impls = |tcx, ()| &tcx.resolutions(()).trait_impls;
523    providers.local_trait_impls =
524        |tcx, trait_id| tcx.resolutions(()).trait_impls.get(&trait_id).map_or(&[], |xs| &xs[..]);
525    providers.expn_that_defined =
526        |tcx, id| tcx.resolutions(()).expn_that_defined.get(&id).copied().unwrap_or(ExpnId::root());
527    providers.in_scope_traits_map = |tcx, id| {
528        tcx.hir_crate(()).owner(tcx, id.def_id).as_owner().map(|owner_info| &owner_info.trait_map)
529    };
530}