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, NumScalableVectors, 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 AliasTyKind<'tcx> = ir::AliasTyKind<TyCtxt<'tcx>>;
39pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
40pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
41pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
42pub type TypingMode<'tcx> = ir::TypingMode<TyCtxt<'tcx>>;
43pub type Placeholder<'tcx, T> = ir::Placeholder<TyCtxt<'tcx>, T>;
44pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion<TyCtxt<'tcx>>;
45pub type PlaceholderType<'tcx> = ir::PlaceholderType<TyCtxt<'tcx>>;
46pub type PlaceholderConst<'tcx> = ir::PlaceholderConst<TyCtxt<'tcx>>;
47pub type BoundTy<'tcx> = ir::BoundTy<TyCtxt<'tcx>>;
48pub type BoundConst<'tcx> = ir::BoundConst<TyCtxt<'tcx>>;
49pub type BoundRegion<'tcx> = ir::BoundRegion<TyCtxt<'tcx>>;
50pub type BoundVariableKind<'tcx> = ir::BoundVariableKind<TyCtxt<'tcx>>;
51pub type BoundRegionKind<'tcx> = ir::BoundRegionKind<TyCtxt<'tcx>>;
52pub type BoundTyKind<'tcx> = ir::BoundTyKind<TyCtxt<'tcx>>;
53
54pub trait Article {
55    fn article(&self) -> &'static str;
56}
57
58impl<'tcx> Article for TyKind<'tcx> {
59    /// Get the article ("a" or "an") to use with this type.
60    fn article(&self) -> &'static str {
61        match self {
62            Int(_) | Float(_) | Array(_, _) => "an",
63            Adt(def, _) if def.is_enum() => "an",
64            // This should never happen, but ICEing and causing the user's code
65            // to not compile felt too harsh.
66            Error(_) => "a",
67            _ => "a",
68        }
69    }
70}
71
72impl<'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>)]
73impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
74    /// Coroutine has not been resumed yet.
75    const UNRESUMED: usize = 0;
76    /// Coroutine has returned or is completed.
77    const RETURNED: usize = 1;
78    /// Coroutine has been poisoned.
79    const POISONED: usize = 2;
80    /// Number of variants to reserve in coroutine state. Corresponds to
81    /// `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`
82    /// (end of a coroutine) states.
83    const RESERVED_VARIANTS: usize = 3;
84
85    const UNRESUMED_NAME: &'static str = "Unresumed";
86    const RETURNED_NAME: &'static str = "Returned";
87    const POISONED_NAME: &'static str = "Panicked";
88
89    /// The valid variant indices of this coroutine.
90    #[inline]
91    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
92        // FIXME requires optimized MIR
93        FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
94    }
95
96    /// The discriminant for the given variant. Panics if the `variant_index` is
97    /// out of range.
98    #[inline]
99    fn discriminant_for_variant(
100        &self,
101        def_id: DefId,
102        tcx: TyCtxt<'tcx>,
103        variant_index: VariantIdx,
104    ) -> Discr<'tcx> {
105        // Coroutines don't support explicit discriminant values, so they are
106        // the same as the variant index.
107        assert!(self.variant_range(def_id, tcx).contains(&variant_index));
108        Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
109    }
110
111    /// The set of all discriminants for the coroutine, enumerated with their
112    /// variant indices.
113    #[inline]
114    fn discriminants(
115        self,
116        def_id: DefId,
117        tcx: TyCtxt<'tcx>,
118    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
119        self.variant_range(def_id, tcx).map(move |index| {
120            (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
121        })
122    }
123
124    /// Calls `f` with a reference to the name of the enumerator for the given
125    /// variant `v`.
126    fn variant_name(v: VariantIdx) -> Cow<'static, str> {
127        match v.as_usize() {
128            Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
129            Self::RETURNED => Cow::from(Self::RETURNED_NAME),
130            Self::POISONED => Cow::from(Self::POISONED_NAME),
131            _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
132        }
133    }
134
135    /// The type of the state discriminant used in the coroutine type.
136    #[inline]
137    fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
138        tcx.types.u32
139    }
140
141    /// This returns the types of the MIR locals which had to be stored across suspension points.
142    /// It is calculated in rustc_mir_transform::coroutine::StateTransform.
143    /// All the types here must be in the tuple in CoroutineInterior.
144    ///
145    /// The locals are grouped by their variant number. Note that some locals may
146    /// be repeated in multiple variants.
147    #[inline]
148    fn state_tys(
149        self,
150        def_id: DefId,
151        tcx: TyCtxt<'tcx>,
152    ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
153        let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
154        layout.variant_fields.iter().map(move |variant| {
155            variant.iter().map(move |field| {
156                if tcx.is_async_drop_in_place_coroutine(def_id) {
157                    layout.field_tys[*field].ty
158                } else {
159                    ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args)
160                }
161            })
162        })
163    }
164
165    /// This is the types of the fields of a coroutine which are not stored in a
166    /// variant.
167    #[inline]
168    fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
169        self.upvar_tys()
170    }
171}
172
173#[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)]
174pub enum UpvarArgs<'tcx> {
175    Closure(GenericArgsRef<'tcx>),
176    Coroutine(GenericArgsRef<'tcx>),
177    CoroutineClosure(GenericArgsRef<'tcx>),
178}
179
180impl<'tcx> UpvarArgs<'tcx> {
181    /// Returns an iterator over the list of types of captured paths by the closure/coroutine.
182    /// In case there was a type error in figuring out the types of the captured path, an
183    /// empty iterator is returned.
184    #[inline]
185    pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
186        let tupled_tys = match self {
187            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
188            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
189            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
190        };
191
192        match tupled_tys.kind() {
193            TyKind::Error(_) => ty::List::empty(),
194            TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
195            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"),
196            ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
        ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
197        }
198    }
199
200    #[inline]
201    pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
202        match self {
203            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
204            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
205            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
206        }
207    }
208}
209
210/// An inline const is modeled like
211/// ```ignore (illustrative)
212/// const InlineConst<'l0...'li, T0...Tj, R>: R;
213/// ```
214/// where:
215///
216/// - 'l0...'li and T0...Tj are the generic parameters
217///   inherited from the item that defined the inline const,
218/// - R represents the type of the constant.
219///
220/// When the inline const is instantiated, `R` is instantiated as the actual inferred
221/// type of the constant. The reason that `R` is represented as an extra type parameter
222/// is the same reason that [`ty::ClosureArgs`] have `CS` and `U` as type parameters:
223/// inline const can reference lifetimes that are internal to the creating function.
224#[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)]
225pub struct InlineConstArgs<'tcx> {
226    /// Generic parameters from the enclosing item,
227    /// concatenated with the inferred type of the constant.
228    pub args: GenericArgsRef<'tcx>,
229}
230
231/// Struct returned by `split()`.
232pub struct InlineConstArgsParts<'tcx, T> {
233    pub parent_args: &'tcx [GenericArg<'tcx>],
234    pub ty: T,
235}
236
237impl<'tcx> InlineConstArgs<'tcx> {
238    /// Construct `InlineConstArgs` from `InlineConstArgsParts`.
239    pub fn new(
240        tcx: TyCtxt<'tcx>,
241        parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
242    ) -> InlineConstArgs<'tcx> {
243        InlineConstArgs {
244            args: tcx.mk_args_from_iter(
245                parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
246            ),
247        }
248    }
249
250    /// Divides the inline const args into their respective components.
251    /// The ordering assumed here must match that used by `InlineConstArgs::new` above.
252    fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
253        match self.args[..] {
254            [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
255            _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
256        }
257    }
258
259    /// Returns the generic parameters of the inline const's parent.
260    pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
261        self.split().parent_args
262    }
263
264    /// Returns the type of this inline const.
265    pub fn ty(self) -> Ty<'tcx> {
266        self.split().ty.expect_ty()
267    }
268}
269
270pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
271pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
272
273#[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)]
274#[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)]
275pub struct ParamTy {
276    pub index: u32,
277    pub name: Symbol,
278}
279
280impl rustc_type_ir::inherent::ParamLike for ParamTy {
281    fn index(self) -> u32 {
282        self.index
283    }
284}
285
286impl<'tcx> ParamTy {
287    pub fn new(index: u32, name: Symbol) -> ParamTy {
288        ParamTy { index, name }
289    }
290
291    pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
292        ParamTy::new(def.index, def.name)
293    }
294
295    #[inline]
296    pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
297        Ty::new_param(tcx, self.index, self.name)
298    }
299
300    pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
301        let generics = tcx.generics_of(item_with_generics);
302        let type_param = generics.type_param(self, tcx);
303        tcx.def_span(type_param.def_id)
304    }
305}
306
307#[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)]
308#[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)]
309pub struct ParamConst {
310    pub index: u32,
311    pub name: Symbol,
312}
313
314impl rustc_type_ir::inherent::ParamLike for ParamConst {
315    fn index(self) -> u32 {
316        self.index
317    }
318}
319
320impl ParamConst {
321    pub fn new(index: u32, name: Symbol) -> ParamConst {
322        ParamConst { index, name }
323    }
324
325    pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
326        ParamConst::new(def.index, def.name)
327    }
328
329    #[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(329u32),
                                    ::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")]
