Skip to main content

rustc_middle/ty/
sty.rs

1//! This module contains `TyKind` and its major components.
2
3#![allow(rustc::usage_of_ty_tykind)]
4
5use std::borrow::Cow;
6use std::debug_assert_matches;
7use std::ops::{ControlFlow, Range};
8
9use hir::def::{CtorKind, DefKind};
10use rustc_abi::{FIRST_VARIANT, FieldIdx, ScalableElt, VariantIdx};
11use rustc_errors::{ErrorGuaranteed, MultiSpan};
12use rustc_hir as hir;
13use rustc_hir::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, extension};
16use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
17use rustc_type_ir::TyKind::*;
18use rustc_type_ir::solve::SizedTraitKind;
19use rustc_type_ir::walk::TypeWalker;
20use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, TypeVisitableExt, elaborate};
21use tracing::instrument;
22use ty::util::IntTypeExt;
23
24use super::GenericParamDefKind;
25use crate::infer::canonical::Canonical;
26use crate::traits::ObligationCause;
27use crate::ty::InferTy::*;
28use crate::ty::{
29    self, AdtDef, Const, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, Region,
30    Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, ValTree,
31};
32
33// Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here
34#[rustc_diagnostic_item = "TyKind"]
35pub type TyKind<'tcx> = ir::TyKind<TyCtxt<'tcx>>;
36pub type TypeAndMut<'tcx> = ir::TypeAndMut<TyCtxt<'tcx>>;
37pub type AliasTy<'tcx> = ir::AliasTy<TyCtxt<'tcx>>;
38pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
39pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
40pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
41pub type TypingMode<'tcx> = ir::TypingMode<TyCtxt<'tcx>>;
42pub type Placeholder<'tcx, T> = ir::Placeholder<TyCtxt<'tcx>, T>;
43pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion<TyCtxt<'tcx>>;
44pub type PlaceholderType<'tcx> = ir::PlaceholderType<TyCtxt<'tcx>>;
45pub type PlaceholderConst<'tcx> = ir::PlaceholderConst<TyCtxt<'tcx>>;
46pub type BoundTy<'tcx> = ir::BoundTy<TyCtxt<'tcx>>;
47pub type BoundConst<'tcx> = ir::BoundConst<TyCtxt<'tcx>>;
48pub type BoundRegion<'tcx> = ir::BoundRegion<TyCtxt<'tcx>>;
49pub type BoundVariableKind<'tcx> = ir::BoundVariableKind<TyCtxt<'tcx>>;
50pub type BoundRegionKind<'tcx> = ir::BoundRegionKind<TyCtxt<'tcx>>;
51pub type BoundTyKind<'tcx> = ir::BoundTyKind<TyCtxt<'tcx>>;
52
53pub trait Article {
54    fn article(&self) -> &'static str;
55}
56
57impl<'tcx> Article for TyKind<'tcx> {
58    /// Get the article ("a" or "an") to use with this type.
59    fn article(&self) -> &'static str {
60        match self {
61            Int(_) | Float(_) | Array(_, _) => "an",
62            Adt(def, _) if def.is_enum() => "an",
63            // This should never happen, but ICEing and causing the user's code
64            // to not compile felt too harsh.
65            Error(_) => "a",
66            _ => "a",
67        }
68    }
69}
70
71impl<'tcx> CoroutineArgsExt<'tcx> for ty::CoroutineArgs<TyCtxt<'tcx>> {
    #[doc = " Coroutine has not been resumed yet."]
    const UNRESUMED: usize = 0;
    #[doc = " Coroutine has returned or is completed."]
    const RETURNED: usize = 1;
    #[doc = " Coroutine has been poisoned."]
    const POISONED: usize = 2;
    #[doc =
    " Number of variants to reserve in coroutine state. Corresponds to"]
    #[doc =
    " `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`"]
    #[doc = " (end of a coroutine) states."]
    const RESERVED_VARIANTS: usize = 3;
    const UNRESUMED_NAME: &'static str = "Unresumed";
    const RETURNED_NAME: &'static str = "Returned";
    const POISONED_NAME: &'static str = "Panicked";
    #[doc = " The valid variant indices of this coroutine."]
    #[inline]
    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>)
        -> Range<VariantIdx> {
        FIRST_VARIANT..tcx.coroutine_layout(def_id,
                            self.args).unwrap().variant_fields.next_index()
    }
    #[doc =
    " The discriminant for the given variant. Panics if the `variant_index` is"]
    #[doc = " out of range."]
    #[inline]
    fn discriminant_for_variant(&self, def_id: DefId, tcx: TyCtxt<'tcx>,
        variant_index: VariantIdx) -> Discr<'tcx> {
        if !self.variant_range(def_id, tcx).contains(&variant_index) {
            ::core::panicking::panic("assertion failed: self.variant_range(def_id, tcx).contains(&variant_index)")
        };
        Discr {
            val: variant_index.as_usize() as u128,
            ty: self.discr_ty(tcx),
        }
    }
    #[doc =
    " The set of all discriminants for the coroutine, enumerated with their"]
    #[doc = " variant indices."]
    #[inline]
    fn discriminants(self, def_id: DefId, tcx: TyCtxt<'tcx>)
        -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
        self.variant_range(def_id,
                tcx).map(move |index|
                {
                    (index,
                        Discr {
                            val: index.as_usize() as u128,
                            ty: self.discr_ty(tcx),
                        })
                })
    }
    #[doc =
    " Calls `f` with a reference to the name of the enumerator for the given"]
    #[doc = " variant `v`."]
    fn variant_name(v: VariantIdx) -> Cow<'static, str> {
        match v.as_usize() {
            Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
            Self::RETURNED => Cow::from(Self::RETURNED_NAME),
            Self::POISONED => Cow::from(Self::POISONED_NAME),
            _ =>
                Cow::from(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("Suspend{0}",
                                    v.as_usize() - Self::RESERVED_VARIANTS))
                        })),
        }
    }
    #[doc = " The type of the state discriminant used in the coroutine type."]
    #[inline]
    fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { tcx.types.u32 }
    #[doc =
    " This returns the types of the MIR locals which had to be stored across suspension points."]
    #[doc =
    " It is calculated in rustc_mir_transform::coroutine::StateTransform."]
    #[doc = " All the types here must be in the tuple in CoroutineInterior."]
    #[doc = ""]
    #[doc =
    " The locals are grouped by their variant number. Note that some locals may"]
    #[doc = " be repeated in multiple variants."]
    #[inline]
    fn state_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>)
        -> impl Iterator<Item : Iterator<Item = Ty<'tcx>>> {
        let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
        layout.variant_fields.iter().map(move |variant|
                {
                    variant.iter().map(move |field|
                            {
                                if tcx.is_async_drop_in_place_coroutine(def_id) {
                                    layout.field_tys[*field].ty
                                } else {
                                    ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx,
                                        self.args)
                                }
                            })
                })
    }
    #[doc =
    " This is the types of the fields of a coroutine which are not stored in a"]
    #[doc = " variant."]
    #[inline]
    fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> { self.upvar_tys() }
}#[extension(pub trait CoroutineArgsExt<'tcx>)]
72impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
73    /// Coroutine has not been resumed yet.
74    const UNRESUMED: usize = 0;
75    /// Coroutine has returned or is completed.
76    const RETURNED: usize = 1;
77    /// Coroutine has been poisoned.
78    const POISONED: usize = 2;
79    /// Number of variants to reserve in coroutine state. Corresponds to
80    /// `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`
81    /// (end of a coroutine) states.
82    const RESERVED_VARIANTS: usize = 3;
83
84    const UNRESUMED_NAME: &'static str = "Unresumed";
85    const RETURNED_NAME: &'static str = "Returned";
86    const POISONED_NAME: &'static str = "Panicked";
87
88    /// The valid variant indices of this coroutine.
89    #[inline]
90    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
91        // FIXME requires optimized MIR
92        FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
93    }
94
95    /// The discriminant for the given variant. Panics if the `variant_index` is
96    /// out of range.
97    #[inline]
98    fn discriminant_for_variant(
99        &self,
100        def_id: DefId,
101        tcx: TyCtxt<'tcx>,
102        variant_index: VariantIdx,
103    ) -> Discr<'tcx> {
104        // Coroutines don't support explicit discriminant values, so they are
105        // the same as the variant index.
106        assert!(self.variant_range(def_id, tcx).contains(&variant_index));
107        Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
108    }
109
110    /// The set of all discriminants for the coroutine, enumerated with their
111    /// variant indices.
112    #[inline]
113    fn discriminants(
114        self,
115        def_id: DefId,
116        tcx: TyCtxt<'tcx>,
117    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
118        self.variant_range(def_id, tcx).map(move |index| {
119            (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
120        })
121    }
122
123    /// Calls `f` with a reference to the name of the enumerator for the given
124    /// variant `v`.
125    fn variant_name(v: VariantIdx) -> Cow<'static, str> {
126        match v.as_usize() {
127            Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
128            Self::RETURNED => Cow::from(Self::RETURNED_NAME),
129            Self::POISONED => Cow::from(Self::POISONED_NAME),
130            _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
131        }
132    }
133
134    /// The type of the state discriminant used in the coroutine type.
135    #[inline]
136    fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
137        tcx.types.u32
138    }
139
140    /// This returns the types of the MIR locals which had to be stored across suspension points.
141    /// It is calculated in rustc_mir_transform::coroutine::StateTransform.
142    /// All the types here must be in the tuple in CoroutineInterior.
143    ///
144    /// The locals are grouped by their variant number. Note that some locals may
145    /// be repeated in multiple variants.
146    #[inline]
147    fn state_tys(
148        self,
149        def_id: DefId,
150        tcx: TyCtxt<'tcx>,
151    ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
152        let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
153        layout.variant_fields.iter().map(move |variant| {
154            variant.iter().map(move |field| {
155                if tcx.is_async_drop_in_place_coroutine(def_id) {
156                    layout.field_tys[*field].ty
157                } else {
158                    ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args)
159                }
160            })
161        })
162    }
163
164    /// This is the types of the fields of a coroutine which are not stored in a
165    /// variant.
166    #[inline]
167    fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
168        self.upvar_tys()
169    }
170}
171
172#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UpvarArgs<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            UpvarArgs::Closure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Closure", &__self_0),
            UpvarArgs::Coroutine(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coroutine", &__self_0),
            UpvarArgs::CoroutineClosure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CoroutineClosure", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for UpvarArgs<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for UpvarArgs<'tcx> {
    #[inline]
    fn clone(&self) -> UpvarArgs<'tcx> {
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for UpvarArgs<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    UpvarArgs::Closure(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    UpvarArgs::Coroutine(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    UpvarArgs::CoroutineClosure(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for UpvarArgs<'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 {
                        UpvarArgs::Closure(__binding_0) => {
                            UpvarArgs::Closure(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        UpvarArgs::Coroutine(__binding_0) => {
                            UpvarArgs::Coroutine(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        UpvarArgs::CoroutineClosure(__binding_0) => {
                            UpvarArgs::CoroutineClosure(::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 {
                    UpvarArgs::Closure(__binding_0) => {
                        UpvarArgs::Closure(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    UpvarArgs::Coroutine(__binding_0) => {
                        UpvarArgs::Coroutine(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    UpvarArgs::CoroutineClosure(__binding_0) => {
                        UpvarArgs::CoroutineClosure(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for UpvarArgs<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    UpvarArgs::Closure(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);
                                }
                            }
                        }
                    }
                    UpvarArgs::Coroutine(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);
                                }
                            }
                        }
                    }
                    UpvarArgs::CoroutineClosure(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)]
173pub enum UpvarArgs<'tcx> {
174    Closure(GenericArgsRef<'tcx>),
175    Coroutine(GenericArgsRef<'tcx>),
176    CoroutineClosure(GenericArgsRef<'tcx>),
177}
178
179impl<'tcx> UpvarArgs<'tcx> {
180    /// Returns an iterator over the list of types of captured paths by the closure/coroutine.
181    /// In case there was a type error in figuring out the types of the captured path, an
182    /// empty iterator is returned.
183    #[inline]
184    pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
185        let tupled_tys = match self {
186            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
187            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
188            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
189        };
190
191        match tupled_tys.kind() {
192            TyKind::Error(_) => ty::List::empty(),
193            TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
194            TyKind::Infer(_) => crate::util::bug::bug_fmt(format_args!("upvar_tys called before capture types are inferred"))bug!("upvar_tys called before capture types are inferred"),
195            ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
        ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
196        }
197    }
198
199    #[inline]
200    pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
201        match self {
202            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
203            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
204            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
205        }
206    }
207}
208
209/// An inline const is modeled like
210/// ```ignore (illustrative)
211/// const InlineConst<'l0...'li, T0...Tj, R>: R;
212/// ```
213/// where:
214///
215/// - 'l0...'li and T0...Tj are the generic parameters
216///   inherited from the item that defined the inline const,
217/// - R represents the type of the constant.
218///
219/// When the inline const is instantiated, `R` is instantiated as the actual inferred
220/// type of the constant. The reason that `R` is represented as an extra type parameter
221/// is the same reason that [`ty::ClosureArgs`] have `CS` and `U` as type parameters:
222/// inline const can reference lifetimes that are internal to the creating function.
223#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for InlineConstArgs<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for InlineConstArgs<'tcx> {
    #[inline]
    fn clone(&self) -> InlineConstArgs<'tcx> {
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InlineConstArgs<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "InlineConstArgs", "args", &&self.args)
    }
}Debug)]
224pub struct InlineConstArgs<'tcx> {
225    /// Generic parameters from the enclosing item,
226    /// concatenated with the inferred type of the constant.
227    pub args: GenericArgsRef<'tcx>,
228}
229
230/// Struct returned by `split()`.
231pub struct InlineConstArgsParts<'tcx, T> {
232    pub parent_args: &'tcx [GenericArg<'tcx>],
233    pub ty: T,
234}
235
236impl<'tcx> InlineConstArgs<'tcx> {
237    /// Construct `InlineConstArgs` from `InlineConstArgsParts`.
238    pub fn new(
239        tcx: TyCtxt<'tcx>,
240        parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
241    ) -> InlineConstArgs<'tcx> {
242        InlineConstArgs {
243            args: tcx.mk_args_from_iter(
244                parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
245            ),
246        }
247    }
248
249    /// Divides the inline const args into their respective components.
250    /// The ordering assumed here must match that used by `InlineConstArgs::new` above.
251    fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
252        match self.args[..] {
253            [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
254            _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
255        }
256    }
257
258    /// Returns the generic parameters of the inline const's parent.
259    pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
260        self.split().parent_args
261    }
262
263    /// Returns the type of this inline const.
264    pub fn ty(self) -> Ty<'tcx> {
265        self.split().ty.expect_ty()
266    }
267}
268
269pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
270pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
271
272#[derive(#[automatically_derived]
impl ::core::clone::Clone for ParamTy {
    #[inline]
    fn clone(&self) -> ParamTy {
        let _: ::core::clone::AssertParamIsClone<u32>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ParamTy { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamTy {
    #[inline]
    fn eq(&self, other: &ParamTy) -> bool {
        self.index == other.index && self.name == other.name
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ParamTy {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for ParamTy {
    #[inline]
    fn partial_cmp(&self, other: &ParamTy)
        -> ::core::option::Option<::core::cmp::Ordering> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.index, &other.index)
            {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
                ::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for ParamTy {
    #[inline]
    fn cmp(&self, other: &ParamTy) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.index, &other.index) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for ParamTy {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.index, state);
        ::core::hash::Hash::hash(&self.name, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ParamTy {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    ParamTy { index: ref __binding_0, name: 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 ParamTy {
            fn decode(__decoder: &mut __D) -> Self {
                ParamTy {
                    index: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
273#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for ParamTy {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    ParamTy { index: ref __binding_0, name: ref __binding_1 } =>
                        {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
274pub struct ParamTy {
275    pub index: u32,
276    pub name: Symbol,
277}
278
279impl rustc_type_ir::inherent::ParamLike for ParamTy {
280    fn index(self) -> u32 {
281        self.index
282    }
283}
284
285impl<'tcx> ParamTy {
286    pub fn new(index: u32, name: Symbol) -> ParamTy {
287        ParamTy { index, name }
288    }
289
290    pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
291        ParamTy::new(def.index, def.name)
292    }
293
294    #[inline]
295    pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
296        Ty::new_param(tcx, self.index, self.name)
297    }
298
299    pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
300        let generics = tcx.generics_of(item_with_generics);
301        let type_param = generics.type_param(self, tcx);
302        tcx.def_span(type_param.def_id)
303    }
304}
305
306#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParamConst { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ParamConst {
    #[inline]
    fn clone(&self) -> ParamConst {
        let _: ::core::clone::AssertParamIsClone<u32>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::hash::Hash for ParamConst {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.index, state);
        ::core::hash::Hash::hash(&self.name, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ParamConst {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    ParamConst { index: ref __binding_0, name: 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 ParamConst {
            fn decode(__decoder: &mut __D) -> Self {
                ParamConst {
                    index: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, #[automatically_derived]
impl ::core::cmp::Eq for ParamConst {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamConst {
    #[inline]
    fn eq(&self, other: &ParamConst) -> bool {
        self.index == other.index && self.name == other.name
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Ord for ParamConst {
    #[inline]
    fn cmp(&self, other: &ParamConst) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.index, &other.index) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::cmp::PartialOrd for ParamConst {
    #[inline]
    fn partial_cmp(&self, other: &ParamConst)
        -> ::core::option::Option<::core::cmp::Ordering> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.index, &other.index)
            {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
                ::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}PartialOrd)]
307#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for ParamConst {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    ParamConst { index: ref __binding_0, name: ref __binding_1 }
                        => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
308pub struct ParamConst {
309    pub index: u32,
310    pub name: Symbol,
311}
312
313impl rustc_type_ir::inherent::ParamLike for ParamConst {
314    fn index(self) -> u32 {
315        self.index
316    }
317}
318
319impl ParamConst {
320    pub fn new(index: u32, name: Symbol) -> ParamConst {
321        ParamConst { index, name }
322    }
323
324    pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
325        ParamConst::new(def.index, def.name)
326    }
327
328    #[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("find_const_ty_from_env",
                                    "rustc_middle::ty::sty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(328u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["self", "env"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&env)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut candidates =
                env.caller_bounds().iter().filter_map(|clause|
                        {
                            match clause.kind().skip_binder() {
                                ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
                                    if !!(param_ct, ty).has_escaping_bound_vars() {
                                        ::core::panicking::panic("assertion failed: !(param_ct, ty).has_escaping_bound_vars()")
                                    };
                                    match param_ct.kind() {
                                        ty::ConstKind::Param(param_ct) if
                                            param_ct.index == self.index => Some(ty),
                                        _ => None,
                                    }
                                }
                                _ => None,
                            }
                        });
            let ty =
                candidates.next().unwrap_or_else(||
                        {
                            crate::util::bug::bug_fmt(format_args!("cannot find `{0:?}` in param-env: {1:#?}",
                                    self, env));
                        });
            if !candidates.next().is_none() {
                {
                    ::core::panicking::panic_fmt(format_args!("did not expect duplicate `ConstParamHasTy` for `{0:?}` in param-env: {1:#?}",
                            self, env));
                }
            };
            ty
        }
    }
}#[instrument(level = "debug")]
329    pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
330        let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
331            // `ConstArgHasType` are never desugared to be higher ranked.
332            match clause.kind().skip_binder() {
333                ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
334                    assert!(!(param_ct, ty).has_escaping_bound_vars());
335
336                    match param_ct.kind() {
337                        ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
338                        _ => None,
339                    }
340                }
341                _ => None,
342            }
343        });
344
345        // N.B. it may be tempting to fix ICEs by making this function return
346        // `Option<Ty<'tcx>>` instead of `Ty<'tcx>`; however, this is generally
347        // considered to be a bandaid solution, since it hides more important
348        // underlying issues with how we construct generics and predicates of
349        // items. It's advised to fix the underlying issue rather than trying
350        // to modify this function.
351        let ty = candidates.next().unwrap_or_else(|| {
352            bug!("cannot find `{self:?}` in param-env: {env:#?}");
353        });
354        assert!(
355            candidates.next().is_none(),
356            "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
357        );
358        ty
359    }
360}
361
362/// Constructors for `Ty`
363impl<'tcx> Ty<'tcx> {
364    /// Avoid using this in favour of more specific `new_*` methods, where possible.
365    /// The more specific methods will often optimize their creation.
366    #[allow(rustc::usage_of_ty_tykind)]
367    #[inline]
368    fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
369        tcx.mk_ty_from_kind(st)
370    }
371
372    #[inline]
373    pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
374        Ty::new(tcx, TyKind::Infer(infer))
375    }
376
377    #[inline]
378    pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
379        // Use a pre-interned one when possible.
380        tcx.types
381            .ty_vars
382            .get(v.as_usize())
383            .copied()
384            .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
385    }
386
387    #[inline]
388    pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
389        Ty::new_infer(tcx, IntVar(v))
390    }
391
392    #[inline]
393    pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
394        Ty::new_infer(tcx, FloatVar(v))
395    }
396
397    #[inline]
398    pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
399        // Use a pre-interned one when possible.
400        tcx.types
401            .fresh_tys
402            .get(n as usize)
403            .copied()
404            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
405    }
406
407    #[inline]
408    pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
409        // Use a pre-interned one when possible.
410        tcx.types
411            .fresh_int_tys
412            .get(n as usize)
413            .copied()
414            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
415    }
416
417    #[inline]
418    pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
419        // Use a pre-interned one when possible.
420        tcx.types
421            .fresh_float_tys
422            .get(n as usize)
423            .copied()
424            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
425    }
426
427    #[inline]
428    pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
429        Ty::new(tcx, Param(ParamTy { index, name }))
430    }
431
432    #[inline]
433    pub fn new_bound(
434        tcx: TyCtxt<'tcx>,
435        index: ty::DebruijnIndex,
436        bound_ty: ty::BoundTy<'tcx>,
437    ) -> Ty<'tcx> {
438        // Use a pre-interned one when possible.
439        if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
440            && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
441            && let Some(ty) = inner.get(var.as_usize()).copied()
442        {
443            ty
444        } else {
445            Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
446        }
447    }
448
449    #[inline]
450    pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
451        // Use a pre-interned one when possible.
452        if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
453            ty
454        } else {
455            Ty::new(
456                tcx,
457                Bound(
458                    ty::BoundVarIndexKind::Canonical,
459                    ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
460                ),
461            )
462        }
463    }
464
465    #[inline]
466    pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
467        Ty::new(tcx, Placeholder(placeholder))
468    }
469
470    #[inline]
471    pub fn new_alias(
472        tcx: TyCtxt<'tcx>,
473        kind: ty::AliasTyKind,
474        alias_ty: ty::AliasTy<'tcx>,
475    ) -> Ty<'tcx> {
476        if true {
    match (kind, tcx.def_kind(alias_ty.def_id)) {
        (ty::Opaque, DefKind::OpaqueTy) |
            (ty::Projection | ty::Inherent, DefKind::AssocTy) |
            (ty::Free, DefKind::TyAlias) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "(ty::Opaque, DefKind::OpaqueTy) |\n(ty::Projection | ty::Inherent, DefKind::AssocTy) |\n(ty::Free, DefKind::TyAlias)",
                ::core::option::Option::None);
        }
    };
};debug_assert_matches!(
477            (kind, tcx.def_kind(alias_ty.def_id)),
478            (ty::Opaque, DefKind::OpaqueTy)
479                | (ty::Projection | ty::Inherent, DefKind::AssocTy)
480                | (ty::Free, DefKind::TyAlias)
481        );
482        Ty::new(tcx, Alias(kind, alias_ty))
483    }
484
485    #[inline]
486    pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
487        Ty::new(tcx, Pat(base, pat))
488    }
489
490    #[inline]
491    pub fn new_field_representing_type(
492        tcx: TyCtxt<'tcx>,
493        base: Ty<'tcx>,
494        variant: VariantIdx,
495        field: FieldIdx,
496    ) -> Ty<'tcx> {
497        let Some(did) = tcx.lang_items().field_representing_type() else {
498            crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
499        };
500        let def = tcx.adt_def(did);
501        let args = tcx.mk_args(&[
502            base.into(),
503            Const::new_value(
504                tcx,
505                ValTree::from_scalar_int(tcx, variant.as_u32().into()),
506                tcx.types.u32,
507            )
508            .into(),
509            Const::new_value(
510                tcx,
511                ValTree::from_scalar_int(tcx, field.as_u32().into()),
512                tcx.types.u32,
513            )
514            .into(),
515        ]);
516        Ty::new_adt(tcx, def, args)
517    }
518
519    #[inline]
520    #[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_opaque",
                                    "rustc_middle::ty::sty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(520u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            Ty::new_alias(tcx, ty::Opaque,
                AliasTy::new_from_args(tcx, def_id, args))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
