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::ptr::NonNull;
20use std::{assert_matches, fmt, iter, str};
21
22pub use adt::*;
23pub use assoc::*;
24pub use generic_args::{GenericArgKind, TermKind, *};
25pub use generics::*;
26pub use intrinsic::IntrinsicDef;
27use rustc_abi::{
28    Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, VariantIdx,
29};
30use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
31use rustc_ast::node_id::NodeMap;
32use rustc_ast::{self as ast};
33pub use rustc_ast_ir::{Movability, Mutability, try_visit};
34use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
35use rustc_data_structures::intern::Interned;
36use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
37use rustc_data_structures::steal::Steal;
38use rustc_data_structures::unord::{UnordMap, UnordSet};
39use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
40use rustc_hir::attrs::StrippedCfgItem;
41use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
42use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
43use rustc_hir::definitions::PerParentDisambiguatorState;
44use rustc_hir::{self as hir, LangItem, MissingLifetimeKind, attrs as attr, find_attr};
45use rustc_index::IndexVec;
46use rustc_index::bit_set::BitMatrix;
47use rustc_macros::{
48    BlobDecodable, Decodable, Encodable, StableHash, TyDecodable, TyEncodable, TypeFoldable,
49    TypeVisitable, extension,
50};
51use rustc_serialize::{Decodable, Encodable};
52use rustc_session::config::OptLevel;
53pub use rustc_session::lint::RegisteredTools;
54use rustc_span::hygiene::MacroKind;
55use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol};
56use rustc_target::callconv::FnAbi;
57pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
58pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
59#[allow(
60    hidden_glob_reexports,
61    rustc::usage_of_type_ir_inherent,
62    rustc::non_glob_import_of_type_ir_inherent
63)]
64use rustc_type_ir::inherent;
65pub use rustc_type_ir::relate::VarianceDiagInfo;
66pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind, VisibleForLeakCheck};
67pub use rustc_type_ir::*;
68#[allow(hidden_glob_reexports, unused_imports)]
69use rustc_type_ir::{InferCtxtLike, Interner};
70use tracing::{debug, instrument, trace};
71pub use vtable::*;
72
73pub use self::closure::{
74    BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
75    MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
76    UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
77    place_to_string_for_capture,
78};
79pub use self::consts::{
80    AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr, ExprKind,
81    LitToConstInput, ScalarInt, SimdAlign, UnevaluatedConst, UnevaluatedConstKind, ValTree,
82    ValTreeKindExt, Value, const_lit_matches_ty,
83};
84pub use self::context::{
85    CtxtInterners, CurrentGcx, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
86};
87pub use self::fold::*;
88pub use self::instance::{Instance, InstanceKind, ReifyReason};
89pub(crate) use self::list::RawList;
90pub use self::list::{List, ListWithCachedTypeInfo};
91pub use self::opaque_types::OpaqueTypeKey;
92pub use self::pattern::{Pattern, PatternKind};
93pub use self::predicate::{
94    AliasTerm, AliasTermKind, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate,
95    ExistentialPredicate, ExistentialPredicateStableCmpExt, ExistentialProjection,
96    ExistentialTraitRef, HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
97    PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
98    PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
99    PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
100    RegionConstraint, RegionEqPredicate, RegionOutlivesPredicate, SubtypePredicate, TraitPredicate,
101    TraitRef, TypeOutlivesPredicate,
102};
103pub use self::region::{
104    EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region, RegionKind, RegionVid,
105};
106pub use self::sty::{
107    AliasTy, AliasTyKind, Article, Binder, BoundConst, BoundRegion, BoundRegionKind, BoundTy,
108    BoundTyKind, BoundVariableKind, CanonicalPolyFnSig, CoroutineArgsExt, EarlyBinder, FnSig,
109    FnSigKind, InlineConstArgs, InlineConstArgsParts, ParamConst, ParamTy, PlaceholderConst,
110    PlaceholderRegion, PlaceholderType, PolyFnSig, TyKind, TypeAndMut, TypingMode,
111    TypingModeEqWrapper, Unnormalized, UpvarArgs,
112};
113pub use self::trait_def::TraitDef;
114pub use self::typeck_results::{
115    CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
116    Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
117};
118use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
119use crate::metadata::{AmbigModChild, ModChild};
120use crate::middle::privacy::EffectiveVisibilities;
121use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
122use crate::query::{IntoQueryKey, Providers};
123use crate::ty;
124use crate::ty::codec::{TyDecoder, TyEncoder};
125pub use crate::ty::diagnostics::*;
126use crate::ty::fast_reject::SimplifiedType;
127use crate::ty::layout::{FnAbiError, LayoutError};
128use crate::ty::util::Discr;
129use crate::ty::walk::TypeWalker;
130
131pub mod abstract_const;
132pub mod adjustment;
133pub mod cast;
134pub mod codec;
135pub mod error;
136pub mod fast_reject;
137pub mod inhabitedness;
138pub mod layout;
139pub mod normalize_erasing_regions;
140pub mod offload_meta;
141pub mod pattern;
142pub mod print;
143pub mod relate;
144pub mod significant_drop_order;
145pub mod trait_def;
146pub mod util;
147pub mod vtable;
148
149mod adt;
150mod assoc;
151mod closure;
152mod consts;
153mod context;
154mod diagnostics;
155mod elaborate_impl;
156mod erase_regions;
157mod fold;
158mod generic_args;
159mod generics;
160mod impls_ty;
161mod instance;
162mod intrinsic;
163mod list;
164mod opaque_types;
165mod predicate;
166mod region;
167mod structural_impls;
168#[allow(hidden_glob_reexports)]
169mod sty;
170mod typeck_results;
171mod visit;
172
173// Data types
174
175#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ResolverGlobalCtxt {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["visibilities_for_hashing", "expn_that_defined",
                        "effective_visibilities", "macro_reachable_adts",
                        "extern_crate_map", "maybe_unused_trait_imports",
                        "module_children", "ambig_module_children", "glob_map",
                        "main_def", "trait_impls", "proc_macros",
                        "confused_type_with_std_module", "doc_link_resolutions",
                        "doc_link_traits_in_scope", "all_macro_rules",
                        "stripped_cfg_items", "delegation_infos"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.visibilities_for_hashing, &self.expn_that_defined,
                        &self.effective_visibilities, &self.macro_reachable_adts,
                        &self.extern_crate_map, &self.maybe_unused_trait_imports,
                        &self.module_children, &self.ambig_module_children,
                        &self.glob_map, &self.main_def, &self.trait_impls,
                        &self.proc_macros, &self.confused_type_with_std_module,
                        &self.doc_link_resolutions, &self.doc_link_traits_in_scope,
                        &self.all_macro_rules, &self.stripped_cfg_items,
                        &&self.delegation_infos];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "ResolverGlobalCtxt", names, values)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            ResolverGlobalCtxt {
            #[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 {
                    ResolverGlobalCtxt {
                        visibilities_for_hashing: ref __binding_0,
                        expn_that_defined: ref __binding_1,
                        effective_visibilities: ref __binding_2,
                        macro_reachable_adts: ref __binding_3,
                        extern_crate_map: ref __binding_4,
                        maybe_unused_trait_imports: ref __binding_5,
                        module_children: ref __binding_6,
                        ambig_module_children: ref __binding_7,
                        glob_map: ref __binding_8,
                        main_def: ref __binding_9,
                        trait_impls: ref __binding_10,
                        proc_macros: ref __binding_11,
                        confused_type_with_std_module: ref __binding_12,
                        doc_link_resolutions: ref __binding_13,
                        doc_link_traits_in_scope: ref __binding_14,
                        all_macro_rules: ref __binding_15,
                        stripped_cfg_items: ref __binding_16,
                        delegation_infos: ref __binding_17 } => {
                        { __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); }
                        { __binding_7.stable_hash(__hcx, __hasher); }
                        { __binding_8.stable_hash(__hcx, __hasher); }
                        { __binding_9.stable_hash(__hcx, __hasher); }
                        { __binding_10.stable_hash(__hcx, __hasher); }
                        { __binding_11.stable_hash(__hcx, __hasher); }
                        { __binding_12.stable_hash(__hcx, __hasher); }
                        { __binding_13.stable_hash(__hcx, __hasher); }
                        { __binding_14.stable_hash(__hcx, __hasher); }
                        { __binding_15.stable_hash(__hcx, __hasher); }
                        { __binding_16.stable_hash(__hcx, __hasher); }
                        { __binding_17.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
176pub struct ResolverGlobalCtxt {
177    pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
178    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
179    pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
180    pub effective_visibilities: EffectiveVisibilities,
181    // FIXME: This table contains ADTs reachable from macro 2.0.
182    // Currently, reachability of a definition from a macro is determined by nominal visibility
183    // (see `compute_effective_visibilities`). This is incorrect and leads to the necessity
184    // of traversing ADT fields in `rustc_privacy`. Remove this workaround once the
185    // correct reachability logic is implemented for macros.
186    pub macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,
187    pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
188    pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
189    pub module_children: LocalDefIdMap<Vec<ModChild>>,
190    pub ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
191    pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
192    pub main_def: Option<MainDefinition>,
193    pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
194    /// A list of proc macro LocalDefIds, written out in the order in which
195    /// they are declared in the static array generated by proc_macro_harness.
196    pub proc_macros: Vec<LocalDefId>,
197    /// Mapping from ident span to path span for paths that don't exist as written, but that
198    /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
199    pub confused_type_with_std_module: FxIndexMap<Span, Span>,
200    pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
201    pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
202    pub all_macro_rules: UnordSet<Symbol>,
203    pub stripped_cfg_items: Vec<StrippedCfgItem>,
204    // Information about delegations which is used when handling recursive delegations
205    // and ensures easy access to delegation-only `LocalDefId`s.
206    pub delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,
207}
208
209#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PerOwnerResolverData<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["node_id_to_def_id", "lifetime_elision_allowed",
                        "label_res_map", "lifetimes_res_map", "trait_map",
                        "import_res", "id", "def_id"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.node_id_to_def_id, &self.lifetime_elision_allowed,
                        &self.label_res_map, &self.lifetimes_res_map,
                        &self.trait_map, &self.import_res, &self.id, &&self.def_id];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "PerOwnerResolverData", names, values)
    }
}Debug)]
210pub struct PerOwnerResolverData<'tcx> {
211    pub node_id_to_def_id: NodeMap<LocalDefId> = Default::default(),
212    /// Whether lifetime elision was successful.
213    pub lifetime_elision_allowed: bool = false,
214    /// Resolutions for labels.
215    /// Maps from NodeId of the break/continue expression to the NodeId of their corresponding blocks or loops.
216    pub label_res_map: NodeMap<ast::NodeId> = Default::default(),
217    /// Resolutions for lifetimes.
218    pub lifetimes_res_map: NodeMap<LifetimeRes> = Default::default(),
219
220    pub trait_map: NodeMap<&'tcx [hir::TraitCandidate<'tcx>]> = Default::default(),
221
222    /// Resolution for import nodes, which have multiple resolutions in different namespaces.
223    pub import_res: hir::def::PerNS<Option<Res<ast::NodeId>>> = Default::default(),
224
225    /// The id of the owner
226    pub id: ast::NodeId,
227    /// The `DefId` of the owner, can't be found in `node_id_to_def_id`.
228    pub def_id: LocalDefId,
229}
230
231impl<'tcx> PerOwnerResolverData<'tcx> {
232    pub fn new(id: ast::NodeId, def_id: LocalDefId) -> PerOwnerResolverData<'tcx> {
233        PerOwnerResolverData { id, def_id, .. }
234    }
235
236    /// Obtains resolution for a label with the given `NodeId`.
237    pub fn get_label_res(&self, id: ast::NodeId) -> Option<ast::NodeId> {
238        self.label_res_map.get(&id).copied()
239    }
240
241    /// Obtains resolution for a lifetime with the given `NodeId`.
242    pub fn get_lifetime_res(&self, id: ast::NodeId) -> Option<LifetimeRes> {
243        self.lifetimes_res_map.get(&id).copied()
244    }
245}
246
247/// Resolutions that should only be used for lowering.
248/// This struct is meant to be consumed by lowering.
249#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ResolverAstLowering<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["partial_res_map", "extra_lifetime_params_map", "next_node_id",
                        "owners", "lint_buffer", "disambiguators"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.partial_res_map, &self.extra_lifetime_params_map,
                        &self.next_node_id, &self.owners, &self.lint_buffer,
                        &&self.disambiguators];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "ResolverAstLowering", names, values)
    }
}Debug)]
250pub struct ResolverAstLowering<'tcx> {
251    /// Resolutions for nodes that have a single resolution.
252    pub partial_res_map: NodeMap<hir::def::PartialRes>,
253    /// Lifetime parameters that lowering will have to introduce.
254    pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, MissingLifetimeKind)>>,
255
256    pub next_node_id: ast::NodeId,
257
258    pub owners: NodeMap<PerOwnerResolverData<'tcx>>,
259
260    /// Lints that were emitted by the resolver and early lints.
261    pub lint_buffer: Steal<LintBuffer>,
262
263    pub disambiguators: LocalDefIdMap<Steal<PerParentDisambiguatorState>>,
264}
265
266#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DelegationInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DelegationInfo", "resolution_id", &&self.resolution_id)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            DelegationInfo {
            #[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 {
                    DelegationInfo { resolution_id: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
267pub struct DelegationInfo {
268    // `DefId` (either the resolution at delegation.id or item_id in case of a trait impl) for signature resolution,
269    // for details see https://github.com/rust-lang/rust/issues/118212#issuecomment-2160686914
270    /// Refers to the next element in a delegation resolution chain.
271    /// Usually points to the final resolution, as most "chains" are just
272    /// one step to a trait or an impl.
273    pub resolution_id: Result<DefId, ErrorGuaranteed>,
274}
275
276#[derive(#[automatically_derived]
impl ::core::clone::Clone for MainDefinition {
    #[inline]
    fn clone(&self) -> MainDefinition {
        let _: ::core::clone::AssertParamIsClone<Res<ast::NodeId>>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainDefinition { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainDefinition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "MainDefinition", "res", &self.res, "is_import", &self.is_import,
            "span", &&self.span)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            MainDefinition {
            #[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 {
                    MainDefinition {
                        res: ref __binding_0,
                        is_import: ref __binding_1,
                        span: ref __binding_2 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
277pub struct MainDefinition {
278    pub res: Res<ast::NodeId>,
279    pub is_import: bool,
280    pub span: Span,
281}
282
283impl MainDefinition {
284    pub fn opt_fn_def_id(self) -> Option<DefId> {
285        if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
286    }
287}
288
289#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImplTraitHeader<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplTraitHeader<'tcx> {
    #[inline]
    fn clone(&self) -> ImplTraitHeader<'tcx> {
        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) {
                match *self {
                    ImplTraitHeader {
                        trait_ref: ref __binding_0,
                        polarity: ref __binding_1,
                        safety: ref __binding_2,
                        constness: ref __binding_3 } => {
                        ::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)]
290pub struct ImplTraitHeader<'tcx> {
291    pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
292    pub polarity: ImplPolarity,
293    pub safety: hir::Safety,
294    pub constness: hir::Constness,
295}
296
297#[derive(#[automatically_derived]
impl ::core::marker::Copy for Asyncness { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Asyncness {
    #[inline]
    fn clone(&self) -> Asyncness { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Asyncness {
    #[inline]
    fn eq(&self, other: &Asyncness) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Asyncness {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Asyncness {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, 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);
                match *self { Asyncness::Yes => {} Asyncness::No => {} }
            }
        }
    };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)]
298#[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() -> Asyncness { Self::No }
}Default)]
299pub enum Asyncness {
300    Yes,
301    #[default]
302    No,
303}
304
305impl Asyncness {
306    pub fn is_async(self) -> bool {
307        #[allow(non_exhaustive_omitted_patterns)] match self {
    Asyncness::Yes => true,
    _ => false,
}matches!(self, Asyncness::Yes)
308    }
309}
310
311#[derive(#[automatically_derived]
impl<Id: ::core::clone::Clone> ::core::clone::Clone for Visibility<Id> {
    #[inline]
    fn clone(&self) -> Visibility<Id> {
        match self {
            Visibility::Public => Visibility::Public,
            Visibility::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 {
            Visibility::Public =>
                ::core::fmt::Formatter::write_str(f, "Public"),
            Visibility::Restricted(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Restricted", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<Id: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Visibility<Id> {
    #[inline]
    fn eq(&self, other: &Visibility<Id>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Visibility::Restricted(__self_0),
                    Visibility::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) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            Visibility::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)]
312pub enum Visibility<Id = LocalDefId> {
313    /// Visible everywhere (including in other crates).
314    Public,
315    /// Visible only in the given crate-local module.
316    Restricted(Id),
317}
318
319impl Visibility {
320    pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
321        match self {
322            ty::Visibility::Restricted(restricted_id) => {
323                if restricted_id.is_top_level_module() {
324                    "pub(crate)".to_string()
325                } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
326                    "pub(self)".to_string()
327                } else {
328                    ::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!(
329                        "pub(in crate{})",
330                        tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
331                    )
332                }
333            }
334            ty::Visibility::Public => "pub".to_string(),
335        }
336    }
337}
338
339#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ClosureSizeProfileData<'tcx> {
    #[inline]
    fn clone(&self) -> ClosureSizeProfileData<'tcx> {
        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::cmp::PartialEq for ClosureSizeProfileData<'tcx> {
    #[inline]
    fn eq(&self, other: &ClosureSizeProfileData<'tcx>) -> 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) {
                match *self {
                    ClosureSizeProfileData {
                        before_feature_tys: ref __binding_0,
                        after_feature_tys: ref __binding_1 } => {
                        ::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)]
340#[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)]
341pub struct ClosureSizeProfileData<'tcx> {
342    /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
343    pub before_feature_tys: Ty<'tcx>,
344    /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
345    pub after_feature_tys: Ty<'tcx>,
346}
347
348impl TyCtxt<'_> {
349    #[inline]
350    pub fn opt_parent(self, id: DefId) -> Option<DefId> {
351        self.def_key(id).parent.map(|index| DefId { index, ..id })
352    }
353
354    #[inline]
355    #[track_caller]
356    pub fn parent(self, id: DefId) -> DefId {
357        match self.opt_parent(id) {
358            Some(id) => id,
359            // not `unwrap_or_else` to avoid breaking caller tracking
360            None => crate::util::bug::bug_fmt(format_args!("{0:?} doesn\'t have a parent", id))bug!("{id:?} doesn't have a parent"),
361        }
362    }
363
364    #[inline]
365    #[track_caller]
366    pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
367        self.opt_parent(id.to_def_id()).map(DefId::expect_local)
368    }
369
370    #[inline]
371    #[track_caller]
372    pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
373        self.parent(id.into().to_def_id()).expect_local()
374    }
375
376    /// Compare def-ids based on their position in def-id tree, ancestor def-ids are considered
377    /// larger than descendant def-ids, and two different def-ids are considered unordered if
378    /// neither of them is an ancestor of the other.
379    fn def_id_partial_cmp(self, lhs: DefId, rhs: DefId) -> Option<Ordering> {
380        // Def-ids from different crates are always unordered.
381        if lhs.krate != rhs.krate {
382            return None;
383        }
384
385        // Def-ids of parent nodes are always created before def-ids of child nodes
386        // and have a smaller index, so we only need to search in one direction,
387        // either from lhs to rhs, or vice versa.
388        let search = |mut start: DefId, finish: DefId, ord| {
389            while start.index != finish.index {
390                match self.opt_parent(start) {
391                    Some(parent) => start.index = parent.index,
392                    None => return None,
393                }
394            }
395            Some(ord)
396        };
397        match lhs.index.cmp(&rhs.index) {
398            Ordering::Equal => Some(Ordering::Equal),
399            Ordering::Less => search(rhs, lhs, Ordering::Greater),
400            Ordering::Greater => search(lhs, rhs, Ordering::Less),
401        }
402    }
403
404    pub fn is_descendant_of(self, descendant: DefId, ancestor: DefId) -> bool {
405        #[allow(non_exhaustive_omitted_patterns)] match self.def_id_partial_cmp(descendant,
        ancestor) {
    Some(Ordering::Less | Ordering::Equal) => true,
    _ => false,
}matches!(
406            self.def_id_partial_cmp(descendant, ancestor),
407            Some(Ordering::Less | Ordering::Equal)
408        )
409    }
410}
411
412impl<Id> Visibility<Id> {
413    pub fn is_public(self) -> bool {
414        #[allow(non_exhaustive_omitted_patterns)] match self {
    Visibility::Public => true,
    _ => false,
}matches!(self, Visibility::Public)
415    }
416
417    pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
418        match self {
419            Visibility::Public => Visibility::Public,
420            Visibility::Restricted(id) => Visibility::Restricted(f(id)),
421        }
422    }
423}
424
425impl<Id: Into<DefId>> Visibility<Id> {
426    pub fn to_def_id(self) -> Visibility<DefId> {
427        self.map_id(Into::into)
428    }
429
430    /// Returns `true` if an item with this visibility is accessible from the given module.
431    pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
432        match self {
433            // Public items are visible everywhere.
434            Visibility::Public => true,
435            Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
436        }
437    }
438
439    pub fn partial_cmp(
440        self,
441        vis: Visibility<impl Into<DefId>>,
442        tcx: TyCtxt<'_>,
443    ) -> Option<Ordering> {
444        match (self, vis) {
445            (Visibility::Public, Visibility::Public) => Some(Ordering::Equal),
446            (Visibility::Public, Visibility::Restricted(_)) => Some(Ordering::Greater),
447            (Visibility::Restricted(_), Visibility::Public) => Some(Ordering::Less),
448            (Visibility::Restricted(lhs_id), Visibility::Restricted(rhs_id)) => {
449                let (lhs_id, rhs_id) = (lhs_id.into(), rhs_id.into());
450                tcx.def_id_partial_cmp(lhs_id, rhs_id)
451            }
452        }
453    }
454}
455
456impl<Id: Into<DefId> + Debug + Copy> Visibility<Id> {
457    /// Returns `true` if this visibility is strictly larger than the given visibility.
458    #[track_caller]
459    pub fn greater_than(
460        self,
461        vis: Visibility<impl Into<DefId> + Debug + Copy>,
462        tcx: TyCtxt<'_>,
463    ) -> bool {
464        match self.partial_cmp(vis, tcx) {
465            Some(ord) => ord.is_gt(),
466            None => {
467                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:?}"));
468                false
469            }
470        }
471    }
472}
473
474impl Visibility<DefId> {
475    pub fn expect_local(self) -> Visibility {
476        self.map_id(|id| id.expect_local())
477    }
478
479    /// Returns `true` if this item is visible anywhere in the local crate.
480    pub fn is_visible_locally(self) -> bool {
481        match self {
482            Visibility::Public => true,
483            Visibility::Restricted(def_id) => def_id.is_local(),
484        }
485    }
486}
487
488/// The crate variances map is computed during typeck and contains the
489/// variance of every item in the local crate. You should not use it
490/// directly, because to do so will make your pass dependent on the
491/// HIR of every item in the local crate. Instead, use
492/// `tcx.variances_of()` to get the variance for a *particular*
493/// item.
494#[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)]
495pub struct CrateVariancesMap<'tcx> {
496    /// For each item with generics, maps to a vector of the variance
497    /// of its generics. If an item has no generics, it will have no
498    /// entry.
499    pub variances: DefIdMap<&'tcx [ty::Variance]>,
500}
501
502// Contains information needed to resolve types and (in the future) look up
503// the types of AST nodes.
504#[derive(#[automatically_derived]
impl ::core::marker::Copy for CReaderCacheKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CReaderCacheKey {
    #[inline]
    fn clone(&self) -> CReaderCacheKey {
        let _: ::core::clone::AssertParamIsClone<Option<CrateNum>>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for CReaderCacheKey {
    #[inline]
    fn eq(&self, other: &CReaderCacheKey) -> 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)]
505pub struct CReaderCacheKey {
506    pub cnum: Option<CrateNum>,
507    pub pos: usize,
508}
509
510/// Use this rather than `TyKind`, whenever possible.
511#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Ty<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for Ty<'tcx> {
    #[inline]
    fn clone(&self) -> Ty<'tcx> {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'tcx,
                WithCachedTypeInfo<TyKind<'tcx>>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for Ty<'tcx> {
    #[inline]
    fn eq(&self, other: &Ty<'tcx>) -> 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)]
512#[rustc_diagnostic_item = "Ty"]
513#[rustc_pass_by_value]
514pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
515
516impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
517    type Kind = TyKind<'tcx>;
518
519    fn kind(self) -> TyKind<'tcx> {
520        *self.kind()
521    }
522}
523
524impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
525    fn flags(&self) -> TypeFlags {
526        self.0.flags
527    }
528
529    fn outer_exclusive_binder(&self) -> DebruijnIndex {
530        self.0.outer_exclusive_binder
531    }
532}
533
534/// The crate outlives map is computed during typeck and contains the
535/// outlives of every item in the local crate. You should not use it
536/// directly, because to do so will make your pass dependent on the
537/// HIR of every item in the local crate. Instead, use
538/// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
539/// item.
540#[derive(const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            CratePredicatesMap<'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 {
                    CratePredicatesMap { predicates: ref __binding_0 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CratePredicatesMap<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "CratePredicatesMap", "predicates", &&self.predicates)
    }
}Debug)]
541pub struct CratePredicatesMap<'tcx> {
542    /// For each struct with outlive bounds, maps to a vector of the
543    /// predicate of its outlive bounds. If an item has no outlives
544    /// bounds, it will have no entry.
545    pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
546}
547
548#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Term<'tcx> {
    #[inline]
    fn clone(&self) -> Term<'tcx> {
        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::cmp::PartialEq for Term<'tcx> {
    #[inline]
    fn eq(&self, other: &Term<'tcx>) -> 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: &Term<'tcx>)
        -> ::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: &Term<'tcx>) -> ::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)]