330    pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
331        let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
332            // `ConstArgHasType` are never desugared to be higher ranked.
333            match clause.kind().skip_binder() {
334                ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
335                    assert!(!(param_ct, ty).has_escaping_bound_vars());
336
337                    match param_ct.kind() {
338                        ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
339                        _ => None,
340                    }
341                }
342                _ => None,
343            }
344        });
345
346        // N.B. it may be tempting to fix ICEs by making this function return
347        // `Option<Ty<'tcx>>` instead of `Ty<'tcx>`; however, this is generally
348        // considered to be a bandaid solution, since it hides more important
349        // underlying issues with how we construct generics and predicates of
350        // items. It's advised to fix the underlying issue rather than trying
351        // to modify this function.
352        let ty = candidates.next().unwrap_or_else(|| {
353            bug!("cannot find `{self:?}` in param-env: {env:#?}");
354        });
355        assert!(
356            candidates.next().is_none(),
357            "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
358        );
359        ty
360    }
361}
362
363/// Constructors for `Ty`
364impl<'tcx> Ty<'tcx> {
365    /// Avoid using this in favour of more specific `new_*` methods, where possible.
366    /// The more specific methods will often optimize their creation.
367    #[allow(rustc::usage_of_ty_tykind)]
368    #[inline]
369    fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
370        tcx.mk_ty_from_kind(st)
371    }
372
373    #[inline]
374    pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
375        Ty::new(tcx, TyKind::Infer(infer))
376    }
377
378    #[inline]
379    pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
380        // Use a pre-interned one when possible.
381        tcx.types
382            .ty_vars
383            .get(v.as_usize())
384            .copied()
385            .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
386    }
387
388    #[inline]
389    pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
390        Ty::new_infer(tcx, IntVar(v))
391    }
392
393    #[inline]
394    pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
395        Ty::new_infer(tcx, FloatVar(v))
396    }
397
398    #[inline]
399    pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
400        // Use a pre-interned one when possible.
401        tcx.types
402            .fresh_tys
403            .get(n as usize)
404            .copied()
405            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
406    }
407
408    #[inline]
409    pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
410        // Use a pre-interned one when possible.
411        tcx.types
412            .fresh_int_tys
413            .get(n as usize)
414            .copied()
415            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
416    }
417
418    #[inline]
419    pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
420        // Use a pre-interned one when possible.
421        tcx.types
422            .fresh_float_tys
423            .get(n as usize)
424            .copied()
425            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
426    }
427
428    #[inline]
429    pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
430        Ty::new(tcx, Param(ParamTy { index, name }))
431    }
432
433    #[inline]
434    pub fn new_bound(
435        tcx: TyCtxt<'tcx>,
436        index: ty::DebruijnIndex,
437        bound_ty: ty::BoundTy<'tcx>,
438    ) -> Ty<'tcx> {
439        // Use a pre-interned one when possible.
440        if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
441            && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
442            && let Some(ty) = inner.get(var.as_usize()).copied()
443        {
444            ty
445        } else {
446            Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
447        }
448    }
449
450    #[inline]
451    pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
452        // Use a pre-interned one when possible.
453        if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
454            ty
455        } else {
456            Ty::new(
457                tcx,
458                Bound(
459                    ty::BoundVarIndexKind::Canonical,
460                    ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
461                ),
462            )
463        }
464    }
465
466    #[inline]
467    pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
468        Ty::new(tcx, Placeholder(placeholder))
469    }
470
471    #[inline]
472    pub fn new_alias(tcx: TyCtxt<'tcx>, alias_ty: ty::AliasTy<'tcx>) -> Ty<'tcx> {
473        if true {
    match (alias_ty.kind, tcx.def_kind(alias_ty.kind.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!(
474            (alias_ty.kind, tcx.def_kind(alias_ty.kind.def_id())),
475            (ty::Opaque { .. }, DefKind::OpaqueTy)
476                | (ty::Projection { .. } | ty::Inherent { .. }, DefKind::AssocTy)
477                | (ty::Free { .. }, DefKind::TyAlias)
478        );
479        Ty::new(tcx, Alias(alias_ty))
480    }
481
482    #[inline]
483    pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
484        Ty::new(tcx, Pat(base, pat))
485    }
486
487    #[inline]
488    pub fn new_field_representing_type(
489        tcx: TyCtxt<'tcx>,
490        base: Ty<'tcx>,
491        variant: VariantIdx,
492        field: FieldIdx,
493    ) -> Ty<'tcx> {
494        let Some(did) = tcx.lang_items().field_representing_type() else {
495            crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
496        };
497        let def = tcx.adt_def(did);
498        let args = tcx.mk_args(&[
499            base.into(),
500            Const::new_value(
501                tcx,
502                ValTree::from_scalar_int(tcx, variant.as_u32().into()),
503                tcx.types.u32,
504            )
505            .into(),
506            Const::new_value(
507                tcx,
508                ValTree::from_scalar_int(tcx, field.as_u32().into()),
509                tcx.types.u32,
510            )
511            .into(),
512        ]);
513        Ty::new_adt(tcx, def, args)
514    }
515
516    #[inline]
517    #[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(517u32),
                                    ::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,
                AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
