1#![allow(rustc::usage_of_ty_tykind)]
4
5use std::assert_matches::debug_assert_matches;
6use std::borrow::Cow;
7use std::ops::{ControlFlow, Range};
8
9use hir::def::{CtorKind, DefKind};
10use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
11use rustc_errors::{ErrorGuaranteed, MultiSpan};
12use rustc_hir as hir;
13use rustc_hir::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, extension};
16use rustc_span::{DUMMY_SP, Span, Symbol, sym};
17use rustc_type_ir::TyKind::*;
18use rustc_type_ir::solve::SizedTraitKind;
19use rustc_type_ir::walk::TypeWalker;
20use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind, TypeVisitableExt, elaborate};
21use tracing::instrument;
22use ty::util::IntTypeExt;
23
24use super::GenericParamDefKind;
25use crate::infer::canonical::Canonical;
26use crate::ty::InferTy::*;
27use crate::ty::{
28 self, AdtDef, BoundRegionKind, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv,
29 Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy,
30};
31
32#[rustc_diagnostic_item = "TyKind"]
34pub type TyKind<'tcx> = ir::TyKind<TyCtxt<'tcx>>;
35pub type TypeAndMut<'tcx> = ir::TypeAndMut<TyCtxt<'tcx>>;
36pub type AliasTy<'tcx> = ir::AliasTy<TyCtxt<'tcx>>;
37pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
38pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
39pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
40pub type TypingMode<'tcx> = ir::TypingMode<TyCtxt<'tcx>>;
41
42pub trait Article {
43 fn article(&self) -> &'static str;
44}
45
46impl<'tcx> Article for TyKind<'tcx> {
47 fn article(&self) -> &'static str {
49 match self {
50 Int(_) | Float(_) | Array(_, _) => "an",
51 Adt(def, _) if def.is_enum() => "an",
52 Error(_) => "a",
55 _ => "a",
56 }
57 }
58}
59
60#[extension(pub trait CoroutineArgsExt<'tcx>)]
61impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
62 const UNRESUMED: usize = 0;
64 const RETURNED: usize = 1;
66 const POISONED: usize = 2;
68 const RESERVED_VARIANTS: usize = 3;
72
73 const UNRESUMED_NAME: &'static str = "Unresumed";
74 const RETURNED_NAME: &'static str = "Returned";
75 const POISONED_NAME: &'static str = "Panicked";
76
77 #[inline]
79 fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
80 FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
82 }
83
84 #[inline]
87 fn discriminant_for_variant(
88 &self,
89 def_id: DefId,
90 tcx: TyCtxt<'tcx>,
91 variant_index: VariantIdx,
92 ) -> Discr<'tcx> {
93 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
96 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
97 }
98
99 #[inline]
102 fn discriminants(
103 self,
104 def_id: DefId,
105 tcx: TyCtxt<'tcx>,
106 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
107 self.variant_range(def_id, tcx).map(move |index| {
108 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
109 })
110 }
111
112 fn variant_name(v: VariantIdx) -> Cow<'static, str> {
115 match v.as_usize() {
116 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
117 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
118 Self::POISONED => Cow::from(Self::POISONED_NAME),
119 _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
120 }
121 }
122
123 #[inline]
125 fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
126 tcx.types.u32
127 }
128
129 #[inline]
136 fn state_tys(
137 self,
138 def_id: DefId,
139 tcx: TyCtxt<'tcx>,
140 ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
141 let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
142 layout.variant_fields.iter().map(move |variant| {
143 variant.iter().map(move |field| {
144 if tcx.is_async_drop_in_place_coroutine(def_id) {
145 layout.field_tys[*field].ty
146 } else {
147 ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args)
148 }
149 })
150 })
151 }
152
153 #[inline]
156 fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
157 self.upvar_tys()
158 }
159}
160
161#[derive(Debug, Copy, Clone, HashStable, TypeFoldable, TypeVisitable)]
162pub enum UpvarArgs<'tcx> {
163 Closure(GenericArgsRef<'tcx>),
164 Coroutine(GenericArgsRef<'tcx>),
165 CoroutineClosure(GenericArgsRef<'tcx>),
166}
167
168impl<'tcx> UpvarArgs<'tcx> {
169 #[inline]
173 pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
174 let tupled_tys = match self {
175 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
176 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
177 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
178 };
179
180 match tupled_tys.kind() {
181 TyKind::Error(_) => ty::List::empty(),
182 TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
183 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
184 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
185 }
186 }
187
188 #[inline]
189 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
190 match self {
191 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
192 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
193 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
194 }
195 }
196}
197
198#[derive(Copy, Clone, Debug)]
213pub struct InlineConstArgs<'tcx> {
214 pub args: GenericArgsRef<'tcx>,
217}
218
219pub struct InlineConstArgsParts<'tcx, T> {
221 pub parent_args: &'tcx [GenericArg<'tcx>],
222 pub ty: T,
223}
224
225impl<'tcx> InlineConstArgs<'tcx> {
226 pub fn new(
228 tcx: TyCtxt<'tcx>,
229 parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
230 ) -> InlineConstArgs<'tcx> {
231 InlineConstArgs {
232 args: tcx.mk_args_from_iter(
233 parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
234 ),
235 }
236 }
237
238 fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
241 match self.args[..] {
242 [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
243 _ => bug!("inline const args missing synthetics"),
244 }
245 }
246
247 pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
249 self.split().parent_args
250 }
251
252 pub fn ty(self) -> Ty<'tcx> {
254 self.split().ty.expect_ty()
255 }
256}
257
258#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
259#[derive(HashStable)]
260pub enum BoundVariableKind {
261 Ty(BoundTyKind),
262 Region(BoundRegionKind),
263 Const,
264}
265
266impl BoundVariableKind {
267 pub fn expect_region(self) -> BoundRegionKind {
268 match self {
269 BoundVariableKind::Region(lt) => lt,
270 _ => bug!("expected a region, but found another kind"),
271 }
272 }
273
274 pub fn expect_ty(self) -> BoundTyKind {
275 match self {
276 BoundVariableKind::Ty(ty) => ty,
277 _ => bug!("expected a type, but found another kind"),
278 }
279 }
280
281 pub fn expect_const(self) {
282 match self {
283 BoundVariableKind::Const => (),
284 _ => bug!("expected a const, but found another kind"),
285 }
286 }
287}
288
289pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
290pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
291
292#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
293#[derive(HashStable)]
294pub struct ParamTy {
295 pub index: u32,
296 pub name: Symbol,
297}
298
299impl rustc_type_ir::inherent::ParamLike for ParamTy {
300 fn index(self) -> u32 {
301 self.index
302 }
303}
304
305impl<'tcx> ParamTy {
306 pub fn new(index: u32, name: Symbol) -> ParamTy {
307 ParamTy { index, name }
308 }
309
310 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
311 ParamTy::new(def.index, def.name)
312 }
313
314 #[inline]
315 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
316 Ty::new_param(tcx, self.index, self.name)
317 }
318
319 pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
320 let generics = tcx.generics_of(item_with_generics);
321 let type_param = generics.type_param(self, tcx);
322 tcx.def_span(type_param.def_id)
323 }
324}
325
326#[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
327#[derive(HashStable)]
328pub struct ParamConst {
329 pub index: u32,
330 pub name: Symbol,
331}
332
333impl rustc_type_ir::inherent::ParamLike for ParamConst {
334 fn index(self) -> u32 {
335 self.index
336 }
337}
338
339impl ParamConst {
340 pub fn new(index: u32, name: Symbol) -> ParamConst {
341 ParamConst { index, name }
342 }
343
344 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
345 ParamConst::new(def.index, def.name)
346 }
347
348 #[instrument(level = "debug")]
349 pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
350 let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
351 match clause.kind().skip_binder() {
353 ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
354 assert!(!(param_ct, ty).has_escaping_bound_vars());
355
356 match param_ct.kind() {
357 ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
358 _ => None,
359 }
360 }
361 _ => None,
362 }
363 });
364
365 let ty = candidates.next().unwrap_or_else(|| {
372 bug!("cannot find `{self:?}` in param-env: {env:#?}");
373 });
374 assert!(
375 candidates.next().is_none(),
376 "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
377 );
378 ty
379 }
380}
381
382#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
383#[derive(HashStable)]
384pub struct BoundTy {
385 pub var: BoundVar,
386 pub kind: BoundTyKind,
387}
388
389impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundTy {
390 fn var(self) -> BoundVar {
391 self.var
392 }
393
394 fn assert_eq(self, var: ty::BoundVariableKind) {
395 assert_eq!(self.kind, var.expect_ty())
396 }
397}
398
399#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
400#[derive(HashStable)]
401pub enum BoundTyKind {
402 Anon,
403 Param(DefId),
404}
405
406impl From<BoundVar> for BoundTy {
407 fn from(var: BoundVar) -> Self {
408 BoundTy { var, kind: BoundTyKind::Anon }
409 }
410}
411
412impl<'tcx> Ty<'tcx> {
414 #[allow(rustc::usage_of_ty_tykind)]
417 #[inline]
418 fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
419 tcx.mk_ty_from_kind(st)
420 }
421
422 #[inline]
423 pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
424 Ty::new(tcx, TyKind::Infer(infer))
425 }
426
427 #[inline]
428 pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
429 tcx.types
431 .ty_vars
432 .get(v.as_usize())
433 .copied()
434 .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
435 }
436
437 #[inline]
438 pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
439 Ty::new_infer(tcx, IntVar(v))
440 }
441
442 #[inline]
443 pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
444 Ty::new_infer(tcx, FloatVar(v))
445 }
446
447 #[inline]
448 pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
449 tcx.types
451 .fresh_tys
452 .get(n as usize)
453 .copied()
454 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
455 }
456
457 #[inline]
458 pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
459 tcx.types
461 .fresh_int_tys
462 .get(n as usize)
463 .copied()
464 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
465 }
466
467 #[inline]
468 pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
469 tcx.types
471 .fresh_float_tys
472 .get(n as usize)
473 .copied()
474 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
475 }
476
477 #[inline]
478 pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
479 Ty::new(tcx, Param(ParamTy { index, name }))
480 }
481
482 #[inline]
483 pub fn new_bound(
484 tcx: TyCtxt<'tcx>,
485 index: ty::DebruijnIndex,
486 bound_ty: ty::BoundTy,
487 ) -> Ty<'tcx> {
488 if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
490 && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
491 && let Some(ty) = inner.get(var.as_usize()).copied()
492 {
493 ty
494 } else {
495 Ty::new(tcx, Bound(index, bound_ty))
496 }
497 }
498
499 #[inline]
500 pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Ty<'tcx> {
501 Ty::new(tcx, Placeholder(placeholder))
502 }
503
504 #[inline]
505 pub fn new_alias(
506 tcx: TyCtxt<'tcx>,
507 kind: ty::AliasTyKind,
508 alias_ty: ty::AliasTy<'tcx>,
509 ) -> Ty<'tcx> {
510 debug_assert_matches!(
511 (kind, tcx.def_kind(alias_ty.def_id)),
512 (ty::Opaque, DefKind::OpaqueTy)
513 | (ty::Projection | ty::Inherent, DefKind::AssocTy)
514 | (ty::Free, DefKind::TyAlias)
515 );
516 Ty::new(tcx, Alias(kind, alias_ty))
517 }
518
519 #[inline]
520 pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
521 Ty::new(tcx, Pat(base, pat))
522 }
523
524 #[inline]
525 #[instrument(level = "debug", skip(tcx))]
526 pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
527 Ty::new_alias(tcx, ty::Opaque, AliasTy::new_from_args(tcx, def_id, args))
528 }
529
530 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
532 Ty::new(tcx, Error(guar))
533 }
534
535 #[track_caller]
537 pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
538 Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
539 }
540
541 #[track_caller]
544 pub fn new_error_with_message<S: Into<MultiSpan>>(
545 tcx: TyCtxt<'tcx>,
546 span: S,
547 msg: impl Into<Cow<'static, str>>,
548 ) -> Ty<'tcx> {
549 let reported = tcx.dcx().span_delayed_bug(span, msg);
550 Ty::new(tcx, Error(reported))
551 }
552
553 #[inline]
554 pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
555 use ty::IntTy::*;
556 match i {
557 Isize => tcx.types.isize,
558 I8 => tcx.types.i8,
559 I16 => tcx.types.i16,
560 I32 => tcx.types.i32,
561 I64 => tcx.types.i64,
562 I128 => tcx.types.i128,
563 }
564 }
565
566 #[inline]
567 pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
568 use ty::UintTy::*;
569 match ui {
570 Usize => tcx.types.usize,
571 U8 => tcx.types.u8,
572 U16 => tcx.types.u16,
573 U32 => tcx.types.u32,
574 U64 => tcx.types.u64,
575 U128 => tcx.types.u128,
576 }
577 }
578
579 #[inline]
580 pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
581 use ty::FloatTy::*;
582 match f {
583 F16 => tcx.types.f16,
584 F32 => tcx.types.f32,
585 F64 => tcx.types.f64,
586 F128 => tcx.types.f128,
587 }
588 }
589
590 #[inline]
591 pub fn new_ref(
592 tcx: TyCtxt<'tcx>,
593 r: Region<'tcx>,
594 ty: Ty<'tcx>,
595 mutbl: ty::Mutability,
596 ) -> Ty<'tcx> {
597 Ty::new(tcx, Ref(r, ty, mutbl))
598 }
599
600 #[inline]
601 pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
602 Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
603 }
604
605 #[inline]
606 pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
607 Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
608 }
609
610 pub fn new_pinned_ref(
611 tcx: TyCtxt<'tcx>,
612 r: Region<'tcx>,
613 ty: Ty<'tcx>,
614 mutbl: ty::Mutability,
615 ) -> Ty<'tcx> {
616 let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
617 Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
618 }
619
620 #[inline]
621 pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
622 Ty::new(tcx, ty::RawPtr(ty, mutbl))
623 }
624
625 #[inline]
626 pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
627 Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
628 }
629
630 #[inline]
631 pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
632 Ty::new_ptr(tcx, ty, hir::Mutability::Not)
633 }
634
635 #[inline]
636 pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
637 tcx.debug_assert_args_compatible(def.did(), args);
638 if cfg!(debug_assertions) {
639 match tcx.def_kind(def.did()) {
640 DefKind::Struct | DefKind::Union | DefKind::Enum => {}
641 DefKind::Mod
642 | DefKind::Variant
643 | DefKind::Trait
644 | DefKind::TyAlias
645 | DefKind::ForeignTy
646 | DefKind::TraitAlias
647 | DefKind::AssocTy
648 | DefKind::TyParam
649 | DefKind::Fn
650 | DefKind::Const
651 | DefKind::ConstParam
652 | DefKind::Static { .. }
653 | DefKind::Ctor(..)
654 | DefKind::AssocFn
655 | DefKind::AssocConst
656 | DefKind::Macro(..)
657 | DefKind::ExternCrate
658 | DefKind::Use
659 | DefKind::ForeignMod
660 | DefKind::AnonConst
661 | DefKind::InlineConst
662 | DefKind::OpaqueTy
663 | DefKind::Field
664 | DefKind::LifetimeParam
665 | DefKind::GlobalAsm
666 | DefKind::Impl { .. }
667 | DefKind::Closure
668 | DefKind::SyntheticCoroutineBody => {
669 bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did()))
670 }
671 }
672 }
673 Ty::new(tcx, Adt(def, args))
674 }
675
676 #[inline]
677 pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
678 Ty::new(tcx, Foreign(def_id))
679 }
680
681 #[inline]
682 pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
683 Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
684 }
685
686 #[inline]
687 pub fn new_array_with_const_len(
688 tcx: TyCtxt<'tcx>,
689 ty: Ty<'tcx>,
690 ct: ty::Const<'tcx>,
691 ) -> Ty<'tcx> {
692 Ty::new(tcx, Array(ty, ct))
693 }
694
695 #[inline]
696 pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
697 Ty::new(tcx, Slice(ty))
698 }
699
700 #[inline]
701 pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
702 if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
703 }
704
705 pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
706 where
707 I: Iterator<Item = T>,
708 T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
709 {
710 T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
711 }
712
713 #[inline]
714 pub fn new_fn_def(
715 tcx: TyCtxt<'tcx>,
716 def_id: DefId,
717 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
718 ) -> Ty<'tcx> {
719 debug_assert_matches!(
720 tcx.def_kind(def_id),
721 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
722 );
723 let args = tcx.check_and_mk_args(def_id, args);
724 Ty::new(tcx, FnDef(def_id, args))
725 }
726
727 #[inline]
728 pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
729 let (sig_tys, hdr) = fty.split();
730 Ty::new(tcx, FnPtr(sig_tys, hdr))
731 }
732
733 #[inline]
734 pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
735 Ty::new(tcx, UnsafeBinder(b.into()))
736 }
737
738 #[inline]
739 pub fn new_dynamic(
740 tcx: TyCtxt<'tcx>,
741 obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
742 reg: ty::Region<'tcx>,
743 repr: DynKind,
744 ) -> Ty<'tcx> {
745 if cfg!(debug_assertions) {
746 let projection_count = obj
747 .projection_bounds()
748 .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
749 .count();
750 let expected_count: usize = obj
751 .principal_def_id()
752 .into_iter()
753 .flat_map(|principal_def_id| {
754 elaborate::supertraits(
757 tcx,
758 ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
759 )
760 .map(|principal| {
761 tcx.associated_items(principal.def_id())
762 .in_definition_order()
763 .filter(|item| item.is_type())
764 .filter(|item| !item.is_impl_trait_in_trait())
765 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
766 .count()
767 })
768 })
769 .sum();
770 assert_eq!(
771 projection_count, expected_count,
772 "expected {obj:?} to have {expected_count} projections, \
773 but it has {projection_count}"
774 );
775 }
776 Ty::new(tcx, Dynamic(obj, reg, repr))
777 }
778
779 #[inline]
780 pub fn new_projection_from_args(
781 tcx: TyCtxt<'tcx>,
782 item_def_id: DefId,
783 args: ty::GenericArgsRef<'tcx>,
784 ) -> Ty<'tcx> {
785 Ty::new_alias(tcx, ty::Projection, AliasTy::new_from_args(tcx, item_def_id, args))
786 }
787
788 #[inline]
789 pub fn new_projection(
790 tcx: TyCtxt<'tcx>,
791 item_def_id: DefId,
792 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
793 ) -> Ty<'tcx> {
794 Ty::new_alias(tcx, ty::Projection, AliasTy::new(tcx, item_def_id, args))
795 }
796
797 #[inline]
798 pub fn new_closure(
799 tcx: TyCtxt<'tcx>,
800 def_id: DefId,
801 closure_args: GenericArgsRef<'tcx>,
802 ) -> Ty<'tcx> {
803 tcx.debug_assert_args_compatible(def_id, closure_args);
804 Ty::new(tcx, Closure(def_id, closure_args))
805 }
806
807 #[inline]
808 pub fn new_coroutine_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, CoroutineClosure(def_id, closure_args))
815 }
816
817 #[inline]
818 pub fn new_coroutine(
819 tcx: TyCtxt<'tcx>,
820 def_id: DefId,
821 coroutine_args: GenericArgsRef<'tcx>,
822 ) -> Ty<'tcx> {
823 tcx.debug_assert_args_compatible(def_id, coroutine_args);
824 Ty::new(tcx, Coroutine(def_id, coroutine_args))
825 }
826
827 #[inline]
828 pub fn new_coroutine_witness(
829 tcx: TyCtxt<'tcx>,
830 id: DefId,
831 args: GenericArgsRef<'tcx>,
832 ) -> Ty<'tcx> {
833 Ty::new(tcx, CoroutineWitness(id, args))
834 }
835
836 #[inline]
839 pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
840 Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
841 }
842
843 #[inline]
844 pub fn new_diverging_default(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
845 if tcx.features().never_type_fallback() { tcx.types.never } else { tcx.types.unit }
846 }
847
848 fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
851 let adt_def = tcx.adt_def(wrapper_def_id);
852 let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
853 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
854 GenericParamDefKind::Type { has_default, .. } => {
855 if param.index == 0 {
856 ty_param.into()
857 } else {
858 assert!(has_default);
859 tcx.type_of(param.def_id).instantiate(tcx, args).into()
860 }
861 }
862 });
863 Ty::new_adt(tcx, adt_def, args)
864 }
865
866 #[inline]
867 pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
868 let def_id = tcx.lang_items().get(item)?;
869 Some(Ty::new_generic_adt(tcx, def_id, ty))
870 }
871
872 #[inline]
873 pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
874 let def_id = tcx.get_diagnostic_item(name)?;
875 Some(Ty::new_generic_adt(tcx, def_id, ty))
876 }
877
878 #[inline]
879 pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
880 let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
881 Ty::new_generic_adt(tcx, def_id, ty)
882 }
883
884 #[inline]
885 pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
886 let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
887 Ty::new_generic_adt(tcx, def_id, ty)
888 }
889
890 pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
892 let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
893 let context_adt_ref = tcx.adt_def(context_did);
894 let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
895 let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
896 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
897 }
898}
899
900impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
901 fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
902 tcx.types.bool
903 }
904
905 fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
906 tcx.types.u8
907 }
908
909 fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
910 Ty::new_infer(tcx, infer)
911 }
912
913 fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
914 Ty::new_var(tcx, vid)
915 }
916
917 fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
918 Ty::new_param(tcx, param.index, param.name)
919 }
920
921 fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Self {
922 Ty::new_placeholder(tcx, placeholder)
923 }
924
925 fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self {
926 Ty::new_bound(interner, debruijn, var)
927 }
928
929 fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
930 Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
931 }
932
933 fn new_alias(
934 interner: TyCtxt<'tcx>,
935 kind: ty::AliasTyKind,
936 alias_ty: ty::AliasTy<'tcx>,
937 ) -> Self {
938 Ty::new_alias(interner, kind, alias_ty)
939 }
940
941 fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
942 Ty::new_error(interner, guar)
943 }
944
945 fn new_adt(
946 interner: TyCtxt<'tcx>,
947 adt_def: ty::AdtDef<'tcx>,
948 args: ty::GenericArgsRef<'tcx>,
949 ) -> Self {
950 Ty::new_adt(interner, adt_def, args)
951 }
952
953 fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
954 Ty::new_foreign(interner, def_id)
955 }
956
957 fn new_dynamic(
958 interner: TyCtxt<'tcx>,
959 preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
960 region: ty::Region<'tcx>,
961 kind: ty::DynKind,
962 ) -> Self {
963 Ty::new_dynamic(interner, preds, region, kind)
964 }
965
966 fn new_coroutine(
967 interner: TyCtxt<'tcx>,
968 def_id: DefId,
969 args: ty::GenericArgsRef<'tcx>,
970 ) -> Self {
971 Ty::new_coroutine(interner, def_id, args)
972 }
973
974 fn new_coroutine_closure(
975 interner: TyCtxt<'tcx>,
976 def_id: DefId,
977 args: ty::GenericArgsRef<'tcx>,
978 ) -> Self {
979 Ty::new_coroutine_closure(interner, def_id, args)
980 }
981
982 fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
983 Ty::new_closure(interner, def_id, args)
984 }
985
986 fn new_coroutine_witness(
987 interner: TyCtxt<'tcx>,
988 def_id: DefId,
989 args: ty::GenericArgsRef<'tcx>,
990 ) -> Self {
991 Ty::new_coroutine_witness(interner, def_id, args)
992 }
993
994 fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
995 Ty::new_ptr(interner, ty, mutbl)
996 }
997
998 fn new_ref(
999 interner: TyCtxt<'tcx>,
1000 region: ty::Region<'tcx>,
1001 ty: Self,
1002 mutbl: hir::Mutability,
1003 ) -> Self {
1004 Ty::new_ref(interner, region, ty, mutbl)
1005 }
1006
1007 fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1008 Ty::new_array_with_const_len(interner, ty, len)
1009 }
1010
1011 fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1012 Ty::new_slice(interner, ty)
1013 }
1014
1015 fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1016 Ty::new_tup(interner, tys)
1017 }
1018
1019 fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1020 where
1021 It: Iterator<Item = T>,
1022 T: CollectAndApply<Self, Self>,
1023 {
1024 Ty::new_tup_from_iter(interner, iter)
1025 }
1026
1027 fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1028 self.tuple_fields()
1029 }
1030
1031 fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1032 self.to_opt_closure_kind()
1033 }
1034
1035 fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1036 Ty::from_closure_kind(interner, kind)
1037 }
1038
1039 fn from_coroutine_closure_kind(
1040 interner: TyCtxt<'tcx>,
1041 kind: rustc_type_ir::ClosureKind,
1042 ) -> Self {
1043 Ty::from_coroutine_closure_kind(interner, kind)
1044 }
1045
1046 fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1047 Ty::new_fn_def(interner, def_id, args)
1048 }
1049
1050 fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1051 Ty::new_fn_ptr(interner, sig)
1052 }
1053
1054 fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1055 Ty::new_pat(interner, ty, pat)
1056 }
1057
1058 fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1059 Ty::new_unsafe_binder(interner, ty)
1060 }
1061
1062 fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1063 interner.types.unit
1064 }
1065
1066 fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1067 interner.types.usize
1068 }
1069
1070 fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1071 self.discriminant_ty(interner)
1072 }
1073
1074 fn has_unsafe_fields(self) -> bool {
1075 Ty::has_unsafe_fields(self)
1076 }
1077}
1078
1079impl<'tcx> Ty<'tcx> {
1081 #[inline(always)]
1086 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1087 self.0.0
1088 }
1089
1090 #[inline(always)]
1092 pub fn flags(self) -> TypeFlags {
1093 self.0.0.flags
1094 }
1095
1096 #[inline]
1097 pub fn is_unit(self) -> bool {
1098 match self.kind() {
1099 Tuple(tys) => tys.is_empty(),
1100 _ => false,
1101 }
1102 }
1103
1104 #[inline]
1106 pub fn is_usize(self) -> bool {
1107 matches!(self.kind(), Uint(UintTy::Usize))
1108 }
1109
1110 #[inline]
1112 pub fn is_usize_like(self) -> bool {
1113 matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1114 }
1115
1116 #[inline]
1117 pub fn is_never(self) -> bool {
1118 matches!(self.kind(), Never)
1119 }
1120
1121 #[inline]
1122 pub fn is_primitive(self) -> bool {
1123 matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1124 }
1125
1126 #[inline]
1127 pub fn is_adt(self) -> bool {
1128 matches!(self.kind(), Adt(..))
1129 }
1130
1131 #[inline]
1132 pub fn is_ref(self) -> bool {
1133 matches!(self.kind(), Ref(..))
1134 }
1135
1136 #[inline]
1137 pub fn is_ty_var(self) -> bool {
1138 matches!(self.kind(), Infer(TyVar(_)))
1139 }
1140
1141 #[inline]
1142 pub fn ty_vid(self) -> Option<ty::TyVid> {
1143 match self.kind() {
1144 &Infer(TyVar(vid)) => Some(vid),
1145 _ => None,
1146 }
1147 }
1148
1149 #[inline]
1150 pub fn is_ty_or_numeric_infer(self) -> bool {
1151 matches!(self.kind(), Infer(_))
1152 }
1153
1154 #[inline]
1155 pub fn is_phantom_data(self) -> bool {
1156 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1157 }
1158
1159 #[inline]
1160 pub fn is_bool(self) -> bool {
1161 *self.kind() == Bool
1162 }
1163
1164 #[inline]
1166 pub fn is_str(self) -> bool {
1167 *self.kind() == Str
1168 }
1169
1170 #[inline]
1171 pub fn is_param(self, index: u32) -> bool {
1172 match self.kind() {
1173 ty::Param(data) => data.index == index,
1174 _ => false,
1175 }
1176 }
1177
1178 #[inline]
1179 pub fn is_slice(self) -> bool {
1180 matches!(self.kind(), Slice(_))
1181 }
1182
1183 #[inline]
1184 pub fn is_array_slice(self) -> bool {
1185 match self.kind() {
1186 Slice(_) => true,
1187 ty::RawPtr(ty, _) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1188 _ => false,
1189 }
1190 }
1191
1192 #[inline]
1193 pub fn is_array(self) -> bool {
1194 matches!(self.kind(), Array(..))
1195 }
1196
1197 #[inline]
1198 pub fn is_simd(self) -> bool {
1199 match self.kind() {
1200 Adt(def, _) => def.repr().simd(),
1201 _ => false,
1202 }
1203 }
1204
1205 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1206 match self.kind() {
1207 Array(ty, _) | Slice(ty) => *ty,
1208 Str => tcx.types.u8,
1209 _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1210 }
1211 }
1212
1213 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1214 let Adt(def, args) = self.kind() else {
1215 bug!("`simd_size_and_type` called on invalid type")
1216 };
1217 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1218 let variant = def.non_enum_variant();
1219 assert_eq!(variant.fields.len(), 1);
1220 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1221 let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1222 bug!("Simd type has non-array field type {field_ty:?}")
1223 };
1224 (
1229 f0_len
1230 .try_to_target_usize(tcx)
1231 .expect("expected SIMD field to have definite array size"),
1232 *f0_elem_ty,
1233 )
1234 }
1235
1236 #[inline]
1237 pub fn is_mutable_ptr(self) -> bool {
1238 matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1239 }
1240
1241 #[inline]
1243 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1244 match self.kind() {
1245 Ref(_, _, mutability) => Some(*mutability),
1246 _ => None,
1247 }
1248 }
1249
1250 #[inline]
1251 pub fn is_raw_ptr(self) -> bool {
1252 matches!(self.kind(), RawPtr(_, _))
1253 }
1254
1255 #[inline]
1258 pub fn is_any_ptr(self) -> bool {
1259 self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1260 }
1261
1262 #[inline]
1263 pub fn is_box(self) -> bool {
1264 match self.kind() {
1265 Adt(def, _) => def.is_box(),
1266 _ => false,
1267 }
1268 }
1269
1270 #[inline]
1275 pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1276 match self.kind() {
1277 Adt(def, args) if def.is_box() => {
1278 let Some(alloc) = args.get(1) else {
1279 return true;
1281 };
1282 alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1283 tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1284 })
1285 }
1286 _ => false,
1287 }
1288 }
1289
1290 pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1291 match self.kind() {
1292 Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1293 _ => None,
1294 }
1295 }
1296
1297 pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1299 self.boxed_ty()
1300 .unwrap_or_else(|| bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1301 }
1302
1303 #[inline]
1307 pub fn is_scalar(self) -> bool {
1308 matches!(
1309 self.kind(),
1310 Bool | Char
1311 | Int(_)
1312 | Float(_)
1313 | Uint(_)
1314 | FnDef(..)
1315 | FnPtr(..)
1316 | RawPtr(_, _)
1317 | Infer(IntVar(_) | FloatVar(_))
1318 )
1319 }
1320
1321 #[inline]
1323 pub fn is_floating_point(self) -> bool {
1324 matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1325 }
1326
1327 #[inline]
1328 pub fn is_trait(self) -> bool {
1329 matches!(self.kind(), Dynamic(_, _, ty::Dyn))
1330 }
1331
1332 #[inline]
1333 pub fn is_enum(self) -> bool {
1334 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1335 }
1336
1337 #[inline]
1338 pub fn is_union(self) -> bool {
1339 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1340 }
1341
1342 #[inline]
1343 pub fn is_closure(self) -> bool {
1344 matches!(self.kind(), Closure(..))
1345 }
1346
1347 #[inline]
1348 pub fn is_coroutine(self) -> bool {
1349 matches!(self.kind(), Coroutine(..))
1350 }
1351
1352 #[inline]
1353 pub fn is_coroutine_closure(self) -> bool {
1354 matches!(self.kind(), CoroutineClosure(..))
1355 }
1356
1357 #[inline]
1358 pub fn is_integral(self) -> bool {
1359 matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1360 }
1361
1362 #[inline]
1363 pub fn is_fresh_ty(self) -> bool {
1364 matches!(self.kind(), Infer(FreshTy(_)))
1365 }
1366
1367 #[inline]
1368 pub fn is_fresh(self) -> bool {
1369 matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1370 }
1371
1372 #[inline]
1373 pub fn is_char(self) -> bool {
1374 matches!(self.kind(), Char)
1375 }
1376
1377 #[inline]
1378 pub fn is_numeric(self) -> bool {
1379 self.is_integral() || self.is_floating_point()
1380 }
1381
1382 #[inline]
1383 pub fn is_signed(self) -> bool {
1384 matches!(self.kind(), Int(_))
1385 }
1386
1387 #[inline]
1388 pub fn is_ptr_sized_integral(self) -> bool {
1389 matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1390 }
1391
1392 #[inline]
1393 pub fn has_concrete_skeleton(self) -> bool {
1394 !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1395 }
1396
1397 pub fn contains(self, other: Ty<'tcx>) -> bool {
1401 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1402
1403 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1404 type Result = ControlFlow<()>;
1405
1406 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1407 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1408 }
1409 }
1410
1411 let cf = self.visit_with(&mut ContainsTyVisitor(other));
1412 cf.is_break()
1413 }
1414
1415 pub fn contains_closure(self) -> bool {
1419 struct ContainsClosureVisitor;
1420
1421 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1422 type Result = ControlFlow<()>;
1423
1424 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1425 if let ty::Closure(..) = t.kind() {
1426 ControlFlow::Break(())
1427 } else {
1428 t.super_visit_with(self)
1429 }
1430 }
1431 }
1432
1433 let cf = self.visit_with(&mut ContainsClosureVisitor);
1434 cf.is_break()
1435 }
1436
1437 pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1442 self,
1443 tcx: TyCtxt<'tcx>,
1444 mut f: F,
1445 ) -> Ty<'tcx> {
1446 assert!(self.is_coroutine());
1447 let mut cor_ty = self;
1448 let mut ty = cor_ty;
1449 loop {
1450 if let ty::Coroutine(def_id, args) = ty.kind() {
1451 cor_ty = ty;
1452 f(ty);
1453 if tcx.is_async_drop_in_place_coroutine(*def_id) {
1454 ty = args.first().unwrap().expect_ty();
1455 continue;
1456 } else {
1457 return cor_ty;
1458 }
1459 } else {
1460 return cor_ty;
1461 }
1462 }
1463 }
1464
1465 pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1470 match *self.kind() {
1471 _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1472 Ref(_, ty, _) => Some(ty),
1473 RawPtr(ty, _) if explicit => Some(ty),
1474 _ => None,
1475 }
1476 }
1477
1478 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1480 match self.kind() {
1481 Array(ty, _) | Slice(ty) => Some(*ty),
1482 _ => None,
1483 }
1484 }
1485
1486 #[tracing::instrument(level = "trace", skip(tcx))]
1487 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1488 self.kind().fn_sig(tcx)
1489 }
1490
1491 #[inline]
1492 pub fn is_fn(self) -> bool {
1493 matches!(self.kind(), FnDef(..) | FnPtr(..))
1494 }
1495
1496 #[inline]
1497 pub fn is_fn_ptr(self) -> bool {
1498 matches!(self.kind(), FnPtr(..))
1499 }
1500
1501 #[inline]
1502 pub fn is_impl_trait(self) -> bool {
1503 matches!(self.kind(), Alias(ty::Opaque, ..))
1504 }
1505
1506 #[inline]
1507 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1508 match self.kind() {
1509 Adt(adt, _) => Some(*adt),
1510 _ => None,
1511 }
1512 }
1513
1514 #[inline]
1517 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1518 match self.kind() {
1519 Tuple(args) => args,
1520 _ => bug!("tuple_fields called on non-tuple: {self:?}"),
1521 }
1522 }
1523
1524 #[inline]
1528 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1529 match self.kind() {
1530 TyKind::Adt(adt, _) => Some(adt.variant_range()),
1531 TyKind::Coroutine(def_id, args) => {
1532 Some(args.as_coroutine().variant_range(*def_id, tcx))
1533 }
1534 _ => None,
1535 }
1536 }
1537
1538 #[inline]
1543 pub fn discriminant_for_variant(
1544 self,
1545 tcx: TyCtxt<'tcx>,
1546 variant_index: VariantIdx,
1547 ) -> Option<Discr<'tcx>> {
1548 match self.kind() {
1549 TyKind::Adt(adt, _) if adt.is_enum() => {
1550 Some(adt.discriminant_for_variant(tcx, variant_index))
1551 }
1552 TyKind::Coroutine(def_id, args) => {
1553 Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1554 }
1555 _ => None,
1556 }
1557 }
1558
1559 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1561 match self.kind() {
1562 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1563 ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1564
1565 ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1566 let assoc_items = tcx.associated_item_def_ids(
1567 tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1568 );
1569 Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1570 }
1571
1572 ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1573
1574 ty::Bool
1575 | ty::Char
1576 | ty::Int(_)
1577 | ty::Uint(_)
1578 | ty::Float(_)
1579 | ty::Adt(..)
1580 | ty::Foreign(_)
1581 | ty::Str
1582 | ty::Array(..)
1583 | ty::Slice(_)
1584 | ty::RawPtr(_, _)
1585 | ty::Ref(..)
1586 | ty::FnDef(..)
1587 | ty::FnPtr(..)
1588 | ty::Dynamic(..)
1589 | ty::Closure(..)
1590 | ty::CoroutineClosure(..)
1591 | ty::CoroutineWitness(..)
1592 | ty::Never
1593 | ty::Tuple(_)
1594 | ty::UnsafeBinder(_)
1595 | ty::Error(_)
1596 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1597
1598 ty::Bound(..)
1599 | ty::Placeholder(_)
1600 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1601 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1602 }
1603 }
1604 }
1605
1606 pub fn ptr_metadata_ty_or_tail(
1609 self,
1610 tcx: TyCtxt<'tcx>,
1611 normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1612 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1613 let tail = tcx.struct_tail_raw(self, normalize, || {});
1614 match tail.kind() {
1615 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1617 | ty::Uint(_)
1618 | ty::Int(_)
1619 | ty::Bool
1620 | ty::Float(_)
1621 | ty::FnDef(..)
1622 | ty::FnPtr(..)
1623 | ty::RawPtr(..)
1624 | ty::Char
1625 | ty::Ref(..)
1626 | ty::Coroutine(..)
1627 | ty::CoroutineWitness(..)
1628 | ty::Array(..)
1629 | ty::Closure(..)
1630 | ty::CoroutineClosure(..)
1631 | ty::Never
1632 | ty::Error(_)
1633 | ty::Foreign(..)
1635 | ty::Adt(..)
1638 | ty::Tuple(..) => Ok(tcx.types.unit),
1641
1642 ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1643
1644 ty::Dynamic(_, _, ty::Dyn) => {
1645 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1646 Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1647 }
1648
1649 ty::Param(_) | ty::Alias(..) => Err(tail),
1652
1653 | ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
1654
1655 ty::Infer(ty::TyVar(_))
1656 | ty::Pat(..)
1657 | ty::Bound(..)
1658 | ty::Placeholder(..)
1659 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(
1660 "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1661 ),
1662 }
1663 }
1664
1665 pub fn ptr_metadata_ty(
1668 self,
1669 tcx: TyCtxt<'tcx>,
1670 normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1671 ) -> Ty<'tcx> {
1672 match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1673 Ok(metadata) => metadata,
1674 Err(tail) => bug!(
1675 "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1676 ),
1677 }
1678 }
1679
1680 #[track_caller]
1689 pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1690 let Some(pointee_ty) = self.builtin_deref(true) else {
1691 bug!("Type {self:?} is not a pointer or reference type")
1692 };
1693 if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1694 tcx.types.unit
1695 } else {
1696 match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1697 Ok(metadata_ty) => metadata_ty,
1698 Err(tail_ty) => {
1699 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1700 Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1701 }
1702 }
1703 }
1704 }
1705
1706 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1746 match self.kind() {
1747 Int(int_ty) => match int_ty {
1748 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1749 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1750 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1751 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1752 },
1753
1754 Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1758
1759 Error(_) => Some(ty::ClosureKind::Fn),
1760
1761 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1762 }
1763 }
1764
1765 pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1768 match kind {
1769 ty::ClosureKind::Fn => tcx.types.i8,
1770 ty::ClosureKind::FnMut => tcx.types.i16,
1771 ty::ClosureKind::FnOnce => tcx.types.i32,
1772 }
1773 }
1774
1775 pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1788 match kind {
1789 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1790 ty::ClosureKind::FnOnce => tcx.types.i32,
1791 }
1792 }
1793
1794 #[instrument(skip(tcx), level = "debug")]
1804 pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1805 match self.kind() {
1806 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1807 | ty::Uint(_)
1808 | ty::Int(_)
1809 | ty::Bool
1810 | ty::Float(_)
1811 | ty::FnDef(..)
1812 | ty::FnPtr(..)
1813 | ty::UnsafeBinder(_)
1814 | ty::RawPtr(..)
1815 | ty::Char
1816 | ty::Ref(..)
1817 | ty::Coroutine(..)
1818 | ty::CoroutineWitness(..)
1819 | ty::Array(..)
1820 | ty::Pat(..)
1821 | ty::Closure(..)
1822 | ty::CoroutineClosure(..)
1823 | ty::Never
1824 | ty::Error(_) => true,
1825
1826 ty::Str | ty::Slice(_) | ty::Dynamic(_, _, ty::Dyn) => match sizedness {
1827 SizedTraitKind::Sized => false,
1828 SizedTraitKind::MetaSized => true,
1829 },
1830
1831 ty::Foreign(..) => match sizedness {
1832 SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1833 },
1834
1835 ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1836
1837 ty::Adt(def, args) => def
1838 .sizedness_constraint(tcx, sizedness)
1839 .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1840
1841 ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1842
1843 ty::Infer(ty::TyVar(_)) => false,
1844
1845 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1846 bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1847 }
1848 }
1849 }
1850
1851 pub fn is_trivially_pure_clone_copy(self) -> bool {
1860 match self.kind() {
1861 ty::Bool | ty::Char | ty::Never => true,
1862
1863 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1865
1866 ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1867 | ty::Int(..)
1868 | ty::Uint(..)
1869 | ty::Float(..) => true,
1870
1871 ty::FnDef(..) => true,
1873
1874 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1875
1876 ty::Tuple(field_tys) => {
1878 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1879 }
1880
1881 ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1882
1883 ty::FnPtr(..) => false,
1886
1887 ty::Ref(_, _, hir::Mutability::Mut) => false,
1889
1890 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1893
1894 ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1895
1896 ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1898
1899 ty::UnsafeBinder(_) => false,
1900
1901 ty::Alias(..) => false,
1903
1904 ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
1905 false
1906 }
1907 }
1908 }
1909
1910 pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
1911 match *self.kind() {
1912 ty::Bool
1913 | ty::Char
1914 | ty::Int(_)
1915 | ty::Uint(_)
1916 | ty::Float(_)
1917 | ty::Str
1918 | ty::Never
1919 | ty::Param(_)
1920 | ty::Placeholder(_)
1921 | ty::Bound(..) => true,
1922
1923 ty::Slice(ty) => {
1924 ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1925 }
1926 ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
1927
1928 ty::FnPtr(sig_tys, _) => {
1929 sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
1930 }
1931 ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
1932
1933 ty::Infer(infer) => match infer {
1934 ty::TyVar(_) => false,
1935 ty::IntVar(_) | ty::FloatVar(_) => true,
1936 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
1937 },
1938
1939 ty::Adt(_, _)
1940 | ty::Tuple(_)
1941 | ty::Array(..)
1942 | ty::Foreign(_)
1943 | ty::Pat(_, _)
1944 | ty::FnDef(..)
1945 | ty::UnsafeBinder(..)
1946 | ty::Dynamic(..)
1947 | ty::Closure(..)
1948 | ty::CoroutineClosure(..)
1949 | ty::Coroutine(..)
1950 | ty::CoroutineWitness(..)
1951 | ty::Alias(..)
1952 | ty::Error(_) => false,
1953 }
1954 }
1955
1956 pub fn primitive_symbol(self) -> Option<Symbol> {
1958 match self.kind() {
1959 ty::Bool => Some(sym::bool),
1960 ty::Char => Some(sym::char),
1961 ty::Float(f) => match f {
1962 ty::FloatTy::F16 => Some(sym::f16),
1963 ty::FloatTy::F32 => Some(sym::f32),
1964 ty::FloatTy::F64 => Some(sym::f64),
1965 ty::FloatTy::F128 => Some(sym::f128),
1966 },
1967 ty::Int(f) => match f {
1968 ty::IntTy::Isize => Some(sym::isize),
1969 ty::IntTy::I8 => Some(sym::i8),
1970 ty::IntTy::I16 => Some(sym::i16),
1971 ty::IntTy::I32 => Some(sym::i32),
1972 ty::IntTy::I64 => Some(sym::i64),
1973 ty::IntTy::I128 => Some(sym::i128),
1974 },
1975 ty::Uint(f) => match f {
1976 ty::UintTy::Usize => Some(sym::usize),
1977 ty::UintTy::U8 => Some(sym::u8),
1978 ty::UintTy::U16 => Some(sym::u16),
1979 ty::UintTy::U32 => Some(sym::u32),
1980 ty::UintTy::U64 => Some(sym::u64),
1981 ty::UintTy::U128 => Some(sym::u128),
1982 },
1983 ty::Str => Some(sym::str),
1984 _ => None,
1985 }
1986 }
1987
1988 pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
1989 match self.kind() {
1990 ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
1991 _ => false,
1992 }
1993 }
1994
1995 pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
1996 match self.kind() {
1997 ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
1998 _ => false,
1999 }
2000 }
2001
2002 pub fn is_known_rigid(self) -> bool {
2008 self.kind().is_known_rigid()
2009 }
2010
2011 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2022 TypeWalker::new(self.into())
2023 }
2024}
2025
2026impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2027 fn inputs(self) -> &'tcx [Ty<'tcx>] {
2028 self.split_last().unwrap().1
2029 }
2030
2031 fn output(self) -> Ty<'tcx> {
2032 *self.split_last().unwrap().0
2033 }
2034}
2035
2036#[cfg(target_pointer_width = "64")]
2038mod size_asserts {
2039 use rustc_data_structures::static_assert_size;
2040
2041 use super::*;
2042 static_assert_size!(TyKind<'_>, 24);
2044 static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 48);
2045 }