549pub struct Term<'tcx> {
550    ptr: NonNull<()>,
551    marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
552}
553
554impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
555
556impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
557    type Kind = TermKind<'tcx>;
558
559    fn kind(self) -> Self::Kind {
560        self.kind()
561    }
562}
563
564unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
565    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
566{
567}
568unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
569    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
570{
571}
572unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
573unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
574
575impl Debug for Term<'_> {
576    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577        match self.kind() {
578            TermKind::Ty(ty) => f.write_fmt(format_args!("Term::Ty({0:?})", ty))write!(f, "Term::Ty({ty:?})"),
579            TermKind::Const(ct) => f.write_fmt(format_args!("Term::Const({0:?})", ct))write!(f, "Term::Const({ct:?})"),
580        }
581    }
582}
583
584impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
585    fn from(ty: Ty<'tcx>) -> Self {
586        TermKind::Ty(ty).pack()
587    }
588}
589
590impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
591    fn from(c: Const<'tcx>) -> Self {
592        TermKind::Const(c).pack()
593    }
594}
595
596impl<'tcx> StableHash for Term<'tcx> {
597    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
598        self.kind().stable_hash(hcx, hasher);
599    }
600}
601
602impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
603    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
604        self,
605        folder: &mut F,
606    ) -> Result<Self, F::Error> {
607        match self.kind() {
608            ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
609            ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
610        }
611    }
612
613    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
614        match self.kind() {
615            ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
616            ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
617        }
618    }
619}
620
621impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
622    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
623        match self.kind() {
624            ty::TermKind::Ty(ty) => ty.visit_with(visitor),
625            ty::TermKind::Const(ct) => ct.visit_with(visitor),
626        }
627    }
628}
629
630impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
631    fn encode(&self, e: &mut E) {
632        self.kind().encode(e)
633    }
634}
635
636impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
637    fn decode(d: &mut D) -> Self {
638        let res: TermKind<'tcx> = Decodable::decode(d);
639        res.pack()
640    }
641}
642
643impl<'tcx> Term<'tcx> {
644    #[inline]
645    pub fn kind(self) -> TermKind<'tcx> {
646        let ptr =
647            unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
648        // SAFETY: use of `Interned::new_unchecked` here is ok because these
649        // pointers were originally created from `Interned` types in `pack()`,
650        // and this is just going in the other direction.
651        unsafe {
652            match self.ptr.addr().get() & TAG_MASK {
653                TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
654                    ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
655                ))),
656                CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
657                    ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
658                ))),
659                _ => core::intrinsics::unreachable(),
660            }
661        }
662    }
663
664    pub fn as_type(&self) -> Option<Ty<'tcx>> {
665        if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
666    }
667
668    pub fn expect_type(&self) -> Ty<'tcx> {
669        self.as_type().expect("expected a type, but found a const")
670    }
671
672    pub fn as_const(&self) -> Option<Const<'tcx>> {
673        if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
674    }
675
676    pub fn expect_const(&self) -> Const<'tcx> {
677        self.as_const().expect("expected a const, but found a type")
678    }
679
680    pub fn into_arg(self) -> GenericArg<'tcx> {
681        match self.kind() {
682            TermKind::Ty(ty) => ty.into(),
683            TermKind::Const(c) => c.into(),
684        }
685    }
686
687    pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
688        match self.kind() {
689            TermKind::Ty(ty) => match *ty.kind() {
690                ty::Alias(alias_ty) => Some(alias_ty.into()),
691                _ => None,
692            },
693            TermKind::Const(ct) => match ct.kind() {
694                ConstKind::Unevaluated(uv) => Some(uv.into()),
695                _ => None,
696            },
697        }
698    }
699
700    pub fn is_infer(&self) -> bool {
701        match self.kind() {
702            TermKind::Ty(ty) => ty.is_ty_var(),
703            TermKind::Const(ct) => ct.is_ct_infer(),
704        }
705    }
706
707    pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
708        match self.kind() {
709            TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
710            TermKind::Const(ct) => ct.is_trivially_wf(),
711        }
712    }
713
714    /// Iterator that walks `self` and any types reachable from
715    /// `self`, in depth-first order. Note that just walks the types
716    /// that appear in `self`, it does not descend into the fields of
717    /// structs or variants. For example:
718    ///
719    /// ```text
720    /// isize => { isize }
721    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
722    /// [isize] => { [isize], isize }
723    /// ```
724    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
725        TypeWalker::new(self.into())
726    }
727}
728
729const TAG_MASK: usize = 0b11;
730const TYPE_TAG: usize = 0b00;
731const CONST_TAG: usize = 0b01;
732
733impl<'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>)]
734impl<'tcx> TermKind<'tcx> {
735    #[inline]
736    fn pack(self) -> Term<'tcx> {
737        let (tag, ptr) = match self {
738            TermKind::Ty(ty) => {
739                // Ensure we can use the tag bits.
740                assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
741                (TYPE_TAG, NonNull::from(ty.0.0).cast())
742            }
743            TermKind::Const(ct) => {
744                // Ensure we can use the tag bits.
745                assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
746                (CONST_TAG, NonNull::from(ct.0.0).cast())
747            }
748        };
749
750        Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
751    }
752}
753
754/// Represents the bounds declared on a particular set of type
755/// parameters. Should eventually be generalized into a flag list of
756/// where-clauses. You can obtain an `InstantiatedPredicates` list from a
757/// `GenericPredicates` by using the `instantiate` method. Note that this method
758/// reflects an important semantic invariant of `InstantiatedPredicates`: while
759/// the `GenericPredicates` are expressed in terms of the bound type
760/// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
761/// represented a set of bounds for some particular instantiation,
762/// meaning that the generic parameters have been instantiated with
763/// their values.
764///
765/// Example:
766/// ```ignore (illustrative)
767/// struct Foo<T, U: Bar<T>> { ... }
768/// ```
769/// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
770/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
771/// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
772/// [usize:Bar<isize>]]`.
773#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InstantiatedPredicates<'tcx> {
    #[inline]
    fn clone(&self) -> InstantiatedPredicates<'tcx> {
        InstantiatedPredicates {
            predicates: ::core::clone::Clone::clone(&self.predicates),
            spans: ::core::clone::Clone::clone(&self.spans),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InstantiatedPredicates<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "InstantiatedPredicates", "predicates", &self.predicates, "spans",
            &&self.spans)
    }
}Debug)]
774pub struct InstantiatedPredicates<'tcx> {
775    pub predicates: Vec<Unnormalized<'tcx, Clause<'tcx>>>,
776    pub spans: Vec<Span>,
777}
778
779impl<'tcx> InstantiatedPredicates<'tcx> {
780    pub fn empty() -> InstantiatedPredicates<'tcx> {
781        InstantiatedPredicates { predicates: ::alloc::vec::Vec::new()vec![], spans: ::alloc::vec::Vec::new()vec![] }
782    }
783
784    pub fn is_empty(&self) -> bool {
785        self.predicates.is_empty()
786    }
787
788    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
789        self.into_iter()
790    }
791}
792
793impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
794    type Item = (Unnormalized<'tcx, Clause<'tcx>>, Span);
795
796    type IntoIter = std::iter::Zip<
797        std::vec::IntoIter<Unnormalized<'tcx, Clause<'tcx>>>,
798        std::vec::IntoIter<Span>,
799    >;
800
801    fn into_iter(self) -> Self::IntoIter {
802        if true {
    match (&self.predicates.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.predicates.len(), self.spans.len());
803        std::iter::zip(self.predicates, self.spans)
804    }
805}
806
807impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
808    type Item = (Unnormalized<'tcx, Clause<'tcx>>, Span);
809
810    type IntoIter = std::iter::Zip<
811        std::iter::Copied<std::slice::Iter<'a, Unnormalized<'tcx, Clause<'tcx>>>>,
812        std::iter::Copied<std::slice::Iter<'a, Span>>,
813    >;
814
815    fn into_iter(self) -> Self::IntoIter {
816        if true {
    match (&self.predicates.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.predicates.len(), self.spans.len());
817        std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
818    }
819}
820
821#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for ProvisionalHiddenType<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ProvisionalHiddenType<'tcx> {
    #[inline]
    fn clone(&self) -> ProvisionalHiddenType<'tcx> {
        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) {
                match *self {
                    ProvisionalHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } => {
                        ::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)]