518    pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
519        Ty::new_alias(tcx, AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
520    }
521
522    /// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
523    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
524        Ty::new(tcx, Error(guar))
525    }
526
527    /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` to ensure it gets used.
528    #[track_caller]
529    pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
530        Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
531    }
532
533    /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` with the given `msg` to
534    /// ensure it gets used.
535    #[track_caller]
536    pub fn new_error_with_message<S: Into<MultiSpan>>(
537        tcx: TyCtxt<'tcx>,
538        span: S,
539        msg: impl Into<Cow<'static, str>>,
540    ) -> Ty<'tcx> {
541        let reported = tcx.dcx().span_delayed_bug(span, msg);
542        Ty::new(tcx, Error(reported))
543    }
544
545    #[inline]
546    pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
547        use ty::IntTy::*;
548        match i {
549            Isize => tcx.types.isize,
550            I8 => tcx.types.i8,
551            I16 => tcx.types.i16,
552            I32 => tcx.types.i32,
553            I64 => tcx.types.i64,
554            I128 => tcx.types.i128,
555        }
556    }
557
558    #[inline]
559    pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
560        use ty::UintTy::*;
561        match ui {
562            Usize => tcx.types.usize,
563            U8 => tcx.types.u8,
564            U16 => tcx.types.u16,
565            U32 => tcx.types.u32,
566            U64 => tcx.types.u64,
567            U128 => tcx.types.u128,
568        }
569    }
570
571    #[inline]
572    pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
573        use ty::FloatTy::*;
574        match f {
575            F16 => tcx.types.f16,
576            F32 => tcx.types.f32,
577            F64 => tcx.types.f64,
578            F128 => tcx.types.f128,
579        }
580    }
581
582    #[inline]
583    pub fn new_ref(
584        tcx: TyCtxt<'tcx>,
585        r: Region<'tcx>,
586        ty: Ty<'tcx>,
587        mutbl: ty::Mutability,
588    ) -> Ty<'tcx> {
589        Ty::new(tcx, Ref(r, ty, mutbl))
590    }
591
592    #[inline]
593    pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
594        Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
595    }
596
597    #[inline]
598    pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
599        Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
600    }
601
602    pub fn new_pinned_ref(
603        tcx: TyCtxt<'tcx>,
604        r: Region<'tcx>,
605        ty: Ty<'tcx>,
606        mutbl: ty::Mutability,
607    ) -> Ty<'tcx> {
608        let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
609        Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
610    }
611
612    #[inline]
613    pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
614        Ty::new(tcx, ty::RawPtr(ty, mutbl))
615    }
616
617    #[inline]
618    pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
619        Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
620    }
621
622    #[inline]
623    pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
624        Ty::new_ptr(tcx, ty, hir::Mutability::Not)
625    }
626
627    #[inline]
628    pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
629        tcx.debug_assert_args_compatible(def.did(), args);
630        if truecfg!(debug_assertions) {
631            match tcx.def_kind(def.did()) {
632                DefKind::Struct | DefKind::Union | DefKind::Enum => {}
633                DefKind::Mod
634                | DefKind::Variant
635                | DefKind::Trait
636                | DefKind::TyAlias
637                | DefKind::ForeignTy
638                | DefKind::TraitAlias
639                | DefKind::AssocTy
640                | DefKind::TyParam
641                | DefKind::Fn
642                | DefKind::Const { .. }
643                | DefKind::ConstParam
644                | DefKind::Static { .. }
645                | DefKind::Ctor(..)
646                | DefKind::AssocFn
647                | DefKind::AssocConst { .. }
648                | DefKind::Macro(..)
649                | DefKind::ExternCrate
650                | DefKind::Use
651                | DefKind::ForeignMod
652                | DefKind::AnonConst
653                | DefKind::InlineConst
654                | DefKind::OpaqueTy
655                | DefKind::Field
656                | DefKind::LifetimeParam
657                | DefKind::GlobalAsm
658                | DefKind::Impl { .. }
659                | DefKind::Closure
660                | DefKind::SyntheticCoroutineBody => {
661                    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()))
662                }
663            }
664        }
665        Ty::new(tcx, Adt(def, args))
666    }
667
668    #[inline]
669    pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
670        Ty::new(tcx, Foreign(def_id))
671    }
672
673    #[inline]
674    pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
675        Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
676    }
677
678    #[inline]
679    pub fn new_array_with_const_len(
680        tcx: TyCtxt<'tcx>,
681        ty: Ty<'tcx>,
682        ct: ty::Const<'tcx>,
683    ) -> Ty<'tcx> {
684        Ty::new(tcx, Array(ty, ct))
685    }
686
687    #[inline]
688    pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
689        Ty::new(tcx, Slice(ty))
690    }
691
692    #[inline]
693    pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
694        if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
695    }
696
697    pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
698    where
699        I: Iterator<Item = T>,
700        T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
701    {
702        T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
703    }
704
705    #[inline]
706    pub fn new_fn_def(
707        tcx: TyCtxt<'tcx>,
708        def_id: DefId,
709        args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
710    ) -> Ty<'tcx> {
711        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!(
712            tcx.def_kind(def_id),
713            DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
714        );
715        let args = tcx.check_and_mk_args(def_id, args);
716        Ty::new(tcx, FnDef(def_id, args))
717    }
718
719    #[inline]
720    pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
721        let (sig_tys, hdr) = fty.split();
722        Ty::new(tcx, FnPtr(sig_tys, hdr))
723    }
724
725    #[inline]
726    pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
727        Ty::new(tcx, UnsafeBinder(b.into()))
728    }
729
730    #[inline]
731    pub fn new_dynamic(
732        tcx: TyCtxt<'tcx>,
733        obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
734        reg: ty::Region<'tcx>,
735    ) -> Ty<'tcx> {
736        if truecfg!(debug_assertions) {
737            let projection_count = obj
738                .projection_bounds()
739                .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
740                .count();
741            let expected_count: usize = obj
742                .principal_def_id()
743                .into_iter()
744                .flat_map(|principal_def_id| {
745                    // IMPORTANT: This has to agree with HIR ty lowering of dyn trait!
746                    elaborate::supertraits(
747                        tcx,
748                        ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
749                    )
750                    .map(|principal| {
751                        tcx.associated_items(principal.def_id())
752                            .in_definition_order()
753                            .filter(|item| item.is_type() || item.is_type_const())
754                            .filter(|item| !item.is_impl_trait_in_trait())
755                            .filter(|item| !tcx.generics_require_sized_self(item.def_id))
756                            .count()
757                    })
758                })
759                .sum();
760            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!(
761                projection_count, expected_count,
762                "expected {obj:?} to have {expected_count} projections, \
763                but it has {projection_count}"
764            );
765        }
766        Ty::new(tcx, Dynamic(obj, reg))
767    }
768
769    #[inline]
770    pub fn new_projection_from_args(
771        tcx: TyCtxt<'tcx>,
772        item_def_id: DefId,
773        args: ty::GenericArgsRef<'tcx>,
774    ) -> Ty<'tcx> {
775        Ty::new_alias(
776            tcx,
777            AliasTy::new_from_args(tcx, ty::Projection { def_id: item_def_id }, args),
778        )
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, AliasTy::new(tcx, ty::Projection { def_id: 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(interner: TyCtxt<'tcx>, alias_ty: ty::AliasTy<'tcx>) -> Self {
964        Ty::new_alias(interner, alias_ty)
965    }
966
967    fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
968        Ty::new_error(interner, guar)
969    }
970
971    fn new_adt(
972        interner: TyCtxt<'tcx>,
973        adt_def: ty::AdtDef<'tcx>,
974        args: ty::GenericArgsRef<'tcx>,
975    ) -> Self {
976        Ty::new_adt(interner, adt_def, args)
977    }
978
979    fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
980        Ty::new_foreign(interner, def_id)
981    }
982
983    fn new_dynamic(
984        interner: TyCtxt<'tcx>,
985        preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
986        region: ty::Region<'tcx>,
987    ) -> Self {
988        Ty::new_dynamic(interner, preds, region)
989    }
990
991    fn new_coroutine(
992        interner: TyCtxt<'tcx>,
993        def_id: DefId,
994        args: ty::GenericArgsRef<'tcx>,
995    ) -> Self {
996        Ty::new_coroutine(interner, def_id, args)
997    }
998
999    fn new_coroutine_closure(
1000        interner: TyCtxt<'tcx>,
1001        def_id: DefId,
1002        args: ty::GenericArgsRef<'tcx>,
1003    ) -> Self {
1004        Ty::new_coroutine_closure(interner, def_id, args)
1005    }
1006
1007    fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1008        Ty::new_closure(interner, def_id, args)
1009    }
1010
1011    fn new_coroutine_witness(
1012        interner: TyCtxt<'tcx>,
1013        def_id: DefId,
1014        args: ty::GenericArgsRef<'tcx>,
1015    ) -> Self {
1016        Ty::new_coroutine_witness(interner, def_id, args)
1017    }
1018
1019    fn new_coroutine_witness_for_coroutine(
1020        interner: TyCtxt<'tcx>,
1021        def_id: DefId,
1022        coroutine_args: ty::GenericArgsRef<'tcx>,
1023    ) -> Self {
1024        Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1025    }
1026
1027    fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1028        Ty::new_ptr(interner, ty, mutbl)
1029    }
1030
1031    fn new_ref(
1032        interner: TyCtxt<'tcx>,
1033        region: ty::Region<'tcx>,
1034        ty: Self,
1035        mutbl: hir::Mutability,
1036    ) -> Self {
1037        Ty::new_ref(interner, region, ty, mutbl)
1038    }
1039
1040    fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1041        Ty::new_array_with_const_len(interner, ty, len)
1042    }
1043
1044    fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1045        Ty::new_slice(interner, ty)
1046    }
1047
1048    fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1049        Ty::new_tup(interner, tys)
1050    }
1051
1052    fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1053    where
1054        It: Iterator<Item = T>,
1055        T: CollectAndApply<Self, Self>,
1056    {
1057        Ty::new_tup_from_iter(interner, iter)
1058    }
1059
1060    fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1061        self.tuple_fields()
1062    }
1063
1064    fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1065        self.to_opt_closure_kind()
1066    }
1067
1068    fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1069        Ty::from_closure_kind(interner, kind)
1070    }
1071
1072    fn from_coroutine_closure_kind(
1073        interner: TyCtxt<'tcx>,
1074        kind: rustc_type_ir::ClosureKind,
1075    ) -> Self {
1076        Ty::from_coroutine_closure_kind(interner, kind)
1077    }
1078
1079    fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1080        Ty::new_fn_def(interner, def_id, args)
1081    }
1082
1083    fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1084        Ty::new_fn_ptr(interner, sig)
1085    }
1086
1087    fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1088        Ty::new_pat(interner, ty, pat)
1089    }
1090
1091    fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1092        Ty::new_unsafe_binder(interner, ty)
1093    }
1094
1095    fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1096        interner.types.unit
1097    }
1098
1099    fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1100        interner.types.usize
1101    }
1102
1103    fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1104        self.discriminant_ty(interner)
1105    }
1106
1107    fn has_unsafe_fields(self) -> bool {
1108        Ty::has_unsafe_fields(self)
1109    }
1110}
1111
1112/// Type utilities
1113impl<'tcx> Ty<'tcx> {
1114    // It would be nicer if this returned the value instead of a reference,
1115    // like how `Predicate::kind` and `Region::kind` do. (It would result in
1116    // many fewer subsequent dereferences.) But that gives a small but
1117    // noticeable performance hit. See #126069 for details.
1118    #[inline(always)]
1119    pub fn kind(self) -> &'tcx TyKind<'tcx> {
1120        self.0.0
1121    }
1122
1123    // FIXME(compiler-errors): Think about removing this.
1124    #[inline(always)]
1125    pub fn flags(self) -> TypeFlags {
1126        self.0.0.flags
1127    }
1128
1129    #[inline]
1130    pub fn is_unit(self) -> bool {
1131        match self.kind() {
1132            Tuple(tys) => tys.is_empty(),
1133            _ => false,
1134        }
1135    }
1136
1137    /// Check if type is an `usize`.
1138    #[inline]
1139    pub fn is_usize(self) -> bool {
1140        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1141    }
1142
1143    /// Check if type is an `usize` or an integral type variable.
1144    #[inline]
1145    pub fn is_usize_like(self) -> bool {
1146        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1147    }
1148
1149    #[inline]
1150    pub fn is_never(self) -> bool {
1151        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Never => true,
    _ => false,
}matches!(self.kind(), Never)
1152    }
1153
1154    #[inline]
1155    pub fn is_primitive(self) -> bool {
1156        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Uint(_) | Float(_) => true,
    _ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1157    }
