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::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#[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 fn article(&self) -> &'static str {
48 match self {
49 Int(_) | Float(_) | Array(_, _) => "an",
50 Adt(def, _) if def.is_enum() => "an",
51 Error(_) => "a",
54 _ => "a",
55 }
56 }
57}
58
59#[extension(pub trait CoroutineArgsExt<'tcx>)]
60impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
61 const UNRESUMED: usize = 0;
63 const RETURNED: usize = 1;
65 const POISONED: usize = 2;
67 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 #[inline]
78 fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
79 FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
81 }
82
83 #[inline]
86 fn discriminant_for_variant(
87 &self,
88 def_id: DefId,
89 tcx: TyCtxt<'tcx>,
90 variant_index: VariantIdx,
91 ) -> Discr<'tcx> {
92 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 #[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 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 #[inline]
124 fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
125 tcx.types.u32
126 }
127
128 #[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 #[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 #[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#[derive(Copy, Clone, Debug)]
212pub struct InlineConstArgs<'tcx> {
213 pub args: GenericArgsRef<'tcx>,
216}
217
218pub struct InlineConstArgsParts<'tcx, T> {
220 pub parent_args: &'tcx [GenericArg<'tcx>],
221 pub ty: T,
222}
223
224impl<'tcx> InlineConstArgs<'tcx> {
225 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 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 pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
248 self.split().parent_args
249 }
250
251 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 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
400impl<'tcx> Ty<'tcx> {
402 #[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 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 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 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 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 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
512 Ty::new(tcx, Error(guar))
513 }
514
515 #[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 #[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 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 #[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 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 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
1059impl<'tcx> Ty<'tcx> {
1061 #[inline(always)]
1066 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1067 self.0.0
1068 }
1069
1070 #[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 #[inline]
1086 pub fn is_usize(self) -> bool {
1087 matches!(self.kind(), Uint(UintTy::Usize))
1088 }
1089
1090 #[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 #[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 (
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 #[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 #[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 #[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 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 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 #[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 #[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 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 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 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 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 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 #[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 #[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 #[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 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 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 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 | ty::Foreign(..)
1620 | ty::Dynamic(_, _, ty::DynStar)
1622 | ty::Adt(..)
1625 | 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 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 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 #[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 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(..) | 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 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 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 #[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 pub fn is_trivially_pure_clone_copy(self) -> bool {
1841 match self.kind() {
1842 ty::Bool | ty::Char | ty::Never => true,
1843
1844 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 ty::FnDef(..) => true,
1854
1855 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1856
1857 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 ty::FnPtr(..) => false,
1867
1868 ty::Ref(_, _, hir::Mutability::Mut) => false,
1870
1871 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1874
1875 ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1876
1877 ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1879
1880 ty::UnsafeBinder(_) => false,
1881
1882 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 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 pub fn is_known_rigid(self) -> bool {
1945 self.kind().is_known_rigid()
1946 }
1947
1948 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#[cfg(target_pointer_width = "64")]
1975mod size_asserts {
1976 use rustc_data_structures::static_assert_size;
1977
1978 use super::*;
1979 static_assert_size!(ty::RegionKind<'_>, 24);
1981 static_assert_size!(ty::TyKind<'_>, 24);
1982 }