822pub struct ProvisionalHiddenType<'tcx> {
823    /// The span of this particular definition of the opaque type. So
824    /// for example:
825    ///
826    /// ```ignore (incomplete snippet)
827    /// type Foo = impl Baz;
828    /// fn bar() -> Foo {
829    /// //          ^^^ This is the span we are looking for!
830    /// }
831    /// ```
832    ///
833    /// In cases where the fn returns `(impl Trait, impl Trait)` or
834    /// other such combinations, the result is currently
835    /// over-approximated, but better than nothing.
836    pub span: Span,
837
838    /// The type variable that represents the value of the opaque type
839    /// that we require. In other words, after we compile this function,
840    /// we will be created a constraint like:
841    /// ```ignore (pseudo-rust)
842    /// Foo<'a, T> = ?C
843    /// ```
844    /// where `?C` is the value of this type variable. =) It may
845    /// naturally refer to the type and lifetime parameters in scope
846    /// in this function, though ultimately it should only reference
847    /// those that are arguments to `Foo` in the constraint above. (In
848    /// other words, `?C` should not include `'b`, even though it's a
849    /// lifetime parameter on `foo`.)
850    pub ty: Ty<'tcx>,
851}
852
853/// Whether we're currently in HIR typeck or MIR borrowck.
854#[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]
impl ::core::clone::Clone for DefiningScopeKind {
    #[inline]
    fn clone(&self) -> DefiningScopeKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DefiningScopeKind { }Copy)]
