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    #[inline]
882    pub fn new_diverging_default(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
883        if tcx.features().never_type_fallback() { tcx.types.never } else { tcx.types.unit }
884    }
885
886    // lang and diagnostic tys
887
888    fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
889        let adt_def = tcx.adt_def(wrapper_def_id);
890        let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
891            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
892            GenericParamDefKind::Type { has_default, .. } => {
893                if param.index == 0 {
894                    ty_param.into()
895                } else {
896                    assert!(has_default);
897                    tcx.type_of(param.def_id).instantiate(tcx, args).into()
898                }
899            }
900        });
901        Ty::new_adt(tcx, adt_def, args)
902    }
903
904    #[inline]
905    pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
906        let def_id = tcx.lang_items().get(item)?;
907        Some(Ty::new_generic_adt(tcx, def_id, ty))
908    }
909
910    #[inline]
911    pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
912        let def_id = tcx.get_diagnostic_item(name)?;
913        Some(Ty::new_generic_adt(tcx, def_id, ty))
914    }
915
916    #[inline]
917    pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
918        let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
919        Ty::new_generic_adt(tcx, def_id, ty)
920    }
921
922    #[inline]
923    pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
924        let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
925        Ty::new_generic_adt(tcx, def_id, ty)
926    }
927
928    #[inline]
929    pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
930        let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
931        Ty::new_generic_adt(tcx, def_id, ty)
932    }
933
934    /// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
935    pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
936        let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
937        let context_adt_ref = tcx.adt_def(context_did);
938        let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
939        let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
940        Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
941    }
942}
943
944impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
945    fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
946        tcx.types.bool
947    }
948
949    fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
950        tcx.types.u8
951    }
952
953    fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
954        Ty::new_infer(tcx, infer)
955    }
956
957    fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
958        Ty::new_var(tcx, vid)
959    }
960
961    fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
962        Ty::new_param(tcx, param.index, param.name)
963    }
964
965    fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Self {
966        Ty::new_placeholder(tcx, placeholder)
967    }
968
969    fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self {
970        Ty::new_bound(interner, debruijn, var)
971    }
972
973    fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
974        Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
975    }
976
977    fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
978        Ty::new_canonical_bound(tcx, var)
979    }
980
981    fn new_alias(
982        interner: TyCtxt<'tcx>,
983        kind: ty::AliasTyKind,
984        alias_ty: ty::AliasTy<'tcx>,
985    ) -> Self {
986        Ty::new_alias(interner, kind, alias_ty)
987    }
988
989    fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
990        Ty::new_error(interner, guar)
991    }
992
993    fn new_adt(
994        interner: TyCtxt<'tcx>,
995        adt_def: ty::AdtDef<'tcx>,
996        args: ty::GenericArgsRef<'tcx>,
997    ) -> Self {
998        Ty::new_adt(interner, adt_def, args)
999    }
1000
1001    fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
1002        Ty::new_foreign(interner, def_id)
1003    }
1004
1005    fn new_dynamic(
1006        interner: TyCtxt<'tcx>,
1007        preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
1008        region: ty::Region<'tcx>,
1009    ) -> Self {
1010        Ty::new_dynamic(interner, preds, region)
1011    }
1012
1013    fn new_coroutine(
1014        interner: TyCtxt<'tcx>,
1015        def_id: DefId,
1016        args: ty::GenericArgsRef<'tcx>,
1017    ) -> Self {
1018        Ty::new_coroutine(interner, def_id, args)
1019    }
1020
1021    fn new_coroutine_closure(
1022        interner: TyCtxt<'tcx>,
1023        def_id: DefId,
1024        args: ty::GenericArgsRef<'tcx>,
1025    ) -> Self {
1026        Ty::new_coroutine_closure(interner, def_id, args)
1027    }
1028
1029    fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1030        Ty::new_closure(interner, def_id, args)
1031    }
1032
1033    fn new_coroutine_witness(
1034        interner: TyCtxt<'tcx>,
1035        def_id: DefId,
1036        args: ty::GenericArgsRef<'tcx>,
1037    ) -> Self {
1038        Ty::new_coroutine_witness(interner, def_id, args)
1039    }
1040
1041    fn new_coroutine_witness_for_coroutine(
1042        interner: TyCtxt<'tcx>,
1043        def_id: DefId,
1044        coroutine_args: ty::GenericArgsRef<'tcx>,
1045    ) -> Self {
1046        Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1047    }
1048
1049    fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1050        Ty::new_ptr(interner, ty, mutbl)
1051    }
1052
1053    fn new_ref(
1054        interner: TyCtxt<'tcx>,
1055        region: ty::Region<'tcx>,
1056        ty: Self,
1057        mutbl: hir::Mutability,
1058    ) -> Self {
1059        Ty::new_ref(interner, region, ty, mutbl)
1060    }
1061
1062    fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1063        Ty::new_array_with_const_len(interner, ty, len)
1064    }
1065
1066    fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1067        Ty::new_slice(interner, ty)
1068    }
1069
1070    fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1071        Ty::new_tup(interner, tys)
1072    }
1073
1074    fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1075    where
1076        It: Iterator<Item = T>,
1077        T: CollectAndApply<Self, Self>,
1078    {
1079        Ty::new_tup_from_iter(interner, iter)
1080    }
1081
1082    fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1083        self.tuple_fields()
1084    }
1085
1086    fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1087        self.to_opt_closure_kind()
1088    }
1089
1090    fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1091        Ty::from_closure_kind(interner, kind)
1092    }
1093
1094    fn from_coroutine_closure_kind(
1095        interner: TyCtxt<'tcx>,
1096        kind: rustc_type_ir::ClosureKind,
1097    ) -> Self {
1098        Ty::from_coroutine_closure_kind(interner, kind)
1099    }
1100
1101    fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1102        Ty::new_fn_def(interner, def_id, args)
1103    }
1104
1105    fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1106        Ty::new_fn_ptr(interner, sig)
1107    }
1108
1109    fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1110        Ty::new_pat(interner, ty, pat)
1111    }
1112
1113    fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1114        Ty::new_unsafe_binder(interner, ty)
1115    }
1116
1117    fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1118        interner.types.unit
1119    }
1120
1121    fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1122        interner.types.usize
1123    }
1124
1125    fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1126        self.discriminant_ty(interner)
1127    }
1128
1129    fn has_unsafe_fields(self) -> bool {
1130        Ty::has_unsafe_fields(self)
1131    }
1132}
1133
1134/// Type utilities
1135impl<'tcx> Ty<'tcx> {
1136    // It would be nicer if this returned the value instead of a reference,
1137    // like how `Predicate::kind` and `Region::kind` do. (It would result in
1138    // many fewer subsequent dereferences.) But that gives a small but
1139    // noticeable performance hit. See #126069 for details.
1140    #[inline(always)]
1141    pub fn kind(self) -> &'tcx TyKind<'tcx> {
1142        self.0.0
1143    }
1144
1145    // FIXME(compiler-errors): Think about removing this.
1146    #[inline(always)]
1147    pub fn flags(self) -> TypeFlags {
1148        self.0.0.flags
1149    }
1150
1151    #[inline]
1152    pub fn is_unit(self) -> bool {
1153        match self.kind() {
1154            Tuple(tys) => tys.is_empty(),
1155            _ => false,
1156        }
1157    }
1158
1159    /// Check if type is an `usize`.
1160    #[inline]
1161    pub fn is_usize(self) -> bool {
1162        matches!(self.kind(), Uint(UintTy::Usize))
1163    }
1164
1165    /// Check if type is an `usize` or an integral type variable.
1166    #[inline]
1167    pub fn is_usize_like(self) -> bool {
1168        matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1169    }
1170
1171    #[inline]
1172    pub fn is_never(self) -> bool {
1173        matches!(self.kind(), Never)
1174    }
1175
1176    #[inline]
1177    pub fn is_primitive(self) -> bool {
1178        matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1179    }
1180
1181    #[inline]
1182    pub fn is_adt(self) -> bool {
1183        matches!(self.kind(), Adt(..))
1184    }
1185
1186    #[inline]
1187    pub fn is_ref(self) -> bool {
1188        matches!(self.kind(), Ref(..))
1189    }
1190
1191    #[inline]
1192    pub fn is_ty_var(self) -> bool {
1193        matches!(self.kind(), Infer(TyVar(_)))
1194    }
1195
1196    #[inline]
1197    pub fn ty_vid(self) -> Option<ty::TyVid> {
1198        match self.kind() {
1199            &Infer(TyVar(vid)) => Some(vid),
1200            _ => None,
1201        }
1202    }
1203
1204    #[inline]
1205    pub fn is_ty_or_numeric_infer(self) -> bool {
1206        matches!(self.kind(), Infer(_))
1207    }
1208
1209    #[inline]
1210    pub fn is_phantom_data(self) -> bool {
1211        if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1212    }
1213
1214    #[inline]
1215    pub fn is_bool(self) -> bool {
1216        *self.kind() == Bool
1217    }
1218
1219    /// Returns `true` if this type is a `str`.
1220    #[inline]
1221    pub fn is_str(self) -> bool {
1222        *self.kind() == Str
1223    }
1224
1225    #[inline]
1226    pub fn is_param(self, index: u32) -> bool {
1227        match self.kind() {
1228            ty::Param(data) => data.index == index,
1229            _ => false,
1230        }
1231    }
1232
1233    #[inline]
1234    pub fn is_slice(self) -> bool {
1235        matches!(self.kind(), Slice(_))
1236    }
1237
1238    #[inline]
1239    pub fn is_array_slice(self) -> bool {
1240        match self.kind() {
1241            Slice(_) => true,
1242            ty::RawPtr(ty, _) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1243            _ => false,
1244        }
1245    }
1246
1247    #[inline]
1248    pub fn is_array(self) -> bool {
1249        matches!(self.kind(), Array(..))
1250    }
1251
1252    #[inline]
1253    pub fn is_simd(self) -> bool {
1254        match self.kind() {
1255            Adt(def, _) => def.repr().simd(),
1256            _ => false,
1257        }
1258    }
1259
1260    pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1261        match self.kind() {
1262            Array(ty, _) | Slice(ty) => *ty,
1263            Str => tcx.types.u8,
1264            _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1265        }
1266    }
1267
1268    pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1269        let Adt(def, args) = self.kind() else {
1270            bug!("`simd_size_and_type` called on invalid type")
1271        };
1272        assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1273        let variant = def.non_enum_variant();
1274        assert_eq!(variant.fields.len(), 1);
1275        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1276        let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1277            bug!("Simd type has non-array field type {field_ty:?}")
1278        };
1279        // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1280        // The way we evaluate the `N` in `[T; N]` here only works since we use
1281        // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1282        // if we use it in generic code. See the `simd-array-trait` ui test.
1283        (
1284            f0_len
1285                .try_to_target_usize(tcx)
1286                .expect("expected SIMD field to have definite array size"),
1287            *f0_elem_ty,
1288        )
1289    }
1290
1291    #[inline]
1292    pub fn is_mutable_ptr(self) -> bool {
1293        matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1294    }
1295
1296    /// Get the mutability of the reference or `None` when not a reference
1297    #[inline]
1298    pub fn ref_mutability(self) -> Option<hir::Mutability> {
1299        match self.kind() {
1300            Ref(_, _, mutability) => Some(*mutability),
1301            _ => None,
1302        }
1303    }
1304
1305    #[inline]
1306    pub fn is_raw_ptr(self) -> bool {
1307        matches!(self.kind(), RawPtr(_, _))
1308    }
1309
1310    /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1311    /// `Box` is *not* considered a pointer here!
1312    #[inline]
1313    pub fn is_any_ptr(self) -> bool {
1314        self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1315    }
1316
1317    #[inline]
1318    pub fn is_box(self) -> bool {
1319        match self.kind() {
1320            Adt(def, _) => def.is_box(),
1321            _ => false,
1322        }
1323    }
1324
1325    /// Tests whether this is a Box definitely using the global allocator.
1326    ///
1327    /// If the allocator is still generic, the answer is `false`, but it may
1328    /// later turn out that it does use the global allocator.
1329    #[inline]
1330    pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1331        match self.kind() {
1332            Adt(def, args) if def.is_box() => {
1333                let Some(alloc) = args.get(1) else {
1334                    // Single-argument Box is always global. (for "minicore" tests)
1335                    return true;
1336                };
1337                alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1338                    tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1339                })
1340            }
1341            _ => false,
1342        }
1343    }
1344
1345    pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1346        match self.kind() {
1347            Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1348            _ => None,
1349        }
1350    }
1351
1352    pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1353        match self.kind() {
1354            Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1355            _ => None,
1356        }
1357    }
1358
1359    pub fn pinned_ref(self) -> Option<(Ty<'tcx>, ty::Mutability)> {
1360        if let Adt(def, args) = self.kind()
1361            && def.is_pin()
1362            && let &ty::Ref(_, ty, mutbl) = args.type_at(0).kind()
1363        {
1364            return Some((ty, mutbl));
1365        }
1366        None
1367    }
1368
1369    /// Panics if called on any type other than `Box<T>`.
1370    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1371        self.boxed_ty()
1372            .unwrap_or_else(|| bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1373    }
1374
1375    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1376    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1377    /// contents are abstract to rustc.)
1378    #[inline]
1379    pub fn is_scalar(self) -> bool {
1380        matches!(
1381            self.kind(),
1382            Bool | Char
1383                | Int(_)
1384                | Float(_)
1385                | Uint(_)
1386                | FnDef(..)
1387                | FnPtr(..)
1388                | RawPtr(_, _)
1389                | Infer(IntVar(_) | FloatVar(_))
1390        )
1391    }
1392
1393    /// Returns `true` if this type is a floating point type.
1394    #[inline]
1395    pub fn is_floating_point(self) -> bool {
1396        matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1397    }
1398
1399    #[inline]
1400    pub fn is_trait(self) -> bool {
1401        matches!(self.kind(), Dynamic(_, _))
1402    }
1403
1404    #[inline]
1405    pub fn is_enum(self) -> bool {
1406        matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1407    }
1408
1409    #[inline]
1410    pub fn is_union(self) -> bool {
1411        matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1412    }
1413
1414    #[inline]
1415    pub fn is_closure(self) -> bool {
1416        matches!(self.kind(), Closure(..))
1417    }
1418
1419    #[inline]
1420    pub fn is_coroutine(self) -> bool {
1421        matches!(self.kind(), Coroutine(..))
1422    }
1423
1424    #[inline]
1425    pub fn is_coroutine_closure(self) -> bool {
1426        matches!(self.kind(), CoroutineClosure(..))
1427    }
1428
1429    #[inline]
1430    pub fn is_integral(self) -> bool {
1431        matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1432    }
1433
1434    #[inline]
1435    pub fn is_fresh_ty(self) -> bool {
1436        matches!(self.kind(), Infer(FreshTy(_)))
1437    }
1438
1439    #[inline]
1440    pub fn is_fresh(self) -> bool {
1441        matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1442    }
1443
1444    #[inline]
1445    pub fn is_char(self) -> bool {
1446        matches!(self.kind(), Char)
1447    }
1448
1449    #[inline]
1450    pub fn is_numeric(self) -> bool {
1451        self.is_integral() || self.is_floating_point()
1452    }
1453
1454    #[inline]
1455    pub fn is_signed(self) -> bool {
1456        matches!(self.kind(), Int(_))
1457    }
1458
1459    #[inline]
1460    pub fn is_ptr_sized_integral(self) -> bool {
1461        matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1462    }
1463
1464    #[inline]
1465    pub fn has_concrete_skeleton(self) -> bool {
1466        !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1467    }
1468
1469    /// Checks whether a type recursively contains another type
1470    ///
1471    /// Example: `Option<()>` contains `()`
1472    pub fn contains(self, other: Ty<'tcx>) -> bool {
1473        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1474
1475        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1476            type Result = ControlFlow<()>;
1477
1478            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1479                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1480            }
1481        }
1482
1483        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1484        cf.is_break()
1485    }
1486
1487    /// Checks whether a type recursively contains any closure
1488    ///
1489    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1490    pub fn contains_closure(self) -> bool {
1491        struct ContainsClosureVisitor;
1492
1493        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1494            type Result = ControlFlow<()>;
1495
1496            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1497                if let ty::Closure(..) = t.kind() {
1498                    ControlFlow::Break(())
1499                } else {
1500                    t.super_visit_with(self)
1501                }
1502            }
1503        }
1504
1505        let cf = self.visit_with(&mut ContainsClosureVisitor);
1506        cf.is_break()
1507    }
1508
1509    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1510    ///
1511    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1512    /// to call async drop poll from impl coroutine.
1513    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1514        self,
1515        tcx: TyCtxt<'tcx>,
1516        mut f: F,
1517    ) -> Ty<'tcx> {
1518        assert!(self.is_coroutine());
1519        let mut cor_ty = self;
1520        let mut ty = cor_ty;
1521        loop {
1522            if let ty::Coroutine(def_id, args) = ty.kind() {
1523                cor_ty = ty;
1524                f(ty);
1525                if tcx.is_async_drop_in_place_coroutine(*def_id) {
1526                    ty = args.first().unwrap().expect_ty();
1527                    continue;
1528                } else {
1529                    return cor_ty;
1530                }
1531            } else {
1532                return cor_ty;
1533            }
1534        }
1535    }
1536
1537    /// Returns the type of `*ty`.
1538    ///
1539    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1540    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1541    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1542        match *self.kind() {
1543            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1544            Ref(_, ty, _) => Some(ty),
1545            RawPtr(ty, _) if explicit => Some(ty),
1546            _ => None,
1547        }
1548    }
1549
1550    /// Returns the type of `ty[i]`.
1551    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1552        match self.kind() {
1553            Array(ty, _) | Slice(ty) => Some(*ty),
1554            _ => None,
1555        }
1556    }
1557
1558    #[tracing::instrument(level = "trace", skip(tcx))]
1559    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1560        self.kind().fn_sig(tcx)
1561    }
1562
1563    #[inline]
1564    pub fn is_fn(self) -> bool {
1565        matches!(self.kind(), FnDef(..) | FnPtr(..))
1566    }
1567
1568    #[inline]
1569    pub fn is_fn_ptr(self) -> bool {
1570        matches!(self.kind(), FnPtr(..))
1571    }
1572
1573    #[inline]
1574    pub fn is_impl_trait(self) -> bool {
1575        matches!(self.kind(), Alias(ty::Opaque, ..))
1576    }
1577
1578    #[inline]
1579    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1580        match self.kind() {
1581            Adt(adt, _) => Some(*adt),
1582            _ => None,
1583        }
1584    }
1585
1586    /// Iterates over tuple fields.
1587    /// Panics when called on anything but a tuple.
1588    #[inline]
1589    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1590        match self.kind() {
1591            Tuple(args) => args,
1592            _ => bug!("tuple_fields called on non-tuple: {self:?}"),
1593        }
1594    }
1595
1596    /// If the type contains variants, returns the valid range of variant indices.
1597    //
1598    // FIXME: This requires the optimized MIR in the case of coroutines.
1599    #[inline]
1600    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1601        match self.kind() {
1602            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1603            TyKind::Coroutine(def_id, args) => {
1604                Some(args.as_coroutine().variant_range(*def_id, tcx))
1605            }
1606            _ => None,
1607        }
1608    }
1609
1610    /// If the type contains variants, returns the variant for `variant_index`.
1611    /// Panics if `variant_index` is out of range.
1612    //
1613    // FIXME: This requires the optimized MIR in the case of coroutines.
1614    #[inline]
1615    pub fn discriminant_for_variant(
1616        self,
1617        tcx: TyCtxt<'tcx>,
1618        variant_index: VariantIdx,
1619    ) -> Option<Discr<'tcx>> {
1620        match self.kind() {
1621            TyKind::Adt(adt, _) if adt.is_enum() => {
1622                Some(adt.discriminant_for_variant(tcx, variant_index))
1623            }
1624            TyKind::Coroutine(def_id, args) => {
1625                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1626            }
1627            _ => None,
1628        }
1629    }
1630
1631    /// Returns the type of the discriminant of this type.
1632    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1633        match self.kind() {
1634            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1635            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1636
1637            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1638                let assoc_items = tcx.associated_item_def_ids(
1639                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1640                );
1641                Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1642            }
1643
1644            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1645
1646            ty::Bool
1647            | ty::Char
1648            | ty::Int(_)
1649            | ty::Uint(_)
1650            | ty::Float(_)
1651            | ty::Adt(..)
1652            | ty::Foreign(_)
1653            | ty::Str
1654            | ty::Array(..)
1655            | ty::Slice(_)
1656            | ty::RawPtr(_, _)
1657            | ty::Ref(..)
1658            | ty::FnDef(..)
1659            | ty::FnPtr(..)
1660            | ty::Dynamic(..)
1661            | ty::Closure(..)
1662            | ty::CoroutineClosure(..)
1663            | ty::CoroutineWitness(..)
1664            | ty::Never
1665            | ty::Tuple(_)
1666            | ty::UnsafeBinder(_)
1667            | ty::Error(_)
1668            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1669
1670            ty::Bound(..)
1671            | ty::Placeholder(_)
1672            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1673                bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1674            }
1675        }
1676    }
1677
1678    /// Returns the type of metadata for (potentially wide) pointers to this type,
1679    /// or the struct tail if the metadata type cannot be determined.
1680    pub fn ptr_metadata_ty_or_tail(
1681        self,
1682        tcx: TyCtxt<'tcx>,
1683        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1684    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1685        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1686        match tail.kind() {
1687            // Sized types
1688            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1689            | ty::Uint(_)
1690            | ty::Int(_)
1691            | ty::Bool
1692            | ty::Float(_)
1693            | ty::FnDef(..)
1694            | ty::FnPtr(..)
1695            | ty::RawPtr(..)
1696            | ty::Char
1697            | ty::Ref(..)
1698            | ty::Coroutine(..)
1699            | ty::CoroutineWitness(..)
1700            | ty::Array(..)
1701            | ty::Closure(..)
1702            | ty::CoroutineClosure(..)
1703            | ty::Never
1704            | ty::Error(_)
1705            // Extern types have metadata = ().
1706            | ty::Foreign(..)
1707            // If returned by `struct_tail_raw` this is a unit struct
1708            // without any fields, or not a struct, and therefore is Sized.
1709            | ty::Adt(..)
1710            // If returned by `struct_tail_raw` this is the empty tuple,
1711            // a.k.a. unit type, which is Sized
1712            | ty::Tuple(..) => Ok(tcx.types.unit),
1713
1714            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1715
1716            ty::Dynamic(_, _) => {
1717                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1718                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1719            }
1720
1721            // We don't know the metadata of `self`, but it must be equal to the
1722            // metadata of `tail`.
1723            ty::Param(_) | ty::Alias(..) => Err(tail),
1724
1725            | ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
1726
1727            ty::Infer(ty::TyVar(_))
1728            | ty::Pat(..)
1729            | ty::Bound(..)
1730            | ty::Placeholder(..)
1731            | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(
1732                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1733            ),
1734        }
1735    }
1736
1737    /// Returns the type of metadata for (potentially wide) pointers to this type.
1738    /// Causes an ICE if the metadata type cannot be determined.
1739    pub fn ptr_metadata_ty(
1740        self,
1741        tcx: TyCtxt<'tcx>,
1742        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1743    ) -> Ty<'tcx> {
1744        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1745            Ok(metadata) => metadata,
1746            Err(tail) => bug!(
1747                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1748            ),
1749        }
1750    }
1751
1752    /// Given a pointer or reference type, returns the type of the *pointee*'s
1753    /// metadata. If it can't be determined exactly (perhaps due to still
1754    /// being generic) then a projection through `ptr::Pointee` will be returned.
1755    ///
1756    /// This is particularly useful for getting the type of the result of
1757    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1758    ///
1759    /// Panics if `self` is not dereferenceable.
1760    #[track_caller]
1761    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1762        let Some(pointee_ty) = self.builtin_deref(true) else {
1763            bug!("Type {self:?} is not a pointer or reference type")
1764        };
1765        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1766            tcx.types.unit
1767        } else {
1768            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1769                Ok(metadata_ty) => metadata_ty,
1770                Err(tail_ty) => {
1771                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1772                    Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1773                }
1774            }
1775        }
1776    }
1777
1778    /// When we create a closure, we record its kind (i.e., what trait
1779    /// it implements, constrained by how it uses its borrows) into its
1780    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1781    /// parameter. This is kind of a phantom type, except that the
1782    /// most convenient thing for us to are the integral types. This
1783    /// function converts such a special type into the closure
1784    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1785    ///
1786    /// Note that during type checking, we use an inference variable
1787    /// to represent the closure kind, because it has not yet been
1788    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1789    /// is complete, that type variable will be unified with one of
1790    /// the integral types.
1791    ///
1792    /// ```rust,ignore (snippet of compiler code)
1793    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1794    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1795    /// {
1796    ///     println!("{closure_kind:?}");
1797    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1798    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1799    /// {
1800    ///     println!("{closure_kind:?}");
1801    /// }
1802    /// ```
1803    ///
1804    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1805    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1806    /// has been constrained instead of manually calling this method.
1807    ///
1808    /// ```rust,ignore (snippet of compiler code)
1809    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1810    /// {
1811    ///     println!("{:?}", args.as_closure().kind());
1812    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1813    /// {
1814    ///     println!("{:?}", args.as_coroutine_closure().kind());
1815    /// }
1816    /// ```
1817    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1818        match self.kind() {
1819            Int(int_ty) => match int_ty {
1820                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1821                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1822                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1823                _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1824            },
1825
1826            // "Bound" types appear in canonical queries when the
1827            // closure type is not yet known, and `Placeholder` and `Param`
1828            // may be encountered in generic `AsyncFnKindHelper` goals.
1829            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1830
1831            Error(_) => Some(ty::ClosureKind::Fn),
1832
1833            _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1834        }
1835    }
1836
1837    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1838    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1839    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1840        match kind {
1841            ty::ClosureKind::Fn => tcx.types.i8,
1842            ty::ClosureKind::FnMut => tcx.types.i16,
1843            ty::ClosureKind::FnOnce => tcx.types.i32,
1844        }
1845    }
1846
1847    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1848    /// to `FnMut`. This is because although we have three capability states,
1849    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1850    /// bodies: by-ref and by-value.
1851    ///
1852    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1853    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1854    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1855    ///
1856    /// This method should be used when constructing a `Coroutine` out of a
1857    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1858    /// directly from the `CoroutineClosure`'s `kind`.
1859    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1860        match kind {
1861            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1862            ty::ClosureKind::FnOnce => tcx.types.i32,
1863        }
1864    }
1865
1866    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1867    ///
1868    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1869    /// means nothing -- could be sized, might not be.
1870    ///
1871    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1872    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1873    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1874    /// This is why this method doesn't return `Option<bool>`.
1875    #[instrument(skip(tcx), level = "debug")]
1876    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1877        match self.kind() {
1878            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1879            | ty::Uint(_)
1880            | ty::Int(_)
1881            | ty::Bool
1882            | ty::Float(_)
1883            | ty::FnDef(..)
1884            | ty::FnPtr(..)
1885            | ty::UnsafeBinder(_)
1886            | ty::RawPtr(..)
1887            | ty::Char
1888            | ty::Ref(..)
1889            | ty::Coroutine(..)
1890            | ty::CoroutineWitness(..)
1891            | ty::Array(..)
1892            | ty::Pat(..)
1893            | ty::Closure(..)
1894            | ty::CoroutineClosure(..)
1895            | ty::Never
1896            | ty::Error(_) => true,
1897
1898            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1899                SizedTraitKind::Sized => false,
1900                SizedTraitKind::MetaSized => true,
1901            },
1902
1903            ty::Foreign(..) => match sizedness {
1904                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1905            },
1906
1907            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1908
1909            ty::Adt(def, args) => def
1910                .sizedness_constraint(tcx, sizedness)
1911                .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1912
1913            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1914
1915            ty::Infer(ty::TyVar(_)) => false,
1916
1917            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1918                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1919            }
1920        }
1921    }
1922
1923    /// Fast path helper for primitives which are always `Copy` and which
1924    /// have a side-effect-free `Clone` impl.
1925    ///
1926    /// Returning true means the type is known to be pure and `Copy+Clone`.
1927    /// Returning `false` means nothing -- could be `Copy`, might not be.
1928    ///
1929    /// This is mostly useful for optimizations, as these are the types
1930    /// on which we can replace cloning with dereferencing.
1931    pub fn is_trivially_pure_clone_copy(self) -> bool {
1932        match self.kind() {
1933            ty::Bool | ty::Char | ty::Never => true,
1934
1935            // These aren't even `Clone`
1936            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1937
1938            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1939            | ty::Int(..)
1940            | ty::Uint(..)
1941            | ty::Float(..) => true,
1942
1943            // ZST which can't be named are fine.
1944            ty::FnDef(..) => true,
1945
1946            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1947
1948            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
1949            ty::Tuple(field_tys) => {
1950                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1951            }
1952
1953            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1954
1955            // Sometimes traits aren't implemented for every ABI or arity,
1956            // because we can't be generic over everything yet.
1957            ty::FnPtr(..) => false,
1958
1959            // Definitely absolutely not copy.
1960            ty::Ref(_, _, hir::Mutability::Mut) => false,
1961
1962            // The standard library has a blanket Copy impl for shared references and raw pointers,
1963            // for all unsized types.
1964            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1965
1966            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1967
1968            // Might be, but not "trivial" so just giving the safe answer.
1969            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1970
1971            ty::UnsafeBinder(_) => false,
1972
1973            // Needs normalization or revealing to determine, so no is the safe answer.
1974            ty::Alias(..) => false,
1975
1976            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
1977                false
1978            }
1979        }
1980    }
1981
1982    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
1983        match *self.kind() {
1984            ty::Bool
1985            | ty::Char
1986            | ty::Int(_)
1987            | ty::Uint(_)
1988            | ty::Float(_)
1989            | ty::Str
1990            | ty::Never
1991            | ty::Param(_)
1992            | ty::Placeholder(_)
1993            | ty::Bound(..) => true,
1994
1995            ty::Slice(ty) => {
1996                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1997            }
1998            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
1999
2000            ty::FnPtr(sig_tys, _) => {
2001                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2002            }
2003            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2004
2005            ty::Infer(infer) => match infer {
2006                ty::TyVar(_) => false,
2007                ty::IntVar(_) | ty::FloatVar(_) => true,
2008                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2009            },
2010
2011            ty::Adt(_, _)
2012            | ty::Tuple(_)
2013            | ty::Array(..)
2014            | ty::Foreign(_)
2015            | ty::Pat(_, _)
2016            | ty::FnDef(..)
2017            | ty::UnsafeBinder(..)
2018            | ty::Dynamic(..)
2019            | ty::Closure(..)
2020            | ty::CoroutineClosure(..)
2021            | ty::Coroutine(..)
2022            | ty::CoroutineWitness(..)
2023            | ty::Alias(..)
2024            | ty::Error(_) => false,
2025        }
2026    }
2027
2028    /// If `self` is a primitive, return its [`Symbol`].
2029    pub fn primitive_symbol(self) -> Option<Symbol> {
2030        match self.kind() {
2031            ty::Bool => Some(sym::bool),
2032            ty::Char => Some(sym::char),
2033            ty::Float(f) => match f {
2034                ty::FloatTy::F16 => Some(sym::f16),
2035                ty::FloatTy::F32 => Some(sym::f32),
2036                ty::FloatTy::F64 => Some(sym::f64),
2037                ty::FloatTy::F128 => Some(sym::f128),
2038            },
2039            ty::Int(f) => match f {
2040                ty::IntTy::Isize => Some(sym::isize),
2041                ty::IntTy::I8 => Some(sym::i8),
2042                ty::IntTy::I16 => Some(sym::i16),
2043                ty::IntTy::I32 => Some(sym::i32),
2044                ty::IntTy::I64 => Some(sym::i64),
2045                ty::IntTy::I128 => Some(sym::i128),
2046            },
2047            ty::Uint(f) => match f {
2048                ty::UintTy::Usize => Some(sym::usize),
2049                ty::UintTy::U8 => Some(sym::u8),
2050                ty::UintTy::U16 => Some(sym::u16),
2051                ty::UintTy::U32 => Some(sym::u32),
2052                ty::UintTy::U64 => Some(sym::u64),
2053                ty::UintTy::U128 => Some(sym::u128),
2054            },
2055            ty::Str => Some(sym::str),
2056            _ => None,
2057        }
2058    }
2059
2060    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2061        match self.kind() {
2062            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2063            _ => false,
2064        }
2065    }
2066
2067    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2068        match self.kind() {
2069            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2070            _ => false,
2071        }
2072    }
2073
2074    /// Returns `true` when the outermost type cannot be further normalized,
2075    /// resolved, or instantiated. This includes all primitive types, but also
2076    /// things like ADTs and trait objects, since even if their arguments or
2077    /// nested types may be further simplified, the outermost [`TyKind`] or
2078    /// type constructor remains the same.
2079    pub fn is_known_rigid(self) -> bool {
2080        self.kind().is_known_rigid()
2081    }
2082
2083    /// Iterator that walks `self` and any types reachable from
2084    /// `self`, in depth-first order. Note that just walks the types
2085    /// that appear in `self`, it does not descend into the fields of
2086    /// structs or variants. For example:
2087    ///
2088    /// ```text
2089    /// isize => { isize }
2090    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2091    /// [isize] => { [isize], isize }
2092    /// ```
2093    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2094        TypeWalker::new(self.into())
2095    }
2096}
2097
2098impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2099    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2100        self.split_last().unwrap().1
2101    }
2102
2103    fn output(self) -> Ty<'tcx> {
2104        *self.split_last().unwrap().0
2105    }
2106}
2107
2108// Some types are used a lot. Make sure they don't unintentionally get bigger.
2109#[cfg(target_pointer_width = "64")]
2110mod size_asserts {
2111    use rustc_data_structures::static_assert_size;
2112
2113    use super::*;
2114    // tidy-alphabetical-start
2115    static_assert_size!(TyKind<'_>, 24);
2116    static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 48);
2117    // tidy-alphabetical-end
2118}