521    pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
522        Ty::new_alias(tcx, ty::Opaque, AliasTy::new_from_args(tcx, def_id, args))
523    }
524
525    /// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
526    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
527        Ty::new(tcx, Error(guar))
528    }
529
530    /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` to ensure it gets used.
531    #[track_caller]
532    pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
533        Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
534    }
535
536    /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` with the given `msg` to
537    /// ensure it gets used.
538    #[track_caller]
539    pub fn new_error_with_message<S: Into<MultiSpan>>(
540        tcx: TyCtxt<'tcx>,
541        span: S,
542        msg: impl Into<Cow<'static, str>>,
543    ) -> Ty<'tcx> {
544        let reported = tcx.dcx().span_delayed_bug(span, msg);
545        Ty::new(tcx, Error(reported))
546    }
547
548    #[inline]
549    pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
550        use ty::IntTy::*;
551        match i {
552            Isize => tcx.types.isize,
553            I8 => tcx.types.i8,
554            I16 => tcx.types.i16,
555            I32 => tcx.types.i32,
556            I64 => tcx.types.i64,
557            I128 => tcx.types.i128,
558        }
559    }
560
561    #[inline]
562    pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
563        use ty::UintTy::*;
564        match ui {
565            Usize => tcx.types.usize,
566            U8 => tcx.types.u8,
567            U16 => tcx.types.u16,
568            U32 => tcx.types.u32,
569            U64 => tcx.types.u64,
570            U128 => tcx.types.u128,
571        }
572    }
573
574    #[inline]
575    pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
576        use ty::FloatTy::*;
577        match f {
578            F16 => tcx.types.f16,
579            F32 => tcx.types.f32,
580            F64 => tcx.types.f64,
581            F128 => tcx.types.f128,
582        }
583    }
584
585    #[inline]
586    pub fn new_ref(
587        tcx: TyCtxt<'tcx>,
588        r: Region<'tcx>,
589        ty: Ty<'tcx>,
590        mutbl: ty::Mutability,
591    ) -> Ty<'tcx> {
592        Ty::new(tcx, Ref(r, ty, mutbl))
593    }
594
595    #[inline]
596    pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
597        Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
598    }
599
600    #[inline]
601    pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
602        Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
603    }
604
605    pub fn new_pinned_ref(
606        tcx: TyCtxt<'tcx>,
607        r: Region<'tcx>,
608        ty: Ty<'tcx>,
609        mutbl: ty::Mutability,
610    ) -> Ty<'tcx> {
611        let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
612        Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
613    }
614
615    #[inline]
616    pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
617        Ty::new(tcx, ty::RawPtr(ty, mutbl))
618    }
619
620    #[inline]
621    pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
622        Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
623    }
624
625    #[inline]
626    pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
627        Ty::new_ptr(tcx, ty, hir::Mutability::Not)
628    }
629
630    #[inline]
631    pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
632        tcx.debug_assert_args_compatible(def.did(), args);
633        if truecfg!(debug_assertions) {
634            match tcx.def_kind(def.did()) {
635                DefKind::Struct | DefKind::Union | DefKind::Enum => {}
636                DefKind::Mod
637                | DefKind::Variant
638                | DefKind::Trait
639                | DefKind::TyAlias
640                | DefKind::ForeignTy
641                | DefKind::TraitAlias
642                | DefKind::AssocTy
643                | DefKind::TyParam
644                | DefKind::Fn
645                | DefKind::Const { .. }
646                | DefKind::ConstParam
647                | DefKind::Static { .. }
648                | DefKind::Ctor(..)
649                | DefKind::AssocFn
650                | DefKind::AssocConst { .. }
651                | DefKind::Macro(..)
652                | DefKind::ExternCrate
653                | DefKind::Use
654                | DefKind::ForeignMod
655                | DefKind::AnonConst
656                | DefKind::InlineConst
657                | DefKind::OpaqueTy
658                | DefKind::Field
659                | DefKind::LifetimeParam
660                | DefKind::GlobalAsm
661                | DefKind::Impl { .. }
662                | DefKind::Closure
663                | DefKind::SyntheticCoroutineBody => {
664                    crate::util::bug::bug_fmt(format_args!("not an adt: {1:?} ({0:?})",
        tcx.def_kind(def.did()), def))bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did()))
665                }
666            }
667        }
668        Ty::new(tcx, Adt(def, args))
669    }
670
671    #[inline]
672    pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
673        Ty::new(tcx, Foreign(def_id))
674    }
675
676    #[inline]
677    pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
678        Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
679    }
680
681    #[inline]
682    pub fn new_array_with_const_len(
683        tcx: TyCtxt<'tcx>,
684        ty: Ty<'tcx>,
685        ct: ty::Const<'tcx>,
686    ) -> Ty<'tcx> {
687        Ty::new(tcx, Array(ty, ct))
688    }
689
690    #[inline]
691    pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
692        Ty::new(tcx, Slice(ty))
693    }
694
695    #[inline]
696    pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
697        if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
698    }
699
700    pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
701    where
702        I: Iterator<Item = T>,
703        T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
704    {
705        T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
706    }
707
708    #[inline]
709    pub fn new_fn_def(
710        tcx: TyCtxt<'tcx>,
711        def_id: DefId,
712        args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
713    ) -> Ty<'tcx> {
714        if true {
    match tcx.def_kind(def_id) {
        DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)",
                ::core::option::Option::None);
        }
    };
};debug_assert_matches!(
715            tcx.def_kind(def_id),
716            DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
717        );
718        let args = tcx.check_and_mk_args(def_id, args);
719        Ty::new(tcx, FnDef(def_id, args))
720    }
721
722    #[inline]
723    pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
724        let (sig_tys, hdr) = fty.split();
725        Ty::new(tcx, FnPtr(sig_tys, hdr))
726    }
727
728    #[inline]
729    pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
730        Ty::new(tcx, UnsafeBinder(b.into()))
731    }
732
733    #[inline]
734    pub fn new_dynamic(
735        tcx: TyCtxt<'tcx>,
736        obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
737        reg: ty::Region<'tcx>,
738    ) -> Ty<'tcx> {
739        if truecfg!(debug_assertions) {
740            let projection_count = obj
741                .projection_bounds()
742                .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
743                .count();
744            let expected_count: usize = obj
745                .principal_def_id()
746                .into_iter()
747                .flat_map(|principal_def_id| {
748                    // IMPORTANT: This has to agree with HIR ty lowering of dyn trait!
749                    elaborate::supertraits(
750                        tcx,
751                        ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
752                    )
753                    .map(|principal| {
754                        tcx.associated_items(principal.def_id())
755                            .in_definition_order()
756                            .filter(|item| item.is_type() || item.is_const())
757                            .filter(|item| !item.is_impl_trait_in_trait())
758                            .filter(|item| !tcx.generics_require_sized_self(item.def_id))
759                            .count()
760                    })
761                })
762                .sum();
763            match (&projection_count, &expected_count) {
    (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::Some(format_args!("expected {0:?} to have {1} projections, but it has {2}",
                        obj, expected_count, projection_count)));
        }
    }
};assert_eq!(
764                projection_count, expected_count,
765                "expected {obj:?} to have {expected_count} projections, \
766                but it has {projection_count}"
767            );
768        }
769        Ty::new(tcx, Dynamic(obj, reg))
770    }
771
772    #[inline]
773    pub fn new_projection_from_args(
774        tcx: TyCtxt<'tcx>,
775        item_def_id: DefId,
776        args: ty::GenericArgsRef<'tcx>,
777    ) -> Ty<'tcx> {
778        Ty::new_alias(tcx, ty::Projection, AliasTy::new_from_args(tcx, item_def_id, args))
779    }
780
781    #[inline]
782    pub fn new_projection(
783        tcx: TyCtxt<'tcx>,
784        item_def_id: DefId,
785        args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
786    ) -> Ty<'tcx> {
787        Ty::new_alias(tcx, ty::Projection, AliasTy::new(tcx, item_def_id, args))
788    }
789
790    #[inline]
791    pub fn new_closure(
792        tcx: TyCtxt<'tcx>,
793        def_id: DefId,
794        closure_args: GenericArgsRef<'tcx>,
795    ) -> Ty<'tcx> {
796        tcx.debug_assert_args_compatible(def_id, closure_args);
797        Ty::new(tcx, Closure(def_id, closure_args))
798    }
799
800    #[inline]
801    pub fn new_coroutine_closure(
802        tcx: TyCtxt<'tcx>,
803        def_id: DefId,
804        closure_args: GenericArgsRef<'tcx>,
805    ) -> Ty<'tcx> {
806        tcx.debug_assert_args_compatible(def_id, closure_args);
807        Ty::new(tcx, CoroutineClosure(def_id, closure_args))
808    }
809
810    #[inline]
811    pub fn new_coroutine(
812        tcx: TyCtxt<'tcx>,
813        def_id: DefId,
814        coroutine_args: GenericArgsRef<'tcx>,
815    ) -> Ty<'tcx> {
816        tcx.debug_assert_args_compatible(def_id, coroutine_args);
817        Ty::new(tcx, Coroutine(def_id, coroutine_args))
818    }
819
820    #[inline]
821    pub fn new_coroutine_witness(
822        tcx: TyCtxt<'tcx>,
823        def_id: DefId,
824        args: GenericArgsRef<'tcx>,
825    ) -> Ty<'tcx> {
826        if truecfg!(debug_assertions) {
827            tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args);
828        }
829        Ty::new(tcx, CoroutineWitness(def_id, args))
830    }
831
832    pub fn new_coroutine_witness_for_coroutine(
833        tcx: TyCtxt<'tcx>,
834        def_id: DefId,
835        coroutine_args: GenericArgsRef<'tcx>,
836    ) -> Ty<'tcx> {
837        tcx.debug_assert_args_compatible(def_id, coroutine_args);
838        // HACK: Coroutine witness types are lifetime erased, so they
839        // never reference any lifetime args from the coroutine. We erase
840        // the regions here since we may get into situations where a
841        // coroutine is recursively contained within itself, leading to
842        // witness types that differ by region args. This means that
843        // cycle detection in fulfillment will not kick in, which leads
844        // to unnecessary overflows in async code. See the issue:
845        // <https://github.com/rust-lang/rust/issues/145151>.
846        let args =
847            ty::GenericArgs::for_item(tcx, tcx.typeck_root_def_id(def_id), |def, _| {
848                match def.kind {
849                    ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
850                    ty::GenericParamDefKind::Type { .. }
851                    | ty::GenericParamDefKind::Const { .. } => coroutine_args[def.index as usize],
852                }
853            });
854        Ty::new_coroutine_witness(tcx, def_id, args)
855    }
856
857    // misc
858
859    #[inline]
860    pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
861        Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
862    }
863
864    // lang and diagnostic tys
865
866    fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
867        let adt_def = tcx.adt_def(wrapper_def_id);
868        let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
869            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
870            GenericParamDefKind::Type { has_default, .. } => {
871                if param.index == 0 {
872                    ty_param.into()
873                } else {
874                    if !has_default { ::core::panicking::panic("assertion failed: has_default") };assert!(has_default);
875                    tcx.type_of(param.def_id).instantiate(tcx, args).into()
876                }
877            }
878        });
879        Ty::new_adt(tcx, adt_def, args)
880    }
881
882    #[inline]
883    pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
884        let def_id = tcx.lang_items().get(item)?;
885        Some(Ty::new_generic_adt(tcx, def_id, ty))
886    }
887
888    #[inline]
889    pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
890        let def_id = tcx.get_diagnostic_item(name)?;
891        Some(Ty::new_generic_adt(tcx, def_id, ty))
892    }
893
894    #[inline]
895    pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
896        let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
897        Ty::new_generic_adt(tcx, def_id, ty)
898    }
899
900    #[inline]
901    pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
902        let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
903        Ty::new_generic_adt(tcx, def_id, ty)
904    }
905
906    #[inline]
907    pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
908        let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
909        Ty::new_generic_adt(tcx, def_id, ty)
910    }
911
912    /// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
913    pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
914        let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
915        let context_adt_ref = tcx.adt_def(context_did);
916        let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
917        let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
918        Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
919    }
920}
921
922impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
923    fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
924        tcx.types.bool
925    }
926
927    fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
928        tcx.types.u8
929    }
930
931    fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
932        Ty::new_infer(tcx, infer)
933    }
934
935    fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
936        Ty::new_var(tcx, vid)
937    }
938
939    fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
940        Ty::new_param(tcx, param.index, param.name)
941    }
942
943    fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Self {
944        Ty::new_placeholder(tcx, placeholder)
945    }
946
947    fn new_bound(
948        interner: TyCtxt<'tcx>,
949        debruijn: ty::DebruijnIndex,
950        var: ty::BoundTy<'tcx>,
951    ) -> Self {
952        Ty::new_bound(interner, debruijn, var)
953    }
954
955    fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
956        Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
957    }
958
959    fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
960        Ty::new_canonical_bound(tcx, var)
961    }
962
963    fn new_alias(
964        interner: TyCtxt<'tcx>,
965        kind: ty::AliasTyKind,
966        alias_ty: ty::AliasTy<'tcx>,
967    ) -> Self {
968        Ty::new_alias(interner, kind, alias_ty)
969    }
970
971    fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
972        Ty::new_error(interner, guar)
973    }
974
975    fn new_adt(
976        interner: TyCtxt<'tcx>,
977        adt_def: ty::AdtDef<'tcx>,
978        args: ty::GenericArgsRef<'tcx>,
979    ) -> Self {
980        Ty::new_adt(interner, adt_def, args)
981    }
982
983    fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
984        Ty::new_foreign(interner, def_id)
985    }
986
987    fn new_dynamic(
988        interner: TyCtxt<'tcx>,
989        preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
990        region: ty::Region<'tcx>,
991    ) -> Self {
992        Ty::new_dynamic(interner, preds, region)
993    }
994
995    fn new_coroutine(
996        interner: TyCtxt<'tcx>,
997        def_id: DefId,
998        args: ty::GenericArgsRef<'tcx>,
999    ) -> Self {
1000        Ty::new_coroutine(interner, def_id, args)
1001    }
1002
1003    fn new_coroutine_closure(
1004        interner: TyCtxt<'tcx>,
1005        def_id: DefId,
1006        args: ty::GenericArgsRef<'tcx>,
1007    ) -> Self {
1008        Ty::new_coroutine_closure(interner, def_id, args)
1009    }
1010
1011    fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1012        Ty::new_closure(interner, def_id, args)
1013    }
1014
1015    fn new_coroutine_witness(
1016        interner: TyCtxt<'tcx>,
1017        def_id: DefId,
1018        args: ty::GenericArgsRef<'tcx>,
1019    ) -> Self {
1020        Ty::new_coroutine_witness(interner, def_id, args)
1021    }
1022
1023    fn new_coroutine_witness_for_coroutine(
1024        interner: TyCtxt<'tcx>,
1025        def_id: DefId,
1026        coroutine_args: ty::GenericArgsRef<'tcx>,
1027    ) -> Self {
1028        Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1029    }
1030
1031    fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1032        Ty::new_ptr(interner, ty, mutbl)
1033    }
1034
1035    fn new_ref(
1036        interner: TyCtxt<'tcx>,
1037        region: ty::Region<'tcx>,
1038        ty: Self,
1039        mutbl: hir::Mutability,
1040    ) -> Self {
1041        Ty::new_ref(interner, region, ty, mutbl)
1042    }
1043
1044    fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1045        Ty::new_array_with_const_len(interner, ty, len)
1046    }
1047
1048    fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1049        Ty::new_slice(interner, ty)
1050    }
1051
1052    fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1053        Ty::new_tup(interner, tys)
1054    }
1055
1056    fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1057    where
1058        It: Iterator<Item = T>,
1059        T: CollectAndApply<Self, Self>,
1060    {
1061        Ty::new_tup_from_iter(interner, iter)
1062    }
1063
1064    fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1065        self.tuple_fields()
1066    }
1067
1068    fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1069        self.to_opt_closure_kind()
1070    }
1071
1072    fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1073        Ty::from_closure_kind(interner, kind)
1074    }
1075
1076    fn from_coroutine_closure_kind(
1077        interner: TyCtxt<'tcx>,
1078        kind: rustc_type_ir::ClosureKind,
1079    ) -> Self {
1080        Ty::from_coroutine_closure_kind(interner, kind)
1081    }
1082
1083    fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1084        Ty::new_fn_def(interner, def_id, args)
1085    }
1086
1087    fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1088        Ty::new_fn_ptr(interner, sig)
1089    }
1090
1091    fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1092        Ty::new_pat(interner, ty, pat)
1093    }
1094
1095    fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1096        Ty::new_unsafe_binder(interner, ty)
1097    }
1098
1099    fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1100        interner.types.unit
1101    }
1102
1103    fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1104        interner.types.usize
1105    }
1106
1107    fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1108        self.discriminant_ty(interner)
1109    }
1110
1111    fn has_unsafe_fields(self) -> bool {
1112        Ty::has_unsafe_fields(self)
1113    }
1114}
1115
1116/// Type utilities
1117impl<'tcx> Ty<'tcx> {
1118    // It would be nicer if this returned the value instead of a reference,
1119    // like how `Predicate::kind` and `Region::kind` do. (It would result in
1120    // many fewer subsequent dereferences.) But that gives a small but
1121    // noticeable performance hit. See #126069 for details.
1122    #[inline(always)]
1123    pub fn kind(self) -> &'tcx TyKind<'tcx> {
1124        self.0.0
1125    }
1126
1127    // FIXME(compiler-errors): Think about removing this.
1128    #[inline(always)]
1129    pub fn flags(self) -> TypeFlags {
1130        self.0.0.flags
1131    }
1132
1133    #[inline]
1134    pub fn is_unit(self) -> bool {
1135        match self.kind() {
1136            Tuple(tys) => tys.is_empty(),
1137            _ => false,
1138        }
1139    }
1140
1141    /// Check if type is an `usize`.
1142    #[inline]
1143    pub fn is_usize(self) -> bool {
1144        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1145    }
1146
1147    /// Check if type is an `usize` or an integral type variable.
1148    #[inline]
1149    pub fn is_usize_like(self) -> bool {
1150        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1151    }
1152
1153    #[inline]
1154    pub fn is_never(self) -> bool {
1155        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Never => true,
    _ => false,
}matches!(self.kind(), Never)
1156    }
1157
1158    #[inline]
1159    pub fn is_primitive(self) -> bool {
1160        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Uint(_) | Float(_) => true,
    _ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1161    }