855pub enum DefiningScopeKind {
856    /// During writeback in typeck, we don't care about regions and simply
857    /// erase them. This means we also don't check whether regions are
858    /// universal in the opaque type key. This will only be checked in
859    /// MIR borrowck.
860    HirTypeck,
861    MirBorrowck,
862}
863
864impl<'tcx> ProvisionalHiddenType<'tcx> {
865    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
866        ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
867    }
868
869    pub fn build_mismatch_error(
870        &self,
871        other: &Self,
872        tcx: TyCtxt<'tcx>,
873    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
874        (self.ty, other.ty).error_reported()?;
875        // Found different concrete types for the opaque type.
876        let sub_diag = if self.span == other.span {
877            TypeMismatchReason::ConflictType { span: self.span }
878        } else {
879            TypeMismatchReason::PreviousUse { span: self.span }
880        };
881        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
882            self_ty: self.ty,
883            other_ty: other.ty,
884            other_span: other.span,
885            sub: sub_diag,
886        }))
887    }
888
889    x;#[instrument(level = "debug", skip(tcx), ret)]
890    pub fn remap_generic_params_to_declaration_params(
891        self,
892        opaque_type_key: OpaqueTypeKey<'tcx>,
893        tcx: TyCtxt<'tcx>,
894        defining_scope_kind: DefiningScopeKind,
895    ) -> DefinitionSiteHiddenType<'tcx> {
896        let OpaqueTypeKey { def_id, args } = opaque_type_key;
897
898        // Use args to build up a reverse map from regions to their
899        // identity mappings. This is necessary because of `impl
900        // Trait` lifetimes are computed by replacing existing
901        // lifetimes with 'static and remapping only those used in the
902        // `impl Trait` return type, resulting in the parameters
903        // shifting.
904        let id_args = GenericArgs::identity_for_item(tcx, def_id);
905        debug!(?id_args);
906
907        // This zip may have several times the same lifetime in `args` paired with a different
908        // lifetime from `id_args`. Simply `collect`ing the iterator is the correct behaviour:
909        // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
910        let map = args.iter().zip(id_args).collect();
911        debug!("map = {:#?}", map);
912
913        // Convert the type from the function into a type valid outside by mapping generic
914        // parameters to into the context of the opaque.
915        //
916        // We erase regions when doing this during HIR typeck. We manually use `fold_regions`
917        // here as we do not want to anonymize bound variables.
918        let ty = match defining_scope_kind {
919            DefiningScopeKind::HirTypeck => {
920                fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
921            }
922            DefiningScopeKind::MirBorrowck => self.ty,
923        };
924        let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
925        if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
926            assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
927        }
928        DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
929    }
930}
931
932#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for DefinitionSiteHiddenType<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for DefinitionSiteHiddenType<'tcx> {
    #[inline]
    fn clone(&self) -> DefinitionSiteHiddenType<'tcx> {
        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) {
                match *self {
                    DefinitionSiteHiddenType {
                        span: ref __binding_0, ty: ref __binding_1 } => {
                        ::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)]
933pub struct DefinitionSiteHiddenType<'tcx> {
934    /// The span of the definition of the opaque type. So for example:
935    ///
936    /// ```ignore (incomplete snippet)
937    /// type Foo = impl Baz;
938    /// fn bar() -> Foo {
939    /// //          ^^^ This is the span we are looking for!
940    /// }
941    /// ```
942    ///
943    /// In cases where the fn returns `(impl Trait, impl Trait)` or
944    /// other such combinations, the result is currently
945    /// over-approximated, but better than nothing.
946    pub span: Span,
947
948    /// The final type of the opaque.
949    pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
950}
951
952impl<'tcx> DefinitionSiteHiddenType<'tcx> {
953    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
954        DefinitionSiteHiddenType {
955            span: DUMMY_SP,
956            ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
957        }
958    }
959
960    pub fn build_mismatch_error(
961        &self,
962        other: &Self,
963        tcx: TyCtxt<'tcx>,
964    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
965        let self_ty = self.ty.instantiate_identity().skip_norm_wip();
966        let other_ty = other.ty.instantiate_identity().skip_norm_wip();
967        (self_ty, other_ty).error_reported()?;
968        // Found different concrete types for the opaque type.
969        let sub_diag = if self.span == other.span {
970            TypeMismatchReason::ConflictType { span: self.span }
971        } else {
972            TypeMismatchReason::PreviousUse { span: self.span }
973        };
974        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
975            self_ty,
976            other_ty,
977            other_span: other.span,
978            sub: sub_diag,
979        }))
980    }
981}
982
983pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
984
985impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
986    fn flags(&self) -> TypeFlags {
987        (**self).flags()
988    }
989
990    fn outer_exclusive_binder(&self) -> DebruijnIndex {
991        (**self).outer_exclusive_binder()
992    }
993}
994
995/// When interacting with the type system we must provide information about the
996/// environment. `ParamEnv` is the type that represents this information. See the
997/// [dev guide chapter][param_env_guide] for more information.
998///
999/// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1000#[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]
impl<'tcx> ::core::clone::Clone for ParamEnv<'tcx> {
    #[inline]
    fn clone(&self) -> ParamEnv<'tcx> {
        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::cmp::PartialEq for ParamEnv<'tcx> {
    #[inline]
    fn eq(&self, other: &ParamEnv<'tcx>) -> 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)]
1001#[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)]
1002pub struct ParamEnv<'tcx> {
1003    /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1004    /// basically the set of bounds on the in-scope type parameters, translated
1005    /// into `Obligation`s, and elaborated and normalized.
1006    ///
1007    /// Use the `caller_bounds()` method to access.
1008    caller_bounds: Clauses<'tcx>,
1009}
1010
1011impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1012    fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1013        self.caller_bounds()
1014    }
1015}
1016
1017impl<'tcx> ParamEnv<'tcx> {
1018    /// Construct a trait environment suitable for contexts where there are
1019    /// no where-clauses in scope. In the majority of cases it is incorrect
1020    /// to use an empty environment. See the [dev guide section][param_env_guide]
1021    /// for information on what a `ParamEnv` is and how to acquire one.
1022    ///
1023    /// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1024    #[inline]
1025    pub fn empty() -> Self {
1026        Self::new(ListWithCachedTypeInfo::empty())
1027    }
1028
1029    #[inline]
1030    pub fn caller_bounds(self) -> Clauses<'tcx> {
1031        self.caller_bounds
1032    }
1033
1034    /// Construct a trait environment with the given set of predicates.
1035    #[inline]
1036    pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1037        ParamEnv { caller_bounds }
1038    }
1039
1040    /// Creates a pair of param-env and value for use in queries.
1041    pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1042        ParamEnvAnd { param_env: self, value }
1043    }
1044
1045    /// Eagerly reveal all opaque types in the `param_env`.
1046    pub fn with_normalized(self, tcx: TyCtxt<'tcx>) -> ParamEnv<'tcx> {
1047        // No need to reveal opaques with the new solver enabled,
1048        // since we have lazy norm.
1049        if tcx.next_trait_solver_globally() {
1050            self
1051        } else {
1052            ParamEnv::new(tcx.reveal_opaque_types_in_bounds(self.caller_bounds))
1053        }
1054    }
1055}
1056
1057#[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) -> ParamEnvAnd<'tcx, T> {
        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::cmp::PartialEq for
    ParamEnvAnd<'tcx, T> {
    #[inline]
    fn eq(&self, other: &ParamEnvAnd<'tcx, T>) -> 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)]
1058#[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)]
1059pub struct ParamEnvAnd<'tcx, T> {
1060    pub param_env: ParamEnv<'tcx>,
1061    pub value: T,
1062}
1063
1064/// The environment in which to do trait solving.
1065///
1066/// Most of the time you only need to care about the `ParamEnv`
1067/// as the `TypingMode` is simply stored in the `InferCtxt`.
1068///
1069/// However, there are some places which rely on trait solving
1070/// without using an `InferCtxt` themselves. For these to be
1071/// able to use the trait system they have to be able to initialize
1072/// such an `InferCtxt` with the right `typing_mode`, so they need
1073/// to track both.
1074#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypingEnv<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypingEnv<'tcx> {
    #[inline]
    fn clone(&self) -> TypingEnv<'tcx> {
        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::cmp::PartialEq for TypingEnv<'tcx> {
    #[inline]
    fn eq(&self, other: &TypingEnv<'tcx>) -> 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)]
1075#[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)]
1076pub struct TypingEnv<'tcx> {
1077    #[type_foldable(identity)]
1078    #[type_visitable(ignore)]
1079    typing_mode: TypingModeEqWrapper<'tcx>,
1080    pub param_env: ParamEnv<'tcx>,
1081}
1082
1083impl<'tcx> TypingEnv<'tcx> {
1084    pub fn new(param_env: ParamEnv<'tcx>, typing_mode: TypingMode<'tcx>) -> Self {
1085        Self { typing_mode: TypingModeEqWrapper(typing_mode), param_env }
1086    }
1087
1088    pub fn typing_mode(&self) -> TypingMode<'tcx> {
1089        self.typing_mode.0
1090    }
1091
1092    /// Create a typing environment with no where-clauses in scope
1093    /// where all opaque types and default associated items are revealed.
1094    ///
1095    /// This is only suitable for monomorphized, post-typeck environments.
1096    /// Do not use this for MIR optimizations, as even though they also
1097    /// use `TypingMode::PostAnalysis`, they may still have where-clauses
1098    /// in scope.
1099    pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1100        Self::new(ParamEnv::empty(), TypingMode::Codegen)
1101    }
1102
1103    /// Create a typing environment for use during analysis outside of a body.
1104    ///
1105    /// Using a typing environment inside of bodies is not supported as the body
1106    /// may define opaque types. In this case the used functions have to be
1107    /// converted to use proper canonical inputs instead.
1108    pub fn non_body_analysis(
1109        tcx: TyCtxt<'tcx>,
1110        def_id: impl IntoQueryKey<DefId>,
1111    ) -> TypingEnv<'tcx> {
1112        let def_id = def_id.into_query_key();
1113        Self::new(tcx.param_env(def_id), TypingMode::non_body_analysis())
1114    }
1115
1116    pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
1117        TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::PostAnalysis)
1118    }
1119
1120    pub fn codegen(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
1121        TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::Codegen)
1122    }
1123
1124    /// Modify the `typing_mode` to `PostAnalysis` or `Codegen` and eagerly reveal all opaque types
1125    /// in the `param_env`.
1126    pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1127        let TypingEnv { typing_mode, param_env } = self;
1128        match typing_mode.0.assert_not_erased() {
1129            TypingMode::Coherence
1130            | TypingMode::Typeck { .. }
1131            | TypingMode::PostTypeckUntilBorrowck { .. }
1132            | TypingMode::PostBorrowck { .. } => {}
1133            TypingMode::PostAnalysis | TypingMode::Codegen => return self,
1134        }
1135
1136        let param_env = param_env.with_normalized(tcx);
1137        TypingEnv::new(param_env, TypingMode::PostAnalysis)
1138    }
1139
1140    /// Modify the `typing_mode` to `PostAnalysis` or `Codegen` and eagerly reveal all opaque types
1141    /// in the `param_env`.
1142    pub fn with_codegen_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1143        let TypingEnv { typing_mode, param_env } = self;
1144        match typing_mode.0.assert_not_erased() {
1145            TypingMode::Coherence
1146            | TypingMode::Typeck { .. }
1147            | TypingMode::PostTypeckUntilBorrowck { .. }
1148            | TypingMode::PostBorrowck { .. }
1149            | TypingMode::PostAnalysis => {}
1150            TypingMode::Codegen => return self,
1151        }
1152
1153        let param_env = param_env.with_normalized(tcx);
1154        TypingEnv::new(param_env, TypingMode::Codegen)
1155    }
1156
1157    /// Combine this typing environment with the given `value` to be used by
1158    /// not (yet) canonicalized queries. This only works if the value does not
1159    /// contain anything local to some `InferCtxt`, i.e. inference variables or
1160    /// placeholders.
1161    pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1162    where
1163        T: TypeVisitable<TyCtxt<'tcx>>,
1164    {
1165        // FIXME(#132279): We should assert that the value does not contain any placeholders
1166        // as these placeholders are also local to the current inference context. However, we
1167        // currently use pseudo-canonical queries in the trait solver, which replaces params
1168        // with placeholders during canonicalization. We should also simply not use pseudo-
1169        // canonical queries in the trait solver, at which point we can readd this assert.
1170        //
1171        // As of writing this comment, this is only used when normalizing consts that mention
1172        // params.
1173        /* debug_assert!(
1174            !value.has_placeholders(),
1175            "{value:?} which has placeholder shouldn't be pseudo-canonicalized"
1176        ); */
1177        PseudoCanonicalInput { typing_env: self, value }
1178    }
1179}
1180
1181/// Similar to `CanonicalInput`, this carries the `typing_mode` and the environment
1182/// necessary to do any kind of trait solving inside of nested queries.
1183///
1184/// Unlike proper canonicalization, this requires the `param_env` and the `value` to not
1185/// contain anything local to the `infcx` of the caller, so we don't actually canonicalize
1186/// anything.
1187///
1188/// This should be created by using `infcx.pseudo_canonicalize_query(param_env, value)`
1189/// or by using `typing_env.as_query_input(value)`.
1190#[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) -> PseudoCanonicalInput<'tcx, T> {
        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::cmp::PartialEq for
    PseudoCanonicalInput<'tcx, T> {
    #[inline]
    fn eq(&self, other: &PseudoCanonicalInput<'tcx, T>) -> 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)]
1191#[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)]
1192pub struct PseudoCanonicalInput<'tcx, T> {
1193    pub typing_env: TypingEnv<'tcx>,
1194    pub value: T,
1195}
1196
1197#[derive(#[automatically_derived]
impl ::core::marker::Copy for Destructor { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Destructor {
    #[inline]
    fn clone(&self) -> Destructor {
        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) {
                match *self {
                    Destructor { did: ref __binding_0 } => {
                        ::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)]
1198pub struct Destructor {
1199    /// The `DefId` of the destructor method
1200    pub did: DefId,
1201}
1202
1203// FIXME: consider combining this definition with regular `Destructor`
1204#[derive(#[automatically_derived]
impl ::core::marker::Copy for AsyncDestructor { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AsyncDestructor {
    #[inline]
    fn clone(&self) -> AsyncDestructor {
        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) {
                match *self {
                    AsyncDestructor { impl_did: ref __binding_0 } => {
                        ::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)]
1205pub struct AsyncDestructor {
1206    /// The `DefId` of the `impl AsyncDrop`
1207    pub impl_did: DefId,
1208}
1209
1210#[derive(#[automatically_derived]
impl ::core::clone::Clone for VariantFlags {
    #[inline]
    fn clone(&self) -> VariantFlags {
        let _: ::core::clone::AssertParamIsClone<u8>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for VariantFlags { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for VariantFlags {
    #[inline]
    fn eq(&self, other: &VariantFlags) -> 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) {
                match *self {
                    VariantFlags(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 VariantFlags {
            fn decode(__decoder: &mut __D) -> Self {
                VariantFlags(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };TyDecodable)]
1211pub struct VariantFlags(u8);
1212impl 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! {
1213    impl VariantFlags: u8 {
1214        const NO_VARIANT_FLAGS        = 0;
1215        /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1216        const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1217    }
1218}
1219impl ::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 }
1220
1221/// Definition of a variant -- a struct's fields or an enum variant.
1222#[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) {
                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 } => {
                        ::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)]
1223pub struct VariantDef {
1224    /// `DefId` that identifies the variant itself.
1225    /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1226    pub def_id: DefId,
1227    /// `DefId` that identifies the variant's constructor.
1228    /// If this variant is a struct variant, then this is `None`.
1229    pub ctor: Option<(CtorKind, DefId)>,
1230    /// Variant or struct name.
1231    pub name: Symbol,
1232    /// Discriminant of this variant.
1233    pub discr: VariantDiscr,
1234    /// Fields of this variant.
1235    pub fields: IndexVec<FieldIdx, FieldDef>,
1236    /// The error guarantees from parser, if any.
1237    tainted: Option<ErrorGuaranteed>,
1238    /// Flags of the variant (e.g. is field list non-exhaustive)?
1239    flags: VariantFlags,
1240}
1241
1242impl VariantDef {
1243    /// Creates a new `VariantDef`.
1244    ///
1245    /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1246    /// represents an enum variant).
1247    ///
1248    /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1249    /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1250    ///
1251    /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1252    /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1253    /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1254    /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1255    /// built-in trait), and we do not want to load attributes twice.
1256    ///
1257    /// If someone speeds up attribute loading to not be a performance concern, they can
1258    /// remove this hack and use the constructor `DefId` everywhere.
1259    #[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("compiler/rustc_middle/src/ty/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1259u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                    ::tracing_core::field::FieldSet::new(&["name",
                                                    "variant_did", "ctor", "discr", "fields", "parent_did",
                                                    "recover_tainted", "is_field_list_non_exhaustive"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant_did)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ctor)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&discr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fields)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_did)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&recover_tainted)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&is_field_list_non_exhaustive
                                                            as &dyn 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")]
1260    pub fn new(
1261        name: Symbol,
1262        variant_did: Option<DefId>,
1263        ctor: Option<(CtorKind, DefId)>,
1264        discr: VariantDiscr,
1265        fields: IndexVec<FieldIdx, FieldDef>,
1266        parent_did: DefId,
1267        recover_tainted: Option<ErrorGuaranteed>,
1268        is_field_list_non_exhaustive: bool,
1269    ) -> Self {
1270        let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1271        if is_field_list_non_exhaustive {
1272            flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1273        }
1274
1275        VariantDef {
1276            def_id: variant_did.unwrap_or(parent_did),
1277            ctor,
1278            name,
1279            discr,
1280            fields,
1281            flags,
1282            tainted: recover_tainted,
1283        }
1284    }
1285
1286    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`.
1287    ///
1288    /// Note that this function will return `true` even if the type has been
1289    /// defined in the crate currently being compiled. If that's not what you
1290    /// want, see [`Self::field_list_has_applicable_non_exhaustive`].
1291    #[inline]
1292    pub fn is_field_list_non_exhaustive(&self) -> bool {
1293        self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1294    }
1295
1296    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`
1297    /// and the type has been defined in another crate.
1298    #[inline]
1299    pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1300        self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1301    }
1302
1303    /// Computes the `Ident` of this variant by looking up the `Span`
1304    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1305        Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1306    }
1307
1308    /// Was this variant obtained as part of recovering from a syntactic error?
1309    #[inline]
1310    pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1311        self.tainted.map_or(Ok(()), Err)
1312    }
1313
1314    #[inline]
1315    pub fn ctor_kind(&self) -> Option<CtorKind> {
1316        self.ctor.map(|(kind, _)| kind)
1317    }
1318
1319    #[inline]
1320    pub fn ctor_def_id(&self) -> Option<DefId> {
1321        self.ctor.map(|(_, def_id)| def_id)
1322    }
1323
1324    /// Returns the one field in this variant.
1325    ///
1326    /// `panic!`s if there are no fields or multiple fields.
1327    #[inline]
1328    pub fn single_field(&self) -> &FieldDef {
1329        if !(self.fields.len() == 1) {
    ::core::panicking::panic("assertion failed: self.fields.len() == 1")
};assert!(self.fields.len() == 1);
1330
1331        &self.fields[FieldIdx::ZERO]
1332    }
1333
1334    /// Returns the last field in this variant, if present.
1335    #[inline]
1336    pub fn tail_opt(&self) -> Option<&FieldDef> {
1337        self.fields.raw.last()
1338    }
1339
1340    /// Returns the last field in this variant.
1341    ///
1342    /// # Panics
1343    ///
1344    /// Panics, if the variant has no fields.
1345    #[inline]
1346    pub fn tail(&self) -> &FieldDef {
1347        self.tail_opt().expect("expected unsized ADT to have a tail field")
1348    }
1349
1350    /// Returns whether this variant has unsafe fields.
1351    pub fn has_unsafe_fields(&self) -> bool {
1352        self.fields.iter().any(|x| x.safety.is_unsafe())
1353    }
1354}
1355
1356impl PartialEq for VariantDef {
1357    #[inline]
1358    fn eq(&self, other: &Self) -> bool {
1359        // There should be only one `VariantDef` for each `def_id`, therefore
1360        // it is fine to implement `PartialEq` only based on `def_id`.
1361        //
1362        // Below, we exhaustively destructure `self` and `other` so that if the
1363        // definition of `VariantDef` changes, a compile-error will be produced,
1364        // reminding us to revisit this assumption.
1365
1366        let Self {
1367            def_id: lhs_def_id,
1368            ctor: _,
1369            name: _,
1370            discr: _,
1371            fields: _,
1372            flags: _,
1373            tainted: _,
1374        } = &self;
1375        let Self {
1376            def_id: rhs_def_id,
1377            ctor: _,
1378            name: _,
1379            discr: _,
1380            fields: _,
1381            flags: _,
1382            tainted: _,
1383        } = other;
1384
1385        let res = lhs_def_id == rhs_def_id;
1386
1387        // Double check that implicit assumption detailed above.
1388        if truecfg!(debug_assertions) && res {
1389            let deep = self.ctor == other.ctor
1390                && self.name == other.name
1391                && self.discr == other.discr
1392                && self.fields == other.fields
1393                && self.flags == other.flags;
1394            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");
1395        }
1396
1397        res
1398    }
1399}
1400
1401impl Eq for VariantDef {}
1402
1403impl Hash for VariantDef {
1404    #[inline]
1405    fn hash<H: Hasher>(&self, s: &mut H) {
1406        // There should be only one `VariantDef` for each `def_id`, therefore
1407        // it is fine to implement `Hash` only based on `def_id`.
1408        //
1409        // Below, we exhaustively destructure `self` so that if the definition
1410        // of `VariantDef` changes, a compile-error will be produced, reminding
1411        // us to revisit this assumption.
1412
1413        let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1414        def_id.hash(s)
1415    }
1416}
1417
1418#[derive(#[automatically_derived]
impl ::core::marker::Copy for VariantDiscr { }Copy, #[automatically_derived]
impl ::core::clone::Clone for VariantDiscr {
    #[inline]
    fn clone(&self) -> VariantDiscr {
        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 {
            VariantDiscr::Explicit(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Explicit", &__self_0),
            VariantDiscr::Relative(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Relative", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for VariantDiscr {
    #[inline]
    fn eq(&self, other: &VariantDiscr) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (VariantDiscr::Explicit(__self_0),
                    VariantDiscr::Explicit(__arg1_0)) => __self_0 == __arg1_0,
                (VariantDiscr::Relative(__self_0),
                    VariantDiscr::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)]
1419pub enum VariantDiscr {
1420    /// Explicit value for this variant, i.e., `X = 123`.
1421    /// The `DefId` corresponds to the embedded constant.
1422    Explicit(DefId),
1423
1424    /// The previous variant's discriminant plus one.
1425    /// For efficiency reasons, the distance from the
1426    /// last `Explicit` discriminant is being stored,
1427    /// or `0` for the first variant, if it has none.
1428    Relative(u32),
1429}
1430
1431#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FieldDef {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "FieldDef",
            "did", &self.did, "name", &self.name, "vis", &self.vis, "safety",
            &self.safety, "value", &&self.value)
    }
}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,
                        safety: ref __binding_3,
                        value: ref __binding_4 } => {
                        { __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); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for FieldDef {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    FieldDef {
                        did: ref __binding_0,
                        name: ref __binding_1,
                        vis: ref __binding_2,
                        safety: ref __binding_3,
                        value: ref __binding_4 } => {
                        ::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);
                    }
                }
            }
        }
    };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),
                    safety: ::rustc_serialize::Decodable::decode(__decoder),
                    value: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