1158
1159    #[inline]
1160    pub fn is_adt(self) -> bool {
1161        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(..) => true,
    _ => false,
}matches!(self.kind(), Adt(..))
1162    }
1163
1164    #[inline]
1165    pub fn is_ref(self) -> bool {
1166        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Ref(..) => true,
    _ => false,
}matches!(self.kind(), Ref(..))
1167    }
1168
1169    #[inline]
1170    pub fn is_ty_var(self) -> bool {
1171        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(TyVar(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1172    }
1173
1174    #[inline]
1175    pub fn ty_vid(self) -> Option<ty::TyVid> {
1176        match self.kind() {
1177            &Infer(TyVar(vid)) => Some(vid),
1178            _ => None,
1179        }
1180    }
1181
1182    #[inline]
1183    pub fn is_ty_or_numeric_infer(self) -> bool {
1184        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(_) => true,
    _ => false,
}matches!(self.kind(), Infer(_))
1185    }
1186
1187    #[inline]
1188    pub fn is_phantom_data(self) -> bool {
1189        if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1190    }
1191
1192    #[inline]
1193    pub fn is_bool(self) -> bool {
1194        *self.kind() == Bool
1195    }
1196
1197    /// Returns `true` if this type is a `str`.
1198    #[inline]
1199    pub fn is_str(self) -> bool {
1200        *self.kind() == Str
1201    }
1202
1203    /// Returns true if this type is `&str`. The reference's lifetime is ignored.
1204    #[inline]
1205    pub fn is_imm_ref_str(self) -> bool {
1206        #[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())
1207    }
1208
1209    #[inline]
1210    pub fn is_param(self, index: u32) -> bool {
1211        match self.kind() {
1212            ty::Param(data) => data.index == index,
1213            _ => false,
1214        }
1215    }
1216
1217    #[inline]
1218    pub fn is_slice(self) -> bool {
1219        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Slice(_) => true,
    _ => false,
}matches!(self.kind(), Slice(_))
1220    }
1221
1222    #[inline]
1223    pub fn is_array_slice(self) -> bool {
1224        match self.kind() {
1225            Slice(_) => true,
1226            ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    Slice(_) => true,
    _ => false,
}matches!(ty.kind(), Slice(_)),
1227            _ => false,
1228        }
1229    }
1230
1231    #[inline]
1232    pub fn is_array(self) -> bool {
1233        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Array(..) => true,
    _ => false,
}matches!(self.kind(), Array(..))
1234    }
1235
1236    #[inline]
1237    pub fn is_simd(self) -> bool {
1238        match self.kind() {
1239            Adt(def, _) => def.repr().simd(),
1240            _ => false,
1241        }
1242    }
1243
1244    #[inline]
1245    pub fn is_scalable_vector(self) -> bool {
1246        match self.kind() {
1247            Adt(def, _) => def.repr().scalable(),
1248            _ => false,
1249        }
1250    }
1251
1252    pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1253        match self.kind() {
1254            Array(ty, _) | Slice(ty) => *ty,
1255            Str => tcx.types.u8,
1256            _ => 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),
1257        }
1258    }
1259
1260    pub fn scalable_vector_parts(
1261        self,
1262        tcx: TyCtxt<'tcx>,
1263    ) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
1264        let Adt(def, args) = self.kind() else {
1265            return None;
1266        };
1267        let (num_vectors, vec_def) = match def.repr().scalable? {
1268            ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1269            ScalableElt::Container => (
1270                NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1271                def.non_enum_variant().fields[FieldIdx::ZERO].ty(tcx, args).ty_adt_def()?,
1272            ),
1273        };
1274        let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1275            return None;
1276        };
1277        let variant = vec_def.non_enum_variant();
1278        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);
1279        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1280        Some((element_count, field_ty, num_vectors))
1281    }
1282
1283    pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1284        let Adt(def, args) = self.kind() else {
1285            crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1286        };
1287        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");
1288        let variant = def.non_enum_variant();
1289        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);
1290        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1291        let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1292            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:?}")
1293        };
1294        // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1295        // The way we evaluate the `N` in `[T; N]` here only works since we use
1296        // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1297        // if we use it in generic code. See the `simd-array-trait` ui test.
1298        (
1299            f0_len
1300                .try_to_target_usize(tcx)
1301                .expect("expected SIMD field to have definite array size"),
1302            *f0_elem_ty,
1303        )
1304    }
1305
1306    #[inline]
1307    pub fn is_mutable_ptr(self) -> bool {
1308        #[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))
1309    }
1310
1311    /// Get the mutability of the reference or `None` when not a reference
1312    #[inline]
1313    pub fn ref_mutability(self) -> Option<hir::Mutability> {
1314        match self.kind() {
1315            Ref(_, _, mutability) => Some(*mutability),
1316            _ => None,
1317        }
1318    }
1319
1320    #[inline]
1321    pub fn is_raw_ptr(self) -> bool {
1322        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RawPtr(_, _) => true,
    _ => false,
}matches!(self.kind(), RawPtr(_, _))
1323    }
1324
1325    /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1326    /// `Box` is *not* considered a pointer here!
1327    #[inline]
1328    pub fn is_any_ptr(self) -> bool {
1329        self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1330    }
1331
1332    #[inline]
1333    pub fn is_box(self) -> bool {
1334        match self.kind() {
1335            Adt(def, _) => def.is_box(),
1336            _ => false,
1337        }
1338    }
1339
1340    /// Tests whether this is a Box definitely using the global allocator.
1341    ///
1342    /// If the allocator is still generic, the answer is `false`, but it may
1343    /// later turn out that it does use the global allocator.
1344    #[inline]
1345    pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1346        match self.kind() {
1347            Adt(def, args) if def.is_box() => {
1348                let Some(alloc) = args.get(1) else {
1349                    // Single-argument Box is always global. (for "minicore" tests)
1350                    return true;
1351                };
1352                alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1353                    tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1354                })
1355            }
1356            _ => false,
1357        }
1358    }
1359
1360    pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1361        match self.kind() {
1362            Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1363            _ => None,
1364        }
1365    }
1366
1367    pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1368        match self.kind() {
1369            Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1370            _ => None,
1371        }
1372    }
1373
1374    /// Returns the type, pinnedness, mutability, and the region of a reference (`&T` or `&mut T`)
1375    /// or a pinned-reference type (`Pin<&T>` or `Pin<&mut T>`).
1376    ///
1377    /// Regarding the [`pin_ergonomics`] feature, one of the goals is to make pinned references
1378    /// (`Pin<&T>` and `Pin<&mut T>`) behaves similar to normal references (`&T` and `&mut T`).
1379    /// This function is useful when references and pinned references are processed similarly.
1380    ///
1381    /// [`pin_ergonomics`]: https://github.com/rust-lang/rust/issues/130494
1382    pub fn maybe_pinned_ref(
1383        self,
1384    ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1385        match self.kind() {
1386            Adt(def, args)
1387                if def.is_pin()
1388                    && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1389            {
1390                Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1391            }
1392            &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1393            _ => None,
1394        }
1395    }
1396
1397    /// Panics if called on any type other than `Box<T>`.
1398    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1399        self.boxed_ty()
1400            .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))
1401    }
1402
1403    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1404    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1405    /// contents are abstract to rustc.)
1406    #[inline]
1407    pub fn is_scalar(self) -> bool {
1408        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
        RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
    _ => false,
}matches!(
1409            self.kind(),
1410            Bool | Char
1411                | Int(_)
1412                | Float(_)
1413                | Uint(_)
1414                | FnDef(..)
1415                | FnPtr(..)
1416                | RawPtr(_, _)
1417                | Infer(IntVar(_) | FloatVar(_))
1418        )
1419    }
1420
1421    /// Returns `true` if this type is a floating point type.
1422    #[inline]
1423    pub fn is_floating_point(self) -> bool {
1424        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Float(_) | Infer(FloatVar(_)) => true,
    _ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1425    }