1162
1163    #[inline]
1164    pub fn is_adt(self) -> bool {
1165        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(..) => true,
    _ => false,
}matches!(self.kind(), Adt(..))
1166    }
1167
1168    #[inline]
1169    pub fn is_ref(self) -> bool {
1170        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Ref(..) => true,
    _ => false,
}matches!(self.kind(), Ref(..))
1171    }
1172
1173    #[inline]
1174    pub fn is_ty_var(self) -> bool {
1175        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(TyVar(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1176    }
1177
1178    #[inline]
1179    pub fn ty_vid(self) -> Option<ty::TyVid> {
1180        match self.kind() {
1181            &Infer(TyVar(vid)) => Some(vid),
1182            _ => None,
1183        }
1184    }
1185
1186    #[inline]
1187    pub fn is_ty_or_numeric_infer(self) -> bool {
1188        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(_) => true,
    _ => false,
}matches!(self.kind(), Infer(_))
1189    }
1190
1191    #[inline]
1192    pub fn is_phantom_data(self) -> bool {
1193        if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1194    }
1195
1196    #[inline]
1197    pub fn is_bool(self) -> bool {
1198        *self.kind() == Bool
1199    }
1200
1201    /// Returns `true` if this type is a `str`.
1202    #[inline]
1203    pub fn is_str(self) -> bool {
1204        *self.kind() == Str
1205    }
1206
1207    /// Returns true if this type is `&str`. The reference's lifetime is ignored.
1208    #[inline]
1209    pub fn is_imm_ref_str(self) -> bool {
1210        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    ty::Ref(_, inner, hir::Mutability::Not) if inner.is_str() => true,
    _ => false,
}matches!(self.kind(), ty::Ref(_, inner, hir::Mutability::Not) if inner.is_str())
1211    }
1212
1213    #[inline]
1214    pub fn is_param(self, index: u32) -> bool {
1215        match self.kind() {
1216            ty::Param(data) => data.index == index,
1217            _ => false,
1218        }
1219    }
1220
1221    #[inline]
1222    pub fn is_slice(self) -> bool {
1223        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Slice(_) => true,
    _ => false,
}matches!(self.kind(), Slice(_))
1224    }
1225
1226    #[inline]
1227    pub fn is_array_slice(self) -> bool {
1228        match self.kind() {
1229            Slice(_) => true,
1230            ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    Slice(_) => true,
    _ => false,
}matches!(ty.kind(), Slice(_)),
1231            _ => false,
1232        }
1233    }
1234
1235    #[inline]
1236    pub fn is_array(self) -> bool {
1237        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Array(..) => true,
    _ => false,
}matches!(self.kind(), Array(..))
1238    }
1239
1240    #[inline]
1241    pub fn is_simd(self) -> bool {
1242        match self.kind() {
1243            Adt(def, _) => def.repr().simd(),
1244            _ => false,
1245        }
1246    }
1247
1248    #[inline]
1249    pub fn is_scalable_vector(self) -> bool {
1250        match self.kind() {
1251            Adt(def, _) => def.repr().scalable(),
1252            _ => false,
1253        }
1254    }
1255
1256    pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1257        match self.kind() {
1258            Array(ty, _) | Slice(ty) => *ty,
1259            Str => tcx.types.u8,
1260            _ => crate::util::bug::bug_fmt(format_args!("`sequence_element_type` called on non-sequence value: {0}",
        self))bug!("`sequence_element_type` called on non-sequence value: {}", self),
1261        }
1262    }
1263
1264    pub fn scalable_vector_element_count_and_type(self, tcx: TyCtxt<'tcx>) -> (u16, Ty<'tcx>) {
1265        let Adt(def, args) = self.kind() else {
1266            crate::util::bug::bug_fmt(format_args!("`scalable_vector_size_and_type` called on invalid type"))bug!("`scalable_vector_size_and_type` called on invalid type")
1267        };
1268        let Some(ScalableElt::ElementCount(element_count)) = def.repr().scalable else {
1269            crate::util::bug::bug_fmt(format_args!("`scalable_vector_size_and_type` called on non-scalable vector type"));bug!("`scalable_vector_size_and_type` called on non-scalable vector type");
1270        };
1271        let variant = def.non_enum_variant();
1272        match (&variant.fields.len(), &1) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(variant.fields.len(), 1);
1273        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1274        (element_count, field_ty)
1275    }
1276
1277    pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1278        let Adt(def, args) = self.kind() else {
1279            crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1280        };
1281        if !def.repr().simd() {
    {
        ::core::panicking::panic_fmt(format_args!("`simd_size_and_type` called on non-SIMD type"));
    }
};assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1282        let variant = def.non_enum_variant();
1283        match (&variant.fields.len(), &1) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(variant.fields.len(), 1);
1284        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1285        let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1286            crate::util::bug::bug_fmt(format_args!("Simd type has non-array field type {0:?}",
        field_ty))bug!("Simd type has non-array field type {field_ty:?}")
