Skip to main content

rustc_middle/ty/
mod.rs

1//! Defines how the compiler represents types internally.
2//!
3//! Two important entities in this module are:
4//!
5//! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6//! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7//!
8//! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
9//!
10//! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12#![allow(rustc::usage_of_ty_tykind)]
13
14use std::cmp::Ordering;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ops::ControlFlow;
20use std::ptr::NonNull;
21use std::{assert_matches, fmt, iter, str};
22
23pub use adt::*;
24pub use assoc::*;
25pub use generic_args::{GenericArgKind, TermKind, *};
26pub use generics::*;
27pub use intrinsic::IntrinsicDef;
28use rustc_abi::{
29    Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, VariantIdx,
30};
31use rustc_ast::node_id::NodeMap;
32use rustc_ast::{self as ast, NodeId};
33pub use rustc_ast_ir::{Movability, Mutability, try_visit};
34use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
35use rustc_data_structures::intern::Interned;
36use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
37use rustc_data_structures::steal::Steal;
38use rustc_data_structures::unord::{UnordMap, UnordSet};
39use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
40use rustc_hir::attrs::StrippedCfgItem;
41use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
42use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
43use rustc_hir::definitions::PerParentDisambiguatorState;
44use rustc_hir::{self as hir, LangItem, MissingLifetimeKind, attrs as attr, find_attr};
45use rustc_index::IndexVec;
46use rustc_index::bit_set::BitMatrix;
47use rustc_macros::{
48    BlobDecodable, Decodable, Encodable, StableHash, TyDecodable, TyEncodable, TypeFoldable,
49    TypeVisitable, extension,
50};
51use rustc_serialize::{Decodable, Encodable};
52use rustc_session::config::OptLevel;
53pub use rustc_session::lint::RegisteredTools;
54use rustc_span::def_id::{LocalModId, ModId};
55use rustc_span::hygiene::MacroKind;
56use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol};
57use rustc_target::callconv::FnAbi;
58pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
59pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
60pub use rustc_type_ir::relate::VarianceDiagInfo;
61pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind, VisibleForLeakCheck};
62pub use rustc_type_ir::*;
63use tracing::{debug, instrument};
64pub use vtable::*;
65
66pub use self::closure::{
67    BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
68    MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
69    UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
70    place_to_string_for_capture,
71};
72pub use self::consts::{
73    AliasConst, AliasConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult,
74    Expr, ExprKind, LitToConstInput, ScalarInt, SimdAlign, ValTree, ValTreeKindExt, Value,
75    const_lit_matches_ty,
76};
77pub use self::context::{
78    CtxtInterners, CurrentGcx, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
79};
80pub use self::fold::*;
81pub use self::instance::{Instance, InstanceKind, ReifyReason, ShimKind};
82pub(crate) use self::list::RawList;
83pub use self::list::{List, ListWithCachedTypeInfo};
84pub use self::opaque_types::OpaqueTypeKey;
85pub use self::pattern::{Pattern, PatternKind};
86pub use self::predicate::{
87    AliasTerm, AliasTermKind, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate,
88    ExistentialPredicate, ExistentialPredicateStableCmpExt, ExistentialProjection,
89    ExistentialTraitRef, HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
90    PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
91    PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
92    PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
93    RegionConstraint, RegionEqPredicate, RegionOutlivesPredicate, SubtypePredicate, TraitPredicate,
94    TraitRef, TypeOutlivesPredicate,
95};
96pub use self::region::{
97    EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region, RegionExt, RegionKind,
98    RegionVid,
99};
100pub use self::sty::{
101    Alias, AliasTy, AliasTyKind, Article, Binder, BoundConst, BoundRegion, BoundRegionKind,
102    BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig, CoroutineArgsExt, EarlyBinder,
103    FnSig, FnSigKind, FreeAliasTy, InherentAliasTy, InlineConstArgs, InlineConstArgsParts,
104    OpaqueAliasTy, ParamConst, ParamTy, PlaceholderConst, PlaceholderRegion, PlaceholderType,
105    PolyFnSig, ProjectionAliasTy, TyKind, TypeAndMut, TypingMode, TypingModeEqWrapper,
106    Unnormalized, UpvarArgs,
107};
108pub use self::trait_def::TraitDef;
109pub use self::typeck_results::{
110    CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
111    Rust2024IncompatiblePatInfo, SplattedDef, TypeckResults, UserType, UserTypeAnnotationIndex,
112    UserTypeKind,
113};
114use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
115use crate::metadata::{AmbigModChild, ModChild};
116use crate::middle::privacy::EffectiveVisibilities;
117use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, MirPhase, SourceInfo};
118use crate::query::{IntoQueryKey, Providers};
119use crate::ty;
120use crate::ty::codec::{TyDecoder, TyEncoder};
121pub use crate::ty::diagnostics::*;
122use crate::ty::fast_reject::SimplifiedType;
123use crate::ty::layout::{FnAbiError, LayoutError};
124use crate::ty::print::{with_crate_prefix, with_no_trimmed_paths};
125use crate::ty::util::Discr;
126use crate::ty::walk::TypeWalker;
127
128pub mod abstract_const;
129pub mod adjustment;
130pub mod cast;
131pub mod codec;
132pub mod error;
133pub mod fast_reject;
134pub mod inhabitedness;
135pub mod layout;
136pub mod normalize_erasing_regions;
137pub mod offload_meta;
138pub mod pattern;
139pub mod print;
140pub mod relate;
141pub mod significant_drop_order;
142pub mod trait_def;
143pub mod typetree;
144pub mod util;
145pub mod vtable;
146
147mod adt;
148mod assoc;
149mod closure;
150mod consts;
151mod context;
152mod diagnostics;
153mod elaborate_impl;
154mod erase_regions;
155mod fold;
156mod generic_args;
157mod generics;
158mod impls_ty;
159mod instance;
160mod intrinsic;
161mod list;
162mod opaque_types;
163mod predicate;
164mod region;
165mod structural_impls;
166#[expect(hidden_glob_reexports)]
167mod sty;
168mod typeck_results;
169mod visit;
170
171// Data types
172
173#[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)]
174pub struct ResolverGlobalCtxt {
175    pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
176    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
177    pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
178    pub effective_visibilities: EffectiveVisibilities,
179    // FIXME: This table contains ADTs reachable from macro 2.0.
180    // Currently, reachability of a definition from a macro is determined by nominal visibility
181    // (see `compute_effective_visibilities`). This is incorrect and leads to the necessity
182    // of traversing ADT fields in `rustc_privacy`. Remove this workaround once the
183    // correct reachability logic is implemented for macros.
184    pub macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,
185    pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
186    pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
187    pub module_children: LocalDefIdMap<Vec<ModChild>>,
188    pub ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
189    pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
190    pub main_def: Option<MainDefinition>,
191    pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
192    /// A list of proc macro LocalDefIds, written out in the order in which
193    /// they are declared in the static array generated by proc_macro_harness.
194    pub proc_macros: Vec<LocalDefId>,
195    /// Mapping from ident span to path span for paths that don't exist as written, but that
196    /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
197    pub confused_type_with_std_module: FxIndexMap<Span, Span>,
198    pub doc_link_resolutions: FxIndexMap<LocalModId, DocLinkResMap>,
199    pub doc_link_traits_in_scope: FxIndexMap<LocalModId, Vec<DefId>>,
200    pub all_macro_rules: UnordSet<Symbol>,
201    pub stripped_cfg_items: Vec<StrippedCfgItem>,
202    // Information about delegations which is used when handling recursive delegations
203    // and ensures easy access to delegation-only `LocalDefId`s.
204    pub delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,
205}
206
207#[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", "extra_lifetime_params_map", "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.extra_lifetime_params_map, &self.id, &&self.def_id];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "PerOwnerResolverData", names, values)
    }
}Debug)]
208pub struct PerOwnerResolverData<'tcx> {
209    pub node_id_to_def_id: NodeMap<LocalDefId> = Default::default(),
210    /// Whether lifetime elision was successful.
211    pub lifetime_elision_allowed: bool = false,
212    /// Resolutions for labels.
213    /// Maps from NodeId of the break/continue expression to the NodeId of their corresponding blocks or loops.
214    pub label_res_map: NodeMap<ast::NodeId> = Default::default(),
215    /// Resolutions for lifetimes.
216    pub lifetimes_res_map: NodeMap<LifetimeRes> = Default::default(),
217
218    pub trait_map: NodeMap<&'tcx [hir::TraitCandidate<'tcx>]> = Default::default(),
219
220    /// Resolution for import nodes, which have multiple resolutions in different namespaces.
221    pub import_res: hir::def::PerNS<Option<Res<ast::NodeId>>> = Default::default(),
222    /// Lifetime parameters that lowering will have to introduce.
223    pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, MissingLifetimeKind)>> = Default::default(),
224
225    /// The id of the owner
226    pub id: ast::NodeId,
227    /// The `DefId` of the owner, can't be found in `node_id_to_def_id`.
228    pub def_id: LocalDefId,
229}
230
231impl<'tcx> PerOwnerResolverData<'tcx> {
232    pub fn new(id: ast::NodeId, def_id: LocalDefId) -> PerOwnerResolverData<'tcx> {
233        PerOwnerResolverData { id, def_id, .. }
234    }
235
236    /// Obtains resolution for a label with the given `NodeId`.
237    pub fn get_label_res(&self, id: ast::NodeId) -> Option<ast::NodeId> {
238        self.label_res_map.get(&id).copied()
239    }
240
241    /// Obtains resolution for a lifetime with the given `NodeId`.
242    pub fn get_lifetime_res(&self, id: ast::NodeId) -> Option<LifetimeRes> {
243        self.lifetimes_res_map.get(&id).copied()
244    }
245
246    /// Obtain the list of lifetimes parameters to add to an item.
247    ///
248    /// Extra lifetime parameters should only be added in places that can appear
249    /// as a `binder` in `LifetimeRes`.
250    ///
251    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
252    /// should appear at the enclosing `PolyTraitRef`.
253    pub fn extra_lifetime_params(&self, id: NodeId) -> &[(Ident, NodeId, MissingLifetimeKind)] {
254        self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..])
255    }
256}
257
258/// Resolutions that should only be used for lowering.
259/// This struct is meant to be consumed by lowering.
260#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ResolverAstLowering<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "ResolverAstLowering", "partial_res_map", &self.partial_res_map,
            "next_node_id", &self.next_node_id, "owners", &self.owners,
            "lint_buffer", &self.lint_buffer, "disambiguators",
            &&self.disambiguators)
    }
}Debug)]
261pub struct ResolverAstLowering<'tcx> {
262    /// Resolutions for nodes that have a single resolution.
263    pub partial_res_map: NodeMap<hir::def::PartialRes>,
264
265    pub next_node_id: ast::NodeId,
266
267    pub owners: NodeMap<PerOwnerResolverData<'tcx>>,
268
269    /// Lints that were emitted by the resolver and early lints.
270    pub lint_buffer: Steal<LintBuffer>,
271
272    pub disambiguators: LocalDefIdMap<Steal<PerParentDisambiguatorState>>,
273}
274
275#[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)]
276pub struct DelegationInfo {
277    // `DefId` (either the resolution at delegation.id or item_id in case of a trait impl) for signature resolution,
278    // for details see https://github.com/rust-lang/rust/issues/118212#issuecomment-2160686914
279    /// Refers to the next element in a delegation resolution chain.
280    /// Usually points to the final resolution, as most "chains" are just
281    /// one step to a trait or an impl.
282    pub resolution_id: Result<DefId, ErrorGuaranteed>,
283}
284
285#[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)]
286pub struct MainDefinition {
287    pub res: Res<ast::NodeId>,
288    pub is_import: bool,
289    pub span: Span,
290}
291
292impl MainDefinition {
293    pub fn opt_fn_def_id(self) -> Option<DefId> {
294        if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
295    }
296}
297
298#[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)]
299pub struct ImplTraitHeader<'tcx> {
300    pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
301    pub polarity: ImplPolarity,
302    pub safety: hir::Safety,
303    pub constness: hir::Constness,
304}
305
306impl<'tcx> ImplTraitHeader<'tcx> {
307    /// For trait impls, checks whether
308    /// * the type and trait only use generic lifetime arguments (and no concrete ones like `'static`), and
309    /// * uses any generic param (lifetime or type) only once.
310    ///
311    /// This is a pessimistic analysis, so it will reject alias types
312    /// and other types that may be actually ok. We can allow more in the future.
313    ///
314    /// Constants (associated or generic) are irrelevant for this analysis, as their value is neither
315    /// affected by lifetimes, nor do they affect lifetimes.
316    pub fn is_fully_generic_for_reflection(self) -> bool {
317        #[derive(#[automatically_derived]
impl ::core::default::Default for ParamFinder {
    #[inline]
    fn default() -> ParamFinder {
        ParamFinder { seen: ::core::default::Default::default() }
    }
}Default)]
318        struct ParamFinder {
319            seen: FxHashSet<u32>,
320        }
321
322        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
323            type Result = ControlFlow<()>;
324            fn visit_region(&mut self, r: Region<'tcx>) -> Self::Result {
325                match r.kind() {
326                    RegionKind::ReEarlyParam(param) => {
327                        if self.seen.insert(param.index) {
328                            ControlFlow::Continue(())
329                        } else {
330                            ControlFlow::Break(())
331                        }
332                    }
333                    RegionKind::ReBound(..) => ControlFlow::Continue(()),
334                    RegionKind::ReStatic | RegionKind::ReError(_) => ControlFlow::Break(()),
335                    RegionKind::ReVar(_)
336                    | RegionKind::RePlaceholder(_)
337                    | RegionKind::ReErased
338                    | RegionKind::ReLateParam(_) => crate::util::bug::bug_fmt(format_args!("unexpected lifetime in impl: {0:?}",
        r))bug!("unexpected lifetime in impl: {r:?}"),
339                }
340            }
341
342            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
343                match t.kind() {
344                    TyKind::Param(p) => {
345                        // Reject using a parameter twice (e.g. in `Foo<T, T>`)
346                        if !self.seen.insert(p.index) {
347                            return ControlFlow::Break(());
348                        }
349                    }
350                    TyKind::Alias(..) => return ControlFlow::Break(()),
351                    _ => (),
352                }
353                t.super_visit_with(self)
354            }
355        }
356        self.trait_ref
357            .instantiate_identity()
358            .skip_norm_wip()
359            .visit_with(&mut ParamFinder::default())
360            .is_continue()
361    }
362}
363
364#[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)]
365#[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)]
366pub enum Asyncness {
367    Yes,
368    #[default]
369    No,
370}
371
372impl Asyncness {
373    pub fn is_async(self) -> bool {
374        #[allow(non_exhaustive_omitted_patterns)] match self {
    Asyncness::Yes => true,
    _ => false,
}matches!(self, Asyncness::Yes)
375    }
376}
377
378#[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)]
379pub enum Visibility<Id = LocalModId> {
380    /// Visible everywhere (including in other crates).
381    Public,
382    /// Visible only in the given crate-local module.
383    Restricted(Id),
384}
385
386impl Visibility {
387    pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
388        match self {
389            ty::Visibility::Restricted(restricted_id) => {
390                if restricted_id.is_top_level_module() {
391                    "pub(crate)".to_string()
392                } else if restricted_id == tcx.parent_module_from_def_id(def_id) {
393                    "pub(self)".to_string()
394                } else {
395                    ::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!(
396                        "pub(in crate{})",
397                        tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
398                    )
399                }
400            }
401            ty::Visibility::Public => "pub".to_string(),
402        }
403    }
404}
405
406#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RestrictionKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RestrictionKind::Unrestricted =>
                ::core::fmt::Formatter::write_str(f, "Unrestricted"),
            RestrictionKind::Restricted(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Restricted", __self_0, &__self_1),
        }
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            RestrictionKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    RestrictionKind::Unrestricted => {}
                    RestrictionKind::Restricted(ref __binding_0,
                        ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, #[automatically_derived]
impl ::core::cmp::PartialEq for RestrictionKind {
    #[inline]
    fn eq(&self, other: &RestrictionKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (RestrictionKind::Restricted(__self_0, __self_1),
                    RestrictionKind::Restricted(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for RestrictionKind {
    #[inline]
    fn clone(&self) -> RestrictionKind {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RestrictionKind { }Copy, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for RestrictionKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        RestrictionKind::Unrestricted => { 0usize }
                        RestrictionKind::Restricted(ref __binding_0,
                            ref __binding_1) => {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    RestrictionKind::Unrestricted => {}
                    RestrictionKind::Restricted(ref __binding_0,
                        ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for RestrictionKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { RestrictionKind::Unrestricted }
                    1usize => {
                        RestrictionKind::Restricted(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `RestrictionKind`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
407pub enum RestrictionKind {
408    Unrestricted,
409    Restricted(DefId, Span),
410}
411
412impl RestrictionKind {
413    /// Returns `true` if the behavior is allowed/unrestricted in the given module.
414    /// A value of `false` indicates that the behavior is prohibited.
415    pub fn is_allowed_in(self, module: DefId, tcx: TyCtxt<'_>) -> bool {
416        match self {
417            RestrictionKind::Unrestricted => true,
418            RestrictionKind::Restricted(restricted_to, _) => {
419                tcx.is_descendant_of(module, restricted_to)
420            }
421        }
422    }
423
424    /// Obtain the [`Span`] of the restriction. Panics if the restriction is unrestricted.
425    pub fn expect_span(self) -> Span {
426        match self {
427            RestrictionKind::Unrestricted => {
428                crate::util::bug::bug_fmt(format_args!("called `expect_span` on an unrestricted item"))bug!("called `expect_span` on an unrestricted item")
429            }
430            RestrictionKind::Restricted(_, span) => span,
431        }
432    }
433
434    /// Obtain the path of the restriction. If unrestricted, an empty string is returned.
435    pub fn restriction_path(self, tcx: TyCtxt<'_>) -> String {
436        match self {
437            RestrictionKind::Unrestricted => String::new(),
438            RestrictionKind::Restricted(restricted_to, _) => {
439                if restricted_to.krate == rustc_hir::def_id::LOCAL_CRATE {
440                    {
    let _guard = CratePrefixGuard::new();
    { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(restricted_to) }
}with_crate_prefix!(with_no_trimmed_paths!(tcx.def_path_str(restricted_to)))
441                } else {
442                    tcx.def_path_str(restricted_to.krate.as_mod_id())
443                }
444            }
445        }
446    }
447
448    /// Obtain the stricter restriction between `self` and `rhs`.
449    /// Panics if the restrictions do not reference the same crate.
450    pub fn stricter_of(self, rhs: Self, tcx: TyCtxt<'_>) -> Self {
451        match (self, rhs) {
452            (RestrictionKind::Unrestricted, r) | (r, RestrictionKind::Unrestricted) => r,
453            (
454                RestrictionKind::Restricted(left_did, _),
455                RestrictionKind::Restricted(right_did, _),
456            ) => {
457                if left_did.krate != right_did.krate {
458                    crate::util::bug::bug_fmt(format_args!("stricter_of: left and right restriction do not reference the same crate"));bug!("stricter_of: left and right restriction do not reference the same crate");
459                }
460                if tcx.is_descendant_of(left_did, right_did) { self } else { rhs }
461            }
462        }
463    }
464}
465
466#[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)]
467#[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)]
468pub struct ClosureSizeProfileData<'tcx> {
469    /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
470    pub before_feature_tys: Ty<'tcx>,
471    /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
472    pub after_feature_tys: Ty<'tcx>,
473}
474
475impl TyCtxt<'_> {
476    #[inline]
477    pub fn opt_parent(self, id: DefId) -> Option<DefId> {
478        self.def_key(id).parent.map(|index| DefId { index, ..id })
479    }
480
481    #[inline]
482    #[track_caller]
483    pub fn parent(self, id: DefId) -> DefId {
484        match self.opt_parent(id) {
485            Some(id) => id,
486            // not `unwrap_or_else` to avoid breaking caller tracking
487            None => crate::util::bug::bug_fmt(format_args!("{0:?} doesn\'t have a parent", id))bug!("{id:?} doesn't have a parent"),
488        }
489    }
490
491    #[inline]
492    #[track_caller]
493    pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
494        self.opt_parent(id.to_def_id()).map(DefId::expect_local)
495    }
496
497    #[inline]
498    #[track_caller]
499    pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
500        self.parent(id.into().to_def_id()).expect_local()
501    }
502
503    /// Compare def-ids based on their position in def-id tree, ancestor def-ids are considered
504    /// larger than descendant def-ids, and two different def-ids are considered unordered if
505    /// neither of them is an ancestor of the other.
506    fn def_id_partial_cmp(self, lhs: DefId, rhs: DefId) -> Option<Ordering> {
507        // Def-ids from different crates are always unordered.
508        if lhs.krate != rhs.krate {
509            return None;
510        }
511
512        // Def-ids of parent nodes are always created before def-ids of child nodes
513        // and have a smaller index, so we only need to search in one direction,
514        // either from lhs to rhs, or vice versa.
515        let search = |mut start: DefId, finish: DefId, ord| {
516            while start.index != finish.index {
517                match self.opt_parent(start) {
518                    Some(parent) => start.index = parent.index,
519                    None => return None,
520                }
521            }
522            Some(ord)
523        };
524        match lhs.index.cmp(&rhs.index) {
525            Ordering::Equal => Some(Ordering::Equal),
526            Ordering::Less => search(rhs, lhs, Ordering::Greater),
527            Ordering::Greater => search(lhs, rhs, Ordering::Less),
528        }
529    }
530
531    pub fn is_descendant_of(
532        self,
533        descendant: impl Into<DefId>,
534        ancestor: impl Into<DefId>,
535    ) -> bool {
536        #[allow(non_exhaustive_omitted_patterns)] match self.def_id_partial_cmp(descendant.into(),
        ancestor.into()) {
    Some(Ordering::Less | Ordering::Equal) => true,
    _ => false,
}matches!(
537            self.def_id_partial_cmp(descendant.into(), ancestor.into()),
538            Some(Ordering::Less | Ordering::Equal)
539        )
540    }
541}
542
543impl<Id> Visibility<Id> {
544    pub fn is_public(self) -> bool {
545        #[allow(non_exhaustive_omitted_patterns)] match self {
    Visibility::Public => true,
    _ => false,
}matches!(self, Visibility::Public)
546    }
547
548    pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
549        match self {
550            Visibility::Public => Visibility::Public,
551            Visibility::Restricted(id) => Visibility::Restricted(f(id)),
552        }
553    }
554}
555
556impl Visibility<LocalModId> {
557    pub fn to_mod_id(self) -> Visibility<ModId> {
558        self.map_id(LocalModId::to_mod_id)
559    }
560}
561
562impl<Id: Into<DefId>> Visibility<Id> {
563    /// Returns `true` if an item with this visibility is accessible from the given module.
564    pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
565        match self {
566            // Public items are visible everywhere.
567            Visibility::Public => true,
568            Visibility::Restricted(id) => tcx.is_descendant_of(module, id),
569        }
570    }
571
572    pub fn partial_cmp(
573        self,
574        vis: Visibility<impl Into<DefId>>,
575        tcx: TyCtxt<'_>,
576    ) -> Option<Ordering> {
577        match (self, vis) {
578            (Visibility::Public, Visibility::Public) => Some(Ordering::Equal),
579            (Visibility::Public, Visibility::Restricted(_)) => Some(Ordering::Greater),
580            (Visibility::Restricted(_), Visibility::Public) => Some(Ordering::Less),
581            (Visibility::Restricted(lhs_id), Visibility::Restricted(rhs_id)) => {
582                let (lhs_id, rhs_id) = (lhs_id.into(), rhs_id.into());
583                tcx.def_id_partial_cmp(lhs_id, rhs_id)
584            }
585        }
586    }
587}
588
589impl<Id: Into<DefId> + Debug + Copy> Visibility<Id> {
590    /// Returns `true` if this visibility is strictly larger than the given visibility.
591    #[track_caller]
592    pub fn greater_than(
593        self,
594        vis: Visibility<impl Into<DefId> + Debug + Copy>,
595        tcx: TyCtxt<'_>,
596    ) -> bool {
597        match self.partial_cmp(vis, tcx) {
598            Some(ord) => ord.is_gt(),
599            None => {
600                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:?}"));
601                false
602            }
603        }
604    }
605}
606
607impl Visibility<ModId> {
608    pub fn expect_local(self) -> Visibility {
609        self.map_id(|id| id.expect_local())
610    }
611
612    /// Returns `true` if this item is visible anywhere in the local crate.
613    pub fn is_visible_locally(self) -> bool {
614        match self {
615            Visibility::Public => true,
616            Visibility::Restricted(mod_id) => mod_id.is_local(),
617        }
618    }
619}
620
621/// The crate variances map is computed during typeck and contains the
622/// variance of every item in the local crate. You should not use it
623/// directly, because to do so will make your pass dependent on the
624/// HIR of every item in the local crate. Instead, use
625/// `tcx.variances_of()` to get the variance for a *particular*
626/// item.
627#[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)]
628pub struct CrateVariancesMap<'tcx> {
629    /// For each item with generics, maps to a vector of the variance
630    /// of its generics. If an item has no generics, it will have no
631    /// entry.
632    pub variances: DefIdMap<&'tcx [ty::Variance]>,
633}
634
635// Contains information needed to resolve types and (in the future) look up
636// the types of AST nodes.
637#[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)]
638pub struct CReaderCacheKey {
639    pub cnum: Option<CrateNum>,
640    pub pos: usize,
641}
642
643/// Use this rather than `TyKind`, whenever possible.
644#[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)]
645#[rustc_diagnostic_item = "Ty"]
646#[rustc_pass_by_value]
647pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
648
649impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
650    type Kind = TyKind<'tcx>;
651
652    fn kind(self) -> TyKind<'tcx> {
653        *self.kind()
654    }
655}
656
657impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
658    fn flags(&self) -> TypeFlags {
659        self.0.flags
660    }
661
662    fn outer_exclusive_binder(&self) -> DebruijnIndex {
663        self.0.outer_exclusive_binder
664    }
665}
666
667/// The crate outlives map is computed during typeck and contains the
668/// outlives of every item in the local crate. You should not use it
669/// directly, because to do so will make your pass dependent on the
670/// HIR of every item in the local crate. Instead, use
671/// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
672/// item.
673#[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)]
674pub struct CratePredicatesMap<'tcx> {
675    /// For each struct with outlive bounds, maps to a vector of the
676    /// predicate of its outlive bounds. If an item has no outlives
677    /// bounds, it will have no entry.
678    pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
679}
680
681#[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)]
682pub struct Term<'tcx> {
683    ptr: NonNull<()>,
684    marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
685}
686
687impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
688
689impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
690    type Kind = TermKind<'tcx>;
691
692    fn kind(self) -> Self::Kind {
693        self.kind()
694    }
695}
696
697unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
698    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
699{
700}
701unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
702    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
703{
704}
705unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
706unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
707
708impl Debug for Term<'_> {
709    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710        match self.kind() {
711            TermKind::Ty(ty) => f.write_fmt(format_args!("Term::Ty({0:?})", ty))write!(f, "Term::Ty({ty:?})"),
712            TermKind::Const(ct) => f.write_fmt(format_args!("Term::Const({0:?})", ct))write!(f, "Term::Const({ct:?})"),
713        }
714    }
715}
716
717impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
718    fn from(ty: Ty<'tcx>) -> Self {
719        TermKind::Ty(ty).pack()
720    }
721}
722
723impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
724    fn from(c: Const<'tcx>) -> Self {
725        TermKind::Const(c).pack()
726    }
727}
728
729impl<'tcx> StableHash for Term<'tcx> {
730    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
731        self.kind().stable_hash(hcx, hasher);
732    }
733}
734
735impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
736    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
737        self,
738        folder: &mut F,
739    ) -> Result<Self, F::Error> {
740        match self.kind() {
741            ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
742            ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
743        }
744    }
745
746    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
747        match self.kind() {
748            ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
749            ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
750        }
751    }
752}
753
754impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
755    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
756        match self.kind() {
757            ty::TermKind::Ty(ty) => ty.visit_with(visitor),
758            ty::TermKind::Const(ct) => ct.visit_with(visitor),
759        }
760    }
761}
762
763impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
764    fn encode(&self, e: &mut E) {
765        self.kind().encode(e)
766    }
767}
768
769impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
770    fn decode(d: &mut D) -> Self {
771        let res: TermKind<'tcx> = Decodable::decode(d);
772        res.pack()
773    }
774}
775
776impl<'tcx> Term<'tcx> {
777    #[inline]
778    pub fn kind(self) -> TermKind<'tcx> {
779        let ptr =
780            unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
781        // SAFETY: use of `Interned::new_unchecked` here is ok because these
782        // pointers were originally created from `Interned` types in `pack()`,
783        // and this is just going in the other direction.
784        unsafe {
785            match self.ptr.addr().get() & TAG_MASK {
786                TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
787                    ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
788                ))),
789                CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
790                    ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
791                ))),
792                _ => core::intrinsics::unreachable(),
793            }
794        }
795    }
796
797    pub fn as_type(&self) -> Option<Ty<'tcx>> {
798        if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
799    }
800
801    pub fn expect_type(&self) -> Ty<'tcx> {
802        self.as_type().expect("expected a type, but found a const")
803    }
804
805    pub fn as_const(&self) -> Option<Const<'tcx>> {
806        if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
807    }
808
809    pub fn expect_const(&self) -> Const<'tcx> {
810        self.as_const().expect("expected a const, but found a type")
811    }
812
813    pub fn into_arg(self) -> GenericArg<'tcx> {
814        match self.kind() {
815            TermKind::Ty(ty) => ty.into(),
816            TermKind::Const(c) => c.into(),
817        }
818    }
819
820    pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
821        match self.kind() {
822            TermKind::Ty(ty) => match *ty.kind() {
823                ty::Alias(_, alias_ty) => Some(alias_ty.into()),
824                _ => None,
825            },
826            TermKind::Const(ct) => match ct.kind() {
827                ConstKind::Alias(_, alias_const) => Some(alias_const.into()),
828                _ => None,
829            },
830        }
831    }
832
833    pub fn is_non_rigid_alias(self) -> bool {
834        match self.kind() {
835            ty::TermKind::Ty(ty) => match ty.kind() {
836                ty::Alias(ty::IsRigid::No, _) => true,
837                _ => false,
838            },
839            ty::TermKind::Const(ct) => match ct.kind() {
840                ty::ConstKind::Alias(ty::IsRigid::No, _) => true,
841                _ => false,
842            },
843        }
844    }
845
846    pub fn is_infer(&self) -> bool {
847        match self.kind() {
848            TermKind::Ty(ty) => ty.is_ty_var(),
849            TermKind::Const(ct) => ct.is_ct_infer(),
850        }
851    }
852
853    pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
854        match self.kind() {
855            TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
856            TermKind::Const(ct) => ct.is_trivially_wf(),
857        }
858    }
859
860    /// Iterator that walks `self` and any types reachable from
861    /// `self`, in depth-first order. Note that just walks the types
862    /// that appear in `self`, it does not descend into the fields of
863    /// structs or variants. For example:
864    ///
865    /// ```text
866    /// isize => { isize }
867    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
868    /// [isize] => { [isize], isize }
869    /// ```
870    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
871        TypeWalker::new(self.into())
872    }
873}
874
875const TAG_MASK: usize = 0b11;
876const TYPE_TAG: usize = 0b00;
877const CONST_TAG: usize = 0b01;
878
879impl<'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>)]
880impl<'tcx> TermKind<'tcx> {
881    #[inline]
882    fn pack(self) -> Term<'tcx> {
883        let (tag, ptr) = match self {
884            TermKind::Ty(ty) => {
885                // Ensure we can use the tag bits.
886                assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
887                (TYPE_TAG, NonNull::from(ty.0.0).cast())
888            }
889            TermKind::Const(ct) => {
890                // Ensure we can use the tag bits.
891                assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
892                (CONST_TAG, NonNull::from(ct.0.0).cast())
893            }
894        };
895
896        Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
897    }
898}
899
900/// Represents the bounds declared on a particular set of type
901/// parameters. Should eventually be generalized into a flag list of
902/// where-clauses. You can obtain an `InstantiatedClauses` list from a
903/// `GenericClauses` by using the `instantiate` method. Note that this method
904/// reflects an important semantic invariant of `InstantiatedClauses`: while
905/// the `GenericClauses` are expressed in terms of the bound type
906/// parameters of the impl/trait/whatever, an `InstantiatedClauses` instance
907/// represented a set of bounds for some particular instantiation,
908/// meaning that the generic parameters have been instantiated with
909/// their values.
910///
911/// Example:
912/// ```ignore (illustrative)
913/// struct Foo<T, U: Bar<T>> { ... }
914/// ```
915/// Here, the `GenericClauses` for `Foo` would contain a list of bounds like
916/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
917/// like `Foo<isize,usize>`, then the `InstantiatedClauses` would be `[[],
918/// [usize:Bar<isize>]]`.
919#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InstantiatedClauses<'tcx> {
    #[inline]
    fn clone(&self) -> InstantiatedClauses<'tcx> {
        InstantiatedClauses {
            clauses: ::core::clone::Clone::clone(&self.clauses),
            spans: ::core::clone::Clone::clone(&self.spans),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InstantiatedClauses<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "InstantiatedClauses", "clauses", &self.clauses, "spans",
            &&self.spans)
    }
}Debug)]
920pub struct InstantiatedClauses<'tcx> {
921    pub clauses: Vec<Unnormalized<'tcx, Clause<'tcx>>>,
922    pub spans: Vec<Span>,
923}
924
925impl<'tcx> InstantiatedClauses<'tcx> {
926    pub fn empty() -> InstantiatedClauses<'tcx> {
927        InstantiatedClauses { clauses: ::alloc::vec::Vec::new()vec![], spans: ::alloc::vec::Vec::new()vec![] }
928    }
929
930    pub fn is_empty(&self) -> bool {
931        self.clauses.is_empty()
932    }
933
934    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
935        self.into_iter()
936    }
937}
938
939impl<'tcx> IntoIterator for InstantiatedClauses<'tcx> {
940    type Item = (Unnormalized<'tcx, Clause<'tcx>>, Span);
941
942    type IntoIter = std::iter::Zip<
943        std::vec::IntoIter<Unnormalized<'tcx, Clause<'tcx>>>,
944        std::vec::IntoIter<Span>,
945    >;
946
947    fn into_iter(self) -> Self::IntoIter {
948        if true {
    {
        match (&self.clauses.len(), &self.spans.len()) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.clauses.len(), self.spans.len());
949        std::iter::zip(self.clauses, self.spans)
950    }
951}
952
953impl<'a, 'tcx> IntoIterator for &'a InstantiatedClauses<'tcx> {
954    type Item = (Unnormalized<'tcx, Clause<'tcx>>, Span);
955
956    type IntoIter = std::iter::Zip<
957        std::iter::Copied<std::slice::Iter<'a, Unnormalized<'tcx, Clause<'tcx>>>>,
958        std::iter::Copied<std::slice::Iter<'a, Span>>,
959    >;
960
961    fn into_iter(self) -> Self::IntoIter {
962        if true {
    {
        match (&self.clauses.len(), &self.spans.len()) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.clauses.len(), self.spans.len());
963        std::iter::zip(self.clauses.iter().copied(), self.spans.iter().copied())
964    }
965}
966
967#[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)]
968pub struct ProvisionalHiddenType<'tcx> {
969    /// The span of this particular definition of the opaque type. So
970    /// for example:
971    ///
972    /// ```ignore (incomplete snippet)
973    /// type Foo = impl Baz;
974    /// fn bar() -> Foo {
975    /// //          ^^^ This is the span we are looking for!
976    /// }
977    /// ```
978    ///
979    /// In cases where the fn returns `(impl Trait, impl Trait)` or
980    /// other such combinations, the result is currently
981    /// over-approximated, but better than nothing.
982    pub span: Span,
983
984    /// The type variable that represents the value of the opaque type
985    /// that we require. In other words, after we compile this function,
986    /// we will be created a constraint like:
987    /// ```ignore (pseudo-rust)
988    /// Foo<'a, T> = ?C
989    /// ```
990    /// where `?C` is the value of this type variable. =) It may
991    /// naturally refer to the type and lifetime parameters in scope
992    /// in this function, though ultimately it should only reference
993    /// those that are arguments to `Foo` in the constraint above. (In
994    /// other words, `?C` should not include `'b`, even though it's a
995    /// lifetime parameter on `foo`.)
996    pub ty: Ty<'tcx>,
997}
998
999/// Whether we're currently in HIR typeck or MIR borrowck.
1000#[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)]
1001pub enum DefiningScopeKind {
1002    /// During writeback in typeck, we don't care about regions and simply
1003    /// erase them. This means we also don't check whether regions are
1004    /// universal in the opaque type key. This will only be checked in
1005    /// MIR borrowck.
1006    HirTypeck,
1007    MirBorrowck,
1008}
1009
1010impl<'tcx> ProvisionalHiddenType<'tcx> {
1011    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
1012        ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
1013    }
1014
1015    pub fn build_mismatch_error(
1016        &self,
1017        other: &Self,
1018        tcx: TyCtxt<'tcx>,
1019    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
1020        (self.ty, other.ty).error_reported()?;
1021        // Found different concrete types for the opaque type.
1022        let sub_diag = if self.span == other.span {
1023            TypeMismatchReason::ConflictType { span: self.span }
1024        } else {
1025            TypeMismatchReason::PreviousUse { span: self.span }
1026        };
1027        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
1028            self_ty: self.ty,
1029            other_ty: other.ty,
1030            other_span: other.span,
1031            sub: sub_diag,
1032        }))
1033    }
1034
1035    x;#[instrument(level = "debug", skip(tcx), ret)]
1036    pub fn remap_generic_params_to_declaration_params(
1037        self,
1038        opaque_type_key: OpaqueTypeKey<'tcx>,
1039        tcx: TyCtxt<'tcx>,
1040        defining_scope_kind: DefiningScopeKind,
1041    ) -> DefinitionSiteHiddenType<'tcx> {
1042        let OpaqueTypeKey { def_id, args } = opaque_type_key;
1043
1044        // Use args to build up a reverse map from regions to their
1045        // identity mappings. This is necessary because of `impl
1046        // Trait` lifetimes are computed by replacing existing
1047        // lifetimes with 'static and remapping only those used in the
1048        // `impl Trait` return type, resulting in the parameters
1049        // shifting.
1050        let id_args = GenericArgs::identity_for_item(tcx, def_id);
1051        debug!(?id_args);
1052
1053        // This zip may have several times the same lifetime in `args` paired with a different
1054        // lifetime from `id_args`. Simply `collect`ing the iterator is the correct behaviour:
1055        // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
1056        let map = args.iter().zip(id_args).collect();
1057        debug!("map = {:#?}", map);
1058
1059        // Convert the type from the function into a type valid outside by mapping generic
1060        // parameters to into the context of the opaque.
1061        //
1062        // We erase regions when doing this during HIR typeck. We manually use `fold_regions`
1063        // here as we do not want to anonymize bound variables.
1064        let ty = match defining_scope_kind {
1065            DefiningScopeKind::HirTypeck => {
1066                fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
1067            }
1068            DefiningScopeKind::MirBorrowck => self.ty,
1069        };
1070        let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
1071        if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
1072            assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
1073        }
1074        DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(tcx, result_ty) }
1075    }
1076}
1077
1078#[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)]
1079pub struct DefinitionSiteHiddenType<'tcx> {
1080    /// The span of the definition of the opaque type. So for example:
1081    ///
1082    /// ```ignore (incomplete snippet)
1083    /// type Foo = impl Baz;
1084    /// fn bar() -> Foo {
1085    /// //          ^^^ This is the span we are looking for!
1086    /// }
1087    /// ```
1088    ///
1089    /// In cases where the fn returns `(impl Trait, impl Trait)` or
1090    /// other such combinations, the result is currently
1091    /// over-approximated, but better than nothing.
1092    pub span: Span,
1093
1094    /// The final type of the opaque.
1095    pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
1096}
1097
1098impl<'tcx> DefinitionSiteHiddenType<'tcx> {
1099    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
1100        DefinitionSiteHiddenType {
1101            span: DUMMY_SP,
1102            ty: ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, guar)),
1103        }
1104    }
1105
1106    pub fn build_mismatch_error(
1107        &self,
1108        other: &Self,
1109        tcx: TyCtxt<'tcx>,
1110    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
1111        let self_ty = self.ty.instantiate_identity().skip_norm_wip();
1112        let other_ty = other.ty.instantiate_identity().skip_norm_wip();
1113        (self_ty, other_ty).error_reported()?;
1114        // Found different concrete types for the opaque type.
1115        let sub_diag = if self.span == other.span {
1116            TypeMismatchReason::ConflictType { span: self.span }
1117        } else {
1118            TypeMismatchReason::PreviousUse { span: self.span }
1119        };
1120        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
1121            self_ty,
1122            other_ty,
1123            other_span: other.span,
1124            sub: sub_diag,
1125        }))
1126    }
1127}
1128
1129pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
1130
1131impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1132    fn flags(&self) -> TypeFlags {
1133        (**self).flags()
1134    }
1135
1136    fn outer_exclusive_binder(&self) -> DebruijnIndex {
1137        (**self).outer_exclusive_binder()
1138    }
1139}
1140
1141/// When interacting with the type system we must provide information about the
1142/// environment. `ParamEnv` is the type that represents this information. See the
1143/// [dev guide chapter][param_env_guide] for more information.
1144///
1145/// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1146#[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)]
1147#[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)]
1148pub struct ParamEnv<'tcx> {
1149    /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1150    /// basically the set of bounds on the in-scope type parameters, translated
1151    /// into `Obligation`s, and elaborated and normalized.
1152    ///
1153    /// Use the `caller_bounds()` method to access.
1154    caller_bounds: Clauses<'tcx>,
1155}
1156
1157impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1158    fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1159        self.caller_bounds()
1160    }
1161}
1162
1163impl<'tcx> ParamEnv<'tcx> {
1164    /// Construct a trait environment suitable for contexts where there are
1165    /// no where-clauses in scope. In the majority of cases it is incorrect
1166    /// to use an empty environment. See the [dev guide section][param_env_guide]
1167    /// for information on what a `ParamEnv` is and how to acquire one.
1168    ///
1169    /// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1170    #[inline]
1171    pub fn empty() -> Self {
1172        Self::new(ListWithCachedTypeInfo::empty())
1173    }
1174
1175    #[inline]
1176    pub fn caller_bounds(self) -> Clauses<'tcx> {
1177        self.caller_bounds
1178    }
1179
1180    /// Construct a trait environment with the given set of predicates.
1181    #[inline]
1182    pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1183        ParamEnv { caller_bounds }
1184    }
1185
1186    /// Creates a pair of param-env and value for use in queries.
1187    pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1188        ParamEnvAnd { param_env: self, value }
1189    }
1190
1191    /// Eagerly reveal all opaque types in the `param_env`.
1192    pub fn with_normalized(self, tcx: TyCtxt<'tcx>) -> ParamEnv<'tcx> {
1193        // No need to reveal opaques with the new solver enabled,
1194        // since we have lazy norm.
1195        if tcx.next_trait_solver_globally() {
1196            self
1197        } else {
1198            ParamEnv::new(tcx.reveal_opaque_types_in_bounds(self.caller_bounds))
1199        }
1200    }
1201}
1202
1203#[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)]
1204#[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)]
1205pub struct ParamEnvAnd<'tcx, T> {
1206    pub param_env: ParamEnv<'tcx>,
1207    pub value: T,
1208}
1209
1210/// The environment in which to do trait solving.
1211///
1212/// Most of the time you only need to care about the `ParamEnv`
1213/// as the `TypingMode` is simply stored in the `InferCtxt`.
1214///
1215/// However, there are some places which rely on trait solving
1216/// without using an `InferCtxt` themselves. For these to be
1217/// able to use the trait system they have to be able to initialize
1218/// such an `InferCtxt` with the right `typing_mode`, so they need
1219/// to track both.
1220#[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)]
1221#[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)]
1222pub struct TypingEnv<'tcx> {
1223    #[type_foldable(identity)]
1224    #[type_visitable(ignore)]
1225    typing_mode: TypingModeEqWrapper<'tcx>,
1226    pub param_env: ParamEnv<'tcx>,
1227}
1228
1229impl<'tcx> TypingEnv<'tcx> {
1230    pub fn new(param_env: ParamEnv<'tcx>, typing_mode: TypingMode<'tcx>) -> Self {
1231        Self { typing_mode: TypingModeEqWrapper(typing_mode), param_env }
1232    }
1233
1234    pub fn typing_mode(&self) -> TypingMode<'tcx> {
1235        self.typing_mode.0
1236    }
1237
1238    /// Create a typing environment with no where-clauses in scope
1239    /// where all opaque types and default associated items are revealed.
1240    ///
1241    /// This is only suitable for monomorphized, post-typeck environments.
1242    /// Do not use this for MIR optimizations, as even though they also
1243    /// use `TypingMode::PostAnalysis`, they may still have where-clauses
1244    /// in scope.
1245    pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1246        Self::new(ParamEnv::empty(), TypingMode::Codegen)
1247    }
1248
1249    /// Create a typing environment for use during analysis outside of a body.
1250    ///
1251    /// Using a typing environment inside of bodies is not supported as the body
1252    /// may define opaque types. In this case the used functions have to be
1253    /// converted to use proper canonical inputs instead.
1254    pub fn non_body_analysis(
1255        tcx: TyCtxt<'tcx>,
1256        def_id: impl IntoQueryKey<DefId>,
1257    ) -> TypingEnv<'tcx> {
1258        let def_id = def_id.into_query_key();
1259        Self::new(tcx.param_env(def_id), TypingMode::non_body_analysis())
1260    }
1261
1262    /// Ideally we just use `TypingMode::PostTypeckUntilBorrowck`.
1263    /// But that's not compatible with the old solver yet.
1264    ///
1265    /// FIXME: this should not be needed in the long term.
1266    pub fn post_typeck_until_borrowck_for_mir_build(
1267        tcx: TyCtxt<'tcx>,
1268        def_id: LocalDefId,
1269    ) -> TypingEnv<'tcx> {
1270        if tcx.use_typing_mode_post_typeck_until_borrowck() {
1271            TypingEnv::new(tcx.param_env(def_id.to_def_id()), ty::TypingMode::borrowck(tcx, def_id))
1272        } else {
1273            // FIXME(#132279): We're in a body, we should use a typing
1274            // mode which reveals the opaque types defined by that body.
1275            TypingEnv::non_body_analysis(tcx, def_id)
1276        }
1277    }
1278
1279    pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
1280        TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::PostAnalysis)
1281    }
1282
1283    pub fn codegen(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
1284        TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::Codegen)
1285    }
1286
1287    /// Modify the `typing_mode` to `PostAnalysis` or `Codegen` and eagerly reveal all opaque types
1288    /// in the `param_env`.
1289    pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1290        let TypingEnv { typing_mode, param_env } = self;
1291        match typing_mode.0.assert_not_erased() {
1292            TypingMode::Coherence
1293            | TypingMode::Reflection
1294            | TypingMode::Typeck { .. }
1295            | TypingMode::PostTypeckUntilBorrowck { .. }
1296            | TypingMode::PostBorrowck { .. } => {}
1297            TypingMode::PostAnalysis | TypingMode::Codegen => return self,
1298        }
1299
1300        let param_env = param_env.with_normalized(tcx);
1301        TypingEnv::new(param_env, TypingMode::PostAnalysis)
1302    }
1303
1304    /// Modify the `typing_mode` to `PostAnalysis` or `Codegen` and eagerly reveal all opaque types
1305    /// in the `param_env`.
1306    pub fn with_codegen_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1307        let TypingEnv { typing_mode, param_env } = self;
1308        match typing_mode.0.assert_not_erased() {
1309            TypingMode::Coherence
1310            | TypingMode::Reflection
1311            | TypingMode::Typeck { .. }
1312            | TypingMode::PostTypeckUntilBorrowck { .. }
1313            | TypingMode::PostBorrowck { .. }
1314            | TypingMode::PostAnalysis => {}
1315            TypingMode::Codegen => return self,
1316        }
1317
1318        let param_env = param_env.with_normalized(tcx);
1319        TypingEnv::new(param_env, TypingMode::Codegen)
1320    }
1321
1322    /// Combine this typing environment with the given `value` to be used by
1323    /// not (yet) canonicalized queries. This only works if the value does not
1324    /// contain anything local to some `InferCtxt`, i.e. inference variables or
1325    /// placeholders.
1326    pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1327    where
1328        T: TypeVisitable<TyCtxt<'tcx>>,
1329    {
1330        // FIXME(#132279): We should assert that the value does not contain any placeholders
1331        // as these placeholders are also local to the current inference context. However, we
1332        // currently use pseudo-canonical queries in the trait solver, which replaces params
1333        // with placeholders during canonicalization. We should also simply not use pseudo-
1334        // canonical queries in the trait solver, at which point we can readd this assert.
1335        //
1336        // As of writing this comment, this is only used when normalizing consts that mention
1337        // params.
1338        /* debug_assert!(
1339            !value.has_placeholders(),
1340            "{value:?} which has placeholder shouldn't be pseudo-canonicalized"
1341        ); */
1342        PseudoCanonicalInput { typing_env: self, value }
1343    }
1344}
1345
1346/// Similar to `CanonicalInput`, this carries the `typing_mode` and the environment
1347/// necessary to do any kind of trait solving inside of nested queries.
1348///
1349/// Unlike proper canonicalization, this requires the `param_env` and the `value` to not
1350/// contain anything local to the `infcx` of the caller, so we don't actually canonicalize
1351/// anything.
1352///
1353/// This should be created by using `infcx.pseudo_canonicalize_query(param_env, value)`
1354/// or by using `typing_env.as_query_input(value)`.
1355#[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)]
1356#[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)]
1357pub struct PseudoCanonicalInput<'tcx, T> {
1358    pub typing_env: TypingEnv<'tcx>,
1359    pub value: T,
1360}
1361
1362#[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)]
1363pub struct Destructor {
1364    /// The `DefId` of the destructor method
1365    pub did: DefId,
1366}
1367
1368// FIXME: consider combining this definition with regular `Destructor`
1369#[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)]
1370pub struct AsyncDestructor {
1371    /// The `DefId` of the `impl AsyncDrop`
1372    pub impl_did: DefId,
1373}
1374
1375#[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)]
1376pub struct VariantFlags(u8);
1377impl 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! {
1378    impl VariantFlags: u8 {
1379        const NO_VARIANT_FLAGS        = 0;
1380        /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1381        const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1382    }
1383}
1384impl ::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 }
1385
1386/// Definition of a variant -- a struct's fields or an enum variant.
1387#[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)]
1388pub struct VariantDef {
1389    /// `DefId` that identifies the variant itself.
1390    /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1391    pub def_id: DefId,
1392    /// `DefId` that identifies the variant's constructor.
1393    /// If this variant is a struct variant, then this is `None`.
1394    pub ctor: Option<(CtorKind, DefId)>,
1395    /// Variant or struct name.
1396    pub name: Symbol,
1397    /// Discriminant of this variant.
1398    pub discr: VariantDiscr,
1399    /// Fields of this variant.
1400    pub fields: IndexVec<FieldIdx, FieldDef>,
1401    /// The error guarantees from parser, if any.
1402    tainted: Option<ErrorGuaranteed>,
1403    /// Flags of the variant (e.g. is field list non-exhaustive)?
1404    flags: VariantFlags,
1405}
1406
1407impl VariantDef {
1408    /// Creates a new `VariantDef`.
1409    ///
1410    /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1411    /// represents an enum variant).
1412    ///
1413    /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1414    /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1415    ///
1416    /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1417    /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1418    /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1419    /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1420    /// built-in trait), and we do not want to load attributes twice.
1421    ///
1422    /// If someone speeds up attribute loading to not be a performance concern, they can
1423    /// remove this hack and use the constructor `DefId` everywhere.
1424    #[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(1424u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("variant_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("variant_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ctor")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ctor");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("discr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("discr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fields")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fields");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_did")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_did");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("recover_tainted")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("recover_tainted");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_field_list_non_exhaustive")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_field_list_non_exhaustive");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant_did)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ctor)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&discr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fields)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_did)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&recover_tainted)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&is_field_list_non_exhaustive
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Self = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut flags = VariantFlags::NO_VARIANT_FLAGS;
            if is_field_list_non_exhaustive {
                flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
            }
            VariantDef {
                def_id: variant_did.unwrap_or(parent_did),
                ctor,
                name,
                discr,
                fields,
                flags,
                tainted: recover_tainted,
            }
        }
    }
}#[instrument(level = "debug")]
1425    pub fn new(
1426        name: Symbol,
1427        variant_did: Option<DefId>,
1428        ctor: Option<(CtorKind, DefId)>,
1429        discr: VariantDiscr,
1430        fields: IndexVec<FieldIdx, FieldDef>,
1431        parent_did: DefId,
1432        recover_tainted: Option<ErrorGuaranteed>,
1433        is_field_list_non_exhaustive: bool,
1434    ) -> Self {
1435        let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1436        if is_field_list_non_exhaustive {
1437            flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1438        }
1439
1440        VariantDef {
1441            def_id: variant_did.unwrap_or(parent_did),
1442            ctor,
1443            name,
1444            discr,
1445            fields,
1446            flags,
1447            tainted: recover_tainted,
1448        }
1449    }
1450
1451    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`.
1452    ///
1453    /// Note that this function will return `true` even if the type has been
1454    /// defined in the crate currently being compiled. If that's not what you
1455    /// want, see [`Self::field_list_has_applicable_non_exhaustive`].
1456    #[inline]
1457    pub fn is_field_list_non_exhaustive(&self) -> bool {
1458        self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1459    }
1460
1461    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`
1462    /// and the type has been defined in another crate.
1463    #[inline]
1464    pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1465        self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1466    }
1467
1468    /// Computes the `Ident` of this variant by looking up the `Span`
1469    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1470        Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1471    }
1472
1473    /// Was this variant obtained as part of recovering from a syntactic error?
1474    #[inline]
1475    pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1476        self.tainted.map_or(Ok(()), Err)
1477    }
1478
1479    #[inline]
1480    pub fn ctor_kind(&self) -> Option<CtorKind> {
1481        self.ctor.map(|(kind, _)| kind)
1482    }
1483
1484    #[inline]
1485    pub fn ctor_def_id(&self) -> Option<DefId> {
1486        self.ctor.map(|(_, def_id)| def_id)
1487    }
1488
1489    /// Returns the one field in this variant.
1490    ///
1491    /// `panic!`s if there are no fields or multiple fields.
1492    #[inline]
1493    pub fn single_field(&self) -> &FieldDef {
1494        if !(self.fields.len() == 1) {
    ::core::panicking::panic("assertion failed: self.fields.len() == 1")
};assert!(self.fields.len() == 1);
1495
1496        &self.fields[FieldIdx::ZERO]
1497    }
1498
1499    /// Returns the last field in this variant, if present.
1500    #[inline]
1501    pub fn tail_opt(&self) -> Option<&FieldDef> {
1502        self.fields.raw.last()
1503    }
1504
1505    /// Returns the last field in this variant.
1506    ///
1507    /// # Panics
1508    ///
1509    /// Panics, if the variant has no fields.
1510    #[inline]
1511    pub fn tail(&self) -> &FieldDef {
1512        self.tail_opt().expect("expected unsized ADT to have a tail field")
1513    }
1514
1515    /// Returns whether this variant has unsafe fields.
1516    pub fn has_unsafe_fields(&self) -> bool {
1517        self.fields.iter().any(|x| x.safety.is_unsafe())
1518    }
1519}
1520
1521impl PartialEq for VariantDef {
1522    #[inline]
1523    fn eq(&self, other: &Self) -> bool {
1524        // There should be only one `VariantDef` for each `def_id`, therefore
1525        // it is fine to implement `PartialEq` only based on `def_id`.
1526        //
1527        // Below, we exhaustively destructure `self` and `other` so that if the
1528        // definition of `VariantDef` changes, a compile-error will be produced,
1529        // reminding us to revisit this assumption.
1530
1531        let Self {
1532            def_id: lhs_def_id,
1533            ctor: _,
1534            name: _,
1535            discr: _,
1536            fields: _,
1537            flags: _,
1538            tainted: _,
1539        } = &self;
1540        let Self {
1541            def_id: rhs_def_id,
1542            ctor: _,
1543            name: _,
1544            discr: _,
1545            fields: _,
1546            flags: _,
1547            tainted: _,
1548        } = other;
1549
1550        let res = lhs_def_id == rhs_def_id;
1551
1552        // Double check that implicit assumption detailed above.
1553        if truecfg!(debug_assertions) && res {
1554            let deep = self.ctor == other.ctor
1555                && self.name == other.name
1556                && self.discr == other.discr
1557                && self.fields == other.fields
1558                && self.flags == other.flags;
1559            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");
1560        }
1561
1562        res
1563    }
1564}
1565
1566impl Eq for VariantDef {}
1567
1568impl Hash for VariantDef {
1569    #[inline]
1570    fn hash<H: Hasher>(&self, s: &mut H) {
1571        // There should be only one `VariantDef` for each `def_id`, therefore
1572        // it is fine to implement `Hash` only based on `def_id`.
1573        //
1574        // Below, we exhaustively destructure `self` so that if the definition
1575        // of `VariantDef` changes, a compile-error will be produced, reminding
1576        // us to revisit this assumption.
1577
1578        let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1579        def_id.hash(s)
1580    }
1581}
1582
1583#[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)]
1584pub enum VariantDiscr {
1585    /// Explicit value for this variant, i.e., `X = 123`.
1586    /// The `DefId` corresponds to the embedded constant.
1587    Explicit(DefId),
1588
1589    /// The previous variant's discriminant plus one.
1590    /// For efficiency reasons, the distance from the
1591    /// last `Explicit` discriminant is being stored,
1592    /// or `0` for the first variant, if it has none.
1593    Relative(u32),
1594}
1595
1596#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FieldDef {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["did", "name", "vis", "mut_restriction", "safety", "value"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.did, &self.name, &self.vis, &self.mut_restriction,
                        &self.safety, &&self.value];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "FieldDef",
            names, values)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for FieldDef {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    FieldDef {
                        did: ref __binding_0,
                        name: ref __binding_1,
                        vis: ref __binding_2,
                        mut_restriction: ref __binding_3,
                        safety: ref __binding_4,
                        value: ref __binding_5 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                        { __binding_4.stable_hash(__hcx, __hasher); }
                        { __binding_5.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for FieldDef {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    FieldDef {
                        did: ref __binding_0,
                        name: ref __binding_1,
                        vis: ref __binding_2,
                        mut_restriction: ref __binding_3,
                        safety: ref __binding_4,
                        value: ref __binding_5 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_4,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_5,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for FieldDef {
            fn decode(__decoder: &mut __D) -> Self {
                FieldDef {
                    did: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                    vis: ::rustc_serialize::Decodable::decode(__decoder),
                    mut_restriction: ::rustc_serialize::Decodable::decode(__decoder),
                    safety: ::rustc_serialize::Decodable::decode(__decoder),
                    value: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
1597pub struct FieldDef {
1598    pub did: DefId,
1599    pub name: Symbol,
1600    pub vis: Visibility<ModId>,
1601    pub mut_restriction: RestrictionKind,
1602    pub safety: hir::Safety,
1603    pub value: Option<DefId>,
1604}
1605
1606impl PartialEq for FieldDef {
1607    #[inline]
1608    fn eq(&self, other: &Self) -> bool {
1609        // There should be only one `FieldDef` for each `did`, therefore it is
1610        // fine to implement `PartialEq` only based on `did`.
1611        //
1612        // Below, we exhaustively destructure `self` so that if the definition
1613        // of `FieldDef` changes, a compile-error will be produced, reminding
1614        // us to revisit this assumption.
1615
1616        let Self { did: lhs_did, name: _, vis: _, mut_restriction: _, safety: _, value: _ } = &self;
1617
1618        let Self { did: rhs_did, name: _, vis: _, mut_restriction: _, safety: _, value: _ } = other;
1619
1620        let res = lhs_did == rhs_did;
1621
1622        // Double check that implicit assumption detailed above.
1623        if truecfg!(debug_assertions) && res {
1624            let deep = self.name == other.name
1625                && self.vis == other.vis
1626                && self.mut_restriction == other.mut_restriction
1627                && self.safety == other.safety;
1628            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");
1629        }
1630
1631        res
1632    }
1633}
1634
1635impl Eq for FieldDef {}
1636
1637impl Hash for FieldDef {
1638    #[inline]
1639    fn hash<H: Hasher>(&self, s: &mut H) {
1640        // There should be only one `FieldDef` for each `did`, therefore it is
1641        // fine to implement `Hash` only based on `did`.
1642        //
1643        // Below, we exhaustively destructure `self` so that if the definition
1644        // of `FieldDef` changes, a compile-error will be produced, reminding
1645        // us to revisit this assumption.
1646
1647        let Self { did, name: _, vis: _, mut_restriction: _, safety: _, value: _ } = &self;
1648
1649        did.hash(s)
1650    }
1651}
1652
1653impl<'tcx> FieldDef {
1654    /// Returns the type of this field. The `args` are typically obtained via
1655    /// the second field of [`TyKind::Adt`].
1656    pub fn ty(
1657        &self,
1658        tcx: TyCtxt<'tcx>,
1659        args: GenericArgsRef<'tcx>,
1660    ) -> Unnormalized<'tcx, Ty<'tcx>> {
1661        tcx.type_of(self.did).instantiate(tcx, args)
1662    }
1663
1664    /// Computes the `Ident` of this variant by looking up the `Span`
1665    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1666        Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1667    }
1668}
1669
1670#[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)]
1671pub enum ImplOverlapKind {
1672    /// These impls are always allowed to overlap.
1673    Permitted {
1674        /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1675        marker: bool,
1676    },
1677}
1678
1679/// Useful source information about where a desugared associated type for an
1680/// RPITIT originated from.
1681#[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)]
1682pub enum ImplTraitInTraitData {
1683    Trait { fn_def_id: DefId, opaque_def_id: DefId },
1684    Impl { fn_def_id: DefId },
1685}
1686
1687impl<'tcx> TyCtxt<'tcx> {
1688    pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1689        self.typeck(self.hir_body_owner_def_id(body))
1690    }
1691
1692    pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1693        self.associated_items(id)
1694            .in_definition_order()
1695            .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1696    }
1697
1698    pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1699        let mut flags = ReprFlags::empty();
1700        let mut size = None;
1701        let mut max_align: Option<Align> = None;
1702        let mut min_pack: Option<Align> = None;
1703
1704        // Generate a deterministically-derived seed from the item's path hash
1705        // to allow for cross-crate compilation to actually work
1706        let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1707
1708        // If the user defined a custom seed for layout randomization, xor the item's
1709        // path hash with the user defined seed, this will allowing determinism while
1710        // still allowing users to further randomize layout generation for e.g. fuzzing
1711        if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1712            field_shuffle_seed ^= user_seed;
1713        }
1714
1715        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
1716        )
1717        .map(|elt| match elt {
1718            Some(n) => ScalableElt::ElementCount(*n),
1719            None => ScalableElt::Container,
1720        });
1721        if elt.is_some() {
1722            flags.insert(ReprFlags::IS_SCALABLE);
1723        }
1724        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) {
1725            for (r, _) in reprs {
1726                flags.insert(match *r {
1727                    attr::ReprRust => ReprFlags::empty(),
1728                    attr::ReprC => ReprFlags::IS_C,
1729                    attr::ReprPacked(pack) => {
1730                        min_pack = Some(if let Some(min_pack) = min_pack {
1731                            min_pack.min(pack)
1732                        } else {
1733                            pack
1734                        });
1735                        ReprFlags::empty()
1736                    }
1737                    attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1738                    attr::ReprSimd => ReprFlags::IS_SIMD,
1739                    attr::ReprInt(i) => {
1740                        size = Some(match i {
1741                            attr::IntType::SignedInt(x) => match x {
1742                                ast::IntTy::Isize => IntegerType::Pointer(true),
1743                                ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1744                                ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1745                                ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1746                                ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1747                                ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1748                            },
1749                            attr::IntType::UnsignedInt(x) => match x {
1750                                ast::UintTy::Usize => IntegerType::Pointer(false),
1751                                ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1752                                ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1753                                ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1754                                ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1755                                ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1756                            },
1757                        });
1758                        ReprFlags::empty()
1759                    }
1760                    attr::ReprAlign(align) => {
1761                        max_align = max_align.max(Some(align));
1762                        ReprFlags::empty()
1763                    }
1764                });
1765            }
1766        }
1767
1768        // If `-Z randomize-layout` was enabled for the type definition then we can
1769        // consider performing layout randomization
1770        if self.sess.opts.unstable_opts.randomize_layout {
1771            flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1772        }
1773
1774        // box is special, on the one hand the compiler assumes an ordered layout, with the pointer
1775        // always at offset zero. On the other hand we want scalar abi optimizations.
1776        let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1777
1778        // This is here instead of layout because the choice must make it into metadata.
1779        if is_box {
1780            flags.insert(ReprFlags::IS_LINEAR);
1781        }
1782
1783        // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
1784        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(..)) {
1785            flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1786        }
1787
1788        ReprOptions {
1789            int: size,
1790            align: max_align,
1791            pack: min_pack,
1792            flags,
1793            field_shuffle_seed,
1794            scalable: elt,
1795        }
1796    }
1797
1798    /// Look up the name of a definition across crates. This does not look at HIR.
1799    pub fn opt_item_name(self, def_id: impl IntoQueryKey<DefId>) -> Option<Symbol> {
1800        let def_id = def_id.into_query_key();
1801        if let Some(cnum) = def_id.as_crate_root() {
1802            Some(self.crate_name(cnum))
1803        } else {
1804            let def_key = self.def_key(def_id);
1805            match def_key.disambiguated_data.data {
1806                // The name of a constructor is that of its parent.
1807                rustc_hir::definitions::DefPathData::Ctor => self
1808                    .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1809                _ => def_key.get_opt_name(),
1810            }
1811        }
1812    }
1813
1814    /// Look up the name of a definition across crates. This does not look at HIR.
1815    ///
1816    /// This method will ICE if the corresponding item does not have a name. In these cases, use
1817    /// [`opt_item_name`] instead.
1818    ///
1819    /// [`opt_item_name`]: Self::opt_item_name
1820    pub fn item_name(self, id: impl IntoQueryKey<DefId>) -> Symbol {
1821        let id = id.into_query_key();
1822        self.opt_item_name(id).unwrap_or_else(|| {
1823            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));
1824        })
1825    }
1826
1827    /// Look up the name and span of a definition.
1828    ///
1829    /// See [`item_name`][Self::item_name] for more information.
1830    pub fn opt_item_ident(self, def_id: impl IntoQueryKey<DefId>) -> Option<Ident> {
1831        let def_id = def_id.into_query_key();
1832        let def = self.opt_item_name(def_id)?;
1833        let span = self
1834            .def_ident_span(def_id)
1835            .unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("missing ident span for {0:?}",
        def_id))bug!("missing ident span for {def_id:?}"));
