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