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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PolyFnSig<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.kind().fn_sig(tcx) }
    }
}#[tracing::instrument(level = "trace", skip(tcx))]
1636    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1637        self.kind().fn_sig(tcx)
1638    }
1639
1640    #[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("unnormalized_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(1640u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    ty::Unnormalized<'tcx, PolyFnSig<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.kind().unnormalized_fn_sig(tcx) }
    }
}#[tracing::instrument(level = "trace", skip(tcx))]
1641    pub fn unnormalized_fn_sig(self, tcx: TyCtxt<'tcx>) -> ty::Unnormalized<'tcx, PolyFnSig<'tcx>> {
1642        self.kind().unnormalized_fn_sig(tcx)
1643    }
1644
1645    #[inline]
1646    pub fn is_fn(self) -> bool {
1647        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnDef(..) | FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1648    }
1649
1650    #[inline]
1651    pub fn is_fn_ptr(self) -> bool {
1652        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnPtr(..))
1653    }
1654
1655    #[inline]
1656    pub fn is_opaque(self) -> bool {
1657        #[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 { .. }, .. }))
1658    }
1659
1660    #[inline]
1661    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1662        match self.kind() {
1663            Adt(adt, _) => Some(*adt),
1664            _ => None,
1665        }
1666    }
1667
1668    /// Returns a list of tuple type arguments.
1669    ///
1670    /// Panics when called on anything but a tuple.
1671    #[inline]
1672    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1673        match self.kind() {
1674            Tuple(args) => args,
1675            _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
        self))bug!("tuple_fields called on non-tuple: {self:?}"),
1676        }
1677    }
1678
1679    /// Returns a list of tuple type arguments, or `None` if `self` isn't a tuple.
1680    #[inline]
1681    pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1682        match self.kind() {
1683            Tuple(args) => Some(args),
1684            _ => None,
1685        }
1686    }
1687
1688    /// If the type contains variants, returns the valid range of variant indices.
1689    //
1690    // FIXME: This requires the optimized MIR in the case of coroutines.
1691    #[inline]
1692    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1693        match self.kind() {
1694            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1695            TyKind::Coroutine(def_id, args) => {
1696                Some(args.as_coroutine().variant_range(*def_id, tcx))
1697            }
1698            TyKind::UnsafeBinder(bound_ty) => {
1699                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1700            }
1701            _ => None,
1702        }
1703    }
1704
1705    /// If the type contains variants, returns the variant for `variant_index`.
1706    /// Panics if `variant_index` is out of range.
1707    //
1708    // FIXME: This requires the optimized MIR in the case of coroutines.
1709    #[inline]
1710    pub fn discriminant_for_variant(
1711        self,
1712        tcx: TyCtxt<'tcx>,
1713        variant_index: VariantIdx,
1714    ) -> Option<Discr<'tcx>> {
1715        match self.kind() {
1716            TyKind::Adt(adt, _) if adt.is_enum() => {
1717                Some(adt.discriminant_for_variant(tcx, variant_index))
1718            }
1719            TyKind::Coroutine(def_id, args) => {
1720                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1721            }
1722            TyKind::UnsafeBinder(bound_ty) => tcx
1723                .instantiate_bound_regions_with_erased((*bound_ty).into())
1724                .discriminant_for_variant(tcx, variant_index),
1725            _ => None,
1726        }
1727    }
1728
1729    /// Returns the type of the discriminant of this type.
1730    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1731        match self.kind() {
1732            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1733            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1734
1735            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1736                let assoc_items = tcx.associated_item_def_ids(
1737                    tcx.require_lang_item(LangItem::DiscriminantKind, DUMMY_SP),
1738                );
1739                Ty::new_projection_from_args(
1740                    tcx,
1741                    ty::IsRigid::No,
1742                    assoc_items[0],
1743                    tcx.mk_args(&[self.into()]),
1744                )
1745            }
1746
1747            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1748            ty::UnsafeBinder(bound_ty) => {
1749                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1750            }
1751
1752            ty::Bool
1753            | ty::Char
1754            | ty::Int(_)
1755            | ty::Uint(_)
1756            | ty::Float(_)
1757            | ty::Adt(..)
1758            | ty::Foreign(_)
1759            | ty::Str
1760            | ty::Array(..)
1761            | ty::Slice(_)
1762            | ty::RawPtr(_, _)
1763            | ty::Ref(..)
1764            | ty::FnDef(..)
1765            | ty::FnPtr(..)
1766            | ty::Dynamic(..)
1767            | ty::Closure(..)
1768            | ty::CoroutineClosure(..)
1769            | ty::CoroutineWitness(..)
1770            | ty::Never
1771            | ty::Tuple(_)
1772            | ty::Error(_)
1773            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1774
1775            ty::Bound(..)
1776            | ty::Placeholder(_)
1777            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1778                crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
        self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1779            }