1287        };
1288        // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1289        // The way we evaluate the `N` in `[T; N]` here only works since we use
1290        // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1291        // if we use it in generic code. See the `simd-array-trait` ui test.
1292        (
1293            f0_len
1294                .try_to_target_usize(tcx)
1295                .expect("expected SIMD field to have definite array size"),
1296            *f0_elem_ty,
1297        )
1298    }
1299
1300    #[inline]
1301    pub fn is_mutable_ptr(self) -> bool {
1302        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut) => true,
    _ => false,
}matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1303    }
1304
1305    /// Get the mutability of the reference or `None` when not a reference
1306    #[inline]
1307    pub fn ref_mutability(self) -> Option<hir::Mutability> {
1308        match self.kind() {
1309            Ref(_, _, mutability) => Some(*mutability),
1310            _ => None,
1311        }
1312    }
1313
1314    #[inline]
1315    pub fn is_raw_ptr(self) -> bool {
1316        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RawPtr(_, _) => true,
    _ => false,
}matches!(self.kind(), RawPtr(_, _))
1317    }
1318
1319    /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1320    /// `Box` is *not* considered a pointer here!
1321    #[inline]
1322    pub fn is_any_ptr(self) -> bool {
1323        self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1324    }
1325
1326    #[inline]
1327    pub fn is_box(self) -> bool {
1328        match self.kind() {
1329            Adt(def, _) => def.is_box(),
1330            _ => false,
1331        }
1332    }
1333
1334    /// Tests whether this is a Box definitely using the global allocator.
1335    ///
1336    /// If the allocator is still generic, the answer is `false`, but it may
1337    /// later turn out that it does use the global allocator.
1338    #[inline]
1339    pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1340        match self.kind() {
1341            Adt(def, args) if def.is_box() => {
1342                let Some(alloc) = args.get(1) else {
1343                    // Single-argument Box is always global. (for "minicore" tests)
1344                    return true;
1345                };
1346                alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1347                    tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1348                })
1349            }
1350            _ => false,
1351        }
1352    }
1353
1354    pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1355        match self.kind() {
1356            Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1357            _ => None,
1358        }
1359    }
1360
1361    pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1362        match self.kind() {
1363            Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1364            _ => None,
1365        }
1366    }
1367
1368    pub fn maybe_pinned_ref(
1369        self,
1370    ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1371        match self.kind() {
1372            Adt(def, args)
1373                if def.is_pin()
1374                    && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1375            {
1376                Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1377            }
1378            &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1379            _ => None,
1380        }
1381    }
1382
1383    /// Panics if called on any type other than `Box<T>`.
1384    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1385        self.boxed_ty()
1386            .unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("`expect_boxed_ty` is called on non-box type {0:?}",
        self))bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1387    }