1432pub struct FieldDef {
1433    pub did: DefId,
1434    pub name: Symbol,
1435    pub vis: Visibility<DefId>,
1436    pub safety: hir::Safety,
1437    pub value: Option<DefId>,
1438}
1439
1440impl PartialEq for FieldDef {
1441    #[inline]
1442    fn eq(&self, other: &Self) -> bool {
1443        // There should be only one `FieldDef` for each `did`, therefore it is
1444        // fine to implement `PartialEq` only based on `did`.
1445        //
1446        // Below, we exhaustively destructure `self` so that if the definition
1447        // of `FieldDef` changes, a compile-error will be produced, reminding
1448        // us to revisit this assumption.
1449
1450        let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1451
1452        let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1453
1454        let res = lhs_did == rhs_did;
1455
1456        // Double check that implicit assumption detailed above.
1457        if truecfg!(debug_assertions) && res {
1458            let deep =
1459                self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1460            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");
1461        }
1462
1463        res
1464    }
1465}
1466
1467impl Eq for FieldDef {}
1468
1469impl Hash for FieldDef {
1470    #[inline]
1471    fn hash<H: Hasher>(&self, s: &mut H) {
1472        // There should be only one `FieldDef` for each `did`, therefore it is
1473        // fine to implement `Hash` only based on `did`.
1474        //
1475        // Below, we exhaustively destructure `self` so that if the definition
1476        // of `FieldDef` changes, a compile-error will be produced, reminding
1477        // us to revisit this assumption.
1478
1479        let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1480
1481        did.hash(s)
1482    }
1483}
1484
1485impl<'tcx> FieldDef {
1486    /// Returns the type of this field. The `args` are typically obtained via
1487    /// the second field of [`TyKind::Adt`].
1488    pub fn ty(
1489        &self,
1490        tcx: TyCtxt<'tcx>,
1491        args: GenericArgsRef<'tcx>,
1492    ) -> Unnormalized<'tcx, Ty<'tcx>> {
1493        tcx.type_of(self.did).instantiate(tcx, args)
1494    }
1495
1496    /// Computes the `Ident` of this variant by looking up the `Span`
1497    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1498        Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1499    }
1500}
1501
1502#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImplOverlapKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ImplOverlapKind::Permitted { marker: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Permitted", "marker", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ImplOverlapKind {
    #[inline]
    fn eq(&self, other: &ImplOverlapKind) -> bool {
        match (self, other) {
            (ImplOverlapKind::Permitted { marker: __self_0 },
                ImplOverlapKind::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)]
1503pub enum ImplOverlapKind {
1504    /// These impls are always allowed to overlap.
1505    Permitted {
1506        /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1507        marker: bool,
1508    },
1509}
1510
1511/// Useful source information about where a desugared associated type for an
1512/// RPITIT originated from.
1513#[derive(#[automatically_derived]
impl ::core::clone::Clone for ImplTraitInTraitData {
    #[inline]
    fn clone(&self) -> ImplTraitInTraitData {
        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 {
            ImplTraitInTraitData::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),
            ImplTraitInTraitData::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::cmp::PartialEq for ImplTraitInTraitData {
    #[inline]
    fn eq(&self, other: &ImplTraitInTraitData) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ImplTraitInTraitData::Trait {
                    fn_def_id: __self_0, opaque_def_id: __self_1 },
                    ImplTraitInTraitData::Trait {
                    fn_def_id: __arg1_0, opaque_def_id: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (ImplTraitInTraitData::Impl { fn_def_id: __self_0 },
                    ImplTraitInTraitData::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) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            ImplTraitInTraitData::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)
            }
            ImplTraitInTraitData::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)]
1514pub enum ImplTraitInTraitData {
1515    Trait { fn_def_id: DefId, opaque_def_id: DefId },
1516    Impl { fn_def_id: DefId },
1517}
1518
1519impl<'tcx> TyCtxt<'tcx> {
1520    pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1521        self.typeck(self.hir_body_owner_def_id(body))
1522    }
1523
1524    pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1525        self.associated_items(id)
1526            .in_definition_order()
1527            .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1528    }
1529
1530    pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1531        let mut flags = ReprFlags::empty();
1532        let mut size = None;
1533        let mut max_align: Option<Align> = None;
1534        let mut min_pack: Option<Align> = None;
1535
1536        // Generate a deterministically-derived seed from the item's path hash
1537        // to allow for cross-crate compilation to actually work
1538        let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1539
1540        // If the user defined a custom seed for layout randomization, xor the item's
1541        // path hash with the user defined seed, this will allowing determinism while
1542        // still allowing users to further randomize layout generation for e.g. fuzzing
1543        if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1544            field_shuffle_seed ^= user_seed;
1545        }
1546
1547        let elt = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &self) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcScalableVector {
                        element_count }) => {
                        break 'done Some(element_count);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self, did, RustcScalableVector { element_count } => element_count
1548        )
1549        .map(|elt| match elt {
1550            Some(n) => ScalableElt::ElementCount(*n),
1551            None => ScalableElt::Container,
1552        });
1553        if elt.is_some() {
1554            flags.insert(ReprFlags::IS_SCALABLE);
1555        }
1556        if let Some(reprs) = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &self) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(Repr { reprs, .. }) => {
                        break 'done Some(reprs);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self, did, Repr { reprs, .. } => reprs) {
1557            for (r, _) in reprs {
1558                flags.insert(match *r {
1559                    attr::ReprRust => ReprFlags::empty(),
1560                    attr::ReprC => ReprFlags::IS_C,
1561                    attr::ReprPacked(pack) => {
1562                        min_pack = Some(if let Some(min_pack) = min_pack {
1563                            min_pack.min(pack)
1564                        } else {
1565                            pack
1566                        });
1567                        ReprFlags::empty()
1568                    }
1569                    attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1570                    attr::ReprSimd => ReprFlags::IS_SIMD,
1571                    attr::ReprInt(i) => {
1572                        size = Some(match i {
1573                            attr::IntType::SignedInt(x) => match x {
1574                                ast::IntTy::Isize => IntegerType::Pointer(true),
1575                                ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1576                                ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1577                                ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1578                                ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1579                                ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1580                            },
1581                            attr::IntType::UnsignedInt(x) => match x {
1582                                ast::UintTy::Usize => IntegerType::Pointer(false),
1583                                ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1584                                ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1585                                ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1586                                ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1587                                ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1588                            },
1589                        });
1590                        ReprFlags::empty()
1591                    }
1592                    attr::ReprAlign(align) => {
1593                        max_align = max_align.max(Some(align));
1594                        ReprFlags::empty()
1595                    }
1596                });
1597            }
1598        }
1599
1600        // If `-Z randomize-layout` was enabled for the type definition then we can
1601        // consider performing layout randomization
1602        if self.sess.opts.unstable_opts.randomize_layout {
1603            flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1604        }
1605
1606        // box is special, on the one hand the compiler assumes an ordered layout, with the pointer
1607        // always at offset zero. On the other hand we want scalar abi optimizations.
1608        let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1609
1610        // This is here instead of layout because the choice must make it into metadata.
1611        if is_box {
1612            flags.insert(ReprFlags::IS_LINEAR);
1613        }
1614
1615        // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
1616        if {
        {
            'done:
                {
                for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &self) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcPassIndirectlyInNonRusticAbis(..))
                            => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self, did, RustcPassIndirectlyInNonRusticAbis(..)) {
1617            flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1618        }
1619
1620        ReprOptions {
1621            int: size,
1622            align: max_align,
1623            pack: min_pack,
1624            flags,
1625            field_shuffle_seed,
1626            scalable: elt,
1627        }
1628    }
1629
1630    /// Look up the name of a definition across crates. This does not look at HIR.
1631    pub fn opt_item_name(self, def_id: impl IntoQueryKey<DefId>) -> Option<Symbol> {
1632        let def_id = def_id.into_query_key();
1633        if let Some(cnum) = def_id.as_crate_root() {
1634            Some(self.crate_name(cnum))
1635        } else {
1636            let def_key = self.def_key(def_id);
1637            match def_key.disambiguated_data.data {
1638                // The name of a constructor is that of its parent.
1639                rustc_hir::definitions::DefPathData::Ctor => self
1640                    .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1641                _ => def_key.get_opt_name(),
1642            }
1643        }
1644    }
1645
1646    /// Look up the name of a definition across crates. This does not look at HIR.
1647    ///
1648    /// This method will ICE if the corresponding item does not have a name. In these cases, use
1649    /// [`opt_item_name`] instead.
1650    ///
1651    /// [`opt_item_name`]: Self::opt_item_name
1652    pub fn item_name(self, id: impl IntoQueryKey<DefId>) -> Symbol {
1653        let id = id.into_query_key();
1654        self.opt_item_name(id).unwrap_or_else(|| {
1655            crate::util::bug::bug_fmt(format_args!("item_name: no name for {0:?}",
        self.def_path(id)));bug!("item_name: no name for {:?}", self.def_path(id));
1656        })
1657    }
1658
1659    /// Look up the name and span of a definition.
1660    ///
1661    /// See [`item_name`][Self::item_name] for more information.
1662    pub fn opt_item_ident(self, def_id: impl IntoQueryKey<DefId>) -> Option<Ident> {
1663        let def_id = def_id.into_query_key();
1664        let def = self.opt_item_name(def_id)?;
1665        let span = self
1666            .def_ident_span(def_id)
1667            .unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("missing ident span for {0:?}",
        def_id))bug!("missing ident span for {def_id:?}"));