1426
1427    #[inline]
1428    pub fn is_trait(self) -> bool {
1429        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Dynamic(_, _) => true,
    _ => false,
}matches!(self.kind(), Dynamic(_, _))
1430    }
1431
1432    #[inline]
1433    pub fn is_enum(self) -> bool {
1434        #[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())
1435    }
1436
1437    #[inline]
1438    pub fn is_union(self) -> bool {
1439        #[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())
1440    }
1441
1442    #[inline]
1443    pub fn is_closure(self) -> bool {
1444        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Closure(..) => true,
    _ => false,
}matches!(self.kind(), Closure(..))
1445    }
1446
1447    #[inline]
1448    pub fn is_coroutine(self) -> bool {
1449        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Coroutine(..) => true,
    _ => false,
}matches!(self.kind(), Coroutine(..))
1450    }
1451
1452    #[inline]
1453    pub fn is_coroutine_closure(self) -> bool {
1454        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    CoroutineClosure(..) => true,
    _ => false,
}matches!(self.kind(), CoroutineClosure(..))
1455    }
1456
1457    #[inline]
1458    pub fn is_integral(self) -> bool {
1459        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(IntVar(_)) | Int(_) | Uint(_) => true,
    _ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1460    }
1461
1462    #[inline]
1463    pub fn is_fresh_ty(self) -> bool {
1464        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1465    }
1466
1467    #[inline]
1468    pub fn is_fresh(self) -> bool {
1469        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1470    }
1471
1472    #[inline]
1473    pub fn is_char(self) -> bool {
1474        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Char => true,
    _ => false,
}matches!(self.kind(), Char)
1475    }
1476
1477    #[inline]
1478    pub fn is_numeric(self) -> bool {
1479        self.is_integral() || self.is_floating_point()
1480    }
1481
1482    #[inline]
1483    pub fn is_signed(self) -> bool {
1484        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Int(_) => true,
    _ => false,
}matches!(self.kind(), Int(_))
1485    }
1486
1487    #[inline]
1488    pub fn is_ptr_sized_integral(self) -> bool {
1489        #[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))
1490    }
1491
1492    #[inline]
1493    pub fn has_concrete_skeleton(self) -> bool {
1494        !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Param(_) | Infer(_) | Error(_) => true,
    _ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1495    }