1388
1389    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1390    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1391    /// contents are abstract to rustc.)
1392    #[inline]
1393    pub fn is_scalar(self) -> bool {
1394        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
        RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
    _ => false,
}matches!(
1395            self.kind(),
1396            Bool | Char
1397                | Int(_)
1398                | Float(_)
1399                | Uint(_)
1400                | FnDef(..)
1401                | FnPtr(..)
1402                | RawPtr(_, _)
1403                | Infer(IntVar(_) | FloatVar(_))
1404        )
1405    }
1406
1407    /// Returns `true` if this type is a floating point type.
1408    #[inline]
1409    pub fn is_floating_point(self) -> bool {
1410        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Float(_) | Infer(FloatVar(_)) => true,
    _ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1411    }
1412
1413    #[inline]
1414    pub fn is_trait(self) -> bool {
1415        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Dynamic(_, _) => true,
    _ => false,
}matches!(self.kind(), Dynamic(_, _))
1416    }
1417
1418    #[inline]
1419    pub fn is_enum(self) -> bool {
1420        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(adt_def, _) if adt_def.is_enum() => true,
    _ => false,
}matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1421    }
1422
1423    #[inline]
1424    pub fn is_union(self) -> bool {
1425        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(adt_def, _) if adt_def.is_union() => true,
    _ => false,
}matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1426    }
1427
1428    #[inline]
1429    pub fn is_closure(self) -> bool {
1430        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Closure(..) => true,
    _ => false,
}matches!(self.kind(), Closure(..))
1431    }
1432
1433    #[inline]
1434    pub fn is_coroutine(self) -> bool {
1435        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Coroutine(..) => true,
    _ => false,
}matches!(self.kind(), Coroutine(..))
1436    }
1437
1438    #[inline]
1439    pub fn is_coroutine_closure(self) -> bool {
1440        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    CoroutineClosure(..) => true,
    _ => false,
}matches!(self.kind(), CoroutineClosure(..))
1441    }
1442
1443    #[inline]
1444    pub fn is_integral(self) -> bool {
1445        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(IntVar(_)) | Int(_) | Uint(_) => true,
    _ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1446    }
