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