Skip to main content

rustc_middle/ty/
mod.rs

1//! Defines how the compiler represents types internally.
2//!
3//! Two important entities in this module are:
4//!
5//! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6//! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7//!
8//! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
9//!
10//! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12#![allow(rustc::usage_of_ty_tykind)]
13
14use std::cmp::Ordering;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ops::ControlFlow;
20use std::ptr::NonNull;
21use std::{assert_matches, fmt, iter, str};
22
23pub use adt::*;
24pub use assoc::*;
25pub use generic_args::{GenericArgKind, TermKind, *};
26pub use generics::*;
27pub use intrinsic::IntrinsicDef;
28use rustc_abi::{
29    Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, Size, VariantIdx,
30};
31use rustc_ast::{self as ast};
32pub use rustc_ast_ir::{Movability, Mutability, try_visit};
33use rustc_attr_ir::lang_items::LangItem;
34use rustc_attr_ir::{self as attr, find_attr};
35use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
36use rustc_data_structures::intern::Interned;
37use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
38use rustc_errors::{Diag, ErrorGuaranteed};
39use rustc_hir as hir;
40use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
41use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId};
42use rustc_index::bit_set::BitMatrix;
43use rustc_index::{IndexVec, static_assert_size};
44pub use rustc_lint_defs::RegisteredTools;
45use rustc_macros::{
46    BlobDecodable, Decodable, Encodable, StableHash, TyDecodable, TyEncodable, TypeFoldable,
47    TypeVisitable, extension,
48};
49use rustc_serialize::{Decodable, Encodable};
50use rustc_session::config::OptLevel;
51use rustc_span::def_id::{LocalModId, ModId};
52use rustc_span::hygiene::MacroKind;
53use rustc_span::{DUMMY_SP, ExpnKind, Ident, Span, Symbol, bug};
54use rustc_target::callconv::FnAbi;
55pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
56pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
57pub use rustc_type_ir::relate::VarianceDiagInfo;
58pub use rustc_type_ir::search_graph::RequiredDepth;
59pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind, VisibleForLeakCheck};
60pub use rustc_type_ir::*;
61use tracing::{debug, instrument};
62pub use vtable::*;
63
64pub use self::closure::{
65    BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
66    MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
67    UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
68    place_to_string_for_capture,
69};
70pub use self::consts::{
71    AliasConst, AliasConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult,
72    Expr, ExprKind, LitToConstInput, ScalarInt, SimdAlign, ValTree, ValTreeKindExt, Value,
73    const_lit_matches_ty,
74};
75pub use self::context::{
76    CtxtInterners, CurrentGcx, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
77};
78pub use self::fold::*;
79pub use self::instance::{Instance, InstanceKind, ReifyReason, ShimKind};
80pub(crate) use self::list::RawList;
81pub use self::list::{List, ListWithCachedTypeInfo};
82pub use self::opaque_types::OpaqueTypeKey;
83pub use self::pattern::{Pattern, PatternKind};
84pub use self::predicate::{
85    AliasTerm, AliasTermKind, ArgOutlivesClause, Clause, ClauseKind, CoercePredicate,
86    ExistentialPredicate, ExistentialPredicateStableCmpExt, ExistentialProjection,
87    ExistentialTraitRef, HostEffectClause, NormalizesTo, OutlivesClause, PolyCoercePredicate,
88    PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
89    PolyProjectionClause, PolyRegionOutlivesClause, PolySubtypePredicate, PolyTraitClause,
90    PolyTraitRef, PolyTypeOutlivesClause, Predicate, PredicateKind, ProjectionClause,
91    RegionConstraint, RegionEqPredicate, RegionOutlivesClause, SubtypePredicate, TraitClause,
92    TraitRef, TypeOutlivesClause,
93};
94pub use self::region::{
95    EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region, RegionKind, RegionVid,
96};
97pub use self::sty::{
98    Alias, AliasTy, AliasTyKind, Article, Binder, BoundConst, BoundRegion, BoundRegionKind,
99    BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig, CoroutineArgsExt, EarlyBinder,
100    FnSig, FnSigKind, FreeAliasTy, InherentAliasTy, InlineConstArgs, InlineConstArgsParts,
101    OpaqueAliasTy, ParamConst, ParamTy, PlaceholderConst, PlaceholderRegion, PlaceholderType,
102    PolyFnSig, ProjectionAliasTy, TyKind, TypeAndMut, TypingMode, TypingModeEqWrapper,
103    Unnormalized, UpvarArgs,
104};
105pub use self::trait_def::TraitDef;
106pub use self::typeck_results::{
107    CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
108    Rust2024IncompatiblePatInfo, SplattedDef, TypeckResults, UserType, UserTypeAnnotationIndex,
109    UserTypeKind,
110};
111use crate::diagnostics::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
112use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, MirPhase, SourceInfo};
113use crate::query::{IntoQueryKey, Providers};
114use crate::ty;
115use crate::ty::codec::{TyDecoder, TyEncoder};
116pub use crate::ty::diagnostics::*;
117use crate::ty::fast_reject::SimplifiedType;
118use crate::ty::layout::{FnAbiError, LayoutError};
119use crate::ty::print::{with_crate_prefix, with_no_trimmed_paths};
120use crate::ty::util::Discr;
121use crate::ty::walk::TypeWalker;
122
123pub mod abstract_const;
124pub mod adjustment;
125pub mod cast;
126pub mod codec;
127// FIXME(#159654): This should get deleted soon
128pub mod consts;
129pub mod error;
130pub mod fast_reject;
131pub mod inhabitedness;
132pub mod layout;
133pub mod normalize_erasing_regions;
134pub mod offload_meta;
135pub mod pattern;
136pub mod print;
137pub mod relate;
138pub mod significant_drop_order;
139pub mod sty;
140pub mod trait_def;
141pub mod typetree;
142pub mod util;
143pub mod vtable;
144
145mod adt;
146mod assoc;
147mod closure;
148mod context;
149mod diagnostics;
150mod elaborate_impl;
151mod erase_regions;
152mod fold;
153mod generic_args;
154mod generics;
155mod impls_ty;
156mod instance;
157mod intrinsic;
158mod list;
159mod opaque_types;
160mod predicate;
161mod region;
162mod structural_impls;
163mod typeck_results;
164mod visit;
165
166// Data types
167
168#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImplTraitHeader<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ImplTraitHeader<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplTraitHeader<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<ty::EarlyBinder<'tcx,
                ty::TraitRef<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<ImplPolarity>;
        let _: ::core::clone::AssertParamIsClone<hir::Safety>;
        let _: ::core::clone::AssertParamIsClone<hir::Constness>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ImplTraitHeader<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ImplTraitHeader", "trait_ref", &self.trait_ref, "polarity",
            &self.polarity, "safety", &self.safety, "constness",
            &&self.constness)
    }
}Debug, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ImplTraitHeader<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let ImplTraitHeader {
                        trait_ref: ref __binding_0,
                        polarity: ref __binding_1,
                        safety: ref __binding_2,
                        constness: ref __binding_3 } = *self;
                ::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);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ImplTraitHeader<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                ImplTraitHeader {
                    trait_ref: ::rustc_serialize::Decodable::decode(__decoder),
                    polarity: ::rustc_serialize::Decodable::decode(__decoder),
                    safety: ::rustc_serialize::Decodable::decode(__decoder),
                    constness: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            ImplTraitHeader<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ImplTraitHeader {
                        trait_ref: ref __binding_0,
                        polarity: ref __binding_1,
                        safety: ref __binding_2,
                        constness: ref __binding_3 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
169pub struct ImplTraitHeader<'tcx> {
170    pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
171    pub polarity: ImplPolarity,
172    pub safety: hir::Safety,
173    pub constness: hir::Constness,
174}
175
176impl<'tcx> ImplTraitHeader<'tcx> {
177    /// For trait impls, checks whether
178    /// * the type and trait only use generic lifetime arguments (and no concrete ones like `'static`), and
179    /// * uses any generic param (lifetime or type) only once.
180    ///
181    /// This is a pessimistic analysis, so it will reject alias types
182    /// and other types that may be actually ok. We can allow more in the future.
183    ///
184    /// Constants (associated or generic) are irrelevant for this analysis, as their value is neither
185    /// affected by lifetimes, nor do they affect lifetimes.
186    pub fn is_fully_generic_for_reflection(self) -> bool {
187        #[derive(#[automatically_derived]
impl ::core::default::Default for ParamFinder {
    #[inline]
    fn default() -> Self {
        ParamFinder { seen: ::core::default::Default::default() }
    }
}Default)]
188        struct ParamFinder {
189            seen: FxHashSet<u32>,
190        }
191
192        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
193            type Result = ControlFlow<()>;
194            fn visit_region(&mut self, r: Region<'tcx>) -> Self::Result {
195                match r.kind() {
196                    RegionKind::ReEarlyParam(param) => {
197                        if self.seen.insert(param.index) {
198                            ControlFlow::Continue(())
199                        } else {
200                            ControlFlow::Break(())
201                        }
202                    }
203                    RegionKind::ReBound(..) => ControlFlow::Continue(()),
204                    RegionKind::ReStatic | RegionKind::ReError(_) => ControlFlow::Break(()),
205                    RegionKind::ReVar(_)
206                    | RegionKind::RePlaceholder(_)
207                    | RegionKind::ReErased
208                    | RegionKind::ReLateParam(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected lifetime in impl: {0:?}", r), Location::caller())bug!("unexpected lifetime in impl: {r:?}"),
209                }
210            }
211
212            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
213                match t.kind() {
214                    TyKind::Param(p) => {
215                        // Reject using a parameter twice (e.g. in `Foo<T, T>`)
216                        if !self.seen.insert(p.index) {
217                            return ControlFlow::Break(());
218                        }
219                    }
220                    TyKind::Alias(..) => return ControlFlow::Break(()),
221                    _ => (),
222                }
223                t.super_visit_with(self)
224            }
225        }
226        self.trait_ref
227            .instantiate_identity()
228            .skip_norm_wip()
229            .visit_with(&mut ParamFinder::default())
230            .is_continue()
231    }
232}
233
234#[derive(#[automatically_derived]
impl ::core::marker::Copy for Asyncness { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Asyncness { }
#[automatically_derived]
impl ::core::clone::Clone for Asyncness {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Asyncness { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Asyncness {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Asyncness { }Eq, #[automatically_derived]
impl ::core::hash::Hash for Asyncness {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for Asyncness {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Asyncness::Yes => { 0usize }
                        Asyncness::No => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for Asyncness {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Asyncness::Yes }
                    1usize => { Asyncness::No }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Asyncness`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Asyncness {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self { Asyncness::Yes => {} Asyncness::No => {} }
            }
        }
    };StableHash, #[automatically_derived]
impl ::core::fmt::Debug for Asyncness {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Asyncness::Yes => "Yes", Asyncness::No => "No", })
    }
}Debug)]
235#[derive(const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Asyncness {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        Asyncness::Yes => { Asyncness::Yes }
                        Asyncness::No => { Asyncness::No }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    Asyncness::Yes => { Asyncness::Yes }
                    Asyncness::No => { Asyncness::No }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Asyncness {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self { Asyncness::Yes => {} Asyncness::No => {} }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, #[automatically_derived]
impl ::core::default::Default for Asyncness {
    #[inline]
    fn default() -> Self { Self::No }
}Default)]
236pub enum Asyncness {
237    Yes,
238    #[default]
239    No,
240}
241
242impl Asyncness {
243    pub fn is_async(self) -> bool {
244        #[allow(non_exhaustive_omitted_patterns)] match self {
    Asyncness::Yes => true,
    _ => false,
}matches!(self, Asyncness::Yes)
245    }
246}
247
248#[derive(#[automatically_derived]
impl<Id: ::core::clone::Clone> ::core::clone::Clone for Visibility<Id> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Public => Visibility::Public,
            Self::Restricted(__self_0) =>
                Visibility::Restricted(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<Id: ::core::fmt::Debug> ::core::fmt::Debug for Visibility<Id> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Public => ::core::fmt::Formatter::write_str(f, "Public"),
            Self::Restricted(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Restricted", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<Id: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
    Visibility<Id> {
}
#[automatically_derived]
impl<Id: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Visibility<Id> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Restricted(__self_0), Self::Restricted(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<Id: ::core::cmp::Eq> ::core::cmp::Eq for Visibility<Id> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Id>;
    }
}Eq, #[automatically_derived]
impl<Id: ::core::marker::Copy> ::core::marker::Copy for Visibility<Id> { }Copy, #[automatically_derived]
impl<Id: ::core::hash::Hash> ::core::hash::Hash for Visibility<Id> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Restricted(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, const _: () =
    {
        impl<Id, __E: ::rustc_span::SpanEncoder>
            ::rustc_serialize::Encodable<__E> for Visibility<Id> where
            Id: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Visibility::Public => { 0usize }
                        Visibility::Restricted(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    Visibility::Public => {}
                    Visibility::Restricted(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<Id, __D: ::rustc_span::BlobDecoder>
            ::rustc_serialize::Decodable<__D> for Visibility<Id> where
            Id: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Visibility::Public }
                    1usize => {
                        Visibility::Restricted(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Visibility`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };BlobDecodable, const _: () =
    {
        impl<Id> ::rustc_data_structures::stable_hash::StableHash for
            Visibility<Id> where
            Id: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    Visibility::Public => {}
                    Visibility::Restricted(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
249pub enum Visibility<Id = LocalModId> {
250    /// Visible everywhere (including in other crates).
251    Public,
252    /// Visible only in the given crate-local module.
253    Restricted(Id),
254}
255
256impl Visibility {
257    pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
258        match self {
259            ty::Visibility::Restricted(restricted_id) => {
260                if restricted_id.is_top_level_module() {
261                    "pub(crate)".to_string()
262                } else if restricted_id == tcx.parent_module_from_def_id(def_id) {
263                    "pub(self)".to_string()
264                } else {
265                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pub(in crate{0})",
                tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()))
    })format!(
266                        "pub(in crate{})",
267                        tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
268                    )
269                }
270            }
271            ty::Visibility::Public => "pub".to_string(),
272        }
273    }
274}
275
276#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RestrictionKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Unrestricted =>
                ::core::fmt::Formatter::write_str(f, "Unrestricted"),
            Self::Restricted(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Restricted", __self_0, &__self_1),
        }
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            RestrictionKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    RestrictionKind::Unrestricted => {}
                    RestrictionKind::Restricted(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RestrictionKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RestrictionKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Restricted(__self_0, __self_1),
                    Self::Restricted(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RestrictionKind { }
#[automatically_derived]
impl ::core::clone::Clone for RestrictionKind {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RestrictionKind { }Copy, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for RestrictionKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        RestrictionKind::Unrestricted => { 0usize }
                        RestrictionKind::Restricted(ref __binding_0,
                            ref __binding_1) => {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    RestrictionKind::Unrestricted => {}
                    RestrictionKind::Restricted(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for RestrictionKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { RestrictionKind::Unrestricted }
                    1usize => {
                        RestrictionKind::Restricted(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `RestrictionKind`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
277pub enum RestrictionKind {
278    Unrestricted,
279    Restricted(DefId, Span),
280}
281
282impl RestrictionKind {
283    /// Returns `true` if the behavior is allowed/unrestricted in the given module.
284    /// A value of `false` indicates that the behavior is prohibited.
285    pub fn is_allowed_in(self, module: DefId, tcx: TyCtxt<'_>) -> bool {
286        match self {
287            RestrictionKind::Unrestricted => true,
288            RestrictionKind::Restricted(restricted_to, _) => {
289                tcx.is_descendant_of(module, restricted_to)
290            }
291        }
292    }
293
294    /// Obtain the [`Span`] of the restriction. Panics if the restriction is unrestricted.
295    pub fn expect_span(self) -> Span {
296        match self {
297            RestrictionKind::Unrestricted => {
298                ::rustc_span::macros::bug_impl(None,
    format_args!("called `expect_span` on an unrestricted item"),
    Location::caller())bug!("called `expect_span` on an unrestricted item")
299            }
300            RestrictionKind::Restricted(_, span) => span,
301        }
302    }
303
304    /// Obtain the path of the restriction. If unrestricted, an empty string is returned.
305    pub fn restriction_path(self, tcx: TyCtxt<'_>) -> String {
306        match self {
307            RestrictionKind::Unrestricted => String::new(),
308            RestrictionKind::Restricted(restricted_to, _) => {
309                if restricted_to.krate == rustc_hir::def_id::LOCAL_CRATE {
310                    {
    let _guard = CratePrefixGuard::new();
    { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(restricted_to) }
}with_crate_prefix!(with_no_trimmed_paths!(tcx.def_path_str(restricted_to)))
311                } else {
312                    tcx.def_path_str(restricted_to.krate.as_mod_id())
313                }
314            }
315        }
316    }
317
318    /// Obtain the stricter restriction between `self` and `rhs`.
319    /// Panics if the restrictions do not reference the same crate.
320    pub fn stricter_of(self, rhs: Self, tcx: TyCtxt<'_>) -> Self {
321        match (self, rhs) {
322            (RestrictionKind::Unrestricted, r) | (r, RestrictionKind::Unrestricted) => r,
323            (
324                RestrictionKind::Restricted(left_did, _),
325                RestrictionKind::Restricted(right_did, _),
326            ) => {
327                if left_did.krate != right_did.krate {
328                    ::rustc_span::macros::bug_impl(None,
    format_args!("stricter_of: left and right restriction do not reference the same crate"),
    Location::caller());bug!("stricter_of: left and right restriction do not reference the same crate");
329                }
330                if tcx.is_descendant_of(left_did, right_did) { self } else { rhs }
331            }
332        }
333    }
334}
335
336#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ClosureSizeProfileData<'tcx>
    {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureSizeProfileData<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureSizeProfileData<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ClosureSizeProfileData", "before_feature_tys",
            &self.before_feature_tys, "after_feature_tys",
            &&self.after_feature_tys)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for
    ClosureSizeProfileData<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ClosureSizeProfileData<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.before_feature_tys == other.before_feature_tys &&
            self.after_feature_tys == other.after_feature_tys
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ClosureSizeProfileData<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ClosureSizeProfileData<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for ClosureSizeProfileData<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.before_feature_tys, state);
        ::core::hash::Hash::hash(&self.after_feature_tys, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ClosureSizeProfileData<'tcx>
            {
            fn encode(&self, __encoder: &mut __E) {
                let ClosureSizeProfileData {
                        before_feature_tys: ref __binding_0,
                        after_feature_tys: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ClosureSizeProfileData<'tcx>
            {
            fn decode(__decoder: &mut __D) -> Self {
                ClosureSizeProfileData {
                    before_feature_tys: ::rustc_serialize::Decodable::decode(__decoder),
                    after_feature_tys: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            ClosureSizeProfileData<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ClosureSizeProfileData {
                        before_feature_tys: ref __binding_0,
                        after_feature_tys: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
337#[derive(const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ClosureSizeProfileData<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ClosureSizeProfileData {
                            before_feature_tys: __binding_0,
                            after_feature_tys: __binding_1 } => {
                            ClosureSizeProfileData {
                                before_feature_tys: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                after_feature_tys: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ClosureSizeProfileData {
                        before_feature_tys: __binding_0,
                        after_feature_tys: __binding_1 } => {
                        ClosureSizeProfileData {
                            before_feature_tys: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            after_feature_tys: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ClosureSizeProfileData<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ClosureSizeProfileData {
                        before_feature_tys: ref __binding_0,
                        after_feature_tys: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
338pub struct ClosureSizeProfileData<'tcx> {
339    /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
340    pub before_feature_tys: Ty<'tcx>,
341    /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
342    pub after_feature_tys: Ty<'tcx>,
343}
344
345impl TyCtxt<'_> {
346    #[inline]
347    pub fn opt_parent(self, id: DefId) -> Option<DefId> {
348        self.def_key(id).parent.map(|index| DefId { index, ..id })
349    }
350
351    #[inline]
352    #[track_caller]
353    pub fn parent(self, id: DefId) -> DefId {
354        match self.opt_parent(id) {
355            Some(id) => id,
356            // not `unwrap_or_else` to avoid breaking caller tracking
357            None => ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} doesn\'t have a parent", id), Location::caller())bug!("{id:?} doesn't have a parent"),
358        }
359    }
360
361    #[inline]
362    #[track_caller]
363    pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
364        self.opt_parent(id.to_def_id()).map(DefId::expect_local)
365    }
366
367    #[inline]
368    #[track_caller]
369    pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
370        self.parent(id.into().to_def_id()).expect_local()
371    }
372
373    /// Compare def-ids based on their position in def-id tree, ancestor def-ids are considered
374    /// larger than descendant def-ids, and two different def-ids are considered unordered if
375    /// neither of them is an ancestor of the other.
376    pub fn def_id_partial_cmp(self, lhs: DefId, rhs: DefId) -> Option<Ordering> {
377        // Def-ids from different crates are always unordered.
378        if lhs.krate != rhs.krate {
379            return None;
380        }
381
382        // Def-ids of parent nodes are always created before def-ids of child nodes
383        // and have a smaller index, so we only need to search in one direction,
384        // either from lhs to rhs, or vice versa.
385        let search = |mut start: DefId, finish: DefId, ord| {
386            while start.index != finish.index {
387                match self.opt_parent(start) {
388                    Some(parent) => start.index = parent.index,
389                    None => return None,
390                }
391            }
392            Some(ord)
393        };
394        match lhs.index.cmp(&rhs.index) {
395            Ordering::Equal => Some(Ordering::Equal),
396            Ordering::Less => search(rhs, lhs, Ordering::Greater),
397            Ordering::Greater => search(lhs, rhs, Ordering::Less),
398        }
399    }
400
401    pub fn is_descendant_of(
402        self,
403        descendant: impl Into<DefId>,
404        ancestor: impl Into<DefId>,
405    ) -> bool {
406        #[allow(non_exhaustive_omitted_patterns)] match self.def_id_partial_cmp(descendant.into(),
        ancestor.into()) {
    Some(Ordering::Less | Ordering::Equal) => true,
    _ => false,
}matches!(
407            self.def_id_partial_cmp(descendant.into(), ancestor.into()),
408            Some(Ordering::Less | Ordering::Equal)
409        )
410    }
411}
412
413impl<Id> Visibility<Id> {
414    pub fn is_public(self) -> bool {
415        #[allow(non_exhaustive_omitted_patterns)] match self {
    Visibility::Public => true,
    _ => false,
}matches!(self, Visibility::Public)
416    }
417
418    pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
419        match self {
420            Visibility::Public => Visibility::Public,
421            Visibility::Restricted(id) => Visibility::Restricted(f(id)),
422        }
423    }
424}
425
426impl Visibility<LocalModId> {
427    pub fn to_mod_id(self) -> Visibility<ModId> {
428        self.map_id(LocalModId::to_mod_id)
429    }
430}
431
432impl<Id: Into<ModId>> Visibility<Id> {
433    /// Returns `true` if an item with this visibility is accessible from the given definition.
434    pub fn is_accessible_from(self, def_id: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
435        match self {
436            // Public items are visible everywhere.
437            Visibility::Public => true,
438            Visibility::Restricted(id) => tcx.is_descendant_of(def_id, id.into()),
439        }
440    }
441
442    pub fn partial_cmp(
443        self,
444        vis: Visibility<impl Into<ModId>>,
445        tcx: TyCtxt<'_>,
446    ) -> Option<Ordering> {
447        match (self, vis) {
448            (Visibility::Public, Visibility::Public) => Some(Ordering::Equal),
449            (Visibility::Public, Visibility::Restricted(_)) => Some(Ordering::Greater),
450            (Visibility::Restricted(_), Visibility::Public) => Some(Ordering::Less),
451            (Visibility::Restricted(lhs_id), Visibility::Restricted(rhs_id)) => {
452                let (lhs_id, rhs_id) = (lhs_id.into(), rhs_id.into());
453                tcx.def_id_partial_cmp(lhs_id.to_def_id(), rhs_id.to_def_id())
454            }
455        }
456    }
457}
458
459impl<Id: Into<ModId> + Debug + Copy> Visibility<Id> {
460    /// Returns `true` if this visibility is strictly larger than the given visibility.
461    #[track_caller]
462    pub fn greater_than(
463        self,
464        vis: Visibility<impl Into<ModId> + Debug + Copy>,
465        tcx: TyCtxt<'_>,
466    ) -> bool {
467        match self.partial_cmp(vis, tcx) {
468            Some(ord) => ord.is_gt(),
469            None => {
470                tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unordered visibilities: {0:?} and {1:?}",
                self, vis))
    })format!("unordered visibilities: {self:?} and {vis:?}"));
471                false
472            }
473        }
474    }
475}
476
477impl Visibility<ModId> {
478    pub fn expect_local(self) -> Visibility {
479        self.map_id(|id| id.expect_local())
480    }
481
482    /// Returns `true` if this item is visible anywhere in the local crate.
483    pub fn is_visible_locally(self) -> bool {
484        match self {
485            Visibility::Public => true,
486            Visibility::Restricted(mod_id) => mod_id.is_local(),
487        }
488    }
489}
490
491/// The crate variances map is computed during typeck and contains the
492/// variance of every item in the local crate. You should not use it
493/// directly, because to do so will make your pass dependent on the
494/// HIR of every item in the local crate. Instead, use
495/// `tcx.variances_of()` to get the variance for a *particular*
496/// item.
497#[derive(const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            CrateVariancesMap<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    CrateVariancesMap { variances: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CrateVariancesMap<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "CrateVariancesMap", "variances", &&self.variances)
    }
}Debug)]
498pub struct CrateVariancesMap<'tcx> {
499    /// For each item with generics, maps to a vector of the variance
500    /// of its generics. If an item has no generics, it will have no
501    /// entry.
502    pub variances: DefIdMap<&'tcx [ty::Variance]>,
503}
504
505// Contains information needed to resolve types and (in the future) look up
506// the types of AST nodes.
507#[derive(#[automatically_derived]
impl ::core::marker::Copy for CReaderCacheKey { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CReaderCacheKey { }
#[automatically_derived]
impl ::core::clone::Clone for CReaderCacheKey {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<CrateNum>>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CReaderCacheKey { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CReaderCacheKey {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.cnum == other.cnum && self.pos == other.pos
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CReaderCacheKey {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<CrateNum>>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for CReaderCacheKey {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.cnum, state);
        ::core::hash::Hash::hash(&self.pos, state)
    }
}Hash)]
508pub struct CReaderCacheKey {
509    pub cnum: Option<CrateNum>,
510    pub pos: usize,
511}
512
513/// Use this rather than `TyKind`, whenever possible.
514#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Ty<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for Ty<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Ty<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'tcx,
                WithCachedTypeInfo<TyKind<'tcx>>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for Ty<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for Ty<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for Ty<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<Interned<'tcx,
                WithCachedTypeInfo<TyKind<'tcx>>>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for Ty<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            Ty<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Ty(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
515#[rustc_diagnostic_item = "Ty"]
516#[rustc_pass_by_value]
517pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
518
519impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
520    type Kind = TyKind<'tcx>;
521
522    fn kind(self) -> TyKind<'tcx> {
523        *self.kind()
524    }
525}
526
527impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
528    fn flags(&self) -> TypeFlags {
529        self.0.flags
530    }
531
532    fn outer_exclusive_binder(&self) -> DebruijnIndex {
533        self.0.outer_exclusive_binder
534    }
535}
536
537/// The crate outlives map is computed during typeck and contains the
538/// outlives of every item in the local crate. You should not use it
539/// directly, because to do so will make your pass dependent on the
540/// HIR of every item in the local crate. Instead, use
541/// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
542/// item.
543#[derive(const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            CrateClausesMap<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    CrateClausesMap { clauses: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CrateClausesMap<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "CrateClausesMap", "clauses", &&self.clauses)
    }
}Debug)]
544pub struct CrateClausesMap<'tcx> {
545    /// For each struct with outlive bounds, maps to a vector of the
546    /// clause of its outlive bounds. If an item has no outlives
547    /// bounds, it will have no entry.
548    pub clauses: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
549}
550
551#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for Term<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Term<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<NonNull<()>>;
        let _:
                ::core::clone::AssertParamIsClone<PhantomData<(Ty<'tcx>,
                Const<'tcx>)>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for Term<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for Term<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for Term<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.ptr == other.ptr && self.marker == other.marker
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for Term<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NonNull<()>>;
        let _:
                ::core::cmp::AssertParamIsEq<PhantomData<(Ty<'tcx>,
                Const<'tcx>)>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialOrd for Term<'tcx> {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl<'tcx> ::core::cmp::Ord for Term<'tcx> {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.ptr, &other.ptr) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.marker, &other.marker),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for Term<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.ptr, state);
        ::core::hash::Hash::hash(&self.marker, state)
    }
}Hash)]
552pub struct Term<'tcx> {
553    ptr: NonNull<()>,
554    marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
555}
556
557impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
558
559impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
560    type Kind = TermKind<'tcx>;
561
562    fn kind(self) -> Self::Kind {
563        self.kind()
564    }
565}
566
567unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
568    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
569{
570}
571unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
572    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
573{
574}
575unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
576unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
577
578impl Debug for Term<'_> {
579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580        match self.kind() {
581            TermKind::Ty(ty) => f.write_fmt(format_args!("Term::Ty({0:?})", ty))write!(f, "Term::Ty({ty:?})"),
582            TermKind::Const(ct) => f.write_fmt(format_args!("Term::Const({0:?})", ct))write!(f, "Term::Const({ct:?})"),
583        }
584    }
585}
586
587impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
588    fn from(ty: Ty<'tcx>) -> Self {
589        TermKind::Ty(ty).pack()
590    }
591}
592
593impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
594    fn from(c: Const<'tcx>) -> Self {
595        TermKind::Const(c).pack()
596    }
597}
598
599impl<'tcx> StableHash for Term<'tcx> {
600    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
601        self.kind().stable_hash(hcx, hasher);
602    }
603}
604
605impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
606    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
607        self,
608        folder: &mut F,
609    ) -> Result<Self, F::Error> {
610        match self.kind() {
611            ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
612            ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
613        }
614    }
615
616    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
617        match self.kind() {
618            ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
619            ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
620        }
621    }
622}
623
624impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
625    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
626        match self.kind() {
627            ty::TermKind::Ty(ty) => ty.visit_with(visitor),
628            ty::TermKind::Const(ct) => ct.visit_with(visitor),
629        }
630    }
631}
632
633impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
634    fn encode(&self, e: &mut E) {
635        self.kind().encode(e)
636    }
637}
638
639impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
640    fn decode(d: &mut D) -> Self {
641        let res: TermKind<'tcx> = Decodable::decode(d);
642        res.pack()
643    }
644}
645
646impl<'tcx> Term<'tcx> {
647    #[inline]
648    pub fn kind(self) -> TermKind<'tcx> {
649        let ptr =
650            unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
651        // SAFETY: use of `Interned::new_unchecked` here is ok because these
652        // pointers were originally created from `Interned` types in `pack()`,
653        // and this is just going in the other direction.
654        unsafe {
655            match self.ptr.addr().get() & TAG_MASK {
656                TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
657                    ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
658                ))),
659                CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
660                    ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
661                ))),
662                _ => core::intrinsics::unreachable(),
663            }
664        }
665    }
666
667    pub fn as_type(&self) -> Option<Ty<'tcx>> {
668        if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
669    }
670
671    pub fn expect_type(&self) -> Ty<'tcx> {
672        self.as_type().expect("expected a type, but found a const")
673    }
674
675    pub fn as_const(&self) -> Option<Const<'tcx>> {
676        if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
677    }
678
679    pub fn expect_const(&self) -> Const<'tcx> {
680        self.as_const().expect("expected a const, but found a type")
681    }
682
683    pub fn into_arg(self) -> GenericArg<'tcx> {
684        match self.kind() {
685            TermKind::Ty(ty) => ty.into(),
686            TermKind::Const(c) => c.into(),
687        }
688    }
689
690    pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
691        match self.kind() {
692            TermKind::Ty(ty) => match *ty.kind() {
693                ty::Alias(_, alias_ty) => Some(alias_ty.into()),
694                _ => None,
695            },
696            TermKind::Const(ct) => match ct.kind() {
697                ConstKind::Alias(_, alias_const) => Some(alias_const.into()),
698                _ => None,
699            },
700        }
701    }
702
703    pub fn is_non_rigid_alias(self) -> bool {
704        match self.kind() {
705            ty::TermKind::Ty(ty) => match ty.kind() {
706                ty::Alias(ty::IsRigid::No, _) => true,
707                _ => false,
708            },
709            ty::TermKind::Const(ct) => match ct.kind() {
710                ty::ConstKind::Alias(ty::IsRigid::No, _) => true,
711                _ => false,
712            },
713        }
714    }
715
716    pub fn is_infer(&self) -> bool {
717        match self.kind() {
718            TermKind::Ty(ty) => ty.is_ty_var(),
719            TermKind::Const(ct) => ct.is_ct_infer(),
720        }
721    }
722
723    pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
724        match self.kind() {
725            TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
726            TermKind::Const(ct) => ct.is_trivially_wf(),
727        }
728    }
729
730    /// Iterator that walks `self` and any types reachable from
731    /// `self`, in depth-first order. Note that just walks the types
732    /// that appear in `self`, it does not descend into the fields of
733    /// structs or variants. For example:
734    ///
735    /// ```text
736    /// isize => { isize }
737    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
738    /// [isize] => { [isize], isize }
739    /// ```
740    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
741        TypeWalker::new(self.into())
742    }
743}
744
745const TAG_MASK: usize = 0b11;
746const TYPE_TAG: usize = 0b00;
747const CONST_TAG: usize = 0b01;
748
749pub trait TermKindPackExt<'tcx> {
    fn pack(self)
    -> Term<'tcx>;
}
impl<'tcx> TermKindPackExt<'tcx> for TermKind<'tcx> {
    #[inline]
    fn pack(self) -> Term<'tcx> {
        let (tag, ptr) =
            match self {
                TermKind::Ty(ty) => {
                    {
                        match (&(align_of_val(&*ty.0.0) & TAG_MASK), &0) {
                            (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);
                                }
                            }
                        }
                    };
                    (TYPE_TAG, NonNull::from(ty.0.0).cast())
                }
                TermKind::Const(ct) => {
                    {
                        match (&(align_of_val(&*ct.0.0) & TAG_MASK), &0) {
                            (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);
                                }
                            }
                        }
                    };
                    (CONST_TAG, NonNull::from(ct.0.0).cast())
                }
            };
        Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
    }
}#[extension(pub trait TermKindPackExt<'tcx>)]
750impl<'tcx> TermKind<'tcx> {
751    #[inline]
752    fn pack(self) -> Term<'tcx> {
753        let (tag, ptr) = match self {
754            TermKind::Ty(ty) => {
755                // Ensure we can use the tag bits.
756                assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
757                (TYPE_TAG, NonNull::from(ty.0.0).cast())
758            }
759            TermKind::Const(ct) => {
760                // Ensure we can use the tag bits.
761                assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
762                (CONST_TAG, NonNull::from(ct.0.0).cast())
763            }
764        };
765
766        Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
767    }
768}
769
770/// Represents the bounds declared on a particular set of type
771/// parameters. Should eventually be generalized into a flag list of
772/// where-clauses. You can obtain an `InstantiatedClauses` list from a
773/// `GenericClauses` by using the `instantiate` method. Note that this method
774/// reflects an important semantic invariant of `InstantiatedClauses`: while
775/// the `GenericClauses` are expressed in terms of the bound type
776/// parameters of the impl/trait/whatever, an `InstantiatedClauses` instance
777/// represented a set of bounds for some particular instantiation,
778/// meaning that the generic parameters have been instantiated with
779/// their values.
780///
781/// Example:
782/// ```ignore (illustrative)
783/// struct Foo<T, U: Bar<T>> { ... }
784/// ```
785/// Here, the `GenericClauses` for `Foo` would contain a list of bounds like
786/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
787/// like `Foo<isize,usize>`, then the `InstantiatedClauses` would be `[[],
788/// [usize:Bar<isize>]]`.
789#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InstantiatedClauses<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        InstantiatedClauses {
            clauses: ::core::clone::Clone::clone(&self.clauses),
            spans: ::core::clone::Clone::clone(&self.spans),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InstantiatedClauses<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "InstantiatedClauses", "clauses", &self.clauses, "spans",
            &&self.spans)
    }
}Debug)]
790pub struct InstantiatedClauses<'tcx> {
791    pub clauses: Vec<Unnormalized<'tcx, Clause<'tcx>>>,
792    pub spans: Vec<Span>,
793}
794
795impl<'tcx> InstantiatedClauses<'tcx> {
796    pub fn empty() -> InstantiatedClauses<'tcx> {
797        InstantiatedClauses { clauses: ::alloc::vec::Vec::new()vec![], spans: ::alloc::vec::Vec::new()vec![] }
798    }
799
800    pub fn is_empty(&self) -> bool {
801        self.clauses.is_empty()
802    }
803
804    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
805        self.into_iter()
806    }
807}
808
809impl<'tcx> IntoIterator for InstantiatedClauses<'tcx> {
810    type Item = (Unnormalized<'tcx, Clause<'tcx>>, Span);
811
812    type IntoIter = std::iter::Zip<
813        std::vec::IntoIter<Unnormalized<'tcx, Clause<'tcx>>>,
814        std::vec::IntoIter<Span>,
815    >;
816
817    fn into_iter(self) -> Self::IntoIter {
818        if true {
    {
        match (&self.clauses.len(), &self.spans.len()) {
            (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!(self.clauses.len(), self.spans.len());
819        std::iter::zip(self.clauses, self.spans)
820    }
821}
822
823impl<'a, 'tcx> IntoIterator for &'a InstantiatedClauses<'tcx> {
824    type Item = (Unnormalized<'tcx, Clause<'tcx>>, Span);
825
826    type IntoIter = std::iter::Zip<
827        std::iter::Copied<std::slice::Iter<'a, Unnormalized<'tcx, Clause<'tcx>>>>,
828        std::iter::Copied<std::slice::Iter<'a, Span>>,
829    >;
830
831    fn into_iter(self) -> Self::IntoIter {
832        if true {
    {
        match (&self.clauses.len(), &self.spans.len()) {
            (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!(self.clauses.len(), self.spans.len());
833        std::iter::zip(self.clauses.iter().copied(), self.spans.iter().copied())
834    }
835}
836
837#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ProvisionalHiddenType<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ProvisionalHiddenType<'tcx>
    {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ProvisionalHiddenType<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ProvisionalHiddenType<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ProvisionalHiddenType", "span", &self.span, "ty", &&self.ty)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ProvisionalHiddenType<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ProvisionalHiddenType { span: __binding_0, ty: __binding_1 }
                            => {
                            ProvisionalHiddenType {
                                span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ty: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ProvisionalHiddenType { span: __binding_0, ty: __binding_1 }
                        => {
                        ProvisionalHiddenType {
                            span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ty: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ProvisionalHiddenType<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ProvisionalHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            ProvisionalHiddenType<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ProvisionalHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ProvisionalHiddenType<'tcx>
            {
            fn encode(&self, __encoder: &mut __E) {
                let ProvisionalHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ProvisionalHiddenType<'tcx>
            {
            fn decode(__decoder: &mut __D) -> Self {
                ProvisionalHiddenType {
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                    ty: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
838pub struct ProvisionalHiddenType<'tcx> {
839    /// The span of this particular definition of the opaque type. So
840    /// for example:
841    ///
842    /// ```ignore (incomplete snippet)
843    /// type Foo = impl Baz;
844    /// fn bar() -> Foo {
845    /// //          ^^^ This is the span we are looking for!
846    /// }
847    /// ```
848    ///
849    /// In cases where the fn returns `(impl Trait, impl Trait)` or
850    /// other such combinations, the result is currently
851    /// over-approximated, but better than nothing.
852    pub span: Span,
853
854    /// The type variable that represents the value of the opaque type
855    /// that we require. In other words, after we compile this function,
856    /// we will be created a constraint like:
857    /// ```ignore (pseudo-rust)
858    /// Foo<'a, T> = ?C
859    /// ```
860    /// where `?C` is the value of this type variable. =) It may
861    /// naturally refer to the type and lifetime parameters in scope
862    /// in this function, though ultimately it should only reference
863    /// those that are arguments to `Foo` in the constraint above. (In
864    /// other words, `?C` should not include `'b`, even though it's a
865    /// lifetime parameter on `foo`.)
866    pub ty: Ty<'tcx>,
867}
868
869/// Whether we're currently in HIR typeck or MIR borrowck.
870#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DefiningScopeKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DefiningScopeKind::HirTypeck => "HirTypeck",
                DefiningScopeKind::MirBorrowck => "MirBorrowck",
            })
    }
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DefiningScopeKind { }
#[automatically_derived]
impl ::core::clone::Clone for DefiningScopeKind {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DefiningScopeKind { }Copy)]
871pub enum DefiningScopeKind {
872    /// During writeback in typeck, we don't care about regions and simply
873    /// erase them. This means we also don't check whether regions are
874    /// universal in the opaque type key. This will only be checked in
875    /// MIR borrowck.
876    HirTypeck,
877    MirBorrowck,
878}
879
880impl<'tcx> ProvisionalHiddenType<'tcx> {
881    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
882        ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
883    }
884
885    pub fn build_mismatch_error(
886        &self,
887        other: &Self,
888        tcx: TyCtxt<'tcx>,
889    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
890        (self.ty, other.ty).error_reported()?;
891        // Found different concrete types for the opaque type.
892        let sub_diag = if self.span == other.span {
893            TypeMismatchReason::ConflictType { span: self.span }
894        } else {
895            TypeMismatchReason::PreviousUse { span: self.span }
896        };
897        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
898            self_ty: self.ty,
899            other_ty: other.ty,
900            other_span: other.span,
901            sub: sub_diag,
902        }))
903    }
904
905    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("remap_generic_params_to_declaration_params",
                                "rustc_middle::ty", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(905u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("self")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("self");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("opaque_type_key")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("opaque_type_key");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("defining_scope_kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("defining_scope_kind");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque_type_key)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&defining_scope_kind)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                DefinitionSiteHiddenType<'tcx> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let OpaqueTypeKey { def_id, args } = opaque_type_key;
                        let id_args = GenericArgs::identity_for_item(tcx, def_id);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs:921",
                                                "rustc_middle::ty", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(921u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("id_args")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("id_args");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id_args)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let map = args.iter().zip(id_args).collect();
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs:927",
                                                "rustc_middle::ty", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(927u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("map = {0:#?}",
                                                                            map) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let ty =
                            match defining_scope_kind {
                                DefiningScopeKind::HirTypeck => {
                                    fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
                                }
                                DefiningScopeKind::MirBorrowck => self.ty,
                            };
                        let result_ty =
                            ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map,
                                        self.span));
                        if true &&
                                #[allow(non_exhaustive_omitted_patterns)] match defining_scope_kind
                                    {
                                    DefiningScopeKind::HirTypeck => true,
                                    _ => false,
                                } {
                            {
                                match (&result_ty,
                                        &fold_regions(tcx, result_ty,
                                                |_, _| tcx.lifetimes.re_erased)) {
                                    (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);
                                        }
                                    }
                                }
                            };
                        }
                        DefinitionSiteHiddenType {
                            span: self.span,
                            ty: ty::EarlyBinder::bind(tcx, result_ty),
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs:905",
                        "rustc_middle::ty", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(905u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
906    pub fn remap_generic_params_to_declaration_params(
907        self,
908        opaque_type_key: OpaqueTypeKey<'tcx>,
909        tcx: TyCtxt<'tcx>,
910        defining_scope_kind: DefiningScopeKind,
911    ) -> DefinitionSiteHiddenType<'tcx> {
912        let OpaqueTypeKey { def_id, args } = opaque_type_key;
913
914        // Use args to build up a reverse map from regions to their
915        // identity mappings. This is necessary because of `impl
916        // Trait` lifetimes are computed by replacing existing
917        // lifetimes with 'static and remapping only those used in the
918        // `impl Trait` return type, resulting in the parameters
919        // shifting.
920        let id_args = GenericArgs::identity_for_item(tcx, def_id);
921        debug!(?id_args);
922
923        // This zip may have several times the same lifetime in `args` paired with a different
924        // lifetime from `id_args`. Simply `collect`ing the iterator is the correct behaviour:
925        // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
926        let map = args.iter().zip(id_args).collect();
927        debug!("map = {:#?}", map);
928
929        // Convert the type from the function into a type valid outside by mapping generic
930        // parameters to into the context of the opaque.
931        //
932        // We erase regions when doing this during HIR typeck. We manually use `fold_regions`
933        // here as we do not want to anonymize bound variables.
934        let ty = match defining_scope_kind {
935            DefiningScopeKind::HirTypeck => {
936                fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
937            }
938            DefiningScopeKind::MirBorrowck => self.ty,
939        };
940        let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
941        if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
942            assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
943        }
944        DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(tcx, result_ty) }
945    }
946}
947
948#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for DefinitionSiteHiddenType<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for
    DefinitionSiteHiddenType<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for DefinitionSiteHiddenType<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _:
                ::core::clone::AssertParamIsClone<ty::EarlyBinder<'tcx,
                Ty<'tcx>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for DefinitionSiteHiddenType<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DefinitionSiteHiddenType", "span", &self.span, "ty", &&self.ty)
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            DefinitionSiteHiddenType<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    DefinitionSiteHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for
            DefinitionSiteHiddenType<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let DefinitionSiteHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for
            DefinitionSiteHiddenType<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                DefinitionSiteHiddenType {
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                    ty: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
949pub struct DefinitionSiteHiddenType<'tcx> {
950    /// The span of the definition of the opaque type. So for example:
951    ///
952    /// ```ignore (incomplete snippet)
953    /// type Foo = impl Baz;
954    /// fn bar() -> Foo {
955    /// //          ^^^ This is the span we are looking for!
956    /// }
957    /// ```
958    ///
959    /// In cases where the fn returns `(impl Trait, impl Trait)` or
960    /// other such combinations, the result is currently
961    /// over-approximated, but better than nothing.
962    pub span: Span,
963
964    /// The final type of the opaque.
965    pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
966}
967
968impl<'tcx> DefinitionSiteHiddenType<'tcx> {
969    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
970        DefinitionSiteHiddenType {
971            span: DUMMY_SP,
972            ty: ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, guar)),
973        }
974    }
975
976    pub fn build_mismatch_error(
977        &self,
978        other: &Self,
979        tcx: TyCtxt<'tcx>,
980    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
981        let self_ty = self.ty.instantiate_identity().skip_norm_wip();
982        let other_ty = other.ty.instantiate_identity().skip_norm_wip();
983        (self_ty, other_ty).error_reported()?;
984        // Found different concrete types for the opaque type.
985        let sub_diag = if self.span == other.span {
986            TypeMismatchReason::ConflictType { span: self.span }
987        } else {
988            TypeMismatchReason::PreviousUse { span: self.span }
989        };
990        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
991            self_ty,
992            other_ty,
993            other_span: other.span,
994            sub: sub_diag,
995        }))
996    }
997}
998
999pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
1000
1001impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1002    fn flags(&self) -> TypeFlags {
1003        (**self).flags()
1004    }
1005
1006    fn outer_exclusive_binder(&self) -> DebruijnIndex {
1007        (**self).outer_exclusive_binder()
1008    }
1009}
1010
1011/// When interacting with the type system we must provide information about the
1012/// environment. `ParamEnv` is the type that represents this information. See the
1013/// [dev guide chapter][param_env_guide] for more information.
1014///
1015/// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1016#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ParamEnv<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "ParamEnv",
            "caller_bounds", &&self.caller_bounds)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ParamEnv<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ParamEnv<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ParamEnv<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Clauses<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for ParamEnv<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.caller_bounds, state)
    }
}Hash, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for ParamEnv<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ParamEnv<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.caller_bounds == other.caller_bounds
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ParamEnv<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Clauses<'tcx>>;
    }
}Eq)]
1017#[derive(const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            ParamEnv<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ParamEnv { caller_bounds: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ParamEnv<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ParamEnv { caller_bounds: ref __binding_0 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ParamEnv<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ParamEnv { caller_bounds: __binding_0 } => {
                            ParamEnv {
                                caller_bounds: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ParamEnv { caller_bounds: __binding_0 } => {
                        ParamEnv {
                            caller_bounds: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable)]
1018pub struct ParamEnv<'tcx> {
1019    /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1020    /// basically the set of bounds on the in-scope type parameters, translated
1021    /// into `Obligation`s, and elaborated and normalized.
1022    ///
1023    /// Use the `caller_bounds()` method to access.
1024    caller_bounds: Clauses<'tcx>,
1025}
1026
1027// Empty ParamEnv's are super common (like, 100x more common than nonempty pnes),
1028// so we want to not carry around too much data in this common case.
1029// Make sure that a ParamEnv is no bigger than a single pointer, always.
1030const _: [(); std::mem::size_of::<usize>()] =
    [(); ::std::mem::size_of::<ParamEnv<'_>>()];static_assert_size!(ParamEnv<'_>, std::mem::size_of::<usize>());