1447
1448    #[inline]
1449    pub fn is_fresh_ty(self) -> bool {
1450        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1451    }
1452
1453    #[inline]
1454    pub fn is_fresh(self) -> bool {
1455        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1456    }
1457
1458    #[inline]
1459    pub fn is_char(self) -> bool {
1460        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Char => true,
    _ => false,
}matches!(self.kind(), Char)
1461    }
1462
1463    #[inline]
1464    pub fn is_numeric(self) -> bool {
1465        self.is_integral() || self.is_floating_point()
1466    }
1467
1468    #[inline]
1469    pub fn is_signed(self) -> bool {
1470        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Int(_) => true,
    _ => false,
}matches!(self.kind(), Int(_))
1471    }
1472
1473    #[inline]
1474    pub fn is_ptr_sized_integral(self) -> bool {
1475        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize) => true,
    _ => false,
}matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1476    }
1477
1478    #[inline]
1479    pub fn has_concrete_skeleton(self) -> bool {
1480        !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Param(_) | Infer(_) | Error(_) => true,
    _ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1481    }
1482
1483    /// Checks whether a type recursively contains another type
1484    ///
1485    /// Example: `Option<()>` contains `()`
1486    pub fn contains(self, other: Ty<'tcx>) -> bool {
1487        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1488
1489        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1490            type Result = ControlFlow<()>;
1491
1492            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1493                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1494            }
1495        }
1496
1497        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1498        cf.is_break()
1499    }
1500
1501    /// Checks whether a type recursively contains any closure
1502    ///
1503    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1504    pub fn contains_closure(self) -> bool {
1505        struct ContainsClosureVisitor;
1506
1507        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1508            type Result = ControlFlow<()>;
1509
1510            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1511                if let ty::Closure(..) = t.kind() {
1512                    ControlFlow::Break(())
1513                } else {
1514                    t.super_visit_with(self)
1515                }
1516            }
1517        }
1518
1519        let cf = self.visit_with(&mut ContainsClosureVisitor);
1520        cf.is_break()
1521    }
1522
1523    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1524    ///
1525    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1526    /// to call async drop poll from impl coroutine.
1527    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1528        self,
1529        tcx: TyCtxt<'tcx>,
1530        mut f: F,
1531    ) -> Ty<'tcx> {
1532        if !self.is_coroutine() {
    ::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1533        let mut cor_ty = self;
1534        let mut ty = cor_ty;
1535        loop {
1536            let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1537            cor_ty = ty;
1538            f(ty);
1539            if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1540                return cor_ty;
1541            }
1542            ty = args.first().unwrap().expect_ty();
1543        }
1544    }
1545
1546    /// Returns the type of `*ty`.
1547    ///
1548    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1549    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1550    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1551        match *self.kind() {
1552            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1553            Ref(_, ty, _) => Some(ty),
1554            RawPtr(ty, _) if explicit => Some(ty),
1555            _ => None,
1556        }
1557    }
1558
1559    /// Returns the type of `ty[i]`.
1560    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1561        match self.kind() {
1562            Array(ty, _) | Slice(ty) => Some(*ty),
1563            _ => None,
1564        }
1565    }
1566
1567    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("fn_sig",
                                    "rustc_middle::ty::sty", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1567u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["self"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PolyFnSig<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.kind().fn_sig(tcx) }
    }
}#[tracing::instrument(level = "trace", skip(tcx))]
1568    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1569        self.kind().fn_sig(tcx)
1570    }
1571
1572    #[inline]
1573    pub fn is_fn(self) -> bool {
1574        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnDef(..) | FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1575    }
1576
1577    #[inline]
1578    pub fn is_fn_ptr(self) -> bool {
1579        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnPtr(..))
1580    }
1581
1582    #[inline]
1583    pub fn is_impl_trait(self) -> bool {
1584        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Alias(ty::Opaque, ..) => true,
    _ => false,
}matches!(self.kind(), Alias(ty::Opaque, ..))
1585    }
1586
1587    #[inline]
1588    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1589        match self.kind() {
1590            Adt(adt, _) => Some(*adt),
1591            _ => None,
1592        }
1593    }
1594
1595    /// Returns a list of tuple type arguments.
1596    ///
1597    /// Panics when called on anything but a tuple.
1598    #[inline]
1599    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1600        match self.kind() {
1601            Tuple(args) => args,
1602            _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
        self))bug!("tuple_fields called on non-tuple: {self:?}"),