1496
1497    /// Checks whether a type recursively contains another type
1498    ///
1499    /// Example: `Option<()>` contains `()`
1500    pub fn contains(self, other: Ty<'tcx>) -> bool {
1501        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1502
1503        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1504            type Result = ControlFlow<()>;
1505
1506            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1507                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1508            }
1509        }
1510
1511        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1512        cf.is_break()
1513    }
1514
1515    /// Checks whether a type recursively contains any closure
1516    ///
1517    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1518    pub fn contains_closure(self) -> bool {
1519        struct ContainsClosureVisitor;
1520
1521        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1522            type Result = ControlFlow<()>;
1523
1524            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1525                if let ty::Closure(..) = t.kind() {
1526                    ControlFlow::Break(())
1527                } else {
1528                    t.super_visit_with(self)
1529                }
1530            }
1531        }
1532
1533        let cf = self.visit_with(&mut ContainsClosureVisitor);
1534        cf.is_break()
1535    }
1536
1537    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1538    ///
1539    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1540    /// to call async drop poll from impl coroutine.
1541    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1542        self,
1543        tcx: TyCtxt<'tcx>,
1544        mut f: F,
1545    ) -> Ty<'tcx> {
1546        if !self.is_coroutine() {
    ::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1547        let mut cor_ty = self;
1548        let mut ty = cor_ty;
1549        loop {
1550            let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1551            cor_ty = ty;
1552            f(ty);
1553            if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1554                return cor_ty;
1555            }
1556            ty = args.first().unwrap().expect_ty();
1557        }
1558    }
1559
1560    /// Returns the type of `*ty`.
1561    ///
1562    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1563    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1564    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1565        match *self.kind() {
1566            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1567            Ref(_, ty, _) => Some(ty),
1568            RawPtr(ty, _) if explicit => Some(ty),
1569            _ => None,
1570        }
1571    }
1572
1573    /// Returns the type of `ty[i]`.
1574    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1575        match self.kind() {
1576            Array(ty, _) | Slice(ty) => Some(*ty),
1577            _ => None,
1578        }
1579    }
1580
1581    #[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(1581u32),
                                    ::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))]
1582    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1583        self.kind().fn_sig(tcx)
1584    }
1585
1586    #[inline]
1587    pub fn is_fn(self) -> bool {
1588        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnDef(..) | FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1589    }
1590
1591    #[inline]
1592    pub fn is_fn_ptr(self) -> bool {
1593        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnPtr(..))
1594    }
1595
1596    #[inline]
1597    pub fn is_opaque(self) -> bool {
1598        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => true,
    _ => false,
}matches!(self.kind(), Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }))
1599    }
1600
1601    #[inline]
1602    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1603        match self.kind() {
1604            Adt(adt, _) => Some(*adt),
1605            _ => None,
1606        }
1607    }
1608
1609    /// Returns a list of tuple type arguments.
1610    ///
1611    /// Panics when called on anything but a tuple.
1612    #[inline]
1613    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1614        match self.kind() {
1615            Tuple(args) => args,
1616            _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
        self))bug!("tuple_fields called on non-tuple: {self:?}"),
1617        }
1618    }
1619
1620    /// Returns a list of tuple type arguments, or `None` if `self` isn't a tuple.
1621    #[inline]
1622    pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1623        match self.kind() {
1624            Tuple(args) => Some(args),
1625            _ => None,
1626        }
1627    }
1628
1629    /// If the type contains variants, returns the valid range of variant indices.
1630    //
1631    // FIXME: This requires the optimized MIR in the case of coroutines.
1632    #[inline]
1633    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1634        match self.kind() {
1635            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1636            TyKind::Coroutine(def_id, args) => {
1637                Some(args.as_coroutine().variant_range(*def_id, tcx))
1638            }
1639            TyKind::UnsafeBinder(bound_ty) => {
1640                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1641            }
1642            _ => None,
1643        }
1644    }
1645
1646    /// If the type contains variants, returns the variant for `variant_index`.
1647    /// Panics if `variant_index` is out of range.
1648    //
1649    // FIXME: This requires the optimized MIR in the case of coroutines.
1650    #[inline]
1651    pub fn discriminant_for_variant(
1652        self,
1653        tcx: TyCtxt<'tcx>,
1654        variant_index: VariantIdx,
1655    ) -> Option<Discr<'tcx>> {
1656        match self.kind() {
1657            TyKind::Adt(adt, _) if adt.is_enum() => {
1658                Some(adt.discriminant_for_variant(tcx, variant_index))
1659            }
1660            TyKind::Coroutine(def_id, args) => {
1661                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1662            }
1663            TyKind::UnsafeBinder(bound_ty) => tcx
1664                .instantiate_bound_regions_with_erased((*bound_ty).into())
1665                .discriminant_for_variant(tcx, variant_index),
1666            _ => None,
1667        }
1668    }
1669
1670    /// Returns the type of the discriminant of this type.
1671    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1672        match self.kind() {
1673            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1674            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1675
1676            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1677                let assoc_items = tcx.associated_item_def_ids(
1678                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1679                );
1680                Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1681            }
1682
1683            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1684            ty::UnsafeBinder(bound_ty) => {
1685                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1686            }
1687
1688            ty::Bool
1689            | ty::Char
1690            | ty::Int(_)
1691            | ty::Uint(_)
1692            | ty::Float(_)
1693            | ty::Adt(..)
1694            | ty::Foreign(_)
1695            | ty::Str
1696            | ty::Array(..)
1697            | ty::Slice(_)
1698            | ty::RawPtr(_, _)
1699            | ty::Ref(..)
1700            | ty::FnDef(..)
1701            | ty::FnPtr(..)
1702            | ty::Dynamic(..)
1703            | ty::Closure(..)
1704            | ty::CoroutineClosure(..)
1705            | ty::CoroutineWitness(..)
1706            | ty::Never
1707            | ty::Tuple(_)
1708            | ty::Error(_)
1709            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1710
1711            ty::Bound(..)
1712            | ty::Placeholder(_)
1713            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1714                crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
        self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1715            }