1668        Some(Ident::new(def, span))
1669    }
1670
1671    /// Look up the name and span of a definition.
1672    ///
1673    /// See [`item_name`][Self::item_name] for more information.
1674    pub fn item_ident(self, def_id: impl IntoQueryKey<DefId>) -> Ident {
1675        let def_id = def_id.into_query_key();
1676        self.opt_item_ident(def_id).unwrap_or_else(|| {
1677            crate::util::bug::bug_fmt(format_args!("item_ident: no name for {0:?}",
        self.def_path(def_id)));bug!("item_ident: no name for {:?}", self.def_path(def_id));
1678        })
1679    }
1680
1681    pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1682        if let DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy =
1683            self.def_kind(def_id)
1684        {
1685            Some(self.associated_item(def_id))
1686        } else {
1687            None
1688        }
1689    }
1690
1691    /// If the `def_id` is an associated type that was desugared from a
1692    /// return-position `impl Trait` from a trait, then provide the source info
1693    /// about where that RPITIT came from.
1694    pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1695        if let DefKind::AssocTy = self.def_kind(def_id)
1696            && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1697                self.associated_item(def_id).kind
1698        {
1699            Some(rpitit_info)
1700        } else {
1701            None
1702        }
1703    }
1704
1705    pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1706        variant.fields.iter_enumerated().find_map(|(i, field)| {
1707            self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1708        })
1709    }
1710
1711    /// Returns `Some` if the impls are the same polarity and the trait either
1712    /// has no items or is annotated `#[marker]` and prevents item overrides.
1713    x;#[instrument(level = "debug", skip(self), ret)]
1714    pub fn impls_are_allowed_to_overlap(
1715        self,
1716        def_id1: DefId,
1717        def_id2: DefId,
1718    ) -> Option<ImplOverlapKind> {
1719        let impl1 = self.impl_trait_header(def_id1);
1720        let impl2 = self.impl_trait_header(def_id2);
1721
1722        let trait_ref1 = impl1.trait_ref.skip_binder();
1723        let trait_ref2 = impl2.trait_ref.skip_binder();
1724
1725        // If either trait impl references an error, they're allowed to overlap,
1726        // as one of them essentially doesn't exist.
1727        if trait_ref1.references_error() || trait_ref2.references_error() {
1728            return Some(ImplOverlapKind::Permitted { marker: false });
1729        }
1730
1731        match (impl1.polarity, impl2.polarity) {
1732            (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1733                // `#[rustc_reservation_impl]` impls don't overlap with anything
1734                return Some(ImplOverlapKind::Permitted { marker: false });
1735            }
1736            (ImplPolarity::Positive, ImplPolarity::Negative)
1737            | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1738                // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1739                return None;
1740            }
1741            (ImplPolarity::Positive, ImplPolarity::Positive)
1742            | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1743        };
1744
1745        let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1746        let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1747
1748        if is_marker_overlap {
1749            return Some(ImplOverlapKind::Permitted { marker: true });
1750        }
1751
1752        None
1753    }
1754
1755    /// Returns `ty::VariantDef` if `res` refers to a struct,
1756    /// or variant or their constructors, panics otherwise.
1757    pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1758        match res {
1759            Res::Def(DefKind::Variant, did) => {
1760                let enum_did = self.parent(did);
1761                self.adt_def(enum_did).variant_with_id(did)
1762            }
1763            Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1764            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1765                let variant_did = self.parent(variant_ctor_did);
1766                let enum_did = self.parent(variant_did);
1767                self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1768            }
1769            Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1770                let struct_did = self.parent(ctor_did);
1771                self.adt_def(struct_did).non_enum_variant()
1772            }
1773            _ => crate::util::bug::bug_fmt(format_args!("expect_variant_res used with unexpected res {0:?}",
        res))bug!("expect_variant_res used with unexpected res {:?}", res),