1836        Some(Ident::new(def, span))
1837    }
1838
1839    /// Look up the name and span of a definition.
1840    ///
1841    /// See [`item_name`][Self::item_name] for more information.
1842    pub fn item_ident(self, def_id: impl IntoQueryKey<DefId>) -> Ident {
1843        let def_id = def_id.into_query_key();
1844        self.opt_item_ident(def_id).unwrap_or_else(|| {
1845            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));
1846        })
1847    }
1848
1849    pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1850        if let DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy =
1851            self.def_kind(def_id)
1852        {
1853            Some(self.associated_item(def_id))
1854        } else {
1855            None
1856        }
1857    }
1858
1859    /// If the `def_id` is an associated type that was desugared from a
1860    /// return-position `impl Trait` from a trait, then provide the source info
1861    /// about where that RPITIT came from.
1862    pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1863        if let DefKind::AssocTy = self.def_kind(def_id)
1864            && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1865                self.associated_item(def_id).kind
1866        {
1867            Some(rpitit_info)
1868        } else {
1869            None
1870        }
1871    }
1872
1873    pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1874        variant.fields.iter_enumerated().find_map(|(i, field)| {
1875            self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1876        })
1877    }
1878
1879    /// Returns `Some` if the impls are the same polarity and the trait either
1880    /// has no items or is annotated `#[marker]` and prevents item overrides.
1881    x;#[instrument(level = "debug", skip(self), ret)]
1882    pub fn impls_are_allowed_to_overlap(
1883        self,
1884        def_id1: DefId,
1885        def_id2: DefId,
1886    ) -> Option<ImplOverlapKind> {
1887        let impl1 = self.impl_trait_header(def_id1);
1888        let impl2 = self.impl_trait_header(def_id2);
1889
1890        let trait_ref1 = impl1.trait_ref.skip_binder();
1891        let trait_ref2 = impl2.trait_ref.skip_binder();
1892
1893        // If either trait impl references an error, they're allowed to overlap,
1894        // as one of them essentially doesn't exist.
1895        if trait_ref1.references_error() || trait_ref2.references_error() {
1896            return Some(ImplOverlapKind::Permitted { marker: false });
1897        }
1898
1899        match (impl1.polarity, impl2.polarity) {
1900            (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1901                // `#[rustc_reservation_impl]` impls don't overlap with anything
1902                return Some(ImplOverlapKind::Permitted { marker: false });
1903            }
1904            (ImplPolarity::Positive, ImplPolarity::Negative)
1905            | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1906                // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1907                return None;
1908            }
1909            (ImplPolarity::Positive, ImplPolarity::Positive)
1910            | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1911        };
1912
1913        let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1914        let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1915
1916        if is_marker_overlap {
1917            return Some(ImplOverlapKind::Permitted { marker: true });
1918        }
1919
1920        None
1921    }
1922
1923    /// Returns `ty::VariantDef` if `res` refers to a struct,
1924    /// or variant or their constructors, panics otherwise.
1925    pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1926        match res {
1927            Res::Def(DefKind::Variant, did) => {
1928                let enum_did = self.parent(did);
1929                self.adt_def(enum_did).variant_with_id(did)
1930            }
1931            Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1932            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1933                let variant_did = self.parent(variant_ctor_did);
1934                let enum_did = self.parent(variant_did);
1935                self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1936            }
1937            Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1938                let struct_did = self.parent(ctor_did);
1939                self.adt_def(struct_did).non_enum_variant()
1940            }
1941            _ => 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),
1942        }
1943    }
1944
1945    /// Returns the possibly-auto-generated MIR of a [`ty::InstanceKind`].
1946    #[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(1946u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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