1716        }
1717    }
1718
1719    /// Returns the type of metadata for (potentially wide) pointers to this type,
1720    /// or the struct tail if the metadata type cannot be determined.
1721    pub fn ptr_metadata_ty_or_tail(
1722        self,
1723        tcx: TyCtxt<'tcx>,
1724        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1725    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1726        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1727        match tail.kind() {
1728            // Sized types
1729            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1730            | ty::Uint(_)
1731            | ty::Int(_)
1732            | ty::Bool
1733            | ty::Float(_)
1734            | ty::FnDef(..)
1735            | ty::FnPtr(..)
1736            | ty::RawPtr(..)
1737            | ty::Char
1738            | ty::Ref(..)
1739            | ty::Coroutine(..)
1740            | ty::CoroutineWitness(..)
1741            | ty::Array(..)
1742            | ty::Closure(..)
1743            | ty::CoroutineClosure(..)
1744            | ty::Never
1745            | ty::Error(_)
1746            // Extern types have metadata = ().
1747            | ty::Foreign(..)
1748            // If returned by `struct_tail_raw` this is a unit struct
1749            // without any fields, or not a struct, and therefore is Sized.
1750            | ty::Adt(..)
1751            // If returned by `struct_tail_raw` this is the empty tuple,
1752            // a.k.a. unit type, which is Sized
1753            | ty::Tuple(..) => Ok(tcx.types.unit),
1754
1755            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1756
1757            ty::Dynamic(_, _) => {
1758                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1759                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1760            }
1761
1762            // We don't know the metadata of `self`, but it must be equal to the
1763            // metadata of `tail`.
1764            ty::Param(_) | ty::Alias(..) => Err(tail),
1765
1766            | ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
1767
1768            ty::Infer(ty::TyVar(_))
1769            | ty::Pat(..)
1770            | ty::Bound(..)
1771            | ty::Placeholder(..)
1772            | 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!(
1773                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1774            ),
1775        }
1776    }
1777
1778    /// Returns the type of metadata for (potentially wide) pointers to this type.
1779    /// Causes an ICE if the metadata type cannot be determined.
1780    pub fn ptr_metadata_ty(
1781        self,
1782        tcx: TyCtxt<'tcx>,
1783        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1784    ) -> Ty<'tcx> {
1785        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1786            Ok(metadata) => metadata,
1787            Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1788                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1789            ),
1790        }
1791    }
1792
1793    /// Given a pointer or reference type, returns the type of the *pointee*'s
1794    /// metadata. If it can't be determined exactly (perhaps due to still
1795    /// being generic) then a projection through `ptr::Pointee` will be returned.
1796    ///
1797    /// This is particularly useful for getting the type of the result of
1798    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1799    ///
1800    /// Panics if `self` is not dereferenceable.
1801    #[track_caller]
1802    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1803        let Some(pointee_ty) = self.builtin_deref(true) else {
1804            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")
1805        };
1806        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1807            tcx.types.unit
1808        } else {
1809            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1810                Ok(metadata_ty) => metadata_ty,
1811                Err(tail_ty) => {
1812                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1813                    Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1814                }
1815            }
1816        }
1817    }
1818
1819    /// When we create a closure, we record its kind (i.e., what trait
1820    /// it implements, constrained by how it uses its borrows) into its
1821    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1822    /// parameter. This is kind of a phantom type, except that the
1823    /// most convenient thing for us to are the integral types. This
1824    /// function converts such a special type into the closure
1825    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1826    ///
1827    /// Note that during type checking, we use an inference variable
1828    /// to represent the closure kind, because it has not yet been
1829    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1830    /// is complete, that type variable will be unified with one of
1831    /// the integral types.
1832    ///
1833    /// ```rust,ignore (snippet of compiler code)
1834    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1835    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1836    /// {
1837    ///     println!("{closure_kind:?}");
1838    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1839    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1840    /// {
1841    ///     println!("{closure_kind:?}");
1842    /// }
1843    /// ```
1844    ///
1845    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1846    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1847    /// has been constrained instead of manually calling this method.
1848    ///
1849    /// ```rust,ignore (snippet of compiler code)
1850    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1851    /// {
1852    ///     println!("{:?}", args.as_closure().kind());
1853    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1854    /// {
1855    ///     println!("{:?}", args.as_coroutine_closure().kind());
1856    /// }
1857    /// ```
1858    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1859        match self.kind() {
1860            Int(int_ty) => match int_ty {
1861                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1862                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1863                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1864                _ => 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),
1865            },
1866
1867            // "Bound" types appear in canonical queries when the
1868            // closure type is not yet known, and `Placeholder` and `Param`
1869            // may be encountered in generic `AsyncFnKindHelper` goals.
1870            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1871
1872            Error(_) => Some(ty::ClosureKind::Fn),
1873
1874            _ => 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),
1875        }
1876    }
1877
1878    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1879    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1880    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1881        match kind {
1882            ty::ClosureKind::Fn => tcx.types.i8,
1883            ty::ClosureKind::FnMut => tcx.types.i16,
1884            ty::ClosureKind::FnOnce => tcx.types.i32,
1885        }
1886    }
1887
1888    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1889    /// to `FnMut`. This is because although we have three capability states,
1890    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1891    /// bodies: by-ref and by-value.
1892    ///
1893    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1894    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1895    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1896    ///
1897    /// This method should be used when constructing a `Coroutine` out of a
1898    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1899    /// directly from the `CoroutineClosure`'s `kind`.
1900    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1901        match kind {
1902            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1903            ty::ClosureKind::FnOnce => tcx.types.i32,
1904        }
1905    }
1906
1907    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1908    ///
1909    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1910    /// means nothing -- could be sized, might not be.
1911    ///
1912    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1913    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1914    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1915    /// This is why this method doesn't return `Option<bool>`.
1916    #[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(1916u32),
                                    ::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")]