1774        }
1775    }
1776
1777    /// Returns the possibly-auto-generated MIR of a [`ty::InstanceKind`].
1778    #[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("compiler/rustc_middle/src/ty/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1778u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                    ::tracing_core::field::FieldSet::new(&["instance"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn 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;
        }
        {
            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 compiler/rustc_middle/src/ty/mod.rs:1782",
                                            "rustc_middle::ty", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(1782u32),
                                            ::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};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("calling def_kind on def: {0:?}",
                                                                        def) as &dyn 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 compiler/rustc_middle/src/ty/mod.rs:1784",
                                            "rustc_middle::ty", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(1784u32),
                                            ::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};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("returned from def_kind: {0:?}",
                                                                        def_kind) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    match def_kind {
                        DefKind::Const { .. } | DefKind::Static { .. } |
                            DefKind::AssocConst { .. } | DefKind::Ctor(..) |
                            DefKind::AnonConst | DefKind::InlineConst =>
                            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::VTableShim(..) |
                    ty::InstanceKind::ReifyShim(..) |
                    ty::InstanceKind::Intrinsic(..) |
                    ty::InstanceKind::FnPtrShim(..) |
                    ty::InstanceKind::Virtual(..) |
                    ty::InstanceKind::ClosureOnceShim { .. } |
                    ty::InstanceKind::ConstructCoroutineInClosureShim { .. } |
                    ty::InstanceKind::FutureDropPollShim(..) |
                    ty::InstanceKind::DropGlue(..) |
                    ty::InstanceKind::CloneShim(..) |
                    ty::InstanceKind::ThreadLocalShim(..) |
                    ty::InstanceKind::FnPtrAddrShim(..) |
                    ty::InstanceKind::AsyncDropGlueCtorShim(..) |
                    ty::InstanceKind::AsyncDropGlue(..) =>
                    self.mir_shims(instance),
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
1779    pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1780        match instance {
1781            ty::InstanceKind::Item(def) => {
1782                debug!("calling def_kind on def: {:?}", def);
1783                let def_kind = self.def_kind(def);
1784                debug!("returned from def_kind: {:?}", def_kind);
1785                match def_kind {
1786                    DefKind::Const { .. }
1787                    | DefKind::Static { .. }
1788                    | DefKind::AssocConst { .. }
1789                    | DefKind::Ctor(..)
1790                    | DefKind::AnonConst
1791                    | DefKind::InlineConst => self.mir_for_ctfe(def),
1792                    DefKind::Fn | DefKind::AssocFn
1793                        if matches!(
1794                            self.constness(def),
1795                            hir::Constness::Const { always: true }
1796                        ) =>
1797                    {
1798                        self.mir_for_ctfe(def)
1799                    }
1800                    // If the caller wants `mir_for_ctfe` of a function they should not be using
1801                    // `instance_mir`, so we'll assume const fn also wants the optimized version.
1802                    _ => self.optimized_mir(def),
1803                }
1804            }
1805            ty::InstanceKind::VTableShim(..)
1806            | ty::InstanceKind::ReifyShim(..)
1807            | ty::InstanceKind::Intrinsic(..)
1808            | ty::InstanceKind::FnPtrShim(..)
1809            | ty::InstanceKind::Virtual(..)
1810            | ty::InstanceKind::ClosureOnceShim { .. }
1811            | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1812            | ty::InstanceKind::FutureDropPollShim(..)
1813            | ty::InstanceKind::DropGlue(..)
1814            | ty::InstanceKind::CloneShim(..)
1815            | ty::InstanceKind::ThreadLocalShim(..)
1816            | ty::InstanceKind::FnPtrAddrShim(..)
1817            | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1818            | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1819        }
1820    }
1821
1822    /// Gets all attributes with the given name.
1823    #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."]
1824    pub fn get_attrs(
1825        self,
1826        did: impl Into<DefId>,
1827        attr: Symbol,
1828    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1829        #[allow(deprecated)]
1830        self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1831    }
1832
1833    /// Gets all attributes.
1834    ///
1835    /// To see if an item has a specific attribute, you should use
1836    /// [`rustc_hir::find_attr!`] so you can use matching.
1837    #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."]
1838    pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1839        let did: DefId = did.into();
1840        if let Some(did) = did.as_local() {
1841            self.hir_attrs(self.local_def_id_to_hir_id(did))
1842        } else {
1843            self.attrs_for_def(did)
1844        }
1845    }
1846
1847    pub fn get_attrs_by_path(
1848        self,
1849        did: DefId,
1850        attr: &[Symbol],
1851    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1852        let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1853        if let Some(did) = did.as_local() {
1854            self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1855        } else {
1856            self.attrs_for_def(did).iter().filter(filter_fn)
1857        }
1858    }
1859
1860    /// Returns `true` if this is an `auto trait`.
1861    pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1862        self.trait_def(trait_def_id).has_auto_impl
1863    }
1864
1865    /// Returns `true` if this is coinductive, either because it is
1866    /// an auto trait or because it has the `#[rustc_coinductive]` attribute.
1867    pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1868        self.trait_def(trait_def_id).is_coinductive
1869    }
1870
1871    /// Returns `true` if this is a trait alias.
1872    pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1873        self.def_kind(trait_def_id) == DefKind::TraitAlias
1874    }
1875
1876    /// Arena-alloc of LayoutError for coroutine layout
1877    fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1878        self.arena.alloc(err)
1879    }
1880
1881    /// Returns layout of a non-async-drop coroutine. Layout might be unavailable if the
1882    /// coroutine is tainted by errors.
1883    ///
1884    /// Takes `coroutine_kind` which can be acquired from the `CoroutineArgs::kind_ty`,
1885    /// e.g. `args.as_coroutine().kind_ty()`.
1886    fn ordinary_coroutine_layout(
1887        self,
1888        def_id: DefId,
1889        args: GenericArgsRef<'tcx>,
1890    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1891        let coroutine_kind_ty = args.as_coroutine().kind_ty();
1892        let mir = self.optimized_mir(def_id);
1893        let ty = || Ty::new_coroutine(self, def_id, args);
1894        // Regular coroutine
1895        if coroutine_kind_ty.is_unit() {
1896            mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1897        } else {
1898            // If we have a `Coroutine` that comes from an coroutine-closure,
1899            // then it may be a by-move or by-ref body.
1900            let ty::Coroutine(_, identity_args) =
1901                *self.type_of(def_id).instantiate_identity().skip_norm_wip().kind()
1902            else {
1903                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1904            };
1905            let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1906            // If the types differ, then we must be getting the by-move body of
1907            // a by-ref coroutine.
1908            if identity_kind_ty == coroutine_kind_ty {
1909                mir.coroutine_layout_raw()
1910                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1911            } else {
1912                {
    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));
1913                {
    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!(
1914                    identity_kind_ty.to_opt_closure_kind(),
1915                    Some(ClosureKind::Fn | ClosureKind::FnMut)
1916                );
1917                self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1918                    .coroutine_layout_raw()
1919                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1920            }
1921        }
1922    }
1923
1924    /// Returns layout of a `async_drop_in_place::{closure}` coroutine
1925    ///   (returned from `async fn async_drop_in_place<T>(..)`).
1926    /// Layout might be unavailable if the coroutine is tainted by errors.
1927    fn async_drop_coroutine_layout(
1928        self,
1929        def_id: DefId,
1930        args: GenericArgsRef<'tcx>,
1931    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1932        let ty = || Ty::new_coroutine(self, def_id, args);
1933        if args[0].has_placeholders() || args[0].has_non_region_param() {
1934            return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1935        }
1936        let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1937        self.mir_shims(instance)
1938            .coroutine_layout_raw()
1939            .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1940    }
1941
1942    /// Returns layout of a coroutine. Layout might be unavailable if the
1943    /// coroutine is tainted by errors.
1944    pub fn coroutine_layout(
1945        self,
1946        def_id: DefId,
1947        args: GenericArgsRef<'tcx>,
1948    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1949        if self.is_async_drop_in_place_coroutine(def_id) {
1950            // layout of `async_drop_in_place<T>::{closure}` in case,
1951            // when T is a coroutine, contains this internal coroutine's ptr in upvars
1952            // and doesn't require any locals. Here is an `empty coroutine's layout`
1953            let arg_cor_ty = args.first().unwrap().expect_ty();
1954            if arg_cor_ty.is_coroutine() {
1955                let span = self.def_span(def_id);
1956                let source_info = SourceInfo::outermost(span);
1957                // Even minimal, empty coroutine has 3 states (RESERVED_VARIANTS),
1958                // so variant_fields and variant_source_info should have 3 elements.
1959                let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1960                    iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1961                let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1962                    iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1963                let proxy_layout = CoroutineLayout {
1964                    field_tys: [].into(),
1965                    variant_fields,
1966                    variant_source_info,
1967                    storage_conflicts: BitMatrix::new(0, 0),
1968                };
1969                return Ok(self.arena.alloc(proxy_layout));
1970            } else {
1971                self.async_drop_coroutine_layout(def_id, args)
1972            }
1973        } else {
1974            self.ordinary_coroutine_layout(def_id, args)
1975        }
1976    }
1977
1978    /// If the given `DefId` is an associated item, returns the `DefId` and `DefKind` of the parent trait or impl.
1979    pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1980        if !self.def_kind(def_id).is_assoc() {
1981            return None;
1982        }
1983        let parent = self.parent(def_id);
1984        let def_kind = self.def_kind(parent);
1985        Some((parent, def_kind))
1986    }
1987
1988    /// Returns the trait item that is implemented by the given item `DefId`.
1989    pub fn trait_item_of(self, def_id: impl IntoQueryKey<DefId>) -> Option<DefId> {
1990        let def_id = def_id.into_query_key();
1991        self.opt_associated_item(def_id)?.trait_item_def_id()
1992    }
1993
1994    /// If the given `DefId` is an associated item of a trait,
1995    /// returns the `DefId` of the trait; otherwise, returns `None`.
1996    pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1997        match self.assoc_parent(def_id) {
1998            Some((id, DefKind::Trait)) => Some(id),
1999            _ => None,
2000        }
2001    }
2002
2003    pub fn impl_is_of_trait(self, def_id: impl IntoQueryKey<DefId>) -> bool {
2004        let def_id = def_id.into_query_key();
2005        let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
2006            {
    ::core::panicking::panic_fmt(format_args!("expected Impl for {0:?}",
            def_id));
};panic!("expected Impl for {def_id:?}");
2007        };
2008        of_trait
2009    }
2010
2011    /// If the given `DefId` is an associated item of an impl,
2012    /// returns the `DefId` of the impl; otherwise returns `None`.
2013    pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2014        match self.assoc_parent(def_id) {
2015            Some((id, DefKind::Impl { .. })) => Some(id),
2016            _ => None,
2017        }
2018    }
2019
2020    /// If the given `DefId` is an associated item of an inherent impl,
2021    /// returns the `DefId` of the impl; otherwise, returns `None`.
2022    pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2023        match self.assoc_parent(def_id) {
2024            Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2025            _ => None,
2026        }
2027    }
2028
2029    /// If the given `DefId` is an associated item of a trait impl,
2030    /// returns the `DefId` of the impl; otherwise, returns `None`.
2031    pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2032        match self.assoc_parent(def_id) {
2033            Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2034            _ => None,
2035        }
2036    }
2037
2038    pub fn impl_polarity(self, def_id: impl IntoQueryKey<DefId>) -> ty::ImplPolarity {
2039        let def_id = def_id.into_query_key();
2040        self.impl_trait_header(def_id).polarity
2041    }
2042
2043    /// Given an `impl_id`, return the trait it implements.
2044    pub fn impl_trait_ref(
2045        self,
2046        def_id: impl IntoQueryKey<DefId>,
2047    ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2048        let def_id = def_id.into_query_key();
2049        self.impl_trait_header(def_id).trait_ref
2050    }
2051
2052    /// Given an `impl_id`, return the trait it implements.
2053    /// Returns `None` if it is an inherent impl.
2054    pub fn impl_opt_trait_ref(
2055        self,
2056        def_id: impl IntoQueryKey<DefId>,
2057    ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2058        let def_id = def_id.into_query_key();
2059        self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2060    }
2061
2062    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2063    pub fn impl_trait_id(self, def_id: impl IntoQueryKey<DefId>) -> DefId {
2064        let def_id = def_id.into_query_key();
2065        self.impl_trait_ref(def_id).skip_binder().def_id
2066    }
2067
2068    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2069    /// Returns `None` if it is an inherent impl.
2070    pub fn impl_opt_trait_id(self, def_id: impl IntoQueryKey<DefId>) -> Option<DefId> {
2071        let def_id = def_id.into_query_key();
2072        self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2073    }
2074
2075    pub fn is_exportable(self, def_id: DefId) -> bool {
2076        self.exportable_items(def_id.krate).contains(&def_id)
2077    }
2078
2079    /// Check if the given `DefId` is `#\[automatically_derived\]`, *and*
2080    /// whether it was produced by expanding a builtin derive macro.
2081    pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2082        if self.is_automatically_derived(def_id)
2083            && let Some(def_id) = def_id.as_local()
2084            && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2085            && #[allow(non_exhaustive_omitted_patterns)] match outer.kind {
    ExpnKind::Macro(MacroKind::Derive, _) => true,
    _ => false,
}matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2086            && {
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(outer.macro_def_id.unwrap(),
                        &self) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcBuiltinMacro { .. }) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self, outer.macro_def_id.unwrap(), RustcBuiltinMacro { .. })
2087        {
2088            true
2089        } else {
2090            false
2091        }
2092    }
2093
2094    /// Check if the given `DefId` is `#\[automatically_derived\]`.
2095    pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2096        {
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AutomaticallyDerived) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self, def_id, AutomaticallyDerived)
2097    }
2098
2099    /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2100    /// with the name of the crate containing the impl.
2101    pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2102        if let Some(impl_def_id) = impl_def_id.as_local() {
2103            Ok(self.def_span(impl_def_id))
2104        } else {
2105            Err(self.crate_name(impl_def_id.krate))
2106        }
2107    }
2108
2109    /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2110    /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2111    /// definition's parent/scope to perform comparison.
2112    pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2113        // We could use `Ident::eq` here, but we deliberately don't. The identifier
2114        // comparison fails frequently, and we want to avoid the expensive
2115        // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2116        use_ident.name == def_ident.name
2117            && use_ident
2118                .span
2119                .ctxt()
2120                .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2121    }
2122
2123    pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2124        ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2125        ident
2126    }
2127
2128    // FIXME(vincenzopalazzo): move the HirId to a LocalDefId
2129    pub fn adjust_ident_and_get_scope(
2130        self,
2131        mut ident: Ident,
2132        scope: DefId,
2133        block: hir::HirId,
2134    ) -> (Ident, DefId) {
2135        let scope = ident
2136            .span
2137            .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2138            .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2139            .unwrap_or_else(|| self.parent_module(block).to_def_id());
2140        (ident, scope)
2141    }
2142
2143    /// Checks whether this is a `const fn`. Returns `false` for non-functions.
2144    ///
2145    /// Even if this returns `true`, constness may still be unstable!
2146    #[inline]
2147    pub fn is_const_fn(self, def_id: impl IntoQueryKey<DefId>) -> bool {
2148        let def_id = def_id.into_query_key();
2149        #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
    DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) |
        DefKind::Closure => true,
    _ => false,
}matches!(
2150            self.def_kind(def_id),
2151            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2152        ) && #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { .. } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { .. })
2153    }
2154
2155    /// Whether this item is conditionally constant for the purposes of the
2156    /// effects implementation.
2157    ///
2158    /// This roughly corresponds to all const functions and other callable
2159    /// items, along with const impls and traits, and associated types within
2160    /// those impls and traits.
2161    pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2162        let def_id: DefId = def_id.into();
2163        match self.def_kind(def_id) {
2164            DefKind::Impl { of_trait: true } => {
2165                let header = self.impl_trait_header(def_id);
2166                #[allow(non_exhaustive_omitted_patterns)] match header.constness {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(header.constness, hir::Constness::Const { always: false })
2167                    && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2168            }
2169            DefKind::Impl { of_trait: false } => {
2170                #[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 })
2171            }
2172            DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2173                #[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 })
2174            }
2175            DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2176            DefKind::AssocTy => {
2177                let parent_def_id = self.parent(def_id);
2178                match self.def_kind(parent_def_id) {
2179                    DefKind::Impl { of_trait: false } => false,
2180                    DefKind::Impl { of_trait: true } | DefKind::Trait => {
2181                        self.is_conditionally_const(parent_def_id)
2182                    }
2183                    _ => crate::util::bug::bug_fmt(format_args!("unexpected parent item of associated type: {0:?}",
        parent_def_id))bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2184                }
2185            }
2186            DefKind::AssocFn => {
2187                let parent_def_id = self.parent(def_id);
2188                match self.def_kind(parent_def_id) {
2189                    DefKind::Impl { of_trait: false } => {
2190                        #[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 })
2191                    }
2192                    DefKind::Impl { of_trait: true } => {
2193                        let Some(trait_method_did) = self.trait_item_of(def_id) else {
2194                            return false;
2195                        };
2196                        #[allow(non_exhaustive_omitted_patterns)] match self.constness(trait_method_did)
    {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(
2197                            self.constness(trait_method_did),
2198                            hir::Constness::Const { always: false }
2199                        ) && self.is_conditionally_const(parent_def_id)
2200                    }
2201                    DefKind::Trait => {
2202                        #[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 })
2203                            && self.is_conditionally_const(parent_def_id)
2204                    }
2205                    _ => crate::util::bug::bug_fmt(format_args!("unexpected parent item of associated fn: {0:?}",
        parent_def_id))bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2206                }
2207            }
2208            DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2209                hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2210                hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2211                // FIXME(const_trait_impl): ATPITs could be conditionally const?
2212                hir::OpaqueTyOrigin::TyAlias { .. } => false,
2213            },
2214            DefKind::Closure => {
2215                #[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 })
2216            }
2217            DefKind::Ctor(_, CtorKind::Const)
2218            | DefKind::Mod
2219            | DefKind::Struct
2220            | DefKind::Union
2221            | DefKind::Enum
2222            | DefKind::Variant
2223            | DefKind::TyAlias
2224            | DefKind::ForeignTy
2225            | DefKind::TyParam
2226            | DefKind::Const { .. }
2227            | DefKind::ConstParam
2228            | DefKind::Static { .. }
2229            | DefKind::AssocConst { .. }
2230            | DefKind::Macro(_)
2231            | DefKind::ExternCrate
2232            | DefKind::Use
2233            | DefKind::ForeignMod
2234            | DefKind::AnonConst
2235            | DefKind::InlineConst
2236            | DefKind::Field
2237            | DefKind::LifetimeParam
2238            | DefKind::GlobalAsm
2239            | DefKind::SyntheticCoroutineBody => false,
2240        }
2241    }
2242
2243    #[inline]
2244    pub fn is_const_trait(self, def_id: DefId) -> bool {
2245        #[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 { .. })
2246    }
2247
2248    pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2249        if self.def_kind(def_id) != DefKind::AssocFn {
2250            return false;
2251        }
2252
2253        let Some(item) = self.opt_associated_item(def_id) else {
2254            return false;
2255        };
2256
2257        let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2258            return false;
2259        };
2260
2261        !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2262    }
2263
2264    /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for direct calls*
2265    /// to an `fn`. Indirectly-passed parameters in the returned ABI will include applicable
2266    /// codegen optimization attributes, including `ReadOnly` and `CapturesNone` -- deduction of
2267    /// which requires inspection of function bodies that can lead to cycles when performed during
2268    /// typeck. During typeck, you should therefore use instead the unoptimized ABI returned by
2269    /// `fn_abi_of_instance_no_deduced_attrs`.
2270    ///
2271    /// For performance reasons, you should prefer to call this inherent method rather than invoke
2272    /// the `fn_abi_of_instance_raw` query: it delegates to that query if necessary, but where
2273    /// possible delegates instead to the `fn_abi_of_instance_no_deduced_attrs` query (thus avoiding
2274    /// unnecessary query system overhead).
2275    ///
2276    /// * that includes virtual calls, which are represented by "direct calls" to an
2277    ///   `InstanceKind::Virtual` instance (of `<dyn Trait as Trait>::fn`).
2278    #[inline]
2279    pub fn fn_abi_of_instance(
2280        self,
2281        query: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
2282    ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
2283        // Only deduce attrs in full, optimized builds. Otherwise, avoid the query system overhead
2284        // of ever invoking the `fn_abi_of_instance_raw` query.
2285        if self.sess.opts.optimize != OptLevel::No && self.sess.opts.incremental.is_none() {
2286            self.fn_abi_of_instance_raw(query)
2287        } else {
2288            self.fn_abi_of_instance_no_deduced_attrs(query)
2289        }
2290    }
2291}
2292
2293// `HasAttrs` impls: allow `find_attr!(tcx, id, ...)` to work with both DefId-like types and HirId.
2294
2295impl<'tcx> hir::attrs::HasAttrs<'tcx, TyCtxt<'tcx>> for DefId {
2296    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [hir::Attribute] {
2297        if let Some(did) = self.as_local() {
2298            tcx.hir_attrs(tcx.local_def_id_to_hir_id(did))
2299        } else {
2300            tcx.attrs_for_def(self)
2301        }
2302    }
2303}
2304
2305impl<'tcx> hir::attrs::HasAttrs<'tcx, TyCtxt<'tcx>> for LocalDefId {
2306    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [hir::Attribute] {
2307        tcx.hir_attrs(tcx.local_def_id_to_hir_id(self))
2308    }
2309}
2310
2311impl<'tcx> hir::attrs::HasAttrs<'tcx, TyCtxt<'tcx>> for hir::OwnerId {
2312    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [hir::Attribute] {
2313        hir::attrs::HasAttrs::get_attrs(self.def_id, tcx)
2314    }
2315}
2316
2317impl<'tcx> hir::attrs::HasAttrs<'tcx, TyCtxt<'tcx>> for hir::HirId {
2318    fn get_attrs(self, tcx: &TyCtxt<'tcx>) -> &'tcx [hir::Attribute] {
2319        tcx.hir_attrs(self)
2320    }
2321}
2322
2323pub fn provide(providers: &mut Providers) {
2324    closure::provide(providers);
2325    context::provide(providers);
2326    erase_regions::provide(providers);
2327    inhabitedness::provide(providers);
2328    util::provide(providers);
2329    print::provide(providers);
2330    super::util::bug::provide(providers);
2331    *providers = Providers {
2332        trait_impls_of: trait_def::trait_impls_of_provider,
2333        incoherent_impls: trait_def::incoherent_impls_provider,
2334        trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2335        traits: trait_def::traits_provider,
2336        vtable_allocation: vtable::vtable_allocation_provider,
2337        ..*providers
2338    };
2339}
2340
2341/// A map for the local crate mapping each type to a vector of its
2342/// inherent impls. This is not meant to be used outside of coherence;
2343/// rather, you should request the vector for a specific type via
2344/// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2345/// (constructing this map requires touching the entire crate).
2346#[derive(#[automatically_derived]
impl ::core::clone::Clone for CrateInherentImpls {
    #[inline]
    fn clone(&self) -> CrateInherentImpls {
        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() -> CrateInherentImpls {
        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)]
2347pub struct CrateInherentImpls {
2348    pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2349    pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2350}
2351
2352#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for SymbolName<'tcx> {
    #[inline]
    fn clone(&self) -> SymbolName<'tcx> {
        let _: ::core::clone::AssertParamIsClone<&'tcx str>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for SymbolName<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for SymbolName<'tcx> {
    #[inline]
    fn eq(&self, other: &SymbolName<'tcx>) -> 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: &SymbolName<'tcx>)
        -> ::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: &SymbolName<'tcx>) -> ::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) {
                match *self {
                    SymbolName { name: __binding_0 } => {
                        ::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)]
2353pub struct SymbolName<'tcx> {
2354    /// `&str` gives a consistent ordering, which ensures reproducible builds.
2355    pub name: &'tcx str,
2356}
2357
2358impl<'tcx> SymbolName<'tcx> {
2359    pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2360        SymbolName { name: tcx.arena.alloc_str(name) }
2361    }
2362}
2363
2364impl<'tcx> fmt::Display for SymbolName<'tcx> {
2365    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2366        fmt::Display::fmt(&self.name, fmt)
2367    }
2368}
2369
2370impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2371    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2372        fmt::Display::fmt(&self.name, fmt)
2373    }
2374}
2375
2376/// The constituent parts of a type level constant of kind ADT or array.
2377#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for DestructuredAdtConst<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for DestructuredAdtConst<'tcx> {
    #[inline]
    fn clone(&self) -> DestructuredAdtConst<'tcx> {
        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)]
