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_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();
366 assert!(candidates.next().is_none());
367 ty
368 }
369}
370
371#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
372#[derive(HashStable)]
373pub struct BoundTy {
374 pub var: BoundVar,
375 pub kind: BoundTyKind,
376}
377
378impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundTy {
379 fn var(self) -> BoundVar {
380 self.var
381 }
382
383 fn assert_eq(self, var: ty::BoundVariableKind) {
384 assert_eq!(self.kind, var.expect_ty())
385 }
386}
387
388#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
389#[derive(HashStable)]
390pub enum BoundTyKind {
391 Anon,
392 Param(DefId, Symbol),
393}
394
395impl From<BoundVar> for BoundTy {
396 fn from(var: BoundVar) -> Self {
397 BoundTy { var, kind: BoundTyKind::Anon }
398 }
399}
400
401impl<'tcx> Ty<'tcx> {
403 #[allow(rustc::usage_of_ty_tykind)]
406 #[inline]
407 fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
408 tcx.mk_ty_from_kind(st)
409 }
410
411 #[inline]
412 pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
413 Ty::new(tcx, TyKind::Infer(infer))
414 }
415
416 #[inline]
417 pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
418 tcx.types
420 .ty_vars
421 .get(v.as_usize())
422 .copied()
423 .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
424 }
425
426 #[inline]
427 pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
428 Ty::new_infer(tcx, IntVar(v))
429 }
430
431 #[inline]
432 pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
433 Ty::new_infer(tcx, FloatVar(v))
434 }
435
436 #[inline]
437 pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
438 tcx.types
440 .fresh_tys
441 .get(n as usize)
442 .copied()
443 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
444 }
445
446 #[inline]
447 pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
448 tcx.types
450 .fresh_int_tys
451 .get(n as usize)
452 .copied()
453 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
454 }
455
456 #[inline]
457 pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
458 tcx.types
460 .fresh_float_tys
461 .get(n as usize)
462 .copied()
463 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
464 }
465
466 #[inline]
467 pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
468 Ty::new(tcx, Param(ParamTy { index, name }))
469 }
470
471 #[inline]
472 pub fn new_bound(
473 tcx: TyCtxt<'tcx>,
474 index: ty::DebruijnIndex,
475 bound_ty: ty::BoundTy,
476 ) -> Ty<'tcx> {
477 Ty::new(tcx, Bound(index, bound_ty))
478 }
479
480 #[inline]
481 pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Ty<'tcx> {
482 Ty::new(tcx, Placeholder(placeholder))
483 }
484
485 #[inline]
486 pub fn new_alias(
487 tcx: TyCtxt<'tcx>,
488 kind: ty::AliasTyKind,
489 alias_ty: ty::AliasTy<'tcx>,
490 ) -> Ty<'tcx> {
491 debug_assert_matches!(
492 (kind, tcx.def_kind(alias_ty.def_id)),
493 (ty::Opaque, DefKind::OpaqueTy)
494 | (ty::Projection | ty::Inherent, DefKind::AssocTy)
495 | (ty::Free, DefKind::TyAlias)
496 );
497 Ty::new(tcx, Alias(kind, alias_ty))
498 }
499
500 #[inline]
501 pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
502 Ty::new(tcx, Pat(base, pat))
503 }
504
505 #[inline]
506 #[instrument(level = "debug", skip(tcx))]
507 pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
508 Ty::new_alias(tcx, ty::Opaque, AliasTy::new_from_args(tcx, def_id, args))
509 }
510
511 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
513 Ty::new(tcx, Error(guar))
514 }
515
516 #[track_caller]
518 pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
519 Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
520 }
521
522 #[track_caller]
525 pub fn new_error_with_message<S: Into<MultiSpan>>(
526 tcx: TyCtxt<'tcx>,
527 span: S,
528 msg: impl Into<Cow<'static, str>>,
529 ) -> Ty<'tcx> {
530 let reported = tcx.dcx().span_delayed_bug(span, msg);
531 Ty::new(tcx, Error(reported))
532 }
533
534 #[inline]
535 pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
536 use ty::IntTy::*;
537 match i {
538 Isize => tcx.types.isize,
539 I8 => tcx.types.i8,
540 I16 => tcx.types.i16,
541 I32 => tcx.types.i32,
542 I64 => tcx.types.i64,
543 I128 => tcx.types.i128,
544 }
545 }
546
547 #[inline]
548 pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
549 use ty::UintTy::*;
550 match ui {
551 Usize => tcx.types.usize,
552 U8 => tcx.types.u8,
553 U16 => tcx.types.u16,
554 U32 => tcx.types.u32,
555 U64 => tcx.types.u64,
556 U128 => tcx.types.u128,
557 }
558 }
559
560 #[inline]
561 pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
562 use ty::FloatTy::*;
563 match f {
564 F16 => tcx.types.f16,
565 F32 => tcx.types.f32,
566 F64 => tcx.types.f64,
567 F128 => tcx.types.f128,
568 }
569 }
570
571 #[inline]
572 pub fn new_ref(
573 tcx: TyCtxt<'tcx>,
574 r: Region<'tcx>,
575 ty: Ty<'tcx>,
576 mutbl: ty::Mutability,
577 ) -> Ty<'tcx> {
578 Ty::new(tcx, Ref(r, ty, mutbl))
579 }
580
581 #[inline]
582 pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
583 Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
584 }
585
586 #[inline]
587 pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
588 Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
589 }
590
591 pub fn new_pinned_ref(
592 tcx: TyCtxt<'tcx>,
593 r: Region<'tcx>,
594 ty: Ty<'tcx>,
595 mutbl: ty::Mutability,
596 ) -> Ty<'tcx> {
597 let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
598 Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
599 }
600
601 #[inline]
602 pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
603 Ty::new(tcx, ty::RawPtr(ty, mutbl))
604 }
605
606 #[inline]
607 pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
608 Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
609 }
610
611 #[inline]
612 pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
613 Ty::new_ptr(tcx, ty, hir::Mutability::Not)
614 }
615
616 #[inline]
617 pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
618 tcx.debug_assert_args_compatible(def.did(), args);
619 if cfg!(debug_assertions) {
620 match tcx.def_kind(def.did()) {
621 DefKind::Struct | DefKind::Union | DefKind::Enum => {}
622 DefKind::Mod
623 | DefKind::Variant
624 | DefKind::Trait
625 | DefKind::TyAlias
626 | DefKind::ForeignTy
627 | DefKind::TraitAlias
628 | DefKind::AssocTy
629 | DefKind::TyParam
630 | DefKind::Fn
631 | DefKind::Const
632 | DefKind::ConstParam
633 | DefKind::Static { .. }
634 | DefKind::Ctor(..)
635 | DefKind::AssocFn
636 | DefKind::AssocConst
637 | DefKind::Macro(..)
638 | DefKind::ExternCrate
639 | DefKind::Use
640 | DefKind::ForeignMod
641 | DefKind::AnonConst
642 | DefKind::InlineConst
643 | DefKind::OpaqueTy
644 | DefKind::Field
645 | DefKind::LifetimeParam
646 | DefKind::GlobalAsm
647 | DefKind::Impl { .. }
648 | DefKind::Closure
649 | DefKind::SyntheticCoroutineBody => {
650 bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did()))
651 }
652 }
653 }
654 Ty::new(tcx, Adt(def, args))
655 }
656
657 #[inline]
658 pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
659 Ty::new(tcx, Foreign(def_id))
660 }
661
662 #[inline]
663 pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
664 Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
665 }
666
667 #[inline]
668 pub fn new_array_with_const_len(
669 tcx: TyCtxt<'tcx>,
670 ty: Ty<'tcx>,
671 ct: ty::Const<'tcx>,
672 ) -> Ty<'tcx> {
673 Ty::new(tcx, Array(ty, ct))
674 }
675
676 #[inline]
677 pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
678 Ty::new(tcx, Slice(ty))
679 }
680
681 #[inline]
682 pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
683 if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
684 }
685
686 pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
687 where
688 I: Iterator<Item = T>,
689 T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
690 {
691 T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
692 }
693
694 #[inline]
695 pub fn new_fn_def(
696 tcx: TyCtxt<'tcx>,
697 def_id: DefId,
698 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
699 ) -> Ty<'tcx> {
700 debug_assert_matches!(
701 tcx.def_kind(def_id),
702 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
703 );
704 let args = tcx.check_and_mk_args(def_id, args);
705 Ty::new(tcx, FnDef(def_id, args))
706 }
707
708 #[inline]
709 pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
710 let (sig_tys, hdr) = fty.split();
711 Ty::new(tcx, FnPtr(sig_tys, hdr))
712 }
713
714 #[inline]
715 pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
716 Ty::new(tcx, UnsafeBinder(b.into()))
717 }
718
719 #[inline]
720 pub fn new_dynamic(
721 tcx: TyCtxt<'tcx>,
722 obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
723 reg: ty::Region<'tcx>,
724 repr: DynKind,
725 ) -> Ty<'tcx> {
726 if cfg!(debug_assertions) {
727 let projection_count = obj
728 .projection_bounds()
729 .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
730 .count();
731 let expected_count: usize = obj
732 .principal_def_id()
733 .into_iter()
734 .flat_map(|principal_def_id| {
735 elaborate::supertraits(
738 tcx,
739 ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
740 )
741 .map(|principal| {
742 tcx.associated_items(principal.def_id())
743 .in_definition_order()
744 .filter(|item| item.is_type())
745 .filter(|item| !item.is_impl_trait_in_trait())
746 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
747 .count()
748 })
749 })
750 .sum();
751 assert_eq!(
752 projection_count, expected_count,
753 "expected {obj:?} to have {expected_count} projections, \
754 but it has {projection_count}"
755 );
756 }
757 Ty::new(tcx, Dynamic(obj, reg, repr))
758 }
759
760 #[inline]
761 pub fn new_projection_from_args(
762 tcx: TyCtxt<'tcx>,
763 item_def_id: DefId,
764 args: ty::GenericArgsRef<'tcx>,
765 ) -> Ty<'tcx> {
766 Ty::new_alias(tcx, ty::Projection, AliasTy::new_from_args(tcx, item_def_id, args))
767 }
768
769 #[inline]
770 pub fn new_projection(
771 tcx: TyCtxt<'tcx>,
772 item_def_id: DefId,
773 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
774 ) -> Ty<'tcx> {
775 Ty::new_alias(tcx, ty::Projection, AliasTy::new(tcx, item_def_id, args))
776 }
777
778 #[inline]
779 pub fn new_closure(
780 tcx: TyCtxt<'tcx>,
781 def_id: DefId,
782 closure_args: GenericArgsRef<'tcx>,
783 ) -> Ty<'tcx> {
784 tcx.debug_assert_args_compatible(def_id, closure_args);
785 Ty::new(tcx, Closure(def_id, closure_args))
786 }
787
788 #[inline]
789 pub fn new_coroutine_closure(
790 tcx: TyCtxt<'tcx>,
791 def_id: DefId,
792 closure_args: GenericArgsRef<'tcx>,
793 ) -> Ty<'tcx> {
794 tcx.debug_assert_args_compatible(def_id, closure_args);
795 Ty::new(tcx, CoroutineClosure(def_id, closure_args))
796 }
797
798 #[inline]
799 pub fn new_coroutine(
800 tcx: TyCtxt<'tcx>,
801 def_id: DefId,
802 coroutine_args: GenericArgsRef<'tcx>,
803 ) -> Ty<'tcx> {
804 tcx.debug_assert_args_compatible(def_id, coroutine_args);
805 Ty::new(tcx, Coroutine(def_id, coroutine_args))
806 }
807
808 #[inline]
809 pub fn new_coroutine_witness(
810 tcx: TyCtxt<'tcx>,
811 id: DefId,
812 args: GenericArgsRef<'tcx>,
813 ) -> Ty<'tcx> {
814 Ty::new(tcx, CoroutineWitness(id, args))
815 }
816
817 #[inline]
820 pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
821 Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
822 }
823
824 #[inline]
825 pub fn new_diverging_default(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
826 if tcx.features().never_type_fallback() { tcx.types.never } else { tcx.types.unit }
827 }
828
829 fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
832 let adt_def = tcx.adt_def(wrapper_def_id);
833 let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
834 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(),
835 GenericParamDefKind::Type { has_default, .. } => {
836 if param.index == 0 {
837 ty_param.into()
838 } else {
839 assert!(has_default);
840 tcx.type_of(param.def_id).instantiate(tcx, args).into()
841 }
842 }
843 });
844 Ty::new_adt(tcx, adt_def, args)
845 }
846
847 #[inline]
848 pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
849 let def_id = tcx.lang_items().get(item)?;
850 Some(Ty::new_generic_adt(tcx, def_id, ty))
851 }
852
853 #[inline]
854 pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
855 let def_id = tcx.get_diagnostic_item(name)?;
856 Some(Ty::new_generic_adt(tcx, def_id, ty))
857 }
858
859 #[inline]
860 pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
861 let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
862 Ty::new_generic_adt(tcx, def_id, ty)
863 }
864
865 #[inline]
866 pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
867 let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
868 Ty::new_generic_adt(tcx, def_id, ty)
869 }
870
871 pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
873 let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
874 let context_adt_ref = tcx.adt_def(context_did);
875 let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
876 let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
877 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
878 }
879}
880
881impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
882 fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
883 tcx.types.bool
884 }
885
886 fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
887 tcx.types.u8
888 }
889
890 fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
891 Ty::new_infer(tcx, infer)
892 }
893
894 fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
895 Ty::new_var(tcx, vid)
896 }
897
898 fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
899 Ty::new_param(tcx, param.index, param.name)
900 }
901
902 fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Self {
903 Ty::new_placeholder(tcx, placeholder)
904 }
905
906 fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self {
907 Ty::new_bound(interner, debruijn, var)
908 }
909
910 fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
911 Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
912 }
913
914 fn new_alias(
915 interner: TyCtxt<'tcx>,
916 kind: ty::AliasTyKind,
917 alias_ty: ty::AliasTy<'tcx>,
918 ) -> Self {
919 Ty::new_alias(interner, kind, alias_ty)
920 }
921
922 fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
923 Ty::new_error(interner, guar)
924 }
925
926 fn new_adt(
927 interner: TyCtxt<'tcx>,
928 adt_def: ty::AdtDef<'tcx>,
929 args: ty::GenericArgsRef<'tcx>,
930 ) -> Self {
931 Ty::new_adt(interner, adt_def, args)
932 }
933
934 fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
935 Ty::new_foreign(interner, def_id)
936 }
937
938 fn new_dynamic(
939 interner: TyCtxt<'tcx>,
940 preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
941 region: ty::Region<'tcx>,
942 kind: ty::DynKind,
943 ) -> Self {
944 Ty::new_dynamic(interner, preds, region, kind)
945 }
946
947 fn new_coroutine(
948 interner: TyCtxt<'tcx>,
949 def_id: DefId,
950 args: ty::GenericArgsRef<'tcx>,
951 ) -> Self {
952 Ty::new_coroutine(interner, def_id, args)
953 }
954
955 fn new_coroutine_closure(
956 interner: TyCtxt<'tcx>,
957 def_id: DefId,
958 args: ty::GenericArgsRef<'tcx>,
959 ) -> Self {
960 Ty::new_coroutine_closure(interner, def_id, args)
961 }
962
963 fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
964 Ty::new_closure(interner, def_id, args)
965 }
966
967 fn new_coroutine_witness(
968 interner: TyCtxt<'tcx>,
969 def_id: DefId,
970 args: ty::GenericArgsRef<'tcx>,
971 ) -> Self {
972 Ty::new_coroutine_witness(interner, def_id, args)
973 }
974
975 fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
976 Ty::new_ptr(interner, ty, mutbl)
977 }
978
979 fn new_ref(
980 interner: TyCtxt<'tcx>,
981 region: ty::Region<'tcx>,
982 ty: Self,
983 mutbl: hir::Mutability,
984 ) -> Self {
985 Ty::new_ref(interner, region, ty, mutbl)
986 }
987
988 fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
989 Ty::new_array_with_const_len(interner, ty, len)
990 }
991
992 fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
993 Ty::new_slice(interner, ty)
994 }
995
996 fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
997 Ty::new_tup(interner, tys)
998 }
999
1000 fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1001 where
1002 It: Iterator<Item = T>,
1003 T: CollectAndApply<Self, Self>,
1004 {
1005 Ty::new_tup_from_iter(interner, iter)
1006 }
1007
1008 fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1009 self.tuple_fields()
1010 }
1011
1012 fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1013 self.to_opt_closure_kind()
1014 }
1015
1016 fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1017 Ty::from_closure_kind(interner, kind)
1018 }
1019
1020 fn from_coroutine_closure_kind(
1021 interner: TyCtxt<'tcx>,
1022 kind: rustc_type_ir::ClosureKind,
1023 ) -> Self {
1024 Ty::from_coroutine_closure_kind(interner, kind)
1025 }
1026
1027 fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1028 Ty::new_fn_def(interner, def_id, args)
1029 }
1030
1031 fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1032 Ty::new_fn_ptr(interner, sig)
1033 }
1034
1035 fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1036 Ty::new_pat(interner, ty, pat)
1037 }
1038
1039 fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1040 Ty::new_unsafe_binder(interner, ty)
1041 }
1042
1043 fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1044 interner.types.unit
1045 }
1046
1047 fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1048 interner.types.usize
1049 }
1050
1051 fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1052 self.discriminant_ty(interner)
1053 }
1054
1055 fn has_unsafe_fields(self) -> bool {
1056 Ty::has_unsafe_fields(self)
1057 }
1058}
1059
1060impl<'tcx> Ty<'tcx> {
1062 #[inline(always)]
1067 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1068 self.0.0
1069 }
1070
1071 #[inline(always)]
1073 pub fn flags(self) -> TypeFlags {
1074 self.0.0.flags
1075 }
1076
1077 #[inline]
1078 pub fn is_unit(self) -> bool {
1079 match self.kind() {
1080 Tuple(tys) => tys.is_empty(),
1081 _ => false,
1082 }
1083 }
1084
1085 #[inline]
1087 pub fn is_usize(self) -> bool {
1088 matches!(self.kind(), Uint(UintTy::Usize))
1089 }
1090
1091 #[inline]
1093 pub fn is_usize_like(self) -> bool {
1094 matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1095 }
1096
1097 #[inline]
1098 pub fn is_never(self) -> bool {
1099 matches!(self.kind(), Never)
1100 }
1101
1102 #[inline]
1103 pub fn is_primitive(self) -> bool {
1104 matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1105 }
1106
1107 #[inline]
1108 pub fn is_adt(self) -> bool {
1109 matches!(self.kind(), Adt(..))
1110 }
1111
1112 #[inline]
1113 pub fn is_ref(self) -> bool {
1114 matches!(self.kind(), Ref(..))
1115 }
1116
1117 #[inline]
1118 pub fn is_ty_var(self) -> bool {
1119 matches!(self.kind(), Infer(TyVar(_)))
1120 }
1121
1122 #[inline]
1123 pub fn ty_vid(self) -> Option<ty::TyVid> {
1124 match self.kind() {
1125 &Infer(TyVar(vid)) => Some(vid),
1126 _ => None,
1127 }
1128 }
1129
1130 #[inline]
1131 pub fn is_ty_or_numeric_infer(self) -> bool {
1132 matches!(self.kind(), Infer(_))
1133 }
1134
1135 #[inline]
1136 pub fn is_phantom_data(self) -> bool {
1137 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1138 }
1139
1140 #[inline]
1141 pub fn is_bool(self) -> bool {
1142 *self.kind() == Bool
1143 }
1144
1145 #[inline]
1147 pub fn is_str(self) -> bool {
1148 *self.kind() == Str
1149 }
1150
1151 #[inline]
1152 pub fn is_param(self, index: u32) -> bool {
1153 match self.kind() {
1154 ty::Param(data) => data.index == index,
1155 _ => false,
1156 }
1157 }
1158
1159 #[inline]
1160 pub fn is_slice(self) -> bool {
1161 matches!(self.kind(), Slice(_))
1162 }
1163
1164 #[inline]
1165 pub fn is_array_slice(self) -> bool {
1166 match self.kind() {
1167 Slice(_) => true,
1168 ty::RawPtr(ty, _) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1169 _ => false,
1170 }
1171 }
1172
1173 #[inline]
1174 pub fn is_array(self) -> bool {
1175 matches!(self.kind(), Array(..))
1176 }
1177
1178 #[inline]
1179 pub fn is_simd(self) -> bool {
1180 match self.kind() {
1181 Adt(def, _) => def.repr().simd(),
1182 _ => false,
1183 }
1184 }
1185
1186 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1187 match self.kind() {
1188 Array(ty, _) | Slice(ty) => *ty,
1189 Str => tcx.types.u8,
1190 _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1191 }
1192 }
1193
1194 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1195 let Adt(def, args) = self.kind() else {
1196 bug!("`simd_size_and_type` called on invalid type")
1197 };
1198 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1199 let variant = def.non_enum_variant();
1200 assert_eq!(variant.fields.len(), 1);
1201 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1202 let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1203 bug!("Simd type has non-array field type {field_ty:?}")
1204 };
1205 (
1210 f0_len
1211 .try_to_target_usize(tcx)
1212 .expect("expected SIMD field to have definite array size"),
1213 *f0_elem_ty,
1214 )
1215 }
1216
1217 #[inline]
1218 pub fn is_mutable_ptr(self) -> bool {
1219 matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1220 }
1221
1222 #[inline]
1224 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1225 match self.kind() {
1226 Ref(_, _, mutability) => Some(*mutability),
1227 _ => None,
1228 }
1229 }
1230
1231 #[inline]
1232 pub fn is_raw_ptr(self) -> bool {
1233 matches!(self.kind(), RawPtr(_, _))
1234 }
1235
1236 #[inline]
1239 pub fn is_any_ptr(self) -> bool {
1240 self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1241 }
1242
1243 #[inline]
1244 pub fn is_box(self) -> bool {
1245 match self.kind() {
1246 Adt(def, _) => def.is_box(),
1247 _ => false,
1248 }
1249 }
1250
1251 #[inline]
1256 pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1257 match self.kind() {
1258 Adt(def, args) if def.is_box() => {
1259 let Some(alloc) = args.get(1) else {
1260 return true;
1262 };
1263 alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1264 tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1265 })
1266 }
1267 _ => false,
1268 }
1269 }
1270
1271 pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1272 match self.kind() {
1273 Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1274 _ => None,
1275 }
1276 }
1277
1278 pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1280 self.boxed_ty()
1281 .unwrap_or_else(|| bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1282 }
1283
1284 #[inline]
1288 pub fn is_scalar(self) -> bool {
1289 matches!(
1290 self.kind(),
1291 Bool | Char
1292 | Int(_)
1293 | Float(_)
1294 | Uint(_)
1295 | FnDef(..)
1296 | FnPtr(..)
1297 | RawPtr(_, _)
1298 | Infer(IntVar(_) | FloatVar(_))
1299 )
1300 }
1301
1302 #[inline]
1304 pub fn is_floating_point(self) -> bool {
1305 matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1306 }
1307
1308 #[inline]
1309 pub fn is_trait(self) -> bool {
1310 matches!(self.kind(), Dynamic(_, _, ty::Dyn))
1311 }
1312
1313 #[inline]
1314 pub fn is_dyn_star(self) -> bool {
1315 matches!(self.kind(), Dynamic(_, _, ty::DynStar))
1316 }
1317
1318 #[inline]
1319 pub fn is_enum(self) -> bool {
1320 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1321 }
1322
1323 #[inline]
1324 pub fn is_union(self) -> bool {
1325 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1326 }
1327
1328 #[inline]
1329 pub fn is_closure(self) -> bool {
1330 matches!(self.kind(), Closure(..))
1331 }
1332
1333 #[inline]
1334 pub fn is_coroutine(self) -> bool {
1335 matches!(self.kind(), Coroutine(..))
1336 }
1337
1338 #[inline]
1339 pub fn is_coroutine_closure(self) -> bool {
1340 matches!(self.kind(), CoroutineClosure(..))
1341 }
1342
1343 #[inline]
1344 pub fn is_integral(self) -> bool {
1345 matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1346 }
1347
1348 #[inline]
1349 pub fn is_fresh_ty(self) -> bool {
1350 matches!(self.kind(), Infer(FreshTy(_)))
1351 }
1352
1353 #[inline]
1354 pub fn is_fresh(self) -> bool {
1355 matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1356 }
1357
1358 #[inline]
1359 pub fn is_char(self) -> bool {
1360 matches!(self.kind(), Char)
1361 }
1362
1363 #[inline]
1364 pub fn is_numeric(self) -> bool {
1365 self.is_integral() || self.is_floating_point()
1366 }
1367
1368 #[inline]
1369 pub fn is_signed(self) -> bool {
1370 matches!(self.kind(), Int(_))
1371 }
1372
1373 #[inline]
1374 pub fn is_ptr_sized_integral(self) -> bool {
1375 matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1376 }
1377
1378 #[inline]
1379 pub fn has_concrete_skeleton(self) -> bool {
1380 !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1381 }
1382
1383 pub fn contains(self, other: Ty<'tcx>) -> bool {
1387 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1388
1389 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1390 type Result = ControlFlow<()>;
1391
1392 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1393 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1394 }
1395 }
1396
1397 let cf = self.visit_with(&mut ContainsTyVisitor(other));
1398 cf.is_break()
1399 }
1400
1401 pub fn contains_closure(self) -> bool {
1405 struct ContainsClosureVisitor;
1406
1407 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1408 type Result = ControlFlow<()>;
1409
1410 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1411 if let ty::Closure(..) = t.kind() {
1412 ControlFlow::Break(())
1413 } else {
1414 t.super_visit_with(self)
1415 }
1416 }
1417 }
1418
1419 let cf = self.visit_with(&mut ContainsClosureVisitor);
1420 cf.is_break()
1421 }
1422
1423 pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1428 self,
1429 tcx: TyCtxt<'tcx>,
1430 mut f: F,
1431 ) -> Ty<'tcx> {
1432 assert!(self.is_coroutine());
1433 let mut cor_ty = self;
1434 let mut ty = cor_ty;
1435 loop {
1436 if let ty::Coroutine(def_id, args) = ty.kind() {
1437 cor_ty = ty;
1438 f(ty);
1439 if tcx.is_async_drop_in_place_coroutine(*def_id) {
1440 ty = args.first().unwrap().expect_ty();
1441 continue;
1442 } else {
1443 return cor_ty;
1444 }
1445 } else {
1446 return cor_ty;
1447 }
1448 }
1449 }
1450
1451 pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1456 match *self.kind() {
1457 _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1458 Ref(_, ty, _) => Some(ty),
1459 RawPtr(ty, _) if explicit => Some(ty),
1460 _ => None,
1461 }
1462 }
1463
1464 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1466 match self.kind() {
1467 Array(ty, _) | Slice(ty) => Some(*ty),
1468 _ => None,
1469 }
1470 }
1471
1472 #[tracing::instrument(level = "trace", skip(tcx))]
1473 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1474 self.kind().fn_sig(tcx)
1475 }
1476
1477 #[inline]
1478 pub fn is_fn(self) -> bool {
1479 matches!(self.kind(), FnDef(..) | FnPtr(..))
1480 }
1481
1482 #[inline]
1483 pub fn is_fn_ptr(self) -> bool {
1484 matches!(self.kind(), FnPtr(..))
1485 }
1486
1487 #[inline]
1488 pub fn is_impl_trait(self) -> bool {
1489 matches!(self.kind(), Alias(ty::Opaque, ..))
1490 }
1491
1492 #[inline]
1493 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1494 match self.kind() {
1495 Adt(adt, _) => Some(*adt),
1496 _ => None,
1497 }
1498 }
1499
1500 #[inline]
1503 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1504 match self.kind() {
1505 Tuple(args) => args,
1506 _ => bug!("tuple_fields called on non-tuple: {self:?}"),
1507 }
1508 }
1509
1510 #[inline]
1514 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1515 match self.kind() {
1516 TyKind::Adt(adt, _) => Some(adt.variant_range()),
1517 TyKind::Coroutine(def_id, args) => {
1518 Some(args.as_coroutine().variant_range(*def_id, tcx))
1519 }
1520 _ => None,
1521 }
1522 }
1523
1524 #[inline]
1529 pub fn discriminant_for_variant(
1530 self,
1531 tcx: TyCtxt<'tcx>,
1532 variant_index: VariantIdx,
1533 ) -> Option<Discr<'tcx>> {
1534 match self.kind() {
1535 TyKind::Adt(adt, _) if adt.is_enum() => {
1536 Some(adt.discriminant_for_variant(tcx, variant_index))
1537 }
1538 TyKind::Coroutine(def_id, args) => {
1539 Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1540 }
1541 _ => None,
1542 }
1543 }
1544
1545 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1547 match self.kind() {
1548 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1549 ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1550
1551 ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1552 let assoc_items = tcx.associated_item_def_ids(
1553 tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1554 );
1555 Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1556 }
1557
1558 ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1559
1560 ty::Bool
1561 | ty::Char
1562 | ty::Int(_)
1563 | ty::Uint(_)
1564 | ty::Float(_)
1565 | ty::Adt(..)
1566 | ty::Foreign(_)
1567 | ty::Str
1568 | ty::Array(..)
1569 | ty::Slice(_)
1570 | ty::RawPtr(_, _)
1571 | ty::Ref(..)
1572 | ty::FnDef(..)
1573 | ty::FnPtr(..)
1574 | ty::Dynamic(..)
1575 | ty::Closure(..)
1576 | ty::CoroutineClosure(..)
1577 | ty::CoroutineWitness(..)
1578 | ty::Never
1579 | ty::Tuple(_)
1580 | ty::UnsafeBinder(_)
1581 | ty::Error(_)
1582 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1583
1584 ty::Bound(..)
1585 | ty::Placeholder(_)
1586 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1587 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1588 }
1589 }
1590 }
1591
1592 pub fn ptr_metadata_ty_or_tail(
1595 self,
1596 tcx: TyCtxt<'tcx>,
1597 normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1598 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1599 let tail = tcx.struct_tail_raw(self, normalize, || {});
1600 match tail.kind() {
1601 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1603 | ty::Uint(_)
1604 | ty::Int(_)
1605 | ty::Bool
1606 | ty::Float(_)
1607 | ty::FnDef(..)
1608 | ty::FnPtr(..)
1609 | ty::RawPtr(..)
1610 | ty::Char
1611 | ty::Ref(..)
1612 | ty::Coroutine(..)
1613 | ty::CoroutineWitness(..)
1614 | ty::Array(..)
1615 | ty::Closure(..)
1616 | ty::CoroutineClosure(..)
1617 | ty::Never
1618 | ty::Error(_)
1619 | ty::Foreign(..)
1621 | ty::Dynamic(_, _, ty::DynStar)
1623 | ty::Adt(..)
1626 | ty::Tuple(..) => Ok(tcx.types.unit),
1629
1630 ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1631
1632 ty::Dynamic(_, _, ty::Dyn) => {
1633 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1634 Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1635 }
1636
1637 ty::Param(_) | ty::Alias(..) => Err(tail),
1640
1641 | ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
1642
1643 ty::Infer(ty::TyVar(_))
1644 | ty::Pat(..)
1645 | ty::Bound(..)
1646 | ty::Placeholder(..)
1647 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(
1648 "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1649 ),
1650 }
1651 }
1652
1653 pub fn ptr_metadata_ty(
1656 self,
1657 tcx: TyCtxt<'tcx>,
1658 normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1659 ) -> Ty<'tcx> {
1660 match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1661 Ok(metadata) => metadata,
1662 Err(tail) => bug!(
1663 "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1664 ),
1665 }
1666 }
1667
1668 #[track_caller]
1677 pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1678 let Some(pointee_ty) = self.builtin_deref(true) else {
1679 bug!("Type {self:?} is not a pointer or reference type")
1680 };
1681 if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1682 tcx.types.unit
1683 } else {
1684 match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1685 Ok(metadata_ty) => metadata_ty,
1686 Err(tail_ty) => {
1687 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1688 Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1689 }
1690 }
1691 }
1692 }
1693
1694 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1734 match self.kind() {
1735 Int(int_ty) => match int_ty {
1736 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1737 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1738 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1739 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1740 },
1741
1742 Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1746
1747 Error(_) => Some(ty::ClosureKind::Fn),
1748
1749 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1750 }
1751 }
1752
1753 pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1756 match kind {
1757 ty::ClosureKind::Fn => tcx.types.i8,
1758 ty::ClosureKind::FnMut => tcx.types.i16,
1759 ty::ClosureKind::FnOnce => tcx.types.i32,
1760 }
1761 }
1762
1763 pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1776 match kind {
1777 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1778 ty::ClosureKind::FnOnce => tcx.types.i32,
1779 }
1780 }
1781
1782 #[instrument(skip(tcx), level = "debug")]
1792 pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1793 match self.kind() {
1794 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1795 | ty::Uint(_)
1796 | ty::Int(_)
1797 | ty::Bool
1798 | ty::Float(_)
1799 | ty::FnDef(..)
1800 | ty::FnPtr(..)
1801 | ty::UnsafeBinder(_)
1802 | ty::RawPtr(..)
1803 | ty::Char
1804 | ty::Ref(..)
1805 | ty::Coroutine(..)
1806 | ty::CoroutineWitness(..)
1807 | ty::Array(..)
1808 | ty::Pat(..)
1809 | ty::Closure(..)
1810 | ty::CoroutineClosure(..)
1811 | ty::Never
1812 | ty::Error(_)
1813 | ty::Dynamic(_, _, ty::DynStar) => true,
1814
1815 ty::Str | ty::Slice(_) | ty::Dynamic(_, _, ty::Dyn) => match sizedness {
1816 SizedTraitKind::Sized => false,
1817 SizedTraitKind::MetaSized => true,
1818 },
1819
1820 ty::Foreign(..) => match sizedness {
1821 SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1822 },
1823
1824 ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1825
1826 ty::Adt(def, args) => def
1827 .sizedness_constraint(tcx, sizedness)
1828 .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1829
1830 ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1831
1832 ty::Infer(ty::TyVar(_)) => false,
1833
1834 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1835 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
1836 }
1837 }
1838 }
1839
1840 pub fn is_trivially_pure_clone_copy(self) -> bool {
1849 match self.kind() {
1850 ty::Bool | ty::Char | ty::Never => true,
1851
1852 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1854
1855 ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1856 | ty::Int(..)
1857 | ty::Uint(..)
1858 | ty::Float(..) => true,
1859
1860 ty::FnDef(..) => true,
1862
1863 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1864
1865 ty::Tuple(field_tys) => {
1867 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1868 }
1869
1870 ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1871
1872 ty::FnPtr(..) => false,
1875
1876 ty::Ref(_, _, hir::Mutability::Mut) => false,
1878
1879 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1882
1883 ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1884
1885 ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1887
1888 ty::UnsafeBinder(_) => false,
1889
1890 ty::Alias(..) => false,
1892
1893 ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
1894 false
1895 }
1896 }
1897 }
1898
1899 pub fn primitive_symbol(self) -> Option<Symbol> {
1901 match self.kind() {
1902 ty::Bool => Some(sym::bool),
1903 ty::Char => Some(sym::char),
1904 ty::Float(f) => match f {
1905 ty::FloatTy::F16 => Some(sym::f16),
1906 ty::FloatTy::F32 => Some(sym::f32),
1907 ty::FloatTy::F64 => Some(sym::f64),
1908 ty::FloatTy::F128 => Some(sym::f128),
1909 },
1910 ty::Int(f) => match f {
1911 ty::IntTy::Isize => Some(sym::isize),
1912 ty::IntTy::I8 => Some(sym::i8),
1913 ty::IntTy::I16 => Some(sym::i16),
1914 ty::IntTy::I32 => Some(sym::i32),
1915 ty::IntTy::I64 => Some(sym::i64),
1916 ty::IntTy::I128 => Some(sym::i128),
1917 },
1918 ty::Uint(f) => match f {
1919 ty::UintTy::Usize => Some(sym::usize),
1920 ty::UintTy::U8 => Some(sym::u8),
1921 ty::UintTy::U16 => Some(sym::u16),
1922 ty::UintTy::U32 => Some(sym::u32),
1923 ty::UintTy::U64 => Some(sym::u64),
1924 ty::UintTy::U128 => Some(sym::u128),
1925 },
1926 ty::Str => Some(sym::str),
1927 _ => None,
1928 }
1929 }
1930
1931 pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
1932 match self.kind() {
1933 ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
1934 _ => false,
1935 }
1936 }
1937
1938 pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
1939 match self.kind() {
1940 ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
1941 _ => false,
1942 }
1943 }
1944
1945 pub fn is_known_rigid(self) -> bool {
1951 self.kind().is_known_rigid()
1952 }
1953
1954 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
1965 TypeWalker::new(self.into())
1966 }
1967}
1968
1969impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
1970 fn inputs(self) -> &'tcx [Ty<'tcx>] {
1971 self.split_last().unwrap().1
1972 }
1973
1974 fn output(self) -> Ty<'tcx> {
1975 *self.split_last().unwrap().0
1976 }
1977}
1978
1979#[cfg(target_pointer_width = "64")]
1981mod size_asserts {
1982 use rustc_data_structures::static_assert_size;
1983
1984 use super::*;
1985 static_assert_size!(ty::RegionKind<'_>, 24);
1987 static_assert_size!(ty::TyKind<'_>, 24);
1988 }