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    pub fn maybe_pinned_ref(self) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability)> {
1370        match *self.kind() {
1371            Adt(def, args)
1372                if def.is_pin()
1373                    && let ty::Ref(_, ty, mutbl) = *args.type_at(0).kind() =>
1374            {
1375                Some((ty, ty::Pinnedness::Pinned, mutbl))
1376            }
1377            ty::Ref(_, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl)),
1378            _ => None,
1379        }
1380    }
1381
1382    /// Panics if called on any type other than `Box<T>`.
1383    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1384        self.boxed_ty()
1385            .unwrap_or_else(|| bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1386    }
1387
1388    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1389    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1390    /// contents are abstract to rustc.)
1391    #[inline]
1392    pub fn is_scalar(self) -> bool {
1393        matches!(
1394            self.kind(),
1395            Bool | Char
1396                | Int(_)
1397                | Float(_)
1398                | Uint(_)
1399                | FnDef(..)
1400                | FnPtr(..)
1401                | RawPtr(_, _)
1402                | Infer(IntVar(_) | FloatVar(_))
1403        )
1404    }
1405
1406    /// Returns `true` if this type is a floating point type.
1407    #[inline]
1408    pub fn is_floating_point(self) -> bool {
1409        matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1410    }
1411
1412    #[inline]
1413    pub fn is_trait(self) -> bool {
1414        matches!(self.kind(), Dynamic(_, _))
1415    }
1416
1417    #[inline]
1418    pub fn is_enum(self) -> bool {
1419        matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1420    }
1421
1422    #[inline]
1423    pub fn is_union(self) -> bool {
1424        matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1425    }
1426
1427    #[inline]
1428    pub fn is_closure(self) -> bool {
1429        matches!(self.kind(), Closure(..))
1430    }
1431
1432    #[inline]
1433    pub fn is_coroutine(self) -> bool {
1434        matches!(self.kind(), Coroutine(..))
1435    }
1436
1437    #[inline]
1438    pub fn is_coroutine_closure(self) -> bool {
1439        matches!(self.kind(), CoroutineClosure(..))
1440    }
1441
1442    #[inline]
1443    pub fn is_integral(self) -> bool {
1444        matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1445    }
1446
1447    #[inline]
1448    pub fn is_fresh_ty(self) -> bool {
1449        matches!(self.kind(), Infer(FreshTy(_)))
1450    }
1451
1452    #[inline]
1453    pub fn is_fresh(self) -> bool {
1454        matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1455    }
1456
1457    #[inline]
1458    pub fn is_char(self) -> bool {
1459        matches!(self.kind(), Char)
1460    }
1461
1462    #[inline]
1463    pub fn is_numeric(self) -> bool {
1464        self.is_integral() || self.is_floating_point()
1465    }
1466
1467    #[inline]
1468    pub fn is_signed(self) -> bool {
1469        matches!(self.kind(), Int(_))
1470    }
1471
1472    #[inline]
1473    pub fn is_ptr_sized_integral(self) -> bool {
1474        matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1475    }
1476
1477    #[inline]
1478    pub fn has_concrete_skeleton(self) -> bool {
1479        !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1480    }
1481
1482    /// Checks whether a type recursively contains another type
1483    ///
1484    /// Example: `Option<()>` contains `()`
1485    pub fn contains(self, other: Ty<'tcx>) -> bool {
1486        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1487
1488        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1489            type Result = ControlFlow<()>;
1490
1491            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1492                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1493            }
1494        }
1495
1496        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1497        cf.is_break()
1498    }
1499
1500    /// Checks whether a type recursively contains any closure
1501    ///
1502    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1503    pub fn contains_closure(self) -> bool {
1504        struct ContainsClosureVisitor;
1505
1506        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1507            type Result = ControlFlow<()>;
1508
1509            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1510                if let ty::Closure(..) = t.kind() {
1511                    ControlFlow::Break(())
1512                } else {
1513                    t.super_visit_with(self)
1514                }
1515            }
1516        }
1517
1518        let cf = self.visit_with(&mut ContainsClosureVisitor);
1519        cf.is_break()
1520    }
1521
1522    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1523    ///
1524    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1525    /// to call async drop poll from impl coroutine.
1526    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1527        self,
1528        tcx: TyCtxt<'tcx>,
1529        mut f: F,
1530    ) -> Ty<'tcx> {
1531        assert!(self.is_coroutine());
1532        let mut cor_ty = self;
1533        let mut ty = cor_ty;
1534        loop {
1535            if let ty::Coroutine(def_id, args) = ty.kind() {
1536                cor_ty = ty;
1537                f(ty);
1538                if tcx.is_async_drop_in_place_coroutine(*def_id) {
1539                    ty = args.first().unwrap().expect_ty();
1540                    continue;
1541                } else {
1542                    return cor_ty;
1543                }
1544            } else {
1545                return cor_ty;
1546            }
1547        }
1548    }
1549
1550    /// Returns the type of `*ty`.
1551    ///
1552    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1553    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1554    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1555        match *self.kind() {
1556            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1557            Ref(_, ty, _) => Some(ty),
1558            RawPtr(ty, _) if explicit => Some(ty),
1559            _ => None,
1560        }
1561    }
1562
1563    /// Returns the type of `ty[i]`.
1564    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1565        match self.kind() {
1566            Array(ty, _) | Slice(ty) => Some(*ty),
1567            _ => None,
1568        }
1569    }
1570
1571    #[tracing::instrument(level = "trace", skip(tcx))]
1572    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1573        self.kind().fn_sig(tcx)
1574    }
1575
1576    #[inline]
1577    pub fn is_fn(self) -> bool {
1578        matches!(self.kind(), FnDef(..) | FnPtr(..))
1579    }
1580
1581    #[inline]
1582    pub fn is_fn_ptr(self) -> bool {
1583        matches!(self.kind(), FnPtr(..))
1584    }
1585
1586    #[inline]
1587    pub fn is_impl_trait(self) -> bool {
1588        matches!(self.kind(), Alias(ty::Opaque, ..))
1589    }
1590
1591    #[inline]
1592    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1593        match self.kind() {
1594            Adt(adt, _) => Some(*adt),
1595            _ => None,
1596        }
1597    }
1598
1599    /// Iterates over tuple fields.
1600    /// Panics when called on anything but a tuple.
1601    #[inline]
1602    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1603        match self.kind() {
1604            Tuple(args) => args,
1605            _ => bug!("tuple_fields called on non-tuple: {self:?}"),
1606        }
1607    }
1608
1609    /// If the type contains variants, returns the valid range of variant indices.
1610    //
1611    // FIXME: This requires the optimized MIR in the case of coroutines.
1612    #[inline]
1613    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1614        match self.kind() {
1615            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1616            TyKind::Coroutine(def_id, args) => {
1617                Some(args.as_coroutine().variant_range(*def_id, tcx))
1618            }
1619            _ => None,
1620        }
1621    }
1622
1623    /// If the type contains variants, returns the variant for `variant_index`.
1624    /// Panics if `variant_index` is out of range.
1625    //
1626    // FIXME: This requires the optimized MIR in the case of coroutines.
1627    #[inline]
1628    pub fn discriminant_for_variant(
1629        self,
1630        tcx: TyCtxt<'tcx>,
1631        variant_index: VariantIdx,
1632    ) -> Option<Discr<'tcx>> {
1633        match self.kind() {
1634            TyKind::Adt(adt, _) if adt.is_enum() => {
1635                Some(adt.discriminant_for_variant(tcx, variant_index))
1636            }
1637            TyKind::Coroutine(def_id, args) => {
1638                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1639            }
1640            _ => None,
1641        }
1642    }
1643
1644    /// Returns the type of the discriminant of this type.
1645    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1646        match self.kind() {
1647            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1648            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1649
1650            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1651                let assoc_items = tcx.associated_item_def_ids(
1652                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1653                );
1654                Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1655            }
1656
1657            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1658
1659            ty::Bool
1660            | ty::Char
1661            | ty::Int(_)
1662            | ty::Uint(_)
1663            | ty::Float(_)
1664            | ty::Adt(..)
1665            | ty::Foreign(_)
1666            | ty::Str
1667            | ty::Array(..)
1668            | ty::Slice(_)
1669            | ty::RawPtr(_, _)
1670            | ty::Ref(..)
1671            | ty::FnDef(..)
1672            | ty::FnPtr(..)
1673            | ty::Dynamic(..)
1674            | ty::Closure(..)
1675            | ty::CoroutineClosure(..)
1676            | ty::CoroutineWitness(..)
1677            | ty::Never
1678            | ty::Tuple(_)
1679            | ty::UnsafeBinder(_)
1680            | ty::Error(_)
1681            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1682
1683            ty::Bound(..)
1684            | ty::Placeholder(_)
1685            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1686                bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1687            }
1688        }
1689    }
1690
1691    /// Returns the type of metadata for (potentially wide) pointers to this type,
1692    /// or the struct tail if the metadata type cannot be determined.
1693    pub fn ptr_metadata_ty_or_tail(
1694        self,
1695        tcx: TyCtxt<'tcx>,
1696        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1697    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1698        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1699        match tail.kind() {
1700            // Sized types
1701            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1702            | ty::Uint(_)
1703            | ty::Int(_)
1704            | ty::Bool
1705            | ty::Float(_)
1706            | ty::FnDef(..)
1707            | ty::FnPtr(..)
1708            | ty::RawPtr(..)
1709            | ty::Char
1710            | ty::Ref(..)
1711            | ty::Coroutine(..)
1712            | ty::CoroutineWitness(..)
1713            | ty::Array(..)
1714            | ty::Closure(..)
1715            | ty::CoroutineClosure(..)
1716            | ty::Never
1717            | ty::Error(_)
1718            // Extern types have metadata = ().
1719            | ty::Foreign(..)
1720            // If returned by `struct_tail_raw` this is a unit struct
1721            // without any fields, or not a struct, and therefore is Sized.
1722            | ty::Adt(..)
1723            // If returned by `struct_tail_raw` this is the empty tuple,
1724            // a.k.a. unit type, which is Sized
1725            | ty::Tuple(..) => Ok(tcx.types.unit),
1726
1727            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1728
1729            ty::Dynamic(_, _) => {
1730                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1731                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1732            }
1733
1734            // We don't know the metadata of `self`, but it must be equal to the
1735            // metadata of `tail`.
1736            ty::Param(_) | ty::Alias(..) => Err(tail),
1737
1738            | ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
1739
1740            ty::Infer(ty::TyVar(_))
1741            | ty::Pat(..)
1742            | ty::Bound(..)
1743            | ty::Placeholder(..)
1744            | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(
1745                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1746            ),
1747        }
1748    }
1749
1750    /// Returns the type of metadata for (potentially wide) pointers to this type.
1751    /// Causes an ICE if the metadata type cannot be determined.
1752    pub fn ptr_metadata_ty(
1753        self,
1754        tcx: TyCtxt<'tcx>,
1755        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1756    ) -> Ty<'tcx> {
1757        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1758            Ok(metadata) => metadata,
1759            Err(tail) => bug!(
1760                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1761            ),
1762        }
1763    }
1764
1765    /// Given a pointer or reference type, returns the type of the *pointee*'s
1766    /// metadata. If it can't be determined exactly (perhaps due to still
1767    /// being generic) then a projection through `ptr::Pointee` will be returned.
1768    ///
1769    /// This is particularly useful for getting the type of the result of
1770    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1771    ///
1772    /// Panics if `self` is not dereferenceable.
1773    #[track_caller]
1774    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1775        let Some(pointee_ty) = self.builtin_deref(true) else {
1776            bug!("Type {self:?} is not a pointer or reference type")
1777        };
1778        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1779            tcx.types.unit
1780        } else {
1781            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1782                Ok(metadata_ty) => metadata_ty,
1783                Err(tail_ty) => {
1784                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1785                    Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1786                }
1787            }
1788        }
1789    }
1790
1791    /// When we create a closure, we record its kind (i.e., what trait
1792    /// it implements, constrained by how it uses its borrows) into its
1793    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1794    /// parameter. This is kind of a phantom type, except that the
1795    /// most convenient thing for us to are the integral types. This
1796    /// function converts such a special type into the closure
1797    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1798    ///
1799    /// Note that during type checking, we use an inference variable
1800    /// to represent the closure kind, because it has not yet been
1801    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1802    /// is complete, that type variable will be unified with one of
1803    /// the integral types.
1804    ///
1805    /// ```rust,ignore (snippet of compiler code)
1806    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1807    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1808    /// {
1809    ///     println!("{closure_kind:?}");
1810    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1811    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1812    /// {
1813    ///     println!("{closure_kind:?}");
1814    /// }
1815    /// ```
1816    ///
1817    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1818    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1819    /// has been constrained instead of manually calling this method.
1820    ///
1821    /// ```rust,ignore (snippet of compiler code)
1822    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1823    /// {
1824    ///     println!("{:?}", args.as_closure().kind());
1825    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1826    /// {
1827    ///     println!("{:?}", args.as_coroutine_closure().kind());
1828    /// }
1829    /// ```
1830    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1831        match self.kind() {
1832            Int(int_ty) => match int_ty {
1833                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1834                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1835                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1836                _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1837            },
1838
1839            // "Bound" types appear in canonical queries when the
1840            // closure type is not yet known, and `Placeholder` and `Param`
1841            // may be encountered in generic `AsyncFnKindHelper` goals.
1842            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1843
1844            Error(_) => Some(ty::ClosureKind::Fn),
1845
1846            _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1847        }
1848    }
1849
1850    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1851    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1852    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1853        match kind {
1854            ty::ClosureKind::Fn => tcx.types.i8,
1855            ty::ClosureKind::FnMut => tcx.types.i16,
1856            ty::ClosureKind::FnOnce => tcx.types.i32,
1857        }
1858    }
1859
1860    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1861    /// to `FnMut`. This is because although we have three capability states,
1862    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1863    /// bodies: by-ref and by-value.
1864    ///
1865    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1866    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1867    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1868    ///
1869    /// This method should be used when constructing a `Coroutine` out of a
1870    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1871    /// directly from the `CoroutineClosure`'s `kind`.
1872    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1873        match kind {
1874            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1875            ty::ClosureKind::FnOnce => tcx.types.i32,
1876        }
1877    }
1878
1879    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1880    ///
1881    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1882    /// means nothing -- could be sized, might not be.
1883    ///
1884    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1885    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1886    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1887    /// This is why this method doesn't return `Option<bool>`.
1888    #[instrument(skip(tcx), level = "debug")]
1889    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1890        match self.kind() {
1891            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1892            | ty::Uint(_)
1893            | ty::Int(_)
1894            | ty::Bool
1895            | ty::Float(_)
1896            | ty::FnDef(..)
1897            | ty::FnPtr(..)
1898            | ty::UnsafeBinder(_)
1899            | ty::RawPtr(..)
1900            | ty::Char
1901            | ty::Ref(..)
1902            | ty::Coroutine(..)
1903            | ty::CoroutineWitness(..)
1904            | ty::Array(..)
1905            | ty::Pat(..)
1906            | ty::Closure(..)
1907            | ty::CoroutineClosure(..)
1908            | ty::Never
1909            | ty::Error(_) => true,
1910
1911            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1912                SizedTraitKind::Sized => false,
1913                SizedTraitKind::MetaSized => true,
1914            },
1915
1916            ty::Foreign(..) => match sizedness {
1917                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1918            },
1919
1920            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1921
1922            ty::Adt(def, args) => def
1923                .sizedness_constraint(tcx, sizedness)
1924                .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1925
1926            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1927
1928            ty::Infer(ty::TyVar(_)) => false,
1929
1930            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1931                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1932            }
1933        }
1934    }
1935
1936    /// Fast path helper for primitives which are always `Copy` and which
1937    /// have a side-effect-free `Clone` impl.
1938    ///
1939    /// Returning true means the type is known to be pure and `Copy+Clone`.
1940    /// Returning `false` means nothing -- could be `Copy`, might not be.
1941    ///
1942    /// This is mostly useful for optimizations, as these are the types
1943    /// on which we can replace cloning with dereferencing.
1944    pub fn is_trivially_pure_clone_copy(self) -> bool {
1945        match self.kind() {
1946            ty::Bool | ty::Char | ty::Never => true,
1947
1948            // These aren't even `Clone`
1949            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1950
1951            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1952            | ty::Int(..)
1953            | ty::Uint(..)
1954            | ty::Float(..) => true,
1955
1956            // ZST which can't be named are fine.
1957            ty::FnDef(..) => true,
1958
1959            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1960
1961            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
1962            ty::Tuple(field_tys) => {
1963                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1964            }
1965
1966            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1967
1968            // Sometimes traits aren't implemented for every ABI or arity,
1969            // because we can't be generic over everything yet.
1970            ty::FnPtr(..) => false,
1971
1972            // Definitely absolutely not copy.
1973            ty::Ref(_, _, hir::Mutability::Mut) => false,
1974
1975            // The standard library has a blanket Copy impl for shared references and raw pointers,
1976            // for all unsized types.
1977            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1978
1979            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1980
1981            // Might be, but not "trivial" so just giving the safe answer.
1982            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1983
1984            ty::UnsafeBinder(_) => false,
1985
1986            // Needs normalization or revealing to determine, so no is the safe answer.
1987            ty::Alias(..) => false,
1988
1989            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
1990                false
1991            }
1992        }
1993    }
1994
1995    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
1996        match *self.kind() {
1997            ty::Bool
1998            | ty::Char
1999            | ty::Int(_)
2000            | ty::Uint(_)
2001            | ty::Float(_)
2002            | ty::Str
2003            | ty::Never
2004            | ty::Param(_)
2005            | ty::Placeholder(_)
2006            | ty::Bound(..) => true,
2007
2008            ty::Slice(ty) => {
2009                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2010            }
2011            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2012
2013            ty::FnPtr(sig_tys, _) => {
2014                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2015            }
2016            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2017
2018            ty::Infer(infer) => match infer {
2019                ty::TyVar(_) => false,
2020                ty::IntVar(_) | ty::FloatVar(_) => true,
2021                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2022            },
2023
2024            ty::Adt(_, _)
2025            | ty::Tuple(_)
2026            | ty::Array(..)
2027            | ty::Foreign(_)
2028            | ty::Pat(_, _)
2029            | ty::FnDef(..)
2030            | ty::UnsafeBinder(..)
2031            | ty::Dynamic(..)
2032            | ty::Closure(..)
2033            | ty::CoroutineClosure(..)
2034            | ty::Coroutine(..)
2035            | ty::CoroutineWitness(..)
2036            | ty::Alias(..)
2037            | ty::Error(_) => false,
2038        }
2039    }
2040
2041    /// If `self` is a primitive, return its [`Symbol`].
2042    pub fn primitive_symbol(self) -> Option<Symbol> {
2043        match self.kind() {
2044            ty::Bool => Some(sym::bool),
2045            ty::Char => Some(sym::char),
2046            ty::Float(f) => match f {
2047                ty::FloatTy::F16 => Some(sym::f16),
2048                ty::FloatTy::F32 => Some(sym::f32),
2049                ty::FloatTy::F64 => Some(sym::f64),
2050                ty::FloatTy::F128 => Some(sym::f128),
2051            },
2052            ty::Int(f) => match f {
2053                ty::IntTy::Isize => Some(sym::isize),
2054                ty::IntTy::I8 => Some(sym::i8),
2055                ty::IntTy::I16 => Some(sym::i16),
2056                ty::IntTy::I32 => Some(sym::i32),
2057                ty::IntTy::I64 => Some(sym::i64),
2058                ty::IntTy::I128 => Some(sym::i128),
2059            },
2060            ty::Uint(f) => match f {
2061                ty::UintTy::Usize => Some(sym::usize),
2062                ty::UintTy::U8 => Some(sym::u8),
2063                ty::UintTy::U16 => Some(sym::u16),
2064                ty::UintTy::U32 => Some(sym::u32),
2065                ty::UintTy::U64 => Some(sym::u64),
2066                ty::UintTy::U128 => Some(sym::u128),
2067            },
2068            ty::Str => Some(sym::str),
2069            _ => None,
2070        }
2071    }
2072
2073    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2074        match self.kind() {
2075            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2076            _ => false,
2077        }
2078    }
2079
2080    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2081        match self.kind() {
2082            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2083            _ => false,
2084        }
2085    }
2086
2087    /// Returns `true` when the outermost type cannot be further normalized,
2088    /// resolved, or instantiated. This includes all primitive types, but also
2089    /// things like ADTs and trait objects, since even if their arguments or
2090    /// nested types may be further simplified, the outermost [`TyKind`] or
2091    /// type constructor remains the same.
2092    pub fn is_known_rigid(self) -> bool {
2093        self.kind().is_known_rigid()
2094    }
2095
2096    /// Iterator that walks `self` and any types reachable from
2097    /// `self`, in depth-first order. Note that just walks the types
2098    /// that appear in `self`, it does not descend into the fields of
2099    /// structs or variants. For example:
2100    ///
2101    /// ```text
2102    /// isize => { isize }
2103    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2104    /// [isize] => { [isize], isize }
2105    /// ```
2106    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2107        TypeWalker::new(self.into())
2108    }
2109}
2110
2111impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2112    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2113        self.split_last().unwrap().1
2114    }
2115
2116    fn output(self) -> Ty<'tcx> {
2117        *self.split_last().unwrap().0
2118    }
2119}
2120
2121// Some types are used a lot. Make sure they don't unintentionally get bigger.
2122#[cfg(target_pointer_width = "64")]
2123mod size_asserts {
2124    use rustc_data_structures::static_assert_size;
2125
2126    use super::*;
2127    // tidy-alphabetical-start
2128    static_assert_size!(TyKind<'_>, 24);
2129    static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 48);
2130    // tidy-alphabetical-end
2131}