1780        }
1781    }
1782
1783    /// Returns the type of metadata for (potentially wide) pointers to this type,
1784    /// or the struct tail if the metadata type cannot be determined.
1785    pub fn ptr_metadata_ty_or_tail(
1786        self,
1787        tcx: TyCtxt<'tcx>,
1788        normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1789    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1790        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1791        match tail.kind() {
1792            // Sized types
1793            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1794            | ty::Uint(_)
1795            | ty::Int(_)
1796            | ty::Bool
1797            | ty::Float(_)
1798            | ty::FnDef(..)
1799            | ty::FnPtr(..)
1800            | ty::RawPtr(..)
1801            | ty::Char
1802            | ty::Ref(..)
1803            | ty::Coroutine(..)
1804            | ty::CoroutineWitness(..)
1805            | ty::Array(..)
1806            | ty::Closure(..)
1807            | ty::CoroutineClosure(..)
1808            | ty::Never
1809            | ty::Error(_) => Ok(tcx.types.unit),
1810            // Extern types have metadata = ().
1811            ty::Foreign(..) => Ok(tcx.types.unit),
1812            // If returned by `struct_tail_raw` this is a unit struct
1813            // without any fields, or not a struct, and therefore is Sized.
1814            ty::Adt(..) => Ok(tcx.types.unit),
1815            // If returned by `struct_tail_raw` this is the empty tuple,
1816            // a.k.a. unit type, which is Sized
1817            ty::Tuple(..) => Ok(tcx.types.unit),
1818
1819            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1820
1821            ty::Dynamic(_, _) => {
1822                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1823                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]).skip_norm_wip())
1824            }
1825
1826            // We don't know the metadata of `self`, but it must be equal to the
1827            // metadata of `tail`.
1828            ty::Param(_) | ty::Alias(..) => Err(tail),
1829
1830            ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
1831
1832            ty::Infer(ty::TyVar(_))
1833            | ty::Pat(..)
1834            | ty::Bound(..)
1835            | ty::Placeholder(..)
1836            | 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!(
1837                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1838            ),
1839        }
1840    }
1841
1842    /// Returns the type of metadata for (potentially wide) pointers to this type.
1843    /// Causes an ICE if the metadata type cannot be determined.
1844    pub fn ptr_metadata_ty(
1845        self,
1846        tcx: TyCtxt<'tcx>,
1847        normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1848    ) -> Ty<'tcx> {
1849        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1850            Ok(metadata) => metadata,
1851            Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1852                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1853            ),
1854        }
1855    }
1856
1857    /// Given a pointer or reference type, returns the type of the *pointee*'s
1858    /// metadata. If it can't be determined exactly (perhaps due to still
1859    /// being generic) then a projection through `ptr::Pointee` will be returned.
1860    ///
1861    /// This is particularly useful for getting the type of the result of
1862    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1863    ///
1864    /// Panics if `self` is not dereferenceable.
1865    #[track_caller]
1866    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1867        let Some(pointee_ty) = self.builtin_deref(true) else {
1868            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")
1869        };
1870        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1871            tcx.types.unit
1872        } else {
1873            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x.skip_norm_wip()) {
1874                Ok(metadata_ty) => metadata_ty,
1875                Err(tail_ty) => {
1876                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1877                    Ty::new_projection(tcx, ty::IsRigid::No, metadata_def_id, [tail_ty])
1878                }
1879            }
1880        }
1881    }
1882
1883    /// When we create a closure, we record its kind (i.e., what trait
1884    /// it implements, constrained by how it uses its borrows) into its
1885    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1886    /// parameter. This is kind of a phantom type, except that the
1887    /// most convenient thing for us to are the integral types. This
1888    /// function converts such a special type into the closure
1889    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1890    ///
1891    /// Note that during type checking, we use an inference variable
1892    /// to represent the closure kind, because it has not yet been
1893    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1894    /// is complete, that type variable will be unified with one of
1895    /// the integral types.
1896    ///
1897    /// ```rust,ignore (snippet of compiler code)
1898    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1899    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1900    /// {
1901    ///     println!("{closure_kind:?}");
1902    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1903    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1904    /// {
1905    ///     println!("{closure_kind:?}");
1906    /// }
1907    /// ```
1908    ///
1909    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1910    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1911    /// has been constrained instead of manually calling this method.
1912    ///
1913    /// ```rust,ignore (snippet of compiler code)
1914    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1915    /// {
1916    ///     println!("{:?}", args.as_closure().kind());
1917    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1918    /// {
1919    ///     println!("{:?}", args.as_coroutine_closure().kind());
1920    /// }
1921    /// ```
1922    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1923        match self.kind() {
1924            Int(int_ty) => match int_ty {
1925                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1926                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1927                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1928                _ => 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),
1929            },
1930
1931            // "Bound" types appear in canonical queries when the
1932            // closure type is not yet known, and `Placeholder` and `Param`
1933            // may be encountered in generic `AsyncFnKindHelper` goals.
1934            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1935
1936            Error(_) => Some(ty::ClosureKind::Fn),
1937
1938            _ => 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),
1939        }
1940    }
1941
1942    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1943    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1944    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1945        match kind {
1946            ty::ClosureKind::Fn => tcx.types.i8,
1947            ty::ClosureKind::FnMut => tcx.types.i16,
1948            ty::ClosureKind::FnOnce => tcx.types.i32,
1949        }
1950    }
1951
1952    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1953    /// to `FnMut`. This is because although we have three capability states,
1954    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1955    /// bodies: by-ref and by-value.
1956    ///
1957    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1958    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1959    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1960    ///
1961    /// This method should be used when constructing a `Coroutine` out of a
1962    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1963    /// directly from the `CoroutineClosure`'s `kind`.
1964    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1965        match kind {
1966            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1967            ty::ClosureKind::FnOnce => tcx.types.i32,
1968        }
1969    }
1970
1971    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1972    ///
1973    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1974    /// means nothing -- could be sized, might not be.
1975    ///
1976    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1977    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1978    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1979    /// This is why this method doesn't return `Option<bool>`.
1980    #[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(1980u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sizedness")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sizedness");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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).skip_norm_wip().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")]
1981    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1982        match self.kind() {
1983            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1984            | ty::Uint(_)
1985            | ty::Int(_)
1986            | ty::Bool
1987            | ty::Float(_)
1988            | ty::FnDef(..)
1989            | ty::FnPtr(..)
1990            | ty::UnsafeBinder(_)
1991            | ty::RawPtr(..)
1992            | ty::Char
1993            | ty::Ref(..)
1994            | ty::Coroutine(..)
1995            | ty::CoroutineWitness(..)
1996            | ty::Array(..)
1997            | ty::Pat(..)
1998            | ty::Closure(..)
1999            | ty::CoroutineClosure(..)
2000            | ty::Never
2001            | ty::Error(_) => true,
2002
2003            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
2004                SizedTraitKind::Sized => false,
2005                SizedTraitKind::MetaSized => true,
2006            },
2007
2008            ty::Foreign(..) => match sizedness {
2009                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
2010            },
2011
2012            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
2013
2014            ty::Adt(def, args) => def.sizedness_constraint(tcx, sizedness).is_none_or(|ty| {
2015                ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
2016            }),
2017
2018            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
2019
2020            ty::Infer(ty::TyVar(_)) => false,
2021
2022            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2023                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
2024            }
2025        }
2026    }
2027
2028    /// Fast path helper for primitives which are always `Copy` and which
2029    /// have a side-effect-free `Clone` impl.
2030    ///
2031    /// Returning true means the type is known to be pure and `Copy+Clone`.
2032    /// Returning `false` means nothing -- could be `Copy`, might not be.
2033    ///
2034    /// This is mostly useful for optimizations, as these are the types
2035    /// on which we can replace cloning with dereferencing.
2036    pub fn is_trivially_pure_clone_copy(self) -> bool {
2037        match self.kind() {
2038            ty::Bool | ty::Char | ty::Never => true,
2039
2040            // These aren't even `Clone`
2041            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2042
2043            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2044            | ty::Int(..)
2045            | ty::Uint(..)
2046            | ty::Float(..) => true,
2047
2048            // ZST which can't be named are fine.
2049            ty::FnDef(..) => true,
2050
2051            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2052
2053            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2054            ty::Tuple(field_tys) => {
2055                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2056            }
2057
2058            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
2059
2060            // Sometimes traits aren't implemented for every ABI or arity,
2061            // because we can't be generic over everything yet.
2062            ty::FnPtr(..) => false,
2063
2064            // Definitely absolutely not copy.
2065            ty::Ref(_, _, hir::Mutability::Mut) => false,
2066
2067            // The standard library has a blanket Copy impl for shared references and raw pointers,
2068            // for all unsized types.
2069            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2070
2071            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2072
2073            // Might be, but not "trivial" so just giving the safe answer.
2074            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2075
2076            ty::UnsafeBinder(_) => false,
2077
2078            // Needs normalization or revealing to determine, so no is the safe answer.
2079            ty::Alias(..) => false,
2080
2081            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2082                false
2083            }
2084        }
2085    }
2086
2087    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2088        match *self.kind() {
2089            ty::Bool
2090            | ty::Char
2091            | ty::Int(_)
2092            | ty::Uint(_)
2093            | ty::Float(_)
2094            | ty::Str
2095            | ty::Never
2096            | ty::Param(_)
2097            | ty::Placeholder(_)
2098            | ty::Bound(..) => true,
2099
2100            ty::Slice(ty) => {
2101                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2102            }
2103            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2104
2105            ty::FnPtr(sig_tys, _) => {
2106                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2107            }
2108            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2109
2110            ty::Infer(infer) => match infer {
2111                ty::TyVar(_) => false,
2112                ty::IntVar(_) | ty::FloatVar(_) => true,
2113                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2114            },
2115
2116            ty::Adt(_, _)
2117            | ty::Tuple(_)
2118            | ty::Array(..)
2119            | ty::Foreign(_)
2120            | ty::Pat(_, _)
2121            | ty::FnDef(..)
2122            | ty::UnsafeBinder(..)
2123            | ty::Dynamic(..)
2124            | ty::Closure(..)
2125            | ty::CoroutineClosure(..)
2126            | ty::Coroutine(..)
2127            | ty::CoroutineWitness(..)
2128            | ty::Alias(..)
2129            | ty::Error(_) => false,
2130        }
2131    }
2132
2133    /// If `self` is a primitive, return its [`Symbol`].
2134    pub fn primitive_symbol(self) -> Option<Symbol> {
2135        match self.kind() {
2136            ty::Bool => Some(sym::bool),
2137            ty::Char => Some(sym::char),
2138            ty::Float(f) => match f {
2139                ty::FloatTy::F16 => Some(sym::f16),
2140                ty::FloatTy::F32 => Some(sym::f32),
2141                ty::FloatTy::F64 => Some(sym::f64),
2142                ty::FloatTy::F128 => Some(sym::f128),
2143            },
2144            ty::Int(f) => match f {
2145                ty::IntTy::Isize => Some(sym::isize),
2146                ty::IntTy::I8 => Some(sym::i8),
2147                ty::IntTy::I16 => Some(sym::i16),
2148                ty::IntTy::I32 => Some(sym::i32),
2149                ty::IntTy::I64 => Some(sym::i64),
2150                ty::IntTy::I128 => Some(sym::i128),
2151            },
2152            ty::Uint(f) => match f {
2153                ty::UintTy::Usize => Some(sym::usize),
2154                ty::UintTy::U8 => Some(sym::u8),
2155                ty::UintTy::U16 => Some(sym::u16),
2156                ty::UintTy::U32 => Some(sym::u32),
2157                ty::UintTy::U64 => Some(sym::u64),
2158                ty::UintTy::U128 => Some(sym::u128),
2159            },
2160            ty::Str => Some(sym::str),
2161            _ => None,
2162        }
2163    }
2164
2165    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2166        match self.kind() {
2167            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2168            _ => false,
2169        }
2170    }
2171
2172    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2173        match self.kind() {
2174            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2175            _ => false,
2176        }
2177    }
2178
2179    /// Returns `true` when the outermost type cannot be further normalized,
2180    /// resolved, or instantiated. This includes all primitive types, but also
2181    /// things like ADTs and trait objects, since even if their arguments or
2182    /// nested types may be further simplified, the outermost [`TyKind`] or
2183    /// type constructor remains the same.
2184    pub fn is_known_rigid(self) -> bool {
2185        self.kind().is_known_rigid()
2186    }
2187
2188    /// Iterator that walks `self` and any types reachable from
2189    /// `self`, in depth-first order. Note that just walks the types
2190    /// that appear in `self`, it does not descend into the fields of
2191    /// structs or variants. For example:
2192    ///
2193    /// ```text
2194    /// isize => { isize }
2195    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2196    /// [isize] => { [isize], isize }
2197    /// ```
2198    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2199        TypeWalker::new(self.into())
2200    }
2201}
2202
2203impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2204    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2205        self.split_last().unwrap().1
2206    }
2207
2208    fn output(self) -> Ty<'tcx> {
2209        *self.split_last().unwrap().0
2210    }
2211}
2212
2213impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2214    fn is_kw_underscore_lifetime(self) -> bool {
2215        self == kw::UnderscoreLifetime
2216    }
2217}
2218
2219// Some types are used a lot. Make sure they don't unintentionally get bigger.
2220#[cfg(target_pointer_width = "64")]
2221mod size_asserts {
2222    use rustc_data_structures::static_assert_size;
2223
2224    use super::*;
2225    // tidy-alphabetical-start
2226    const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2227    const _: [(); 40] =
    [(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 40);
2228    // tidy-alphabetical-end
2229}