1031
1032impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1033    fn caller_bounds(self) -> impl Iterator<Item = ty::Clause<'tcx>> {
1034        self.caller_bounds()
1035    }
1036}
1037
1038impl<'tcx> ParamEnv<'tcx> {
1039    /// Construct a trait environment suitable for contexts where there are
1040    /// no where-clauses in scope. In the majority of cases it is incorrect
1041    /// to use an empty environment. See the [dev guide section][param_env_guide]
1042    /// for information on what a `ParamEnv` is and how to acquire one.
1043    ///
1044    /// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1045    #[inline]
1046    pub fn empty() -> Self {
1047        Self { caller_bounds: ListWithCachedTypeInfo::empty() }
1048    }
1049
1050    #[inline]
1051    pub fn caller_bounds(self) -> impl Iterator<Item = ty::Clause<'tcx>> + Clone {
1052        self.caller_bounds.iter()
1053    }
1054
1055    #[inline]
1056    pub fn is_empty(self) -> bool {
1057        self.caller_bounds.as_slice().is_empty()
1058    }
1059
1060    /// Construct a trait environment with the given set of predicates.
1061    #[inline]
1062    pub fn new(
1063        tcx: TyCtxt<'tcx>,
1064        caller_bounds: impl IntoIterator<Item = ty::Clause<'tcx>>,
1065    ) -> Self {
1066        ParamEnv { caller_bounds: tcx.mk_clauses_from_iter(caller_bounds.into_iter()) }
1067    }
1068
1069    /// Creates a pair of param-env and value for use in queries.
1070    pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1071        ParamEnvAnd { param_env: self, value }
1072    }
1073
1074    /// Eagerly reveal all opaque types in the `param_env`.
1075    pub fn with_normalized(self, tcx: TyCtxt<'tcx>) -> ParamEnv<'tcx> {
1076        // No need to reveal opaques with the new solver enabled,
1077        // since we have lazy norm.
1078        if tcx.next_trait_solver_globally() {
1079            self
1080        } else {
1081            ParamEnv::new(tcx, tcx.reveal_opaque_types_in_bounds(self.caller_bounds).iter())
1082        }
1083    }
1084}
1085
1086#[derive(#[automatically_derived]
impl<'tcx, T: ::core::marker::Copy> ::core::marker::Copy for
    ParamEnvAnd<'tcx, T> {
}Copy, #[automatically_derived]
impl<'tcx, T: ::core::clone::Clone> ::core::clone::Clone for
    ParamEnvAnd<'tcx, T> {
    #[inline]
    fn clone(&self) -> Self {
        ParamEnvAnd {
            param_env: ::core::clone::Clone::clone(&self.param_env),
            value: ::core::clone::Clone::clone(&self.value),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for ParamEnvAnd<'tcx, T>
    {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "ParamEnvAnd",
            "param_env", &self.param_env, "value", &&self.value)
    }
}Debug, #[automatically_derived]
impl<'tcx, T: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
    ParamEnvAnd<'tcx, T> {
}
#[automatically_derived]
impl<'tcx, T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
    ParamEnvAnd<'tcx, T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.param_env == other.param_env && self.value == other.value
    }
}PartialEq, #[automatically_derived]
impl<'tcx, T: ::core::cmp::Eq> ::core::cmp::Eq for ParamEnvAnd<'tcx, T> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ParamEnv<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<T>;
    }
}Eq, #[automatically_derived]
impl<'tcx, T: ::core::hash::Hash> ::core::hash::Hash for ParamEnvAnd<'tcx, T>
    {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.param_env, state);
        ::core::hash::Hash::hash(&self.value, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ParamEnvAnd<'tcx, T> where
            T: ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ParamEnvAnd { param_env: __binding_0, value: __binding_1 }
                            => {
                            ParamEnvAnd {
                                param_env: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                value: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ParamEnvAnd { param_env: __binding_0, value: __binding_1 }
                        => {
                        ParamEnvAnd {
                            param_env: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            value: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ParamEnvAnd<'tcx, T> where
            T: ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ParamEnvAnd {
                        param_env: ref __binding_0, value: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
1087#[derive(const _: () =
    {
        impl<'tcx, T> ::rustc_data_structures::stable_hash::StableHash for
            ParamEnvAnd<'tcx, T> where
            T: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ParamEnvAnd {
                        param_env: ref __binding_0, value: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1088pub struct ParamEnvAnd<'tcx, T> {
1089    pub param_env: ParamEnv<'tcx>,
1090    pub value: T,
1091}
1092
1093/// The environment in which to do trait solving.
1094///
1095/// Most of the time you only need to care about the `ParamEnv`
1096/// as the `TypingMode` is simply stored in the `InferCtxt`.
1097///
1098/// However, there are some places which rely on trait solving
1099/// without using an `InferCtxt` themselves. For these to be
1100/// able to use the trait system they have to be able to initialize
1101/// such an `InferCtxt` with the right `typing_mode`, so they need
1102/// to track both.
1103#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypingEnv<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for TypingEnv<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypingEnv<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<TypingModeEqWrapper<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ParamEnv<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypingEnv<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "TypingEnv",
            "typing_mode", &self.typing_mode, "param_env", &&self.param_env)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for TypingEnv<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for TypingEnv<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.typing_mode == other.typing_mode &&
            self.param_env == other.param_env
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for TypingEnv<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<TypingModeEqWrapper<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<ParamEnv<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for TypingEnv<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.typing_mode, state);
        ::core::hash::Hash::hash(&self.param_env, state)
    }
}Hash, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            TypingEnv<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    TypingEnv {
                        typing_mode: ref __binding_0, param_env: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1104#[derive(const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TypingEnv<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    TypingEnv { param_env: ref __binding_1, .. } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for TypingEnv<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        TypingEnv { typing_mode: __binding_0, param_env: __binding_1
                            } => {
                            TypingEnv {
                                typing_mode: __binding_0,
                                param_env: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    TypingEnv { typing_mode: __binding_0, param_env: __binding_1
                        } => {
                        TypingEnv {
                            typing_mode: __binding_0,
                            param_env: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable)]
1105pub struct TypingEnv<'tcx> {
1106    #[type_foldable(identity)]
1107    #[type_visitable(ignore)]
1108    typing_mode: TypingModeEqWrapper<'tcx>,
1109    pub param_env: ParamEnv<'tcx>,
1110}
1111
1112impl<'tcx> rustc_type_ir::inherent::TypingEnv<TyCtxt<'tcx>> for TypingEnv<'tcx> {
1113    fn fully_monomorphized() -> Self {
1114        Self::fully_monomorphized()
1115    }
1116
1117    fn layout_size(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Size {
1118        tcx.layout_of(self.as_query_input(ty))
1119            .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("could not compute layout for {0:?}: {1:?}",
            ty, e));
}panic!("could not compute layout for {ty:?}: {e:?}"))
1120            .size
1121    }
1122}
1123
1124impl<'tcx> TypingEnv<'tcx> {
1125    pub fn new(param_env: ParamEnv<'tcx>, typing_mode: TypingMode<'tcx>) -> Self {
1126        Self { typing_mode: TypingModeEqWrapper(typing_mode), param_env }
1127    }
1128
1129    pub fn typing_mode(&self) -> TypingMode<'tcx> {
1130        self.typing_mode.0
1131    }
1132
1133    /// Create a typing environment with no where-clauses in scope
1134    /// where all opaque types and default associated items are revealed.
1135    ///
1136    /// This is only suitable for monomorphized, post-typeck environments.
1137    /// Do not use this for MIR optimizations, as even though they also
1138    /// use `TypingMode::PostAnalysis`, they may still have where-clauses
1139    /// in scope.
1140    pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1141        Self::new(ParamEnv::empty(), TypingMode::Codegen)
1142    }
1143
1144    /// Create a typing environment for use during analysis outside of a body.
1145    ///
1146    /// Using a typing environment inside of bodies is not supported as the body
1147    /// may define opaque types. In this case the used functions have to be
1148    /// converted to use proper canonical inputs instead.
1149    pub fn non_body_analysis(
1150        tcx: TyCtxt<'tcx>,
1151        def_id: impl IntoQueryKey<DefId>,
1152    ) -> TypingEnv<'tcx> {
1153        let def_id = def_id.into_query_key();
1154        Self::new(tcx.param_env(def_id), TypingMode::non_body_analysis())
1155    }
1156
1157    /// The `TypingEnv` which should be for everything happens after HIR typeck
1158    /// up-to and including borrowck itself.
1159    pub fn post_typeck_until_borrowck(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> TypingEnv<'tcx> {
1160        let param_env = tcx.param_env(def_id.to_def_id());
1161        TypingEnv::new(param_env, ty::TypingMode::borrowck(tcx, def_id))
1162    }
1163
1164    /// Ideally we just use `TypingMode::post_typeck_until_borrowck`.
1165    /// But that's not compatible with the old solver yet.
1166    ///
1167    /// FIXME: this should not be needed in the long term.
1168    pub fn post_typeck_until_borrowck_for_mir_build(
1169        tcx: TyCtxt<'tcx>,
1170        def_id: LocalDefId,
1171    ) -> TypingEnv<'tcx> {
1172        if tcx.use_typing_mode_post_typeck_until_borrowck() {
1173            TypingEnv::new(tcx.param_env(def_id.to_def_id()), ty::TypingMode::borrowck(tcx, def_id))
1174        } else {
1175            // FIXME(#132279): We're in a body, we should use a typing
1176            // mode which reveals the opaque types defined by that body.
1177            TypingEnv::non_body_analysis(tcx, def_id)
1178        }
1179    }
1180
1181    pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
1182        TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::PostAnalysis)
1183    }
1184
1185    pub fn codegen(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
1186        TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::Codegen)
1187    }
1188
1189    /// Modify the `typing_mode` to `PostAnalysis` or `Codegen` and eagerly reveal all opaque types
1190    /// in the `param_env`.
1191    ///
1192    /// Changing the typing_mode to `PostAnalysis` can result in aliases now being normalizeable,
1193    /// so we need to explicitly renormalize them. This mainly affects opaque types which were
1194    /// previously treated as rigid but can now be normalized to their underlying type, as well as
1195    /// aliases with opaque args.
1196    /// Values that contain types/consts from the previous typing env and that will be used in the
1197    /// new `PostAnalysis` typing env should be folded by this method to allow renormalization.
1198    ///
1199    /// FIXME: we might want to return `Unnormalized` since we force the value to be non-rigid.
1200    pub fn with_post_analysis_normalized_invalidating_rigid_aliases<T>(
1201        self,
1202        tcx: TyCtxt<'tcx>,
1203        value: T,
1204    ) -> PseudoCanonicalInput<'tcx, T>
1205    where
1206        T: TypeFoldable<TyCtxt<'tcx>>,
1207    {
1208        let TypingEnv { typing_mode, param_env } = self;
1209        match typing_mode.0.assert_not_erased() {
1210            TypingMode::Coherence
1211            | TypingMode::Reflection
1212            | TypingMode::Typeck { .. }
1213            | TypingMode::PostTypeckUntilBorrowck { .. }
1214            | TypingMode::PostBorrowck { .. } => {}
1215            TypingMode::PostAnalysis | TypingMode::Codegen => return self.as_query_input(value),
1216        }
1217
1218        let param_env = param_env.with_normalized(tcx);
1219        let value = ty::set_aliases_to_non_rigid(tcx, value).skip_norm_wip();
1220        TypingEnv::new(param_env, TypingMode::PostAnalysis).as_query_input(value)
1221    }
1222
1223    /// Same as `with_post_analysis_normalized_invalidating_rigid_aliases` except that we use
1224    /// the `Codegen` typing mode.
1225    pub fn with_codegen_normalized_invalidating_rigid_aliases<T>(
1226        self,
1227        tcx: TyCtxt<'tcx>,
1228        value: T,
1229    ) -> PseudoCanonicalInput<'tcx, T>
1230    where
1231        T: TypeFoldable<TyCtxt<'tcx>>,
1232    {
1233        let TypingEnv { typing_mode, param_env } = self;
1234        match typing_mode.0.assert_not_erased() {
1235            TypingMode::Coherence
1236            | TypingMode::Reflection
1237            | TypingMode::Typeck { .. }
1238            | TypingMode::PostTypeckUntilBorrowck { .. }
1239            | TypingMode::PostBorrowck { .. }
1240            | TypingMode::PostAnalysis => {}
1241            TypingMode::Codegen => return self.as_query_input(value),
1242        }
1243
1244        let param_env = param_env.with_normalized(tcx);
1245        let value = ty::set_aliases_to_non_rigid(tcx, value).skip_norm_wip();
1246        TypingEnv::new(param_env, TypingMode::Codegen).as_query_input(value)
1247    }
1248
1249    /// Combine this typing environment with the given `value` to be used by
1250    /// not (yet) canonicalized queries. This only works if the value does not
1251    /// contain anything local to some `InferCtxt`, i.e. inference variables or
1252    /// placeholders.
1253    pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1254    where
1255        T: TypeVisitable<TyCtxt<'tcx>>,
1256    {
1257        // FIXME(#132279): We should assert that the value does not contain any placeholders
1258        // as these placeholders are also local to the current inference context. However, we
1259        // currently use pseudo-canonical queries in the trait solver, which replaces params
1260        // with placeholders during canonicalization. We should also simply not use pseudo-
1261        // canonical queries in the trait solver, at which point we can readd this assert.
1262        //
1263        // As of writing this comment, this is only used when normalizing consts that mention
1264        // params.
1265        /* debug_assert!(
1266            !value.has_placeholders(),
1267            "{value:?} which has placeholder shouldn't be pseudo-canonicalized"
1268        ); */
1269        PseudoCanonicalInput { typing_env: self, value }
1270    }
1271}
1272
1273/// Similar to `CanonicalInput`, this carries the `typing_mode` and the environment
1274/// necessary to do any kind of trait solving inside of nested queries.
1275///
1276/// Unlike proper canonicalization, this requires the `param_env` and the `value` to not
1277/// contain anything local to the `infcx` of the caller, so we don't actually canonicalize
1278/// anything.
1279///
1280/// This should be created by using `infcx.pseudo_canonicalize_query(param_env, value)`
1281/// or by using `typing_env.as_query_input(value)`.
1282#[derive(#[automatically_derived]
impl<'tcx, T: ::core::marker::Copy> ::core::marker::Copy for
    PseudoCanonicalInput<'tcx, T> {
}Copy, #[automatically_derived]
impl<'tcx, T: ::core::clone::Clone> ::core::clone::Clone for
    PseudoCanonicalInput<'tcx, T> {
    #[inline]
    fn clone(&self) -> Self {
        PseudoCanonicalInput {
            typing_env: ::core::clone::Clone::clone(&self.typing_env),
            value: ::core::clone::Clone::clone(&self.value),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for
    PseudoCanonicalInput<'tcx, T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "PseudoCanonicalInput", "typing_env", &self.typing_env, "value",
            &&self.value)
    }
}Debug, #[automatically_derived]
impl<'tcx, T: ::core::cmp::PartialEq> ::core::marker::StructuralPartialEq for
    PseudoCanonicalInput<'tcx, T> {
}
#[automatically_derived]
impl<'tcx, T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
    PseudoCanonicalInput<'tcx, T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.typing_env == other.typing_env && self.value == other.value
    }
}PartialEq, #[automatically_derived]
impl<'tcx, T: ::core::cmp::Eq> ::core::cmp::Eq for
    PseudoCanonicalInput<'tcx, T> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<TypingEnv<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<T>;
    }
}Eq, #[automatically_derived]
impl<'tcx, T: ::core::hash::Hash> ::core::hash::Hash for
    PseudoCanonicalInput<'tcx, T> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.typing_env, state);
        ::core::hash::Hash::hash(&self.value, state)
    }
}Hash)]
1283#[derive(const _: () =
    {
        impl<'tcx, T> ::rustc_data_structures::stable_hash::StableHash for
            PseudoCanonicalInput<'tcx, T> where
            T: ::rustc_data_structures::stable_hash::StableHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    PseudoCanonicalInput {
                        typing_env: ref __binding_0, value: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PseudoCanonicalInput<'tcx, T> where
            T: ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    PseudoCanonicalInput {
                        typing_env: ref __binding_0, value: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, const _: () =
    {
        impl<'tcx, T>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PseudoCanonicalInput<'tcx, T> where
            T: ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        PseudoCanonicalInput {
                            typing_env: __binding_0, value: __binding_1 } => {
                            PseudoCanonicalInput {
                                typing_env: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                value: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    PseudoCanonicalInput {
                        typing_env: __binding_0, value: __binding_1 } => {
                        PseudoCanonicalInput {
                            typing_env: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            value: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable)]
1284pub struct PseudoCanonicalInput<'tcx, T> {
1285    pub typing_env: TypingEnv<'tcx>,
1286    pub value: T,
1287}
1288
1289#[derive(#[automatically_derived]
impl ::core::marker::Copy for Destructor { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Destructor { }
#[automatically_derived]
impl ::core::clone::Clone for Destructor {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Destructor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "Destructor",
            "did", &&self.did)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Destructor {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Destructor { did: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Destructor {
            fn encode(&self, __encoder: &mut __E) {
                let Destructor { did: ref __binding_0 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Destructor {
            fn decode(__decoder: &mut __D) -> Self {
                Destructor {
                    did: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
1290pub struct Destructor {
1291    /// The `DefId` of the destructor method
1292    pub did: DefId,
1293}
1294
1295// FIXME: consider combining this definition with regular `Destructor`
1296#[derive(#[automatically_derived]
impl ::core::marker::Copy for AsyncDestructor { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AsyncDestructor { }
#[automatically_derived]
impl ::core::clone::Clone for AsyncDestructor {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AsyncDestructor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "AsyncDestructor", "impl_did", &&self.impl_did)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            AsyncDestructor {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    AsyncDestructor { impl_did: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for AsyncDestructor {
            fn encode(&self, __encoder: &mut __E) {
                let AsyncDestructor { impl_did: ref __binding_0 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for AsyncDestructor {
            fn decode(__decoder: &mut __D) -> Self {
                AsyncDestructor {
                    impl_did: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
1297pub struct AsyncDestructor {
1298    /// The `DefId` of the `impl AsyncDrop`
1299    pub impl_did: DefId,
1300}
1301
1302#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for VariantFlags { }
#[automatically_derived]
impl ::core::clone::Clone for VariantFlags {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u8>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for VariantFlags { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for VariantFlags { }
#[automatically_derived]
impl ::core::cmp::PartialEq for VariantFlags {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for VariantFlags {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u8>;
    }
}Eq, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for VariantFlags
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    VariantFlags(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for VariantFlags {
            fn encode(&self, __encoder: &mut __E) {
                let VariantFlags(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for VariantFlags {
            fn decode(__decoder: &mut __D) -> Self {
                VariantFlags(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };TyDecodable)]
1303pub struct VariantFlags(u8);
1304impl VariantFlags {
    #[allow(deprecated, non_upper_case_globals,)]
    pub const NO_VARIANT_FLAGS: Self = Self::from_bits_retain(0);
    #[doc =
    r" Indicates whether the field list of this variant is `#[non_exhaustive]`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_FIELD_LIST_NON_EXHAUSTIVE: Self =
        Self::from_bits_retain(1 << 0);
}
impl ::bitflags::Flags for VariantFlags {
    const FLAGS: &'static [::bitflags::Flag<VariantFlags>] =
        &[{

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("NO_VARIANT_FLAGS",
                            VariantFlags::NO_VARIANT_FLAGS)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_FIELD_LIST_NON_EXHAUSTIVE",
                            VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
                    }];
    type Bits = u8;
    fn bits(&self) -> u8 { VariantFlags::bits(self) }
    fn from_bits_retain(bits: u8) -> VariantFlags {
        VariantFlags::from_bits_retain(bits)
    }
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: iter_without_into_iter,)]
const _: () =
    {
        #[allow(dead_code, deprecated, unused_attributes)]
        impl VariantFlags {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self {
                Self(<u8 as ::bitflags::Bits>::EMPTY)
            }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self {
                let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
                let mut i = 0;
                {
                    {
                        let flag =
                            <VariantFlags as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <VariantFlags as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                let _ = i;
                Self(truncated)
            }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0 }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                let truncated = Self::from_bits_truncate(bits).0;
                if truncated == bits {
                    ::bitflags::__private::core::option::Option::Some(Self(bits))
                } else { ::bitflags::__private::core::option::Option::None }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(bits & Self::all().0)
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                {
                    if name == "NO_VARIANT_FLAGS" {
                        return ::bitflags::__private::core::option::Option::Some(Self(VariantFlags::NO_VARIANT_FLAGS.bits()));
                    }
                };
                ;
                {
                    if name == "IS_FIELD_LIST_NON_EXHAUSTIVE" {
                        return ::bitflags::__private::core::option::Option::Some(Self(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE.bits()));
                    }
                };
                ;
                let _ = name;
                ::bitflags::__private::core::option::Option::None
            }
            /// Whether all bits in this flags value are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.0 == <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().0 | self.0 == self.0
            }
            /// Whether any set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0 & other.0 == other.0
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                *self = Self(self.0).union(other);
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                *self = Self(self.0).difference(other);
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                *self = Self(self.0).symmetric_difference(other);
            }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value { self.insert(other); } else { self.remove(other); }
            }
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0 & other.0)
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0)
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0 & !other.0)
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0 ^ other.0)
            }
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.0)
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for VariantFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for VariantFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for VariantFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for VariantFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for VariantFlags {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor(self, other: VariantFlags) -> Self { self.union(other) }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for VariantFlags {
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for VariantFlags {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for VariantFlags {
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for VariantFlags {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for VariantFlags {
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for VariantFlags {
            type Output = Self;
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for VariantFlags {
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for VariantFlags {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<VariantFlags> for
            VariantFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<VariantFlags> for
            VariantFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl VariantFlags {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self) -> ::bitflags::iter::Iter<VariantFlags> {
                ::bitflags::iter::Iter::__private_const_new(<VariantFlags as
                        ::bitflags::Flags>::FLAGS,
                    VariantFlags::from_bits_retain(self.bits()),
                    VariantFlags::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<VariantFlags> {
                ::bitflags::iter::IterNames::__private_const_new(<VariantFlags
                        as ::bitflags::Flags>::FLAGS,
                    VariantFlags::from_bits_retain(self.bits()),
                    VariantFlags::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for VariantFlags
            {
            type Item = VariantFlags;
            type IntoIter = ::bitflags::iter::Iter<VariantFlags>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
    };bitflags::bitflags! {
1305    impl VariantFlags: u8 {
1306        const NO_VARIANT_FLAGS        = 0;
1307        /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1308        const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1309    }
1310}
1311impl ::std::fmt::Debug for VariantFlags {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        ::bitflags::parser::to_writer(self, f)
    }
}rustc_data_structures::external_bitflags_debug! { VariantFlags }
1312
1313/// Definition of a variant -- a struct's fields or an enum variant.
1314#[derive(#[automatically_derived]
impl ::core::fmt::Debug for VariantDef {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["def_id", "ctor", "name", "discr", "fields", "tainted",
                        "flags"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.def_id, &self.ctor, &self.name, &self.discr, &self.fields,
                        &self.tainted, &&self.flags];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "VariantDef",
            names, values)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for VariantDef {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    VariantDef {
                        def_id: ref __binding_0,
                        ctor: ref __binding_1,
                        name: ref __binding_2,
                        discr: ref __binding_3,
                        fields: ref __binding_4,
                        tainted: ref __binding_5,
                        flags: ref __binding_6 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                        { __binding_4.stable_hash(__hcx, __hasher); }
                        { __binding_5.stable_hash(__hcx, __hasher); }
                        { __binding_6.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for VariantDef {
            fn encode(&self, __encoder: &mut __E) {
                let VariantDef {
                        def_id: ref __binding_0,
                        ctor: ref __binding_1,
                        name: ref __binding_2,
                        discr: ref __binding_3,
                        fields: ref __binding_4,
                        tainted: ref __binding_5,
                        flags: ref __binding_6 } = *self;
                ::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);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for VariantDef {
            fn decode(__decoder: &mut __D) -> Self {
                VariantDef {
                    def_id: ::rustc_serialize::Decodable::decode(__decoder),
                    ctor: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                    discr: ::rustc_serialize::Decodable::decode(__decoder),
                    fields: ::rustc_serialize::Decodable::decode(__decoder),
                    tainted: ::rustc_serialize::Decodable::decode(__decoder),
                    flags: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
1315pub struct VariantDef {
1316    /// `DefId` that identifies the variant itself.
1317    /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1318    pub def_id: DefId,
1319    /// `DefId` that identifies the variant's constructor.
1320    /// If this variant is a struct variant, then this is `None`.
1321    pub ctor: Option<(CtorKind, DefId)>,
1322    /// Variant or struct name.
1323    pub name: Symbol,
1324    /// Discriminant of this variant.
1325    pub discr: VariantDiscr,
1326    /// Fields of this variant.
1327    pub fields: IndexVec<FieldIdx, FieldDef>,
1328    /// The error guarantees from parser, if any.
1329    tainted: Option<ErrorGuaranteed>,
1330    /// Flags of the variant (e.g. is field list non-exhaustive)?
1331    flags: VariantFlags,
1332}
1333
1334impl VariantDef {
1335    /// Creates a new `VariantDef`.
1336    ///
1337    /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1338    /// represents an enum variant).
1339    ///
1340    /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1341    /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1342    ///
1343    /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1344    /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1345    /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1346    /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1347    /// built-in trait), and we do not want to load attributes twice.
1348    ///
1349    /// If someone speeds up attribute loading to not be a performance concern, they can
1350    /// remove this hack and use the constructor `DefId` everywhere.
1351    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("new",
                                    "rustc_middle::ty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1351u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("variant_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("variant_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ctor")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ctor");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("discr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("discr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fields")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fields");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("recover_tainted")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("recover_tainted");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_field_list_non_exhaustive")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_field_list_non_exhaustive");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant_did)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ctor)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&discr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fields)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_did)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&recover_tainted)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&is_field_list_non_exhaustive
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Self = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut flags = VariantFlags::NO_VARIANT_FLAGS;
            if is_field_list_non_exhaustive {
                flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
            }
            VariantDef {
                def_id: variant_did.unwrap_or(parent_did),
                ctor,
                name,
                discr,
                fields,
                flags,
                tainted: recover_tainted,
            }
        }
    }
}#[instrument(level = "debug")]
1352    pub fn new(
1353        name: Symbol,
1354        variant_did: Option<DefId>,
1355        ctor: Option<(CtorKind, DefId)>,
1356        discr: VariantDiscr,
1357        fields: IndexVec<FieldIdx, FieldDef>,
1358        parent_did: DefId,
1359        recover_tainted: Option<ErrorGuaranteed>,
1360        is_field_list_non_exhaustive: bool,
1361    ) -> Self {
1362        let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1363        if is_field_list_non_exhaustive {
1364            flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1365        }
1366
1367        VariantDef {
1368            def_id: variant_did.unwrap_or(parent_did),
1369            ctor,
1370            name,
1371            discr,
1372            fields,
1373            flags,
1374            tainted: recover_tainted,
1375        }
1376    }
1377
1378    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`.
1379    ///
1380    /// Note that this function will return `true` even if the type has been
1381    /// defined in the crate currently being compiled. If that's not what you
1382    /// want, see [`Self::field_list_has_applicable_non_exhaustive`].
1383    #[inline]
1384    pub fn is_field_list_non_exhaustive(&self) -> bool {
1385        self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1386    }
1387
1388    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`
1389    /// and the type has been defined in another crate.
1390    #[inline]
1391    pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1392        self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1393    }
1394
1395    /// Computes the `Ident` of this variant by looking up the `Span`
1396    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1397        Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1398    }
1399
1400    /// Was this variant obtained as part of recovering from a syntactic error?
1401    #[inline]
1402    pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1403        self.tainted.map_or(Ok(()), Err)
1404    }
1405
1406    #[inline]
1407    pub fn ctor_kind(&self) -> Option<CtorKind> {
1408        self.ctor.map(|(kind, _)| kind)
1409    }
1410
1411    #[inline]
1412    pub fn ctor_def_id(&self) -> Option<DefId> {
1413        self.ctor.map(|(_, def_id)| def_id)
1414    }
1415
1416    /// Returns the one field in this variant.
1417    ///
1418    /// `panic!`s if there are no fields or multiple fields.
1419    #[inline]
1420    pub fn single_field(&self) -> &FieldDef {
1421        if !(self.fields.len() == 1) {
    ::core::panicking::panic("assertion failed: self.fields.len() == 1")
};assert!(self.fields.len() == 1);
1422
1423        &self.fields[FieldIdx::ZERO]
1424    }
1425
1426    /// Returns the last field in this variant, if present.
1427    #[inline]
1428    pub fn tail_opt(&self) -> Option<&FieldDef> {
1429        self.fields.raw.last()
1430    }
1431
1432    /// Returns the last field in this variant.
1433    ///
1434    /// # Panics
1435    ///
1436    /// Panics, if the variant has no fields.
1437    #[inline]
1438    pub fn tail(&self) -> &FieldDef {
1439        self.tail_opt().expect("expected unsized ADT to have a tail field")
1440    }
1441
1442    /// Returns whether this variant has unsafe fields.
1443    pub fn has_unsafe_fields(&self) -> bool {
1444        self.fields.iter().any(|x| x.safety.is_unsafe())
1445    }
1446}
1447
1448impl PartialEq for VariantDef {
1449    #[inline]
1450    fn eq(&self, other: &Self) -> bool {
1451        // There should be only one `VariantDef` for each `def_id`, therefore
1452        // it is fine to implement `PartialEq` only based on `def_id`.
1453        //
1454        // Below, we exhaustively destructure `self` and `other` so that if the
1455        // definition of `VariantDef` changes, a compile-error will be produced,
1456        // reminding us to revisit this assumption.
1457
1458        let Self {
1459            def_id: lhs_def_id,
1460            ctor: _,
1461            name: _,
1462            discr: _,
1463            fields: _,
1464            flags: _,
1465            tainted: _,
1466        } = &self;
1467        let Self {
1468            def_id: rhs_def_id,
1469            ctor: _,
1470            name: _,
1471            discr: _,
1472            fields: _,
1473            flags: _,
1474            tainted: _,
1475        } = other;
1476
1477        let res = lhs_def_id == rhs_def_id;
1478
1479        // Double check that implicit assumption detailed above.
1480        if truecfg!(debug_assertions) && res {
1481            let deep = self.ctor == other.ctor
1482                && self.name == other.name
1483                && self.discr == other.discr
1484                && self.fields == other.fields
1485                && self.flags == other.flags;
1486            if !deep {
    {
        ::core::panicking::panic_fmt(format_args!("VariantDef for the same def-id has differing data"));
    }
};assert!(deep, "VariantDef for the same def-id has differing data");
1487        }
1488
1489        res
1490    }
1491}
1492
1493impl Eq for VariantDef {}
1494
1495impl Hash for VariantDef {
1496    #[inline]
1497    fn hash<H: Hasher>(&self, s: &mut H) {
1498        // There should be only one `VariantDef` for each `def_id`, therefore
1499        // it is fine to implement `Hash` only based on `def_id`.
1500        //
1501        // Below, we exhaustively destructure `self` so that if the definition
1502        // of `VariantDef` changes, a compile-error will be produced, reminding
1503        // us to revisit this assumption.
1504
1505        let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1506        def_id.hash(s)
1507    }
1508}
1509
1510#[derive(#[automatically_derived]
impl ::core::marker::Copy for VariantDiscr { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for VariantDiscr { }
#[automatically_derived]
impl ::core::clone::Clone for VariantDiscr {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for VariantDiscr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Explicit(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Explicit", &__self_0),
            Self::Relative(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Relative", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for VariantDiscr { }
#[automatically_derived]
impl ::core::cmp::PartialEq for VariantDiscr {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Explicit(__self_0), Self::Explicit(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Relative(__self_0), Self::Relative(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for VariantDiscr {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for VariantDiscr {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        VariantDiscr::Explicit(ref __binding_0) => { 0usize }
                        VariantDiscr::Relative(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    VariantDiscr::Explicit(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    VariantDiscr::Relative(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for VariantDiscr {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        VariantDiscr::Explicit(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        VariantDiscr::Relative(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `VariantDiscr`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for VariantDiscr
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    VariantDiscr::Explicit(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    VariantDiscr::Relative(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1511pub enum VariantDiscr {
1512    /// Explicit value for this variant, i.e., `X = 123`.
1513    /// The `DefId` corresponds to the embedded constant.
1514    Explicit(DefId),
1515
1516    /// The previous variant's discriminant plus one.
1517    /// For efficiency reasons, the distance from the
1518    /// last `Explicit` discriminant is being stored,
1519    /// or `0` for the first variant, if it has none.
1520    Relative(u32),
1521}
1522
1523#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FieldDef {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["did", "name", "vis", "mut_restriction", "safety", "value"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.did, &self.name, &self.vis, &self.mut_restriction,
                        &self.safety, &&self.value];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "FieldDef",
            names, values)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for FieldDef {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    FieldDef {
                        did: ref __binding_0,
                        name: ref __binding_1,
                        vis: ref __binding_2,
                        mut_restriction: ref __binding_3,
                        safety: ref __binding_4,
                        value: ref __binding_5 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                        { __binding_4.stable_hash(__hcx, __hasher); }
                        { __binding_5.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for FieldDef {
            fn encode(&self, __encoder: &mut __E) {
                let FieldDef {
                        did: ref __binding_0,
                        name: ref __binding_1,
                        vis: ref __binding_2,
                        mut_restriction: ref __binding_3,
                        safety: ref __binding_4,
                        value: ref __binding_5 } = *self;
                ::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);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for FieldDef {
            fn decode(__decoder: &mut __D) -> Self {
                FieldDef {
                    did: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                    vis: ::rustc_serialize::Decodable::decode(__decoder),
                    mut_restriction: ::rustc_serialize::Decodable::decode(__decoder),
                    safety: ::rustc_serialize::Decodable::decode(__decoder),
                    value: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
1524pub struct FieldDef {
1525    pub did: DefId,
1526    pub name: Symbol,
1527    pub vis: Visibility<ModId>,
1528    pub mut_restriction: RestrictionKind,
1529    pub safety: hir::Safety,
1530    pub value: Option<DefId>,
1531}
1532
1533impl PartialEq for FieldDef {
1534    #[inline]
1535    fn eq(&self, other: &Self) -> bool {
1536        // There should be only one `FieldDef` for each `did`, therefore it is
1537        // fine to implement `PartialEq` only based on `did`.
1538        //
1539        // Below, we exhaustively destructure `self` so that if the definition
1540        // of `FieldDef` changes, a compile-error will be produced, reminding
1541        // us to revisit this assumption.
1542
1543        let Self { did: lhs_did, name: _, vis: _, mut_restriction: _, safety: _, value: _ } = &self;
1544
1545        let Self { did: rhs_did, name: _, vis: _, mut_restriction: _, safety: _, value: _ } = other;
1546
1547        let res = lhs_did == rhs_did;
1548
1549        // Double check that implicit assumption detailed above.
1550        if truecfg!(debug_assertions) && res {
1551            let deep = self.name == other.name
1552                && self.vis == other.vis
1553                && self.mut_restriction == other.mut_restriction
1554                && self.safety == other.safety;
1555            if !deep {
    {
        ::core::panicking::panic_fmt(format_args!("FieldDef for the same def-id has differing data"));
    }
};assert!(deep, "FieldDef for the same def-id has differing data");
1556        }
1557
1558        res
1559    }
1560}
1561
1562impl Eq for FieldDef {}
1563
1564impl Hash for FieldDef {
1565    #[inline]
1566    fn hash<H: Hasher>(&self, s: &mut H) {
1567        // There should be only one `FieldDef` for each `did`, therefore it is
1568        // fine to implement `Hash` only based on `did`.
1569        //
1570        // Below, we exhaustively destructure `self` so that if the definition
1571        // of `FieldDef` changes, a compile-error will be produced, reminding
1572        // us to revisit this assumption.
1573
1574        let Self { did, name: _, vis: _, mut_restriction: _, safety: _, value: _ } = &self;
1575
1576        did.hash(s)
1577    }
1578}
1579
1580impl<'tcx> FieldDef {
1581    /// Returns the type of this field. The `args` are typically obtained via
1582    /// the second field of [`TyKind::Adt`].
1583    pub fn ty(
1584        &self,
1585        tcx: TyCtxt<'tcx>,
1586        args: GenericArgsRef<'tcx>,
1587    ) -> Unnormalized<'tcx, Ty<'tcx>> {
1588        tcx.type_of(self.did).instantiate(tcx, args)
1589    }
1590
1591    /// Computes the `Ident` of this variant by looking up the `Span`
1592    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1593        Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1594    }
1595}
1596
1597#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImplOverlapKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Permitted { marker: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Permitted", "marker", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ImplOverlapKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ImplOverlapKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Permitted { marker: __self_0 }, Self::Permitted {
                marker: __arg1_0 }) => __self_0 == __arg1_0,
        }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ImplOverlapKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
1598pub enum ImplOverlapKind {
1599    /// These impls are always allowed to overlap.
1600    Permitted {
1601        /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1602        marker: bool,
1603    },
1604}
1605
1606/// Useful source information about where a desugared associated type for an
1607/// RPITIT originated from.
1608#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImplTraitInTraitData { }
#[automatically_derived]
impl ::core::clone::Clone for ImplTraitInTraitData {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ImplTraitInTraitData { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ImplTraitInTraitData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Trait { fn_def_id: __self_0, opaque_def_id: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Trait",
                    "fn_def_id", __self_0, "opaque_def_id", &__self_1),
            Self::Impl { fn_def_id: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Impl",
                    "fn_def_id", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ImplTraitInTraitData { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ImplTraitInTraitData {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Trait { fn_def_id: __self_0, opaque_def_id: __self_1 },
                    Self::Trait { fn_def_id: __arg1_0, opaque_def_id: __arg1_1
                    }) => __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (Self::Impl { fn_def_id: __self_0 }, Self::Impl {
                    fn_def_id: __arg1_0 }) => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ImplTraitInTraitData {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ImplTraitInTraitData {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Trait { fn_def_id: __self_0, opaque_def_id: __self_1 } => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            Self::Impl { fn_def_id: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for ImplTraitInTraitData {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        ImplTraitInTraitData::Trait {
                            fn_def_id: ref __binding_0, opaque_def_id: ref __binding_1 }
                            => {
                            0usize
                        }
                        ImplTraitInTraitData::Impl { fn_def_id: ref __binding_0 } =>
                            {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    ImplTraitInTraitData::Trait {
                        fn_def_id: ref __binding_0, opaque_def_id: ref __binding_1 }
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    ImplTraitInTraitData::Impl { fn_def_id: ref __binding_0 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for ImplTraitInTraitData {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        ImplTraitInTraitData::Trait {
                            fn_def_id: ::rustc_serialize::Decodable::decode(__decoder),
                            opaque_def_id: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    1usize => {
                        ImplTraitInTraitData::Impl {
                            fn_def_id: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `ImplTraitInTraitData`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            ImplTraitInTraitData {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    ImplTraitInTraitData::Trait {
                        fn_def_id: ref __binding_0, opaque_def_id: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    ImplTraitInTraitData::Impl { fn_def_id: ref __binding_0 } =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1609pub enum ImplTraitInTraitData {
1610    Trait { fn_def_id: DefId, opaque_def_id: DefId },
1611    Impl { fn_def_id: DefId },
1612}
1613
1614impl<'tcx> TyCtxt<'tcx> {
1615    pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1616        self.typeck(self.hir_body_owner_def_id(body))
1617    }
1618
1619    pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1620        self.associated_items(id)
1621            .in_definition_order()
1622            .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1623    }
1624
1625    pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1626        let mut flags = ReprFlags::empty();
1627        let mut size = None;
1628        let mut max_align: Option<Align> = None;
1629        let mut min_pack: Option<Align> = None;
1630
1631        // Generate a deterministically-derived seed from the item's path hash
1632        // to allow for cross-crate compilation to actually work
1633        let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1634
1635        // If the user defined a custom seed for layout randomization, xor the item's
1636        // path hash with the user defined seed, this will allowing determinism while
1637        // still allowing users to further randomize layout generation for e.g. fuzzing
1638        if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1639            field_shuffle_seed ^= user_seed;
1640        }
1641
1642        let elt = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &self) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcScalableVector {
                        element_count }) => {
                        break 'done Some(element_count);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self, did, RustcScalableVector { element_count } => element_count
1643        )
1644        .map(|elt| match elt {
1645            Some(n) => ScalableElt::ElementCount(*n),
1646            None => ScalableElt::Container,
1647        });
1648        if elt.is_some() {
1649            flags.insert(ReprFlags::IS_SCALABLE);
1650        }
1651        if let Some(reprs) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &self) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(Repr { reprs, .. }) => {
                        break 'done Some(reprs);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self, did, Repr { reprs, .. } => reprs) {
1652            for (r, _) in reprs {
1653                flags.insert(match *r {
1654                    attr::ReprRust => ReprFlags::empty(),
1655                    attr::ReprC => ReprFlags::IS_C,
1656                    attr::ReprPacked(pack) => {
1657                        min_pack = Some(if let Some(min_pack) = min_pack {
1658                            min_pack.min(pack)
1659                        } else {
1660                            pack
1661                        });
1662                        ReprFlags::empty()
1663                    }
1664                    attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1665                    attr::ReprSimd => ReprFlags::IS_SIMD,
1666                    attr::ReprInt(i) => {
1667                        size = Some(match i {
1668                            attr::IntType::SignedInt(x) => match x {
1669                                ast::IntTy::Isize => IntegerType::Pointer(true),
1670                                ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1671                                ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1672                                ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1673                                ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1674                                ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1675                            },
1676                            attr::IntType::UnsignedInt(x) => match x {
1677                                ast::UintTy::Usize => IntegerType::Pointer(false),
1678                                ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1679                                ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1680                                ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1681                                ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1682                                ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1683                            },
1684                        });
1685                        ReprFlags::empty()
1686                    }
1687                    attr::ReprAlign(align) => {
1688                        max_align = max_align.max(Some(align));
1689                        ReprFlags::empty()
1690                    }
1691                });
1692            }
1693        }
1694
1695        // If `-Z randomize-layout` was enabled for the type definition then we can
1696        // consider performing layout randomization
1697        if self.sess.opts.unstable_opts.randomize_layout {
1698            flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1699        }
1700
1701        // box is special, on the one hand the compiler assumes an ordered layout, with the pointer
1702        // always at offset zero. On the other hand we want scalar abi optimizations.
1703        let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1704
1705        // This is here instead of layout because the choice must make it into metadata.
1706        if is_box {
1707            flags.insert(ReprFlags::IS_LINEAR);
1708        }
1709
1710        // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
1711        if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &self) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcPassIndirectlyInNonRusticAbis(..))
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self, did, RustcPassIndirectlyInNonRusticAbis(..)) {
1712            flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1713        }
1714
1715        ReprOptions {
1716            int: size,
1717            align: max_align,
1718            pack: min_pack,
1719            flags,
1720            field_shuffle_seed,
1721            scalable: elt,
1722        }
1723    }
1724
1725    /// Look up the name of a definition across crates. This does not look at HIR.
1726    pub fn opt_item_name(self, def_id: impl IntoQueryKey<DefId>) -> Option<Symbol> {
1727        let def_id = def_id.into_query_key();
1728        if let Some(cnum) = def_id.as_crate_root() {
1729            Some(self.crate_name(cnum))
1730        } else {
1731            let def_key = self.def_key(def_id);
1732            match def_key.disambiguated_data.data {
1733                // The name of a constructor is that of its parent.
1734                rustc_hir::definitions::DefPathData::Ctor => self
1735                    .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1736                _ => def_key.get_opt_name(),
1737            }
1738        }
1739    }
1740
1741    /// Look up the name of a definition across crates. This does not look at HIR.
1742    ///
1743    /// This method will ICE if the corresponding item does not have a name. In these cases, use
1744    /// [`opt_item_name`] instead.
1745    ///
1746    /// [`opt_item_name`]: Self::opt_item_name
1747    pub fn item_name(self, id: impl IntoQueryKey<DefId>) -> Symbol {
1748        let id = id.into_query_key();
1749        self.opt_item_name(id).unwrap_or_else(|| {
1750            ::rustc_span::macros::bug_impl(None,
    format_args!("item_name: no name for {0:?}", self.def_path(id)),
    Location::caller());bug!("item_name: no name for {:?}", self.def_path(id));
1751        })
1752    }
1753
1754    /// Look up the name and span of a definition.
1755    ///
1756    /// See [`item_name`][Self::item_name] for more information.
1757    pub fn opt_item_ident(self, def_id: impl IntoQueryKey<DefId>) -> Option<Ident> {
1758        let def_id = def_id.into_query_key();
1759        let def = self.opt_item_name(def_id)?;
1760        let span = self
1761            .def_ident_span(def_id)
1762            .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("missing ident span for {0:?}", def_id), Location::caller())bug!("missing ident span for {def_id:?}"));
1763        Some(Ident::new(def, span))
1764    }
1765
1766    /// Look up the name and span of a definition.
1767    ///
1768    /// See [`item_name`][Self::item_name] for more information.
1769    pub fn item_ident(self, def_id: impl IntoQueryKey<DefId>) -> Ident {
1770        let def_id = def_id.into_query_key();
1771        self.opt_item_ident(def_id).unwrap_or_else(|| {
1772            ::rustc_span::macros::bug_impl(None,
    format_args!("item_ident: no name for {0:?}", self.def_path(def_id)),
    Location::caller());bug!("item_ident: no name for {:?}", self.def_path(def_id));
1773        })
1774    }
1775
1776    pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1777        if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1778            Some(self.associated_item(def_id))
1779        } else {
1780            None
1781        }
1782    }
1783
1784    /// If the `def_id` is an associated type that was desugared from a
1785    /// return-position `impl Trait` from a trait, then provide the source info
1786    /// about where that RPITIT came from.
1787    pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1788        if let DefKind::AssocTy = self.def_kind(def_id)
1789            && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1790                self.associated_item(def_id).kind
1791        {
1792            Some(rpitit_info)
1793        } else {
1794            None
1795        }
1796    }
1797
1798    pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1799        variant.fields.iter_enumerated().find_map(|(i, field)| {
1800            self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1801        })
1802    }
1803
1804    /// Returns `Some` if the impls are the same polarity and the trait either
1805    /// has no items or is annotated `#[marker]` and prevents item overrides.
1806    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("impls_are_allowed_to_overlap",
                                "rustc_middle::ty", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1806u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id1")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id1");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id2")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id2");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id1)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id2)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: Option<ImplOverlapKind> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let impl1 = self.impl_trait_header(def_id1);
                        let impl2 = self.impl_trait_header(def_id2);
                        let trait_ref1 = impl1.trait_ref.skip_binder();
                        let trait_ref2 = impl2.trait_ref.skip_binder();
                        if trait_ref1.references_error() ||
                                trait_ref2.references_error() {
                            return Some(ImplOverlapKind::Permitted { marker: false });
                        }
                        match (impl1.polarity, impl2.polarity) {
                            (ImplPolarity::Positive, ImplPolarity::Negative) |
                                (ImplPolarity::Negative, ImplPolarity::Positive) => {
                                return None;
                            }
                            (ImplPolarity::Positive, ImplPolarity::Positive) |
                                (ImplPolarity::Negative, ImplPolarity::Negative) => {}
                        };
                        let is_marker_impl =
                            |trait_ref: TraitRef<'_>|
                                self.trait_def(trait_ref.def_id).is_marker;
                        let is_marker_overlap =
                            is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
                        if is_marker_overlap {
                            return Some(ImplOverlapKind::Permitted { marker: true });
                        }
                        None
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs:1806",
                        "rustc_middle::ty", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1806u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1807    pub fn impls_are_allowed_to_overlap(
1808        self,
1809        def_id1: DefId,
1810        def_id2: DefId,
1811    ) -> Option<ImplOverlapKind> {
1812        let impl1 = self.impl_trait_header(def_id1);
1813        let impl2 = self.impl_trait_header(def_id2);
1814
1815        let trait_ref1 = impl1.trait_ref.skip_binder();
1816        let trait_ref2 = impl2.trait_ref.skip_binder();
1817
1818        // If either trait impl references an error, they're allowed to overlap,
1819        // as one of them essentially doesn't exist.
1820        if trait_ref1.references_error() || trait_ref2.references_error() {
1821            return Some(ImplOverlapKind::Permitted { marker: false });
1822        }
1823
1824        match (impl1.polarity, impl2.polarity) {
1825            (ImplPolarity::Positive, ImplPolarity::Negative)
1826            | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1827                // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1828                return None;
1829            }
1830            (ImplPolarity::Positive, ImplPolarity::Positive)
1831            | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1832        };
1833
1834        let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1835        let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1836
1837        if is_marker_overlap {
1838            return Some(ImplOverlapKind::Permitted { marker: true });
1839        }
1840
1841        None
1842    }
1843
1844    /// Returns `ty::VariantDef` if `res` refers to a struct,
1845    /// or variant or their constructors, panics otherwise.
1846    pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1847        match res {
1848            Res::Def(DefKind::Variant, did) => {
1849                let enum_did = self.parent(did);
1850                self.adt_def(enum_did).variant_with_id(did)
1851            }
1852            Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1853            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1854                let variant_did = self.parent(variant_ctor_did);
1855                let enum_did = self.parent(variant_did);
1856                self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1857            }
1858            Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1859                let struct_did = self.parent(ctor_did);
1860                self.adt_def(struct_did).non_enum_variant()
1861            }
1862            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("expect_variant_res used with unexpected res {0:?}", res),
    Location::caller())bug!("expect_variant_res used with unexpected res {:?}", res),
1863        }
1864    }
1865
1866    /// Returns the possibly-auto-generated MIR of a [`ty::InstanceKind`].
1867    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instance_mir",
                                    "rustc_middle::ty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1867u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'tcx Body<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let body =
                match instance {
                    ty::InstanceKind::Item(def) => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs:1871",
                                                "rustc_middle::ty", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1871u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("calling def_kind on def: {0:?}",
                                                                            def) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let def_kind = self.def_kind(def);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs:1873",
                                                "rustc_middle::ty", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_middle/src/ty/mod.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1873u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("returned from def_kind: {0:?}",
                                                                            def_kind) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        match def_kind {
                            DefKind::Const | DefKind::Static { .. } |
                                DefKind::AssocConst | DefKind::Ctor(..) | DefKind::AnonConst
                                => self.mir_for_ctfe(def),
                            DefKind::Fn | DefKind::AssocFn if
                                #[allow(non_exhaustive_omitted_patterns)] match self.constness(def)
                                    {
                                    hir::Constness::Const { always: true } => true,
                                    _ => false,
                                } => {
                                self.mir_for_ctfe(def)
                            }
                            _ => self.optimized_mir(def),
                        }
                    }
                    ty::InstanceKind::Intrinsic(..) |
                        ty::InstanceKind::LlvmIntrinsic(..) => {
                        ::rustc_span::macros::bug_impl(None,
                            format_args!("intrinsics have no instance MIR"),
                            Location::caller())
                    }
                    ty::InstanceKind::Virtual(..) =>
                        ::rustc_span::macros::bug_impl(None,
                            format_args!("virtual dispatches have no instance MIR"),
                            Location::caller()),
                    ty::InstanceKind::Shim(shim) => self.mir_shims(shim),
                };
            if !#[allow(non_exhaustive_omitted_patterns)] match body.phase {
                        MirPhase::Runtime(_) => true,
                        _ => false,
                    } {
                {
                    ::core::panicking::panic_fmt(format_args!("body: {1:?} instance: {2:?} {0:?}",
                            if let ty::InstanceKind::Item(d) = instance {
                                Some(self.def_kind(d))
                            } else { None }, body, instance));
                }
            };
            body
        }
    }
}#[instrument(skip(self), level = "debug")]
1868    pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1869        let body = match instance {
1870            ty::InstanceKind::Item(def) => {
1871                debug!("calling def_kind on def: {:?}", def);
1872                let def_kind = self.def_kind(def);
1873                debug!("returned from def_kind: {:?}", def_kind);
1874                match def_kind {
1875                    DefKind::Const
1876                    | DefKind::Static { .. }
1877                    | DefKind::AssocConst
1878                    | DefKind::Ctor(..)
1879                    | DefKind::AnonConst => self.mir_for_ctfe(def),
1880                    DefKind::Fn | DefKind::AssocFn
1881                        if matches!(
1882                            self.constness(def),
1883                            hir::Constness::Const { always: true }
1884                        ) =>
1885                    {
1886                        self.mir_for_ctfe(def)
1887                    }
1888                    // If the caller wants `mir_for_ctfe` of a function they should not be using
1889                    // `instance_mir`, so we'll assume const fn also wants the optimized version.
1890                    _ => self.optimized_mir(def),
1891                }
1892            }
1893            ty::InstanceKind::Intrinsic(..) | ty::InstanceKind::LlvmIntrinsic(..) => {
1894                bug!("intrinsics have no instance MIR")
1895            }
1896            ty::InstanceKind::Virtual(..) => bug!("virtual dispatches have no instance MIR"),
1897            ty::InstanceKind::Shim(shim) => self.mir_shims(shim),
1898        };
1899
1900        assert!(
1901            matches!(body.phase, MirPhase::Runtime(_)),
1902            "body: {body:?} instance: {instance:?} {:?}",
1903            if let ty::InstanceKind::Item(d) = instance { Some(self.def_kind(d)) } else { None },
1904        );
1905
1906        body
1907    }
1908
1909    /// Gets all attributes with the given name.
1910    #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to use `rustc_attr_ir::find_attr!` instead."]
1911    pub fn get_attrs(
1912        self,
1913        did: impl Into<DefId>,
1914        attr: Symbol,
1915    ) -> impl Iterator<Item = &'tcx rustc_attr_ir::Attribute> {
1916        #[expect(deprecated)]
1917        self.get_all_attrs(did).iter().filter(move |a: &&rustc_attr_ir::Attribute| a.has_name(attr))
1918    }
1919
1920    /// Gets all attributes.
1921    ///
1922    /// <div class="warning">
1923    ///
1924    /// To see if an item has a specific attribute, you should use
1925    /// [`rustc_attr_ir::find_attr!`] so you can use matching.
1926    ///
1927    /// </div>
1928    ///
1929    #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to use `rustc_attr_ir::find_attr!` instead."]
1930    pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [rustc_attr_ir::Attribute] {
1931        let did: DefId = did.into();
1932        if let Some(did) = did.as_local() {
1933            self.hir_attrs(self.local_def_id_to_hir_id(did))
1934        } else {
1935            self.attrs_for_def(did)
1936        }
1937    }
1938
1939    pub fn get_attrs_by_path(
1940        self,
1941        did: DefId,
1942        attr: &[Symbol],
1943    ) -> impl Iterator<Item = &'tcx rustc_attr_ir::Attribute> {
1944        let filter_fn = move |a: &&rustc_attr_ir::Attribute| a.path_matches(attr);
1945        if let Some(did) = did.as_local() {
1946            self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1947        } else {
1948            self.attrs_for_def(did).iter().filter(filter_fn)
1949        }
1950    }
1951
1952    /// Returns `true` if this is an `auto trait`.
1953    pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1954        self.trait_def(trait_def_id).has_auto_impl
1955    }
1956
1957    /// Returns `true` if this is coinductive, either because it is
1958    /// an auto trait or because it has the `#[rustc_coinductive]` attribute.
1959    pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1960        self.trait_def(trait_def_id).is_coinductive
1961    }
1962
1963    /// Returns `true` if this is a trait alias.
1964    pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1965        self.def_kind(trait_def_id) == DefKind::TraitAlias
1966    }
1967
1968    /// Arena-alloc of LayoutError for coroutine layout
1969    fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1970        self.arena.alloc(err)
1971    }
1972
1973    /// Returns layout of a non-async-drop coroutine. Layout might be unavailable if the
1974    /// coroutine is tainted by errors.
1975    ///
1976    /// Takes `coroutine_kind` which can be acquired from the `CoroutineArgs::kind_ty`,
1977    /// e.g. `args.as_coroutine().kind_ty()`.
1978    fn ordinary_coroutine_layout(
1979        self,
1980        def_id: DefId,
1981        args: GenericArgsRef<'tcx>,
1982    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1983        let coroutine_kind_ty = args.as_coroutine().kind_ty();
1984        let mir = self.optimized_mir(def_id);
1985        let ty = || Ty::new_coroutine(self, def_id, args);
1986        // Regular coroutine
1987        if coroutine_kind_ty.is_unit() {
1988            mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1989        } else {
1990            // If we have a `Coroutine` that comes from an coroutine-closure,
1991            // then it may be a by-move or by-ref body.
1992            let ty::Coroutine(_, identity_args) =
1993                *self.type_of(def_id).instantiate_identity().skip_norm_wip().kind()
1994            else {
1995                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1996            };
1997            let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1998            // If the types differ, then we must be getting the by-move body of
1999            // a by-ref coroutine.
2000            if identity_kind_ty == coroutine_kind_ty {
2001                mir.coroutine_layout_raw()
2002                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
2003            } else {
2004                {
    match coroutine_kind_ty.to_opt_closure_kind() {
        Some(ClosureKind::FnOnce) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ClosureKind::FnOnce)", ::core::option::Option::None);
        }
    }
};assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
2005                {
    match identity_kind_ty.to_opt_closure_kind() {
        Some(ClosureKind::Fn | ClosureKind::FnMut) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Some(ClosureKind::Fn | ClosureKind::FnMut)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
2006                    identity_kind_ty.to_opt_closure_kind(),
2007                    Some(ClosureKind::Fn | ClosureKind::FnMut)
2008                );
2009                self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
2010                    .coroutine_layout_raw()
2011                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
2012            }
2013        }
2014    }
2015
2016    /// Returns layout of a `async_drop_in_place::{closure}` coroutine
2017    ///   (returned from `async fn async_drop_in_place<T>(..)`).
2018    /// Layout might be unavailable if the coroutine is tainted by errors.
2019    fn async_drop_coroutine_layout(
2020        self,
2021        def_id: DefId,
2022        args: GenericArgsRef<'tcx>,
2023    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
2024        let ty = || Ty::new_coroutine(self, def_id, args);
2025        if args[0].has_placeholders() || args[0].has_non_region_param() {
2026            return Err(self.layout_error(LayoutError::TooGeneric(ty())));
2027        }
2028        let instance = ShimKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
2029        self.mir_shims(instance)
2030            .coroutine_layout_raw()
2031            .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
2032    }
2033
2034    /// Returns layout of a coroutine. Layout might be unavailable if the
2035    /// coroutine is tainted by errors.
2036    pub fn coroutine_layout(
2037        self,
2038        def_id: DefId,
2039        args: GenericArgsRef<'tcx>,
2040    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
2041        if self.is_async_drop_in_place_coroutine(def_id) {
2042            // layout of `async_drop_in_place<T>::{closure}` in case,
2043            // when T is a coroutine, contains this internal coroutine's ptr in upvars
2044            // and doesn't require any locals. Here is an `empty coroutine's layout`
2045            let arg_cor_ty = args.first().unwrap().expect_ty();
2046            if arg_cor_ty.is_coroutine() {
2047                let span = self.def_span(def_id);
2048                let source_info = SourceInfo::outermost(span);
2049                // Even minimal, empty coroutine has 3 states (RESERVED_VARIANTS),
2050                // so variant_fields and variant_source_info should have 3 elements.
2051                let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
2052                    iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
2053                let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
2054                    iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
2055                let proxy_layout = CoroutineLayout {
2056                    field_tys: [].into(),
2057                    variant_fields,
2058                    variant_source_info,
2059                    storage_conflicts: BitMatrix::new(0, 0),
2060                };
2061                return Ok(self.arena.alloc(proxy_layout));
2062            } else {
2063                self.async_drop_coroutine_layout(def_id, args)
2064            }
2065        } else {
2066            self.ordinary_coroutine_layout(def_id, args)
2067        }
2068    }
2069
2070    /// If the given `DefId` is an associated item, returns the `DefId` and `DefKind` of the parent trait or impl.
2071    pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
2072        if !self.def_kind(def_id).is_assoc() {
2073            return None;
2074        }
2075        let parent = self.parent(def_id);
2076        let def_kind = self.def_kind(parent);
2077        Some((parent, def_kind))
2078    }
2079
2080    /// Returns the trait item that is implemented by the given item `DefId`.
2081    pub fn trait_item_of(self, def_id: impl IntoQueryKey<DefId>) -> Option<DefId> {
2082        let def_id = def_id.into_query_key();
2083        self.opt_associated_item(def_id)?.trait_item_def_id()
2084    }
2085
2086    /// If the given `DefId` is an associated item of a trait,
2087    /// returns the `DefId` of the trait; otherwise, returns `None`.
2088    pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
2089        match self.assoc_parent(def_id) {
2090            Some((id, DefKind::Trait)) => Some(id),
2091            _ => None,
2092        }
2093    }
2094
2095    pub fn impl_is_of_trait(self, def_id: impl IntoQueryKey<DefId>) -> bool {
2096        let def_id = def_id.into_query_key();
2097        let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
2098            {
    ::core::panicking::panic_fmt(format_args!("expected Impl for {0:?}",
            def_id));
};panic!("expected Impl for {def_id:?}");
2099        };
2100        of_trait
2101    }
2102
2103    /// If the given `DefId` is an associated item of an impl,
2104    /// returns the `DefId` of the impl; otherwise returns `None`.
2105    pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2106        match self.assoc_parent(def_id) {
2107            Some((id, DefKind::Impl { .. })) => Some(id),
2108            _ => None,
2109        }
2110    }
2111
2112    /// If the given `DefId` is an associated item of an inherent impl,
2113    /// returns the `DefId` of the impl; otherwise, returns `None`.
2114    pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2115        match self.assoc_parent(def_id) {
2116            Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2117            _ => None,
2118        }
2119    }
2120
2121    /// If the given `DefId` is an associated item of a trait impl,
2122    /// returns the `DefId` of the impl; otherwise, returns `None`.
2123    pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2124        match self.assoc_parent(def_id) {
2125            Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2126            _ => None,
2127        }
2128    }
2129
2130    pub fn impl_polarity(self, def_id: impl IntoQueryKey<DefId>) -> ty::ImplPolarity {
2131        let def_id = def_id.into_query_key();
2132        self.impl_trait_header(def_id).polarity
2133    }
2134
2135    /// Given an `impl_id`, return the trait it implements.
2136    pub fn impl_trait_ref(
2137        self,
2138        def_id: impl IntoQueryKey<DefId>,
2139    ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2140        let def_id = def_id.into_query_key();
2141        self.impl_trait_header(def_id).trait_ref
2142    }
2143
2144    /// Given an `impl_id`, return the trait it implements.
2145    /// Returns `None` if it is an inherent impl.
2146    pub fn impl_opt_trait_ref(
2147        self,
2148        def_id: impl IntoQueryKey<DefId>,
2149    ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2150        let def_id = def_id.into_query_key();
2151        self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2152    }
2153
2154    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2155    pub fn impl_trait_id(self, def_id: impl IntoQueryKey<DefId>) -> DefId {
2156        let def_id = def_id.into_query_key();
2157        self.impl_trait_ref(def_id).skip_binder().def_id
2158    }
2159
2160    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2161    /// Returns `None` if it is an inherent impl.
2162    pub fn impl_opt_trait_id(self, def_id: impl IntoQueryKey<DefId>) -> Option<DefId> {
2163        let def_id = def_id.into_query_key();
2164        self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2165    }
2166
2167    pub fn is_exportable(self, def_id: DefId) -> bool {
2168        self.exportable_items(def_id.krate).contains(&def_id)
2169    }
2170
2171    /// Check if the given `DefId` is `#\[automatically_derived\]`, *and*
2172    /// whether it was produced by expanding a builtin derive macro.
2173    pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2174        if self.is_automatically_derived(def_id)
2175            && let Some(def_id) = def_id.as_local()
2176            && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2177            && #[allow(non_exhaustive_omitted_patterns)] match outer.kind {
    ExpnKind::Macro(MacroKind::Derive, _) => true,
    _ => false,
}matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2178            && {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(outer.macro_def_id.unwrap(),
                        &self) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcBuiltinMacro { .. })
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self, outer.macro_def_id.unwrap(), RustcBuiltinMacro { .. })
2179        {
2180            true
2181        } else {
2182            false
2183        }
2184    }
2185
2186    /// Check if the given `DefId` is `#\[automatically_derived\]`.
2187    pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2188        {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(AutomaticallyDerived) =>
                            {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self, def_id, AutomaticallyDerived)
2189    }
2190
2191    /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2192    /// with the name of the crate containing the impl.
2193    pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2194        if let Some(impl_def_id) = impl_def_id.as_local() {
2195            Ok(self.def_span(impl_def_id))
2196        } else {
2197            Err(self.crate_name(impl_def_id.krate))
2198        }
2199    }
2200
2201    /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2202    /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2203    /// definition's parent/scope to perform comparison.
2204    pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2205        // We could use `Ident::eq` here, but we deliberately don't. The identifier
2206        // comparison fails frequently, and we want to avoid the expensive
2207        // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2208        use_ident.name == def_ident.name
2209            && use_ident
2210                .span
2211                .ctxt()
2212                .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2213    }
2214
2215    pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2216        ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2217        ident
2218    }
2219
2220    pub fn adjust_ident_and_get_scope(
2221        self,
2222        mut ident: Ident,
2223        scope: DefId,
2224        mod_id: LocalModId,
2225    ) -> (Ident, ModId) {
2226        let scope = ident
2227            .span
2228            .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2229            .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2230            .unwrap_or(mod_id.to_mod_id());
2231        (ident, scope)
2232    }
2233
2234    /// Checks whether this is a `const fn`. Returns `false` for non-functions.
2235    ///
2236    /// Even if this returns `true`, constness may still be unstable!
2237    #[inline]
2238    pub fn is_const_fn(self, def_id: impl IntoQueryKey<DefId>) -> bool {
2239        let def_id = def_id.into_query_key();
2240        #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
    DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) |
        DefKind::Closure => true,
    _ => false,
}matches!(
2241            self.def_kind(def_id),
2242            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2243        ) && #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { .. } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { .. })
2244    }
2245
2246    /// Whether this item is conditionally constant for the purposes of the
2247    /// effects implementation.
2248    ///
2249    /// This roughly corresponds to all const functions and other callable
2250    /// items, along with const impls and traits, and associated types within
2251    /// those impls and traits.
2252    pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2253        let def_id: DefId = def_id.into();
2254        match self.def_kind(def_id) {
2255            DefKind::Impl { of_trait: true } => {
2256                let header = self.impl_trait_header(def_id);
2257                #[allow(non_exhaustive_omitted_patterns)] match header.constness {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(header.constness, hir::Constness::Const { always: false })
2258                    && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2259            }
2260            DefKind::Impl { of_trait: false } => {
2261                #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { always: false })
2262            }
2263            DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2264                #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { always: false })
2265            }
2266            DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2267            DefKind::AssocTy => {
2268                let parent_def_id = self.parent(def_id);
2269                match self.def_kind(parent_def_id) {
2270                    DefKind::Impl { of_trait: false } => false,
2271                    DefKind::Impl { of_trait: true } | DefKind::Trait => {
2272                        self.is_conditionally_const(parent_def_id)
2273                    }
2274                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected parent item of associated type: {0:?}",
        parent_def_id), Location::caller())bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2275                }
2276            }
2277            DefKind::AssocFn => {
2278                let parent_def_id = self.parent(def_id);
2279                match self.def_kind(parent_def_id) {
2280                    DefKind::Impl { of_trait: false } => {
2281                        #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { always: false })
2282                    }
2283                    DefKind::Impl { of_trait: true } => {
2284                        let Some(trait_method_did) = self.trait_item_of(def_id) else {
2285                            return false;
2286                        };
2287                        #[allow(non_exhaustive_omitted_patterns)] match self.constness(trait_method_did)
    {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(
2288                            self.constness(trait_method_did),
2289                            hir::Constness::Const { always: false }
2290                        ) && self.is_conditionally_const(parent_def_id)
2291                    }
2292                    DefKind::Trait => {
2293                        #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { always: false })
2294                            && self.is_conditionally_const(parent_def_id)
2295                    }
2296                    _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected parent item of associated fn: {0:?}",
        parent_def_id), Location::caller())bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2297                }
2298            }
2299            DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2300                hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2301                hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2302                // FIXME(const_trait_impl): ATPITs could be conditionally const?
2303                hir::OpaqueTyOrigin::TyAlias { .. } => false,
2304            },
2305            DefKind::Closure => {
2306                #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { always: false })
2307            }
2308            DefKind::Ctor(_, CtorKind::Const)
2309            | DefKind::Mod
2310            | DefKind::Struct
2311            | DefKind::Union
2312            | DefKind::Enum
2313            | DefKind::Variant
2314            | DefKind::TyAlias
2315            | DefKind::ForeignTy
2316            | DefKind::TyParam
2317            | DefKind::Const
2318            | DefKind::ConstParam
2319            | DefKind::Static { .. }
2320            | DefKind::AssocConst
2321            | DefKind::Macro(_)
2322            | DefKind::ExternCrate
2323            | DefKind::Use
2324            | DefKind::ForeignMod
2325            | DefKind::AnonConst
2326            | DefKind::Field
2327            | DefKind::LifetimeParam
2328            | DefKind::GlobalAsm
2329            | DefKind::SyntheticCoroutineBody
2330            | DefKind::TestBinderConstraints => false,
2331        }
2332    }
2333
2334    #[inline]
2335    pub fn is_const_trait(self, def_id: DefId) -> bool {
2336        #[allow(non_exhaustive_omitted_patterns)] match self.trait_def(def_id).constness
    {
    hir::Constness::Const { .. } => true,
    _ => false,
}matches!(self.trait_def(def_id).constness, hir::Constness::Const { .. })
2337    }
2338
2339    pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2340        if self.def_kind(def_id) != DefKind::AssocFn {
2341            return false;
2342        }
2343
2344        let Some(item) = self.opt_associated_item(def_id) else {
2345            return false;
2346        };
2347
2348        let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2349            return false;
2350        };
2351
2352        !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2353    }
2354
2355    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
2356    /// to an `fn`. Indirectly-passed parameters in the returned ABI will include applicable
2357    /// codegen optimization attributes, including `ReadOnly` and `CapturesNone` -- deduction of
2358    /// which requires inspection of function bodies that can lead to cycles when performed during
2359    /// typeck. During typeck, you should therefore use instead the unoptimized ABI returned by
2360    /// `fn_abi_of_instance_no_deduced_attrs`.
2361    ///
2362    /// For performance reasons, you should prefer to call this inherent method rather than invoke
2363    /// the `fn_abi_of_instance_raw` query: it delegates to that query if necessary, but where
2364    /// possible delegates instead to the `fn_abi_of_instance_no_deduced_attrs` query (thus avoiding
2365    /// unnecessary query system overhead).
2366    ///
2367    /// * that includes virtual calls, which are represented by "direct calls" to an
2368    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
2369    #[inline]
2370    pub fn fn_abi_of_instance(
2371        self,
2372        query: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
2373    ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
2374        // Only deduce attrs in full, optimized builds. Otherwise, avoid the query system overhead
2375        // of ever invoking the `fn_abi_of_instance_raw` query.
2376        if self.sess.opts.optimize != OptLevel::No && self.sess.opts.incremental.is_none() {
2377            self.fn_abi_of_instance_raw(query)
2378        } else {
2379            self.fn_abi_of_instance_no_deduced_attrs(query)
2380        }
2381    }
2382}
2383
2384// `HasAttrs` impls: allow `find_attr!(tcx, id, ...)` to work with both DefId-like types and HirId.
2385
2386impl<'tcx> rustc_attr_ir::HasAttrs<'tcx, TyCtxt<'tcx>> for DefId {
2387    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [rustc_attr_ir::Attribute] {
2388        if let Some(did) = self.as_local() {
2389            tcx.hir_attrs(tcx.local_def_id_to_hir_id(did))
2390        } else {
2391            tcx.attrs_for_def(self)
2392        }
2393    }
2394}
2395
2396impl<'tcx> rustc_attr_ir::HasAttrs<'tcx, TyCtxt<'tcx>> for LocalDefId {
2397    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [rustc_attr_ir::Attribute] {
2398        tcx.hir_attrs(tcx.local_def_id_to_hir_id(self))
2399    }
2400}
2401
2402impl<'tcx> rustc_attr_ir::HasAttrs<'tcx, TyCtxt<'tcx>> for hir::OwnerId {
2403    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [rustc_attr_ir::Attribute] {
2404        rustc_attr_ir::HasAttrs::get_attrs(self.def_id, tcx)
2405    }
2406}
2407
2408impl<'tcx> rustc_attr_ir::HasAttrs<'tcx, TyCtxt<'tcx>> for hir::HirId {
2409    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [rustc_attr_ir::Attribute] {
2410        tcx.hir_attrs(self)
2411    }
2412}
2413
2414pub fn provide(providers: &mut Providers) {
2415    closure::provide(providers);
2416    context::provide(providers);
2417    erase_regions::provide(providers);
2418    inhabitedness::provide(providers);
2419    util::provide(providers);
2420    print::provide(providers);
2421    super::util::bug::provide(providers);
2422    *providers = Providers {
2423        trait_impls_of: trait_def::trait_impls_of_provider,
2424        incoherent_impls: trait_def::incoherent_impls_provider,
2425        trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2426        traits: trait_def::traits_provider,
2427        vtable_allocation: vtable::vtable_allocation_provider,
2428        ..*providers
2429    };
2430}
2431
2432/// A map for the local crate mapping each type to a vector of its
2433/// inherent impls. This is not meant to be used outside of coherence;
2434/// rather, you should request the vector for a specific type via
2435/// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2436/// (constructing this map requires touching the entire crate).
2437#[derive(#[automatically_derived]
impl ::core::clone::Clone for CrateInherentImpls {
    #[inline]
    fn clone(&self) -> Self {
        CrateInherentImpls {
            inherent_impls: ::core::clone::Clone::clone(&self.inherent_impls),
            incoherent_impls: ::core::clone::Clone::clone(&self.incoherent_impls),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CrateInherentImpls {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "CrateInherentImpls", "inherent_impls", &self.inherent_impls,
            "incoherent_impls", &&self.incoherent_impls)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for CrateInherentImpls {
    #[inline]
    fn default() -> Self {
        CrateInherentImpls {
            inherent_impls: ::core::default::Default::default(),
            incoherent_impls: ::core::default::Default::default(),
        }
    }
}Default, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            CrateInherentImpls {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    CrateInherentImpls {
                        inherent_impls: ref __binding_0,
                        incoherent_impls: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
2438pub struct CrateInherentImpls {
2439    pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2440    pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2441}
2442
2443#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for SymbolName<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SymbolName<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'tcx str>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for SymbolName<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for SymbolName<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for SymbolName<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.name == other.name }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for SymbolName<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<&'tcx str>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialOrd for SymbolName<'tcx> {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl<'tcx> ::core::cmp::Ord for SymbolName<'tcx> {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.name, &other.name)
    }
}Ord, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for SymbolName<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.name, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for SymbolName<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let SymbolName { name: __binding_0 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            SymbolName<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    SymbolName { name: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
2444pub struct SymbolName<'tcx> {
2445    /// `&str` gives a consistent ordering, which ensures reproducible builds.
2446    pub name: &'tcx str,
2447}
2448
2449impl<'tcx> SymbolName<'tcx> {
2450    pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2451        SymbolName { name: tcx.arena.alloc_str(name) }
2452    }
2453}
2454
2455impl<'tcx> fmt::Display for SymbolName<'tcx> {
2456    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2457        fmt::Display::fmt(&self.name, fmt)
2458    }
2459}
2460
2461impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2462    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2463        fmt::Display::fmt(&self.name, fmt)
2464    }
2465}
2466
2467/// The constituent parts of a type level constant of kind ADT or array.
2468#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for DestructuredAdtConst<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for DestructuredAdtConst<'tcx> {
}
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for DestructuredAdtConst<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<VariantIdx>;
        let _: ::core::clone::AssertParamIsClone<&'tcx [ty::Const<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for DestructuredAdtConst<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DestructuredAdtConst", "variant", &self.variant, "fields",
            &&self.fields)
    }
}Debug, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            DestructuredAdtConst<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    DestructuredAdtConst {
                        variant: ref __binding_0, fields: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
2469pub struct DestructuredAdtConst<'tcx> {
2470    pub variant: VariantIdx,
2471    pub fields: &'tcx [ty::Const<'tcx>],
2472}