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