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