2378pub struct DestructuredAdtConst<'tcx> {
2379    pub variant: VariantIdx,
2380    pub fields: &'tcx [ty::Const<'tcx>],
2381}
2382
2383/// Generate TypeTree information for autodiff.
2384/// This function creates TypeTree metadata that describes the memory layout
2385/// of function parameters and return types for Enzyme autodiff.
2386pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2387    // Check if TypeTrees are disabled via NoTT flag
2388    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2389        return FncTree { args: ::alloc::vec::Vec::new()vec![], ret: TypeTree::new() };
2390    }
2391
2392    // Check if this is actually a function type
2393    if !fn_ty.is_fn() {
2394        return FncTree { args: ::alloc::vec::Vec::new()vec![], ret: TypeTree::new() };
2395    }
2396
2397    // Get the function signature
2398    let fn_sig = fn_ty.fn_sig(tcx);
2399    let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2400
2401    // Create TypeTrees for each input parameter
2402    let mut args = ::alloc::vec::Vec::new()vec![];
2403    for ty in sig.inputs().iter() {
2404        let type_tree = typetree_from_ty(tcx, *ty);
2405        args.push(type_tree);
2406    }
2407
2408    // Create TypeTree for return type
2409    let ret = typetree_from_ty(tcx, sig.output());
2410
2411    FncTree { args, ret }
2412}
2413
2414/// Generate TypeTree for a specific type.
2415/// This function analyzes a Rust type and creates appropriate TypeTree metadata.
2416pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2417    let mut visited = Vec::new();
2418    typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2419}
2420
2421/// Maximum recursion depth for TypeTree generation to prevent stack overflow
2422/// from pathological deeply nested types. Combined with cycle detection.
2423const MAX_TYPETREE_DEPTH: usize = 6;
2424
2425/// Internal recursive function for TypeTree generation with cycle detection and depth limiting.
2426fn typetree_from_ty_inner<'tcx>(
2427    tcx: TyCtxt<'tcx>,
2428    ty: Ty<'tcx>,
2429    depth: usize,
2430    visited: &mut Vec<Ty<'tcx>>,
2431) -> TypeTree {
2432    if depth >= MAX_TYPETREE_DEPTH {
2433        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/mod.rs:2433",
                        "rustc_middle::ty", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2433u32),
                        ::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::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("typetree depth limit {0} reached for type: {1}",
                                                    MAX_TYPETREE_DEPTH, ty) as &dyn Value))])
            });
    } else { ; }
};trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2434        return TypeTree::new();
2435    }
2436
2437    if visited.contains(&ty) {
2438        return TypeTree::new();
2439    }
2440
2441    visited.push(ty);
2442    let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2443    visited.pop();
2444    result
2445}
2446
2447/// Implementation of TypeTree generation logic.
2448fn typetree_from_ty_impl<'tcx>(
2449    tcx: TyCtxt<'tcx>,
2450    ty: Ty<'tcx>,
2451    depth: usize,
2452    visited: &mut Vec<Ty<'tcx>>,
2453) -> TypeTree {
2454    typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2455}
2456
2457/// Internal implementation with context about whether this is for a reference target.
2458fn typetree_from_ty_impl_inner<'tcx>(
2459    tcx: TyCtxt<'tcx>,
2460    ty: Ty<'tcx>,
2461    depth: usize,
2462    visited: &mut Vec<Ty<'tcx>>,
2463    is_reference_target: bool,
2464) -> TypeTree {
2465    if ty.is_scalar() {
2466        let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2467            (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2468        } else if ty.is_floating_point() {
2469            match ty {
2470                x if x == tcx.types.f16 => (Kind::Half, 2),
2471                x if x == tcx.types.f32 => (Kind::Float, 4),
2472                x if x == tcx.types.f64 => (Kind::Double, 8),
2473                x if x == tcx.types.f128 => (Kind::F128, 16),
2474                _ => (Kind::Integer, 0),
2475            }
2476        } else {
2477            (Kind::Integer, 0)
2478        };
2479
2480        // Use offset 0 for scalars that are direct targets of references (like &f64)
2481        // Use offset -1 for scalars used directly (like function return types)
2482        let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2483        return TypeTree(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Type { offset, size, kind, child: TypeTree::new() }]))vec![Type { offset, size, kind, child: TypeTree::new() }]);
2484    }
2485
2486    if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2487        let Some(inner_ty) = ty.builtin_deref(true) else {
2488            return TypeTree::new();
2489        };
2490
2491        let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2492        return TypeTree(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Type {
                    offset: -1,
                    size: tcx.data_layout.pointer_size().bytes_usize(),
                    kind: Kind::Pointer,
                    child,
                }]))vec![Type {
2493            offset: -1,
2494            size: tcx.data_layout.pointer_size().bytes_usize(),
2495            kind: Kind::Pointer,
2496            child,
2497        }]);
2498    }
2499
2500    if ty.is_array() {
2501        if let ty::Array(element_ty, len_const) = ty.kind() {
2502            let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2503            if len == 0 {
2504                return TypeTree::new();
2505            }
2506            let element_tree =
2507                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2508            let mut types = Vec::new();
2509            for elem_type in &element_tree.0 {
2510                types.push(Type {
2511                    offset: -1,
2512                    size: elem_type.size,
2513                    kind: elem_type.kind,
2514                    child: elem_type.child.clone(),
2515                });
2516            }
2517
2518            return TypeTree(types);
2519        }
2520    }
2521
2522    if ty.is_slice() {
2523        if let ty::Slice(element_ty) = ty.kind() {
2524            let element_tree =
2525                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2526            return element_tree;
2527        }
2528    }
2529
2530    if let ty::Tuple(tuple_types) = ty.kind() {
2531        if tuple_types.is_empty() {
2532            return TypeTree::new();
2533        }
2534
2535        let mut types = Vec::new();
2536        let mut current_offset = 0;
2537
2538        for tuple_ty in tuple_types.iter() {
2539            let element_tree =
2540                typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2541
2542            let element_layout = tcx
2543                .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2544                .ok()
2545                .map(|layout| layout.size.bytes_usize())
2546                .unwrap_or(0);
2547
2548            for elem_type in &element_tree.0 {
2549                types.push(Type {
2550                    offset: if elem_type.offset == -1 {
2551                        current_offset as isize
2552                    } else {
2553                        current_offset as isize + elem_type.offset
2554                    },
2555                    size: elem_type.size,
2556                    kind: elem_type.kind,
2557                    child: elem_type.child.clone(),
2558                });
2559            }
2560
2561            current_offset += element_layout;
2562        }
2563
2564        return TypeTree(types);
2565    }
2566
2567    if let ty::Adt(adt_def, args) = ty.kind() {
2568        if adt_def.is_struct() {
2569            let struct_layout =
2570                tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2571            if let Ok(layout) = struct_layout {
2572                let mut types = Vec::new();
2573
2574                for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2575                    let field_ty = field_def.ty(tcx, args);
2576                    let field_tree = typetree_from_ty_impl_inner(
2577                        tcx,
2578                        field_ty.skip_norm_wip(),
2579                        depth + 1,
2580                        visited,
2581                        false,
2582                    );
2583
2584                    let field_offset = layout.fields.offset(field_idx).bytes_usize();
2585
2586                    for elem_type in &field_tree.0 {
2587                        types.push(Type {
2588                            offset: if elem_type.offset == -1 {
2589                                field_offset as isize
2590                            } else {
2591                                field_offset as isize + elem_type.offset
2592                            },
2593                            size: elem_type.size,
2594                            kind: elem_type.kind,
2595                            child: elem_type.child.clone(),
2596                        });
2597                    }
2598                }
2599
2600                return TypeTree(types);
2601            }
2602        }
2603    }
2604
2605    TypeTree::new()
2606}