rustc_middle/ty/
sty.rs

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