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