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