1603        }
1604    }
1605
1606    /// Returns a list of tuple type arguments, or `None` if `self` isn't a tuple.
1607    #[inline]
1608    pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1609        match self.kind() {
1610            Tuple(args) => Some(args),
1611            _ => None,
1612        }
1613    }
1614
1615    /// If the type contains variants, returns the valid range of variant indices.
1616    //
1617    // FIXME: This requires the optimized MIR in the case of coroutines.
1618    #[inline]
1619    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1620        match self.kind() {
1621            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1622            TyKind::Coroutine(def_id, args) => {
1623                Some(args.as_coroutine().variant_range(*def_id, tcx))
1624            }
1625            _ => None,
1626        }
1627    }
1628
1629    /// If the type contains variants, returns the variant for `variant_index`.
1630    /// Panics if `variant_index` is out of range.
1631    //
1632    // FIXME: This requires the optimized MIR in the case of coroutines.
1633    #[inline]
1634    pub fn discriminant_for_variant(
1635        self,
1636        tcx: TyCtxt<'tcx>,
1637        variant_index: VariantIdx,
1638    ) -> Option<Discr<'tcx>> {
1639        match self.kind() {
1640            TyKind::Adt(adt, _) if adt.is_enum() => {
1641                Some(adt.discriminant_for_variant(tcx, variant_index))
1642            }
1643            TyKind::Coroutine(def_id, args) => {
1644                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1645            }
1646            _ => None,
1647        }
1648    }
1649
1650    /// Returns the type of the discriminant of this type.
1651    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1652        match self.kind() {
1653            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1654            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1655
1656            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1657                let assoc_items = tcx.associated_item_def_ids(
1658                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1659                );
1660                Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1661            }
1662
1663            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1664
1665            ty::Bool
1666            | ty::Char
1667            | ty::Int(_)
1668            | ty::Uint(_)
1669            | ty::Float(_)
1670            | ty::Adt(..)
1671            | ty::Foreign(_)
1672            | ty::Str
1673            | ty::Array(..)
1674            | ty::Slice(_)
1675            | ty::RawPtr(_, _)
1676            | ty::Ref(..)
1677            | ty::FnDef(..)
1678            | ty::FnPtr(..)
1679            | ty::Dynamic(..)
1680            | ty::Closure(..)
1681            | ty::CoroutineClosure(..)
1682            | ty::CoroutineWitness(..)
1683            | ty::Never
1684            | ty::Tuple(_)
1685            | ty::UnsafeBinder(_)
1686            | ty::Error(_)
1687            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1688
1689            ty::Bound(..)
1690            | ty::Placeholder(_)
1691            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1692                crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
        self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1693            }