1917    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1918        match self.kind() {
1919            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1920            | ty::Uint(_)
1921            | ty::Int(_)
1922            | ty::Bool
1923            | ty::Float(_)
1924            | ty::FnDef(..)
1925            | ty::FnPtr(..)
1926            | ty::UnsafeBinder(_)
1927            | ty::RawPtr(..)
1928            | ty::Char
1929            | ty::Ref(..)
1930            | ty::Coroutine(..)
1931            | ty::CoroutineWitness(..)
1932            | ty::Array(..)
1933            | ty::Pat(..)
1934            | ty::Closure(..)
1935            | ty::CoroutineClosure(..)
1936            | ty::Never
1937            | ty::Error(_) => true,
1938
1939            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1940                SizedTraitKind::Sized => false,
1941                SizedTraitKind::MetaSized => true,
1942            },
1943
1944            ty::Foreign(..) => match sizedness {
1945                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1946            },
1947
1948            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1949
1950            ty::Adt(def, args) => def
1951                .sizedness_constraint(tcx, sizedness)
1952                .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1953
1954            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1955
1956            ty::Infer(ty::TyVar(_)) => false,
1957
1958            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1959                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1960            }
1961        }
1962    }
1963
1964    /// Fast path helper for primitives which are always `Copy` and which
1965    /// have a side-effect-free `Clone` impl.
1966    ///
1967    /// Returning true means the type is known to be pure and `Copy+Clone`.
1968    /// Returning `false` means nothing -- could be `Copy`, might not be.
1969    ///
1970    /// This is mostly useful for optimizations, as these are the types
1971    /// on which we can replace cloning with dereferencing.
1972    pub fn is_trivially_pure_clone_copy(self) -> bool {
1973        match self.kind() {
1974            ty::Bool | ty::Char | ty::Never => true,
1975
1976            // These aren't even `Clone`
1977            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1978
1979            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1980            | ty::Int(..)
1981            | ty::Uint(..)
1982            | ty::Float(..) => true,
1983
1984            // ZST which can't be named are fine.
1985            ty::FnDef(..) => true,
1986
1987            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1988
1989            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
1990            ty::Tuple(field_tys) => {
1991                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1992            }
1993
1994            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1995
1996            // Sometimes traits aren't implemented for every ABI or arity,
1997            // because we can't be generic over everything yet.
1998            ty::FnPtr(..) => false,
1999
2000            // Definitely absolutely not copy.
2001            ty::Ref(_, _, hir::Mutability::Mut) => false,
2002
2003            // The standard library has a blanket Copy impl for shared references and raw pointers,
2004            // for all unsized types.
2005            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2006
2007            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2008
2009            // Might be, but not "trivial" so just giving the safe answer.
2010            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2011
2012            ty::UnsafeBinder(_) => false,
2013
2014            // Needs normalization or revealing to determine, so no is the safe answer.
2015            ty::Alias(..) => false,
2016
2017            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2018                false
2019            }
2020        }
2021    }
2022
2023    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2024        match *self.kind() {
2025            ty::Bool
2026            | ty::Char
2027            | ty::Int(_)
2028            | ty::Uint(_)
2029            | ty::Float(_)
2030            | ty::Str
2031            | ty::Never
2032            | ty::Param(_)
2033            | ty::Placeholder(_)
2034            | ty::Bound(..) => true,
2035
2036            ty::Slice(ty) => {
2037                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2038            }
2039            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2040
2041            ty::FnPtr(sig_tys, _) => {
2042                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2043            }
2044            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2045
2046            ty::Infer(infer) => match infer {
2047                ty::TyVar(_) => false,
2048                ty::IntVar(_) | ty::FloatVar(_) => true,
2049                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2050            },
2051
2052            ty::Adt(_, _)
2053            | ty::Tuple(_)
2054            | ty::Array(..)
2055            | ty::Foreign(_)
2056            | ty::Pat(_, _)
2057            | ty::FnDef(..)
2058            | ty::UnsafeBinder(..)
2059            | ty::Dynamic(..)
2060            | ty::Closure(..)
2061            | ty::CoroutineClosure(..)
2062            | ty::Coroutine(..)
2063            | ty::CoroutineWitness(..)
2064            | ty::Alias(..)
2065            | ty::Error(_) => false,
2066        }
2067    }
2068
2069    /// If `self` is a primitive, return its [`Symbol`].
2070    pub fn primitive_symbol(self) -> Option<Symbol> {
2071        match self.kind() {
2072            ty::Bool => Some(sym::bool),
2073            ty::Char => Some(sym::char),
2074            ty::Float(f) => match f {
2075                ty::FloatTy::F16 => Some(sym::f16),
2076                ty::FloatTy::F32 => Some(sym::f32),
2077                ty::FloatTy::F64 => Some(sym::f64),
2078                ty::FloatTy::F128 => Some(sym::f128),
2079            },
2080            ty::Int(f) => match f {
2081                ty::IntTy::Isize => Some(sym::isize),
2082                ty::IntTy::I8 => Some(sym::i8),
2083                ty::IntTy::I16 => Some(sym::i16),
2084                ty::IntTy::I32 => Some(sym::i32),
2085                ty::IntTy::I64 => Some(sym::i64),
2086                ty::IntTy::I128 => Some(sym::i128),
2087            },
2088            ty::Uint(f) => match f {
2089                ty::UintTy::Usize => Some(sym::usize),
2090                ty::UintTy::U8 => Some(sym::u8),
2091                ty::UintTy::U16 => Some(sym::u16),
2092                ty::UintTy::U32 => Some(sym::u32),
2093                ty::UintTy::U64 => Some(sym::u64),
2094                ty::UintTy::U128 => Some(sym::u128),
2095            },
2096            ty::Str => Some(sym::str),
2097            _ => None,
2098        }
2099    }
2100
2101    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2102        match self.kind() {
2103            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2104            _ => false,
2105        }
2106    }
2107
2108    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2109        match self.kind() {
2110            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2111            _ => false,
2112        }
2113    }
2114
2115    /// Returns `true` when the outermost type cannot be further normalized,
2116    /// resolved, or instantiated. This includes all primitive types, but also
2117    /// things like ADTs and trait objects, since even if their arguments or
2118    /// nested types may be further simplified, the outermost [`TyKind`] or
2119    /// type constructor remains the same.
2120    pub fn is_known_rigid(self) -> bool {
2121        self.kind().is_known_rigid()
2122    }
2123
2124    /// Iterator that walks `self` and any types reachable from
2125    /// `self`, in depth-first order. Note that just walks the types
2126    /// that appear in `self`, it does not descend into the fields of
2127    /// structs or variants. For example:
2128    ///
2129    /// ```text
2130    /// isize => { isize }
2131    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2132    /// [isize] => { [isize], isize }
2133    /// ```
2134    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2135        TypeWalker::new(self.into())
2136    }
2137}
2138
2139impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2140    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2141        self.split_last().unwrap().1
2142    }
2143
2144    fn output(self) -> Ty<'tcx> {
2145        *self.split_last().unwrap().0
2146    }
2147}
2148
2149impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2150    fn is_kw_underscore_lifetime(self) -> bool {
2151        self == kw::UnderscoreLifetime
2152    }
2153}
2154
2155// Some types are used a lot. Make sure they don't unintentionally get bigger.
2156#[cfg(target_pointer_width = "64")]
2157mod size_asserts {
2158    use rustc_data_structures::static_assert_size;
2159
2160    use super::*;
2161    // tidy-alphabetical-start
2162    const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2163    const _: [(); 56] =
    [(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 56);
2164    // tidy-alphabetical-end
2165}