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