1694        }
1695    }
1696
1697    /// Returns the type of metadata for (potentially wide) pointers to this type,
1698    /// or the struct tail if the metadata type cannot be determined.
1699    pub fn ptr_metadata_ty_or_tail(
1700        self,
1701        tcx: TyCtxt<'tcx>,
1702        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1703    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1704        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1705        match tail.kind() {
1706            // Sized types
1707            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1708            | ty::Uint(_)
1709            | ty::Int(_)
1710            | ty::Bool
1711            | ty::Float(_)
1712            | ty::FnDef(..)
1713            | ty::FnPtr(..)
1714            | ty::RawPtr(..)
1715            | ty::Char
1716            | ty::Ref(..)
1717            | ty::Coroutine(..)
1718            | ty::CoroutineWitness(..)
1719            | ty::Array(..)
1720            | ty::Closure(..)
1721            | ty::CoroutineClosure(..)
1722            | ty::Never
1723            | ty::Error(_)
1724            // Extern types have metadata = ().
1725            | ty::Foreign(..)
1726            // If returned by `struct_tail_raw` this is a unit struct
1727            // without any fields, or not a struct, and therefore is Sized.
1728            | ty::Adt(..)
1729            // If returned by `struct_tail_raw` this is the empty tuple,
1730            // a.k.a. unit type, which is Sized
1731            | ty::Tuple(..) => Ok(tcx.types.unit),
1732
1733            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1734
1735            ty::Dynamic(_, _) => {
1736                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1737                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1738            }
1739
1740            // We don't know the metadata of `self`, but it must be equal to the
1741            // metadata of `tail`.
1742            ty::Param(_) | ty::Alias(..) => Err(tail),
1743
1744            | ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
1745
1746            ty::Infer(ty::TyVar(_))
1747            | ty::Pat(..)
1748            | ty::Bound(..)
1749            | ty::Placeholder(..)
1750            | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty_or_tail` applied to unexpected type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1751                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1752            ),
1753        }
1754    }
1755
1756    /// Returns the type of metadata for (potentially wide) pointers to this type.
1757    /// Causes an ICE if the metadata type cannot be determined.
1758    pub fn ptr_metadata_ty(
1759        self,
1760        tcx: TyCtxt<'tcx>,
1761        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1762    ) -> Ty<'tcx> {
1763        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1764            Ok(metadata) => metadata,
1765            Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1766                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1767            ),
1768        }
1769    }
1770
1771    /// Given a pointer or reference type, returns the type of the *pointee*'s
1772    /// metadata. If it can't be determined exactly (perhaps due to still
1773    /// being generic) then a projection through `ptr::Pointee` will be returned.
1774    ///
1775    /// This is particularly useful for getting the type of the result of
1776    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1777    ///
1778    /// Panics if `self` is not dereferenceable.
1779    #[track_caller]
1780    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1781        let Some(pointee_ty) = self.builtin_deref(true) else {
1782            crate::util::bug::bug_fmt(format_args!("Type {0:?} is not a pointer or reference type",
        self))bug!("Type {self:?} is not a pointer or reference type")
1783        };
1784        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1785            tcx.types.unit
1786        } else {
1787            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1788                Ok(metadata_ty) => metadata_ty,
1789                Err(tail_ty) => {
1790                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1791                    Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1792                }
1793            }
1794        }
1795    }
1796
1797    /// When we create a closure, we record its kind (i.e., what trait
1798    /// it implements, constrained by how it uses its borrows) into its
1799    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1800    /// parameter. This is kind of a phantom type, except that the
1801    /// most convenient thing for us to are the integral types. This
1802    /// function converts such a special type into the closure
1803    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1804    ///
1805    /// Note that during type checking, we use an inference variable
1806    /// to represent the closure kind, because it has not yet been
1807    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1808    /// is complete, that type variable will be unified with one of
1809    /// the integral types.
1810    ///
1811    /// ```rust,ignore (snippet of compiler code)
1812    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1813    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1814    /// {
1815    ///     println!("{closure_kind:?}");
1816    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1817    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1818    /// {
1819    ///     println!("{closure_kind:?}");
1820    /// }
1821    /// ```
1822    ///
1823    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1824    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1825    /// has been constrained instead of manually calling this method.
1826    ///
1827    /// ```rust,ignore (snippet of compiler code)
1828    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1829    /// {
1830    ///     println!("{:?}", args.as_closure().kind());
1831    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1832    /// {
1833    ///     println!("{:?}", args.as_coroutine_closure().kind());
1834    /// }
1835    /// ```
1836    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1837        match self.kind() {
1838            Int(int_ty) => match int_ty {
1839                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1840                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1841                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1842                _ => crate::util::bug::bug_fmt(format_args!("cannot convert type `{0:?}` to a closure kind",
        self))bug!("cannot convert type `{:?}` to a closure kind", self),
1843            },
1844
1845            // "Bound" types appear in canonical queries when the
1846            // closure type is not yet known, and `Placeholder` and `Param`
1847            // may be encountered in generic `AsyncFnKindHelper` goals.
1848            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1849
1850            Error(_) => Some(ty::ClosureKind::Fn),
1851
1852            _ => crate::util::bug::bug_fmt(format_args!("cannot convert type `{0:?}` to a closure kind",
        self))bug!("cannot convert type `{:?}` to a closure kind", self),
1853        }
1854    }
1855
1856    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1857    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1858    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1859        match kind {
1860            ty::ClosureKind::Fn => tcx.types.i8,
1861            ty::ClosureKind::FnMut => tcx.types.i16,
1862            ty::ClosureKind::FnOnce => tcx.types.i32,
1863        }
1864    }
1865
1866    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1867    /// to `FnMut`. This is because although we have three capability states,
1868    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1869    /// bodies: by-ref and by-value.
1870    ///
1871    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1872    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1873    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1874    ///
1875    /// This method should be used when constructing a `Coroutine` out of a
1876    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1877    /// directly from the `CoroutineClosure`'s `kind`.
1878    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1879        match kind {
1880            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1881            ty::ClosureKind::FnOnce => tcx.types.i32,
1882        }
1883    }
1884
1885    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1886    ///
1887    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1888    /// means nothing -- could be sized, might not be.
1889    ///
1890    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1891    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1892    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1893    /// This is why this method doesn't return `Option<bool>`.
1894    #[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("has_trivial_sizedness",
                                    "rustc_middle::ty::sty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1894u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["self", "sizedness"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.kind() {
                ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Uint(_) |
                    ty::Int(_) | ty::Bool | ty::Float(_) | ty::FnDef(..) |
                    ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::RawPtr(..) |
                    ty::Char | ty::Ref(..) | ty::Coroutine(..) |
                    ty::CoroutineWitness(..) | ty::Array(..) | ty::Pat(..) |
                    ty::Closure(..) | ty::CoroutineClosure(..) | ty::Never |
                    ty::Error(_) => true,
                ty::Str | ty::Slice(_) | ty::Dynamic(_, _) =>
                    match sizedness {
                        SizedTraitKind::Sized => false,
                        SizedTraitKind::MetaSized => true,
                    },
                ty::Foreign(..) =>
                    match sizedness {
                        SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
                    },
                ty::Tuple(tys) =>
                    tys.last().is_none_or(|ty|
                            ty.has_trivial_sizedness(tcx, sizedness)),
                ty::Adt(def, args) =>
                    def.sizedness_constraint(tcx,
                            sizedness).is_none_or(|ty|
                            ty.instantiate(tcx,
                                    args).has_trivial_sizedness(tcx, sizedness)),
                ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) |
                    ty::Bound(..) => false,
                ty::Infer(ty::TyVar(_)) => false,
                ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) |
                    ty::FreshFloatTy(_)) => {
                    crate::util::bug::bug_fmt(format_args!("`has_trivial_sizedness` applied to unexpected type: {0:?}",
                            self))
                }
            }
        }
    }
}#[instrument(skip(tcx), level = "debug")]
1895    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1896        match self.kind() {
1897            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1898            | ty::Uint(_)
1899            | ty::Int(_)
1900            | ty::Bool
1901            | ty::Float(_)
1902            | ty::FnDef(..)
1903            | ty::FnPtr(..)
1904            | ty::UnsafeBinder(_)
1905            | ty::RawPtr(..)
1906            | ty::Char
1907            | ty::Ref(..)
1908            | ty::Coroutine(..)
1909            | ty::CoroutineWitness(..)
1910            | ty::Array(..)
1911            | ty::Pat(..)
1912            | ty::Closure(..)
1913            | ty::CoroutineClosure(..)
1914            | ty::Never
1915            | ty::Error(_) => true,
1916
1917            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1918                SizedTraitKind::Sized => false,
1919                SizedTraitKind::MetaSized => true,
1920            },
1921
1922            ty::Foreign(..) => match sizedness {
1923                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1924            },
1925
1926            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1927
1928            ty::Adt(def, args) => def
1929                .sizedness_constraint(tcx, sizedness)
1930                .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1931
1932            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1933
1934            ty::Infer(ty::TyVar(_)) => false,
1935
1936            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1937                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1938            }
1939        }
1940    }
1941
1942    /// Fast path helper for primitives which are always `Copy` and which
1943    /// have a side-effect-free `Clone` impl.
1944    ///
1945    /// Returning true means the type is known to be pure and `Copy+Clone`.
1946    /// Returning `false` means nothing -- could be `Copy`, might not be.
1947    ///
1948    /// This is mostly useful for optimizations, as these are the types
1949    /// on which we can replace cloning with dereferencing.
1950    pub fn is_trivially_pure_clone_copy(self) -> bool {
1951        match self.kind() {
1952            ty::Bool | ty::Char | ty::Never => true,
1953
1954            // These aren't even `Clone`
1955            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1956
1957            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1958            | ty::Int(..)
1959            | ty::Uint(..)
1960            | ty::Float(..) => true,
1961
1962            // ZST which can't be named are fine.
1963            ty::FnDef(..) => true,
1964
1965            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1966
1967            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
1968            ty::Tuple(field_tys) => {
1969                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1970            }
1971
1972            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1973
1974            // Sometimes traits aren't implemented for every ABI or arity,
1975            // because we can't be generic over everything yet.
1976            ty::FnPtr(..) => false,
1977
1978            // Definitely absolutely not copy.
1979            ty::Ref(_, _, hir::Mutability::Mut) => false,
1980
1981            // The standard library has a blanket Copy impl for shared references and raw pointers,
1982            // for all unsized types.
1983            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1984
1985            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1986
1987            // Might be, but not "trivial" so just giving the safe answer.
1988            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1989
1990            ty::UnsafeBinder(_) => false,
1991
1992            // Needs normalization or revealing to determine, so no is the safe answer.
1993            ty::Alias(..) => false,
1994
1995            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
1996                false
1997            }
1998        }
1999    }
2000
2001    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2002        match *self.kind() {
2003            ty::Bool
2004            | ty::Char
2005            | ty::Int(_)
2006            | ty::Uint(_)
2007            | ty::Float(_)
2008            | ty::Str
2009            | ty::Never
2010            | ty::Param(_)
2011            | ty::Placeholder(_)
2012            | ty::Bound(..) => true,
2013
2014            ty::Slice(ty) => {
2015                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2016            }
2017            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2018
2019            ty::FnPtr(sig_tys, _) => {
2020                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2021            }
2022            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2023
2024            ty::Infer(infer) => match infer {
2025                ty::TyVar(_) => false,
2026                ty::IntVar(_) | ty::FloatVar(_) => true,
2027                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2028            },
2029
2030            ty::Adt(_, _)
2031            | ty::Tuple(_)
2032            | ty::Array(..)
2033            | ty::Foreign(_)
2034            | ty::Pat(_, _)
2035            | ty::FnDef(..)
2036            | ty::UnsafeBinder(..)
2037            | ty::Dynamic(..)
2038            | ty::Closure(..)
2039            | ty::CoroutineClosure(..)
2040            | ty::Coroutine(..)
2041            | ty::CoroutineWitness(..)
2042            | ty::Alias(..)
2043            | ty::Error(_) => false,
2044        }
2045    }
2046
2047    /// If `self` is a primitive, return its [`Symbol`].
2048    pub fn primitive_symbol(self) -> Option<Symbol> {
2049        match self.kind() {
2050            ty::Bool => Some(sym::bool),
2051            ty::Char => Some(sym::char),
2052            ty::Float(f) => match f {
2053                ty::FloatTy::F16 => Some(sym::f16),
2054                ty::FloatTy::F32 => Some(sym::f32),
2055                ty::FloatTy::F64 => Some(sym::f64),
2056                ty::FloatTy::F128 => Some(sym::f128),
2057            },
2058            ty::Int(f) => match f {
2059                ty::IntTy::Isize => Some(sym::isize),
2060                ty::IntTy::I8 => Some(sym::i8),
2061                ty::IntTy::I16 => Some(sym::i16),
2062                ty::IntTy::I32 => Some(sym::i32),
2063                ty::IntTy::I64 => Some(sym::i64),
2064                ty::IntTy::I128 => Some(sym::i128),
2065            },
2066            ty::Uint(f) => match f {
2067                ty::UintTy::Usize => Some(sym::usize),
2068                ty::UintTy::U8 => Some(sym::u8),
2069                ty::UintTy::U16 => Some(sym::u16),
2070                ty::UintTy::U32 => Some(sym::u32),
2071                ty::UintTy::U64 => Some(sym::u64),
2072                ty::UintTy::U128 => Some(sym::u128),
2073            },
2074            ty::Str => Some(sym::str),
2075            _ => None,
2076        }
2077    }
2078
2079    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2080        match self.kind() {
2081            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2082            _ => false,
2083        }
2084    }
2085
2086    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2087        match self.kind() {
2088            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2089            _ => false,
2090        }
2091    }
2092
2093    /// Returns `true` when the outermost type cannot be further normalized,
2094    /// resolved, or instantiated. This includes all primitive types, but also
2095    /// things like ADTs and trait objects, since even if their arguments or
2096    /// nested types may be further simplified, the outermost [`TyKind`] or
2097    /// type constructor remains the same.
2098    pub fn is_known_rigid(self) -> bool {
2099        self.kind().is_known_rigid()
2100    }
2101
2102    /// Iterator that walks `self` and any types reachable from
2103    /// `self`, in depth-first order. Note that just walks the types
2104    /// that appear in `self`, it does not descend into the fields of
2105    /// structs or variants. For example:
2106    ///
2107    /// ```text
2108    /// isize => { isize }
2109    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2110    /// [isize] => { [isize], isize }
2111    /// ```
2112    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2113        TypeWalker::new(self.into())
2114    }
2115}
2116
2117impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2118    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2119        self.split_last().unwrap().1
2120    }
2121
2122    fn output(self) -> Ty<'tcx> {
2123        *self.split_last().unwrap().0
2124    }
2125}
2126
2127impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2128    fn is_kw_underscore_lifetime(self) -> bool {
2129        self == kw::UnderscoreLifetime
2130    }
2131}
2132
2133// Some types are used a lot. Make sure they don't unintentionally get bigger.
2134#[cfg(target_pointer_width = "64")]
2135mod size_asserts {
2136    use rustc_data_structures::static_assert_size;
2137
2138    use super::*;
2139    // tidy-alphabetical-start
2140    const _: [(); 24] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 24);
2141    const _: [(); 48] =
    [(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 48);
2142    // tidy-alphabetical-end
2143}