1#![allow(rustc::usage_of_ty_tykind)]
4
5use std::borrow::Cow;
6use std::debug_assert_matches;
7use std::ops::{ControlFlow, Range};
8
9use hir::def::{CtorKind, DefKind};
10use rustc_abi::{FIRST_VARIANT, FieldIdx, NumScalableVectors, ScalableElt, VariantIdx};
11use rustc_errors::{ErrorGuaranteed, MultiSpan};
12use rustc_hir as hir;
13use rustc_hir::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{StableHash, TyDecodable, TyEncodable, TypeFoldable, extension};
16use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
17use rustc_type_ir::TyKind::*;
18use rustc_type_ir::solve::SizedTraitKind;
19use rustc_type_ir::walk::TypeWalker;
20use rustc_type_ir::{
21 self as ir, BoundVar, CollectAndApply, MayBeErased, TypeVisitableExt, elaborate,
22};
23use tracing::instrument;
24use ty::util::IntTypeExt;
25
26use super::GenericParamDefKind;
27use crate::infer::canonical::Canonical;
28use crate::traits::ObligationCause;
29use crate::ty::InferTy::*;
30use crate::ty::{
31 self, AdtDef, Const, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, Region,
32 Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, ValTree,
33};
34
35#[rustc_diagnostic_item = "TyKind"]
37pub type TyKind<'tcx> = ir::TyKind<TyCtxt<'tcx>>;
38pub type TypeAndMut<'tcx> = ir::TypeAndMut<TyCtxt<'tcx>>;
39pub type AliasTy<'tcx> = ir::AliasTy<TyCtxt<'tcx>>;
40pub type AliasTyKind<'tcx> = ir::AliasTyKind<TyCtxt<'tcx>>;
41pub type Alias<'tcx, K> = ir::Alias<TyCtxt<'tcx>, K>;
42pub type ProjectionAliasTy<'tcx> = ir::ProjectionAliasTy<TyCtxt<'tcx>>;
43pub type InherentAliasTy<'tcx> = ir::InherentAliasTy<TyCtxt<'tcx>>;
44pub type OpaqueAliasTy<'tcx> = ir::OpaqueAliasTy<TyCtxt<'tcx>>;
45pub type FreeAliasTy<'tcx> = ir::FreeAliasTy<TyCtxt<'tcx>>;
46pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
47pub type FnSigKind<'tcx> = ir::FnSigKind<TyCtxt<'tcx>>;
48pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
49pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
50pub type Unnormalized<'tcx, T> = ir::Unnormalized<TyCtxt<'tcx>, T>;
51pub type TypingMode<'tcx, S = MayBeErased> = ir::TypingMode<TyCtxt<'tcx>, S>;
52pub type TypingModeEqWrapper<'tcx> = ir::TypingModeEqWrapper<TyCtxt<'tcx>>;
53pub type Placeholder<'tcx, T> = ir::Placeholder<TyCtxt<'tcx>, T>;
54pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion<TyCtxt<'tcx>>;
55pub type PlaceholderType<'tcx> = ir::PlaceholderType<TyCtxt<'tcx>>;
56pub type PlaceholderConst<'tcx> = ir::PlaceholderConst<TyCtxt<'tcx>>;
57pub type BoundTy<'tcx> = ir::BoundTy<TyCtxt<'tcx>>;
58pub type BoundConst<'tcx> = ir::BoundConst<TyCtxt<'tcx>>;
59pub type BoundRegion<'tcx> = ir::BoundRegion<TyCtxt<'tcx>>;
60pub type BoundVariableKind<'tcx> = ir::BoundVariableKind<TyCtxt<'tcx>>;
61pub type BoundRegionKind<'tcx> = ir::BoundRegionKind<TyCtxt<'tcx>>;
62pub type BoundTyKind<'tcx> = ir::BoundTyKind<TyCtxt<'tcx>>;
63
64pub trait Article {
65 fn article(&self) -> &'static str;
66}
67
68impl<'tcx> Article for TyKind<'tcx> {
69 fn article(&self) -> &'static str {
71 match self {
72 Int(_) | Float(_) | Array(_, _) => "an",
73 Adt(def, _) if def.is_enum() => "an",
74 Error(_) => "a",
77 _ => "a",
78 }
79 }
80}
81
82impl<'tcx> CoroutineArgsExt<'tcx> for ty::CoroutineArgs<TyCtxt<'tcx>> {
#[doc = " Coroutine has not been resumed yet."]
const UNRESUMED: usize = 0;
#[doc = " Coroutine has returned or is completed."]
const RETURNED: usize = 1;
#[doc = " Coroutine has been poisoned."]
const POISONED: usize = 2;
#[doc =
" Number of variants to reserve in coroutine state. Corresponds to"]
#[doc =
" `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`"]
#[doc = " (end of a coroutine) states."]
const RESERVED_VARIANTS: usize = 3;
const UNRESUMED_NAME: &'static str = "Unresumed";
const RETURNED_NAME: &'static str = "Returned";
const POISONED_NAME: &'static str = "Panicked";
#[doc = " The valid variant indices of this coroutine."]
#[inline]
fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>)
-> Range<VariantIdx> {
FIRST_VARIANT..tcx.coroutine_layout(def_id,
self.args).unwrap().variant_fields.next_index()
}
#[doc =
" The discriminant for the given variant. Panics if the `variant_index` is"]
#[doc = " out of range."]
#[inline]
fn discriminant_for_variant(&self, def_id: DefId, tcx: TyCtxt<'tcx>,
variant_index: VariantIdx) -> Discr<'tcx> {
if !self.variant_range(def_id, tcx).contains(&variant_index) {
::core::panicking::panic("assertion failed: self.variant_range(def_id, tcx).contains(&variant_index)")
};
Discr {
val: variant_index.as_usize() as u128,
ty: self.discr_ty(tcx),
}
}
#[doc =
" The set of all discriminants for the coroutine, enumerated with their"]
#[doc = " variant indices."]
#[inline]
fn discriminants(self, def_id: DefId, tcx: TyCtxt<'tcx>)
-> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
self.variant_range(def_id,
tcx).map(move |index|
{
(index,
Discr {
val: index.as_usize() as u128,
ty: self.discr_ty(tcx),
})
})
}
#[doc =
" Calls `f` with a reference to the name of the enumerator for the given"]
#[doc = " variant `v`."]
fn variant_name(v: VariantIdx) -> Cow<'static, str> {
match v.as_usize() {
Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
Self::RETURNED => Cow::from(Self::RETURNED_NAME),
Self::POISONED => Cow::from(Self::POISONED_NAME),
_ =>
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Suspend{0}",
v.as_usize() - Self::RESERVED_VARIANTS))
})),
}
}
#[doc = " The type of the state discriminant used in the coroutine type."]
#[inline]
fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { tcx.types.u32 }
#[doc =
" This returns the types of the MIR locals which had to be stored across suspension points."]
#[doc =
" It is calculated in rustc_mir_transform::coroutine::StateTransform."]
#[doc = " All the types here must be in the tuple in CoroutineInterior."]
#[doc = ""]
#[doc =
" The locals are grouped by their variant number. Note that some locals may"]
#[doc = " be repeated in multiple variants."]
#[inline]
fn state_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>)
-> impl Iterator<Item : Iterator<Item = Ty<'tcx>>> {
let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
layout.variant_fields.iter().map(move |variant|
{
variant.iter().map(move |field|
{
if tcx.is_async_drop_in_place_coroutine(def_id) {
layout.field_tys[*field].ty
} else {
ty::EarlyBinder::bind(tcx,
layout.field_tys[*field].ty).instantiate(tcx,
self.args).skip_norm_wip()
}
})
})
}
}#[extension(pub trait CoroutineArgsExt<'tcx>)]
83impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
84 const UNRESUMED: usize = 0;
86 const RETURNED: usize = 1;
88 const POISONED: usize = 2;
90 const RESERVED_VARIANTS: usize = 3;
94
95 const UNRESUMED_NAME: &'static str = "Unresumed";
96 const RETURNED_NAME: &'static str = "Returned";
97 const POISONED_NAME: &'static str = "Panicked";
98
99 #[inline]
101 fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
102 FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
104 }
105
106 #[inline]
109 fn discriminant_for_variant(
110 &self,
111 def_id: DefId,
112 tcx: TyCtxt<'tcx>,
113 variant_index: VariantIdx,
114 ) -> Discr<'tcx> {
115 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
118 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
119 }
120
121 #[inline]
124 fn discriminants(
125 self,
126 def_id: DefId,
127 tcx: TyCtxt<'tcx>,
128 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
129 self.variant_range(def_id, tcx).map(move |index| {
130 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
131 })
132 }
133
134 fn variant_name(v: VariantIdx) -> Cow<'static, str> {
137 match v.as_usize() {
138 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
139 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
140 Self::POISONED => Cow::from(Self::POISONED_NAME),
141 _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
142 }
143 }
144
145 #[inline]
147 fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
148 tcx.types.u32
149 }
150
151 #[inline]
158 fn state_tys(
159 self,
160 def_id: DefId,
161 tcx: TyCtxt<'tcx>,
162 ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
163 let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
164 layout.variant_fields.iter().map(move |variant| {
165 variant.iter().map(move |field| {
166 if tcx.is_async_drop_in_place_coroutine(def_id) {
167 layout.field_tys[*field].ty
168 } else {
169 ty::EarlyBinder::bind(tcx, layout.field_tys[*field].ty)
170 .instantiate(tcx, self.args)
171 .skip_norm_wip()
172 }
173 })
174 })
175 }
176}
177
178#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UpvarArgs<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
UpvarArgs::Closure(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Closure", &__self_0),
UpvarArgs::Coroutine(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Coroutine", &__self_0),
UpvarArgs::CoroutineClosure(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"CoroutineClosure", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for UpvarArgs<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for UpvarArgs<'tcx> {
#[inline]
fn clone(&self) -> UpvarArgs<'tcx> {
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, const _: () =
{
impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
UpvarArgs<'tcx> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
UpvarArgs::Closure(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
UpvarArgs::Coroutine(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
UpvarArgs::CoroutineClosure(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for UpvarArgs<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
UpvarArgs::Closure(__binding_0) => {
UpvarArgs::Closure(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
UpvarArgs::Coroutine(__binding_0) => {
UpvarArgs::Coroutine(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
UpvarArgs::CoroutineClosure(__binding_0) => {
UpvarArgs::CoroutineClosure(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
UpvarArgs::Closure(__binding_0) => {
UpvarArgs::Closure(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
UpvarArgs::Coroutine(__binding_0) => {
UpvarArgs::Coroutine(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
UpvarArgs::CoroutineClosure(__binding_0) => {
UpvarArgs::CoroutineClosure(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for UpvarArgs<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
UpvarArgs::Closure(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
UpvarArgs::Coroutine(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
UpvarArgs::CoroutineClosure(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
179pub enum UpvarArgs<'tcx> {
180 Closure(GenericArgsRef<'tcx>),
181 Coroutine(GenericArgsRef<'tcx>),
182 CoroutineClosure(GenericArgsRef<'tcx>),
183}
184
185impl<'tcx> UpvarArgs<'tcx> {
186 #[inline]
190 pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
191 let tupled_tys = 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 match tupled_tys.kind() {
198 TyKind::Error(_) => ty::List::empty(),
199 TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
200 TyKind::Infer(_) => crate::util::bug::bug_fmt(format_args!("upvar_tys called before capture types are inferred"))bug!("upvar_tys called before capture types are inferred"),
201 ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
202 }
203 }
204
205 #[inline]
206 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
207 match self {
208 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
209 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
210 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
211 }
212 }
213}
214
215#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for InlineConstArgs<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for InlineConstArgs<'tcx> {
#[inline]
fn clone(&self) -> InlineConstArgs<'tcx> {
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InlineConstArgs<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InlineConstArgs", "args", &&self.args)
}
}Debug)]
230pub struct InlineConstArgs<'tcx> {
231 pub args: GenericArgsRef<'tcx>,
234}
235
236pub struct InlineConstArgsParts<'tcx, T> {
238 pub parent_args: &'tcx [GenericArg<'tcx>],
239 pub ty: T,
240}
241
242impl<'tcx> InlineConstArgs<'tcx> {
243 pub fn new(
245 tcx: TyCtxt<'tcx>,
246 parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
247 ) -> InlineConstArgs<'tcx> {
248 InlineConstArgs {
249 args: tcx.mk_args_from_iter(
250 parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
251 ),
252 }
253 }
254
255 fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
258 match self.args[..] {
259 [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
260 _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
261 }
262 }
263
264 pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
266 self.split().parent_args
267 }
268
269 pub fn ty(self) -> Ty<'tcx> {
271 self.split().ty.expect_ty()
272 }
273}
274
275pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
276pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
277
278#[derive(#[automatically_derived]
impl ::core::clone::Clone for ParamTy {
#[inline]
fn clone(&self) -> ParamTy {
let _: ::core::clone::AssertParamIsClone<u32>;
let _: ::core::clone::AssertParamIsClone<Symbol>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ParamTy { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamTy {
#[inline]
fn eq(&self, other: &ParamTy) -> bool {
self.index == other.index && self.name == other.name
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ParamTy {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u32>;
let _: ::core::cmp::AssertParamIsEq<Symbol>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for ParamTy {
#[inline]
fn partial_cmp(&self, other: &ParamTy)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for ParamTy {
#[inline]
fn cmp(&self, other: &ParamTy) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.index, &other.index) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.name, &other.name),
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::hash::Hash for ParamTy {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.index, state);
::core::hash::Hash::hash(&self.name, state)
}
}Hash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for ParamTy {
fn encode(&self, __encoder: &mut __E) {
match *self {
ParamTy { index: ref __binding_0, name: ref __binding_1 } =>
{
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for ParamTy {
fn decode(__decoder: &mut __D) -> Self {
ParamTy {
index: ::rustc_serialize::Decodable::decode(__decoder),
name: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};TyDecodable)]
279#[derive(const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for ParamTy {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
ParamTy { index: ref __binding_0, name: ref __binding_1 } =>
{
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
280pub struct ParamTy {
281 pub index: u32,
282 pub name: Symbol,
283}
284
285impl rustc_type_ir::inherent::ParamLike for ParamTy {
286 fn index(self) -> u32 {
287 self.index
288 }
289}
290
291impl<'tcx> ParamTy {
292 pub fn new(index: u32, name: Symbol) -> ParamTy {
293 ParamTy { index, name }
294 }
295
296 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
297 ParamTy::new(def.index, def.name)
298 }
299
300 #[inline]
301 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
302 Ty::new_param(tcx, self.index, self.name)
303 }
304
305 pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
306 let generics = tcx.generics_of(item_with_generics);
307 let type_param = generics.type_param(self, tcx);
308 tcx.def_span(type_param.def_id)
309 }
310}
311
312#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParamConst { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ParamConst {
#[inline]
fn clone(&self) -> ParamConst {
let _: ::core::clone::AssertParamIsClone<u32>;
let _: ::core::clone::AssertParamIsClone<Symbol>;
*self
}
}Clone, #[automatically_derived]
impl ::core::hash::Hash for ParamConst {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.index, state);
::core::hash::Hash::hash(&self.name, state)
}
}Hash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for ParamConst {
fn encode(&self, __encoder: &mut __E) {
match *self {
ParamConst { index: ref __binding_0, name: ref __binding_1 }
=> {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for ParamConst {
fn decode(__decoder: &mut __D) -> Self {
ParamConst {
index: ::rustc_serialize::Decodable::decode(__decoder),
name: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};TyDecodable, #[automatically_derived]
impl ::core::cmp::Eq for ParamConst {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u32>;
let _: ::core::cmp::AssertParamIsEq<Symbol>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamConst {
#[inline]
fn eq(&self, other: &ParamConst) -> bool {
self.index == other.index && self.name == other.name
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Ord for ParamConst {
#[inline]
fn cmp(&self, other: &ParamConst) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.index, &other.index) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.name, &other.name),
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::cmp::PartialOrd for ParamConst {
#[inline]
fn partial_cmp(&self, other: &ParamConst)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd)]
313#[derive(const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for ParamConst {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
ParamConst { index: ref __binding_0, name: ref __binding_1 }
=> {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
314pub struct ParamConst {
315 pub index: u32,
316 pub name: Symbol,
317}
318
319impl rustc_type_ir::inherent::ParamLike for ParamConst {
320 fn index(self) -> u32 {
321 self.index
322 }
323}
324
325impl ParamConst {
326 pub fn new(index: u32, name: Symbol) -> ParamConst {
327 ParamConst { index, name }
328 }
329
330 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
331 ParamConst::new(def.index, def.name)
332 }
333
334 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("find_const_ty_from_env",
"rustc_middle::ty::sty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
::tracing_core::__macro_support::Option::Some(334u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("env")
}> =
::tracing::__macro_support::FieldName::new("env");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&env)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let mut candidates =
env.caller_bounds().iter().filter_map(|clause|
{
match clause.kind().skip_binder() {
ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
if !!(param_ct, ty).has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !(param_ct, ty).has_escaping_bound_vars()")
};
match param_ct.kind() {
ty::ConstKind::Param(param_ct) if
param_ct.index == self.index => Some(ty),
_ => None,
}
}
_ => None,
}
});
let ty =
candidates.next().unwrap_or_else(||
{
crate::util::bug::bug_fmt(format_args!("cannot find `{0:?}` in param-env: {1:#?}",
self, env));
});
if !candidates.next().is_none() {
{
::core::panicking::panic_fmt(format_args!("did not expect duplicate `ConstParamHasTy` for `{0:?}` in param-env: {1:#?}",
self, env));
}
};
ty
}
}
}#[instrument(level = "debug")]
335 pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
336 let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
337 match clause.kind().skip_binder() {
339 ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
340 assert!(!(param_ct, ty).has_escaping_bound_vars());
341
342 match param_ct.kind() {
343 ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
344 _ => None,
345 }
346 }
347 _ => None,
348 }
349 });
350
351 let ty = candidates.next().unwrap_or_else(|| {
358 bug!("cannot find `{self:?}` in param-env: {env:#?}");
359 });
360 assert!(
361 candidates.next().is_none(),
362 "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
363 );
364 ty
365 }
366}
367
368impl<'tcx> Ty<'tcx> {
370 #[inline]
373 fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
374 tcx.mk_ty_from_kind(st)
375 }
376
377 #[inline]
378 pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
379 Ty::new(tcx, TyKind::Infer(infer))
380 }
381
382 #[inline]
383 pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
384 tcx.types
386 .ty_vars
387 .get(v.as_usize())
388 .copied()
389 .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
390 }
391
392 #[inline]
393 pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
394 Ty::new_infer(tcx, IntVar(v))
395 }
396
397 #[inline]
398 pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
399 Ty::new_infer(tcx, FloatVar(v))
400 }
401
402 #[inline]
403 pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
404 tcx.types
406 .fresh_tys
407 .get(n as usize)
408 .copied()
409 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
410 }
411
412 #[inline]
413 pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
414 tcx.types
416 .fresh_int_tys
417 .get(n as usize)
418 .copied()
419 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
420 }
421
422 #[inline]
423 pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
424 tcx.types
426 .fresh_float_tys
427 .get(n as usize)
428 .copied()
429 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
430 }
431
432 #[inline]
433 pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
434 Ty::new(tcx, Param(ParamTy { index, name }))
435 }
436
437 #[inline]
438 pub fn new_bound(
439 tcx: TyCtxt<'tcx>,
440 index: ty::DebruijnIndex,
441 bound_ty: ty::BoundTy<'tcx>,
442 ) -> Ty<'tcx> {
443 if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
445 && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
446 && let Some(ty) = inner.get(var.as_usize()).copied()
447 {
448 ty
449 } else {
450 Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
451 }
452 }
453
454 #[inline]
455 pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
456 if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
458 ty
459 } else {
460 Ty::new(
461 tcx,
462 Bound(
463 ty::BoundVarIndexKind::Canonical,
464 ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
465 ),
466 )
467 }
468 }
469
470 #[inline]
471 pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
472 Ty::new(tcx, Placeholder(placeholder))
473 }
474
475 #[inline]
476 pub fn new_alias(
477 tcx: TyCtxt<'tcx>,
478 is_rigid: ty::IsRigid,
479 alias_ty: ty::AliasTy<'tcx>,
480 ) -> Ty<'tcx> {
481 if truecfg!(debug_assertions) {
482 match alias_ty.kind {
483 ty::AliasTyKind::Projection { def_id } => {
484 if true {
{
match tcx.def_kind(def_id) {
DefKind::AssocTy => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocTy", ::core::option::Option::None);
}
}
};
}debug_assert_matches!(tcx.def_kind(def_id), DefKind::AssocTy)
485 }
486 ty::AliasTyKind::Inherent { def_id } => {
487 if true {
{
match tcx.def_kind(def_id) {
DefKind::AssocTy => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocTy", ::core::option::Option::None);
}
}
};
}debug_assert_matches!(tcx.def_kind(def_id), DefKind::AssocTy)
488 }
489 ty::AliasTyKind::Opaque { def_id } => {
490 if true {
{
match tcx.def_kind(def_id) {
DefKind::OpaqueTy => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::OpaqueTy", ::core::option::Option::None);
}
}
};
}debug_assert_matches!(tcx.def_kind(def_id), DefKind::OpaqueTy)
491 }
492 ty::AliasTyKind::Free { def_id } => {
493 if true {
{
match tcx.def_kind(def_id) {
DefKind::TyAlias => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::TyAlias", ::core::option::Option::None);
}
}
};
}debug_assert_matches!(tcx.def_kind(def_id), DefKind::TyAlias)
494 }
495 }
496 }
497 Ty::new(tcx, Alias(is_rigid, 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 pub fn new_field_representing_type(
507 tcx: TyCtxt<'tcx>,
508 base: Ty<'tcx>,
509 variant: VariantIdx,
510 field: FieldIdx,
511 ) -> Ty<'tcx> {
512 let Some(did) = tcx.lang_items().field_representing_type() else {
513 crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
514 };
515 let def = tcx.adt_def(did);
516 let args = tcx.mk_args(&[
517 base.into(),
518 Const::new_value(
519 tcx,
520 ValTree::from_scalar_int(tcx, variant.as_u32().into()),
521 tcx.types.u32,
522 )
523 .into(),
524 Const::new_value(
525 tcx,
526 ValTree::from_scalar_int(tcx, field.as_u32().into()),
527 tcx.types.u32,
528 )
529 .into(),
530 ]);
531 Ty::new_adt(tcx, def, args)
532 }
533
534 #[inline]
535 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("new_opaque",
"rustc_middle::ty::sty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
::tracing_core::__macro_support::Option::Some(535u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("is_rigid")
}> =
::tracing::__macro_support::FieldName::new("is_rigid");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("args")
}> =
::tracing::__macro_support::FieldName::new("args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_rigid)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
Ty::new_alias(tcx, is_rigid,
AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
}
}
}#[instrument(level = "debug", skip(tcx))]
536 pub fn new_opaque(
537 tcx: TyCtxt<'tcx>,
538 is_rigid: ty::IsRigid,
539 def_id: DefId,
540 args: GenericArgsRef<'tcx>,
541 ) -> Ty<'tcx> {
542 Ty::new_alias(tcx, is_rigid, AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
543 }
544
545 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
547 Ty::new(tcx, Error(guar))
548 }
549
550 #[track_caller]
552 pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
553 Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
554 }
555
556 #[track_caller]
559 pub fn new_error_with_message<S: Into<MultiSpan>>(
560 tcx: TyCtxt<'tcx>,
561 span: S,
562 msg: impl Into<Cow<'static, str>>,
563 ) -> Ty<'tcx> {
564 let reported = tcx.dcx().span_delayed_bug(span, msg);
565 Ty::new(tcx, Error(reported))
566 }
567
568 #[inline]
569 pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
570 use ty::IntTy::*;
571 match i {
572 Isize => tcx.types.isize,
573 I8 => tcx.types.i8,
574 I16 => tcx.types.i16,
575 I32 => tcx.types.i32,
576 I64 => tcx.types.i64,
577 I128 => tcx.types.i128,
578 }
579 }
580
581 #[inline]
582 pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
583 use ty::UintTy::*;
584 match ui {
585 Usize => tcx.types.usize,
586 U8 => tcx.types.u8,
587 U16 => tcx.types.u16,
588 U32 => tcx.types.u32,
589 U64 => tcx.types.u64,
590 U128 => tcx.types.u128,
591 }
592 }
593
594 #[inline]
595 pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
596 use ty::FloatTy::*;
597 match f {
598 F16 => tcx.types.f16,
599 F32 => tcx.types.f32,
600 F64 => tcx.types.f64,
601 F128 => tcx.types.f128,
602 }
603 }
604
605 #[inline]
606 pub fn new_ref(
607 tcx: TyCtxt<'tcx>,
608 r: Region<'tcx>,
609 ty: Ty<'tcx>,
610 mutbl: ty::Mutability,
611 ) -> Ty<'tcx> {
612 Ty::new(tcx, Ref(r, ty, mutbl))
613 }
614
615 #[inline]
616 pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
617 Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
618 }
619
620 #[inline]
621 pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
622 Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
623 }
624
625 pub fn new_pinned_ref(
626 tcx: TyCtxt<'tcx>,
627 r: Region<'tcx>,
628 ty: Ty<'tcx>,
629 mutbl: ty::Mutability,
630 ) -> Ty<'tcx> {
631 let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
632 Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
633 }
634
635 #[inline]
636 pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
637 Ty::new(tcx, ty::RawPtr(ty, mutbl))
638 }
639
640 #[inline]
641 pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
642 Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
643 }
644
645 #[inline]
646 pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
647 Ty::new_ptr(tcx, ty, hir::Mutability::Not)
648 }
649
650 #[inline]
651 pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
652 tcx.debug_assert_args_compatible(def.did(), args);
653 if truecfg!(debug_assertions) {
654 match tcx.def_kind(def.did()) {
655 DefKind::Struct | DefKind::Union | DefKind::Enum => {}
656 DefKind::Mod
657 | DefKind::Variant
658 | DefKind::Trait
659 | DefKind::TyAlias
660 | DefKind::ForeignTy
661 | DefKind::TraitAlias
662 | DefKind::AssocTy
663 | DefKind::TyParam
664 | DefKind::Fn
665 | DefKind::Const { .. }
666 | DefKind::ConstParam
667 | DefKind::Static { .. }
668 | DefKind::Ctor(..)
669 | DefKind::AssocFn
670 | DefKind::AssocConst { .. }
671 | DefKind::Macro(..)
672 | DefKind::ExternCrate
673 | DefKind::Use
674 | DefKind::ForeignMod
675 | DefKind::AnonConst
676 | DefKind::OpaqueTy
677 | DefKind::Field
678 | DefKind::LifetimeParam
679 | DefKind::GlobalAsm
680 | DefKind::Impl { .. }
681 | DefKind::Closure
682 | DefKind::SyntheticCoroutineBody => {
683 crate::util::bug::bug_fmt(format_args!("not an adt: {1:?} ({0:?})",
tcx.def_kind(def.did()), def))bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did()))
684 }
685 }
686 }
687 Ty::new(tcx, Adt(def, args))
688 }
689
690 #[inline]
691 pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
692 Ty::new(tcx, Foreign(def_id))
693 }
694
695 #[inline]
696 pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
697 Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
698 }
699
700 #[inline]
701 pub fn new_array_with_const_len(
702 tcx: TyCtxt<'tcx>,
703 ty: Ty<'tcx>,
704 ct: ty::Const<'tcx>,
705 ) -> Ty<'tcx> {
706 Ty::new(tcx, Array(ty, ct))
707 }
708
709 #[inline]
710 pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
711 Ty::new(tcx, Slice(ty))
712 }
713
714 #[inline]
715 pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
716 if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
717 }
718
719 pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
720 where
721 I: Iterator<Item = T>,
722 T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
723 {
724 T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
725 }
726
727 #[inline]
729 pub fn new_fn_def(
730 tcx: TyCtxt<'tcx>,
731 def_id: DefId,
732 args: ty::Binder<'tcx, impl IntoIterator<Item: Into<GenericArg<'tcx>>>>,
733 ) -> Ty<'tcx> {
734 if true {
{
match tcx.def_kind(def_id) {
DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) =>
{}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
735 tcx.def_kind(def_id),
736 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
737 );
738 let args = args.map_bound(|args| tcx.check_and_mk_args(def_id, args));
740 Ty::new(tcx, FnDef(def_id, args))
741 }
742
743 #[inline]
744 pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
745 let (sig_tys, hdr) = fty.split();
746 Ty::new(tcx, FnPtr(sig_tys, hdr))
747 }
748
749 #[inline]
750 pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
751 Ty::new(tcx, UnsafeBinder(b.into()))
752 }
753
754 #[inline]
755 pub fn new_dynamic(
756 tcx: TyCtxt<'tcx>,
757 obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
758 reg: ty::Region<'tcx>,
759 ) -> Ty<'tcx> {
760 if truecfg!(debug_assertions) {
761 let projection_count = obj
762 .projection_bounds()
763 .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
764 .count();
765 let expected_count: usize = obj.principal_def_id().map_or(0, |principal_def_id| {
766 elaborate::supertraits(
768 tcx,
769 ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
770 )
771 .map(|principal| {
772 tcx.associated_items(principal.def_id())
773 .in_definition_order()
774 .filter(|item| item.is_type() || item.is_type_const())
775 .filter(|item| !item.is_impl_trait_in_trait())
776 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
777 .count()
778 })
779 .sum()
780 });
781 {
match (&projection_count, &expected_count) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("expected {0:?} to have {1} projections, but it has {2}",
obj, expected_count, projection_count)));
}
}
}
};assert_eq!(
782 projection_count, expected_count,
783 "expected {obj:?} to have {expected_count} projections, \
784 but it has {projection_count}"
785 );
786 }
787 Ty::new(tcx, Dynamic(obj, reg))
788 }
789
790 #[inline]
791 pub fn new_projection_from_args(
792 tcx: TyCtxt<'tcx>,
793 is_rigid: ty::IsRigid,
794 item_def_id: DefId,
795 args: ty::GenericArgsRef<'tcx>,
796 ) -> Ty<'tcx> {
797 Ty::new_alias(
798 tcx,
799 is_rigid,
800 AliasTy::new_from_args(tcx, ty::Projection { def_id: item_def_id }, args),
801 )
802 }
803
804 #[inline]
805 pub fn new_projection(
806 tcx: TyCtxt<'tcx>,
807 is_rigid: ty::IsRigid,
808 item_def_id: DefId,
809 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
810 ) -> Ty<'tcx> {
811 Ty::new_alias(
812 tcx,
813 is_rigid,
814 AliasTy::new(tcx, ty::Projection { def_id: item_def_id }, args),
815 )
816 }
817
818 #[inline]
819 pub fn new_closure(
820 tcx: TyCtxt<'tcx>,
821 def_id: DefId,
822 closure_args: GenericArgsRef<'tcx>,
823 ) -> Ty<'tcx> {
824 tcx.debug_assert_args_compatible(def_id, closure_args);
825 Ty::new(tcx, Closure(def_id, closure_args))
826 }
827
828 #[inline]
829 pub fn new_coroutine_closure(
830 tcx: TyCtxt<'tcx>,
831 def_id: DefId,
832 closure_args: GenericArgsRef<'tcx>,
833 ) -> Ty<'tcx> {
834 tcx.debug_assert_args_compatible(def_id, closure_args);
835 Ty::new(tcx, CoroutineClosure(def_id, closure_args))
836 }
837
838 #[inline]
839 pub fn new_coroutine(
840 tcx: TyCtxt<'tcx>,
841 def_id: DefId,
842 coroutine_args: GenericArgsRef<'tcx>,
843 ) -> Ty<'tcx> {
844 tcx.debug_assert_args_compatible(def_id, coroutine_args);
845 Ty::new(tcx, Coroutine(def_id, coroutine_args))
846 }
847
848 #[inline]
849 pub fn new_coroutine_witness(
850 tcx: TyCtxt<'tcx>,
851 def_id: DefId,
852 args: GenericArgsRef<'tcx>,
853 ) -> Ty<'tcx> {
854 if truecfg!(debug_assertions) {
855 tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args);
856 }
857 Ty::new(tcx, CoroutineWitness(def_id, args))
858 }
859
860 pub fn new_coroutine_witness_for_coroutine(
861 tcx: TyCtxt<'tcx>,
862 def_id: DefId,
863 coroutine_args: GenericArgsRef<'tcx>,
864 ) -> Ty<'tcx> {
865 tcx.debug_assert_args_compatible(def_id, coroutine_args);
866 let args =
875 ty::GenericArgs::for_item(tcx, tcx.typeck_root_def_id(def_id), |def, _| {
876 match def.kind {
877 ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
878 ty::GenericParamDefKind::Type { .. }
879 | ty::GenericParamDefKind::Const { .. } => coroutine_args[def.index as usize],
880 }
881 });
882 Ty::new_coroutine_witness(tcx, def_id, args)
883 }
884
885 #[inline]
888 pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
889 Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
890 }
891
892 fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
895 let adt_def = tcx.adt_def(wrapper_def_id);
896 let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
897 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
898 GenericParamDefKind::Type { has_default, .. } => {
899 if param.index == 0 {
900 ty_param.into()
901 } else {
902 if !has_default { ::core::panicking::panic("assertion failed: has_default") };assert!(has_default);
903 tcx.type_of(param.def_id).instantiate(tcx, args).skip_norm_wip().into()
904 }
905 }
906 });
907 Ty::new_adt(tcx, adt_def, args)
908 }
909
910 #[inline]
911 pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
912 let def_id = tcx.lang_items().get(item)?;
913 Some(Ty::new_generic_adt(tcx, def_id, ty))
914 }
915
916 #[inline]
917 pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
918 let def_id = tcx.get_diagnostic_item(name)?;
919 Some(Ty::new_generic_adt(tcx, def_id, ty))
920 }
921
922 #[inline]
923 pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
924 let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
925 Ty::new_generic_adt(tcx, def_id, ty)
926 }
927
928 #[inline]
929 pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
930 let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
931 Ty::new_generic_adt(tcx, def_id, ty)
932 }
933
934 #[inline]
935 pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
936 let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
937 Ty::new_generic_adt(tcx, def_id, ty)
938 }
939
940 pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
942 let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
943 let context_adt_ref = tcx.adt_def(context_did);
944 let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
945 let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
946 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
947 }
948}
949
950impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
951 fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
952 tcx.types.bool
953 }
954
955 fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
956 tcx.types.u8
957 }
958
959 fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
960 Ty::new_infer(tcx, infer)
961 }
962
963 fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
964 Ty::new_var(tcx, vid)
965 }
966
967 fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
968 Ty::new_param(tcx, param.index, param.name)
969 }
970
971 fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Self {
972 Ty::new_placeholder(tcx, placeholder)
973 }
974
975 fn new_bound(
976 interner: TyCtxt<'tcx>,
977 debruijn: ty::DebruijnIndex,
978 var: ty::BoundTy<'tcx>,
979 ) -> Self {
980 Ty::new_bound(interner, debruijn, var)
981 }
982
983 fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
984 Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
985 }
986
987 fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
988 Ty::new_canonical_bound(tcx, var)
989 }
990
991 fn new_alias(
992 interner: TyCtxt<'tcx>,
993 is_rigid: ty::IsRigid,
994 alias_ty: ty::AliasTy<'tcx>,
995 ) -> Self {
996 Ty::new_alias(interner, is_rigid, alias_ty)
997 }
998
999 fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
1000 Ty::new_error(interner, guar)
1001 }
1002
1003 fn new_adt(
1004 interner: TyCtxt<'tcx>,
1005 adt_def: ty::AdtDef<'tcx>,
1006 args: ty::GenericArgsRef<'tcx>,
1007 ) -> Self {
1008 Ty::new_adt(interner, adt_def, args)
1009 }
1010
1011 fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
1012 Ty::new_foreign(interner, def_id)
1013 }
1014
1015 fn new_dynamic(
1016 interner: TyCtxt<'tcx>,
1017 preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
1018 region: ty::Region<'tcx>,
1019 ) -> Self {
1020 Ty::new_dynamic(interner, preds, region)
1021 }
1022
1023 fn new_coroutine(
1024 interner: TyCtxt<'tcx>,
1025 def_id: DefId,
1026 args: ty::GenericArgsRef<'tcx>,
1027 ) -> Self {
1028 Ty::new_coroutine(interner, def_id, args)
1029 }
1030
1031 fn new_coroutine_closure(
1032 interner: TyCtxt<'tcx>,
1033 def_id: DefId,
1034 args: ty::GenericArgsRef<'tcx>,
1035 ) -> Self {
1036 Ty::new_coroutine_closure(interner, def_id, args)
1037 }
1038
1039 fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1040 Ty::new_closure(interner, def_id, args)
1041 }
1042
1043 fn new_coroutine_witness(
1044 interner: TyCtxt<'tcx>,
1045 def_id: DefId,
1046 args: ty::GenericArgsRef<'tcx>,
1047 ) -> Self {
1048 Ty::new_coroutine_witness(interner, def_id, args)
1049 }
1050
1051 fn new_coroutine_witness_for_coroutine(
1052 interner: TyCtxt<'tcx>,
1053 def_id: DefId,
1054 coroutine_args: ty::GenericArgsRef<'tcx>,
1055 ) -> Self {
1056 Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1057 }
1058
1059 fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1060 Ty::new_ptr(interner, ty, mutbl)
1061 }
1062
1063 fn new_ref(
1064 interner: TyCtxt<'tcx>,
1065 region: ty::Region<'tcx>,
1066 ty: Self,
1067 mutbl: hir::Mutability,
1068 ) -> Self {
1069 Ty::new_ref(interner, region, ty, mutbl)
1070 }
1071
1072 fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1073 Ty::new_array_with_const_len(interner, ty, len)
1074 }
1075
1076 fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1077 Ty::new_slice(interner, ty)
1078 }
1079
1080 fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1081 Ty::new_tup(interner, tys)
1082 }
1083
1084 fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1085 where
1086 It: Iterator<Item = T>,
1087 T: CollectAndApply<Self, Self>,
1088 {
1089 Ty::new_tup_from_iter(interner, iter)
1090 }
1091
1092 fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1093 self.tuple_fields()
1094 }
1095
1096 fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1097 self.to_opt_closure_kind()
1098 }
1099
1100 fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1101 Ty::from_closure_kind(interner, kind)
1102 }
1103
1104 fn from_coroutine_closure_kind(
1105 interner: TyCtxt<'tcx>,
1106 kind: rustc_type_ir::ClosureKind,
1107 ) -> Self {
1108 Ty::from_coroutine_closure_kind(interner, kind)
1109 }
1110
1111 fn new_fn_def(
1112 interner: TyCtxt<'tcx>,
1113 def_id: DefId,
1114 args: ty::Binder<'tcx, ty::GenericArgsRef<'tcx>>,
1115 ) -> Self {
1116 Ty::new_fn_def(interner, def_id, args)
1117 }
1118
1119 fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1120 Ty::new_fn_ptr(interner, sig)
1121 }
1122
1123 fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1124 Ty::new_pat(interner, ty, pat)
1125 }
1126
1127 fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1128 Ty::new_unsafe_binder(interner, ty)
1129 }
1130
1131 fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1132 interner.types.unit
1133 }
1134
1135 fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1136 interner.types.usize
1137 }
1138
1139 fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1140 self.discriminant_ty(interner)
1141 }
1142
1143 fn has_unsafe_fields(self) -> bool {
1144 Ty::has_unsafe_fields(self)
1145 }
1146}
1147
1148impl<'tcx> Ty<'tcx> {
1150 #[inline(always)]
1155 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1156 self.0.0
1157 }
1158
1159 #[inline]
1160 pub fn is_unit(self) -> bool {
1161 match self.kind() {
1162 Tuple(tys) => tys.is_empty(),
1163 _ => false,
1164 }
1165 }
1166
1167 #[inline]
1169 pub fn is_usize(self) -> bool {
1170 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Uint(UintTy::Usize) => true,
_ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1171 }
1172
1173 #[inline]
1175 pub fn is_usize_like(self) -> bool {
1176 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
_ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1177 }
1178
1179 #[inline]
1180 pub fn is_never(self) -> bool {
1181 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Never => true,
_ => false,
}matches!(self.kind(), Never)
1182 }
1183
1184 #[inline]
1185 pub fn is_primitive(self) -> bool {
1186 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Bool | Char | Int(_) | Uint(_) | Float(_) => true,
_ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1187 }
1188
1189 #[inline]
1190 pub fn is_adt(self) -> bool {
1191 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Adt(..) => true,
_ => false,
}matches!(self.kind(), Adt(..))
1192 }
1193
1194 #[inline]
1195 pub fn is_ref(self) -> bool {
1196 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Ref(..) => true,
_ => false,
}matches!(self.kind(), Ref(..))
1197 }
1198
1199 #[inline]
1200 pub fn is_ty_var(self) -> bool {
1201 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(TyVar(_)) => true,
_ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1202 }
1203
1204 #[inline]
1205 pub fn ty_vid(self) -> Option<ty::TyVid> {
1206 match self.kind() {
1207 &Infer(TyVar(vid)) => Some(vid),
1208 _ => None,
1209 }
1210 }
1211
1212 #[inline]
1213 pub fn float_vid(self) -> Option<ty::FloatVid> {
1214 match self.kind() {
1215 &Infer(FloatVar(vid)) => Some(vid),
1216 _ => None,
1217 }
1218 }
1219
1220 #[inline]
1221 pub fn is_ty_or_numeric_infer(self) -> bool {
1222 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(_) => true,
_ => false,
}matches!(self.kind(), Infer(_))
1223 }
1224
1225 #[inline]
1226 pub fn is_phantom_data(self) -> bool {
1227 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1228 }
1229
1230 #[inline]
1231 pub fn is_unsafe_cell(self) -> bool {
1232 if let Adt(def, _) = self.kind() { def.is_unsafe_cell() } else { false }
1233 }
1234
1235 #[inline]
1236 pub fn is_bool(self) -> bool {
1237 *self.kind() == Bool
1238 }
1239
1240 #[inline]
1242 pub fn is_str(self) -> bool {
1243 *self.kind() == Str
1244 }
1245
1246 #[inline]
1248 pub fn is_imm_ref_str(self) -> bool {
1249 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
ty::Ref(_, inner, hir::Mutability::Not) if inner.is_str() => true,
_ => false,
}matches!(self.kind(), ty::Ref(_, inner, hir::Mutability::Not) if inner.is_str())
1250 }
1251
1252 #[inline]
1253 pub fn is_param(self, index: u32) -> bool {
1254 match self.kind() {
1255 ty::Param(data) => data.index == index,
1256 _ => false,
1257 }
1258 }
1259
1260 #[inline]
1261 pub fn is_slice(self) -> bool {
1262 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Slice(_) => true,
_ => false,
}matches!(self.kind(), Slice(_))
1263 }
1264
1265 #[inline]
1266 pub fn is_array_slice(self) -> bool {
1267 match self.kind() {
1268 Slice(_) => true,
1269 ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
Slice(_) => true,
_ => false,
}matches!(ty.kind(), Slice(_)),
1270 _ => false,
1271 }
1272 }
1273
1274 #[inline]
1275 pub fn is_array(self) -> bool {
1276 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Array(..) => true,
_ => false,
}matches!(self.kind(), Array(..))
1277 }
1278
1279 #[inline]
1280 pub fn is_simd(self) -> bool {
1281 match self.kind() {
1282 Adt(def, _) => def.repr().simd(),
1283 _ => false,
1284 }
1285 }
1286
1287 #[inline]
1288 pub fn is_scalable_vector(self) -> bool {
1289 match self.kind() {
1290 Adt(def, _) => def.repr().scalable(),
1291 _ => false,
1292 }
1293 }
1294
1295 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1296 match self.kind() {
1297 Array(ty, _) | Slice(ty) => *ty,
1298 Str => tcx.types.u8,
1299 _ => crate::util::bug::bug_fmt(format_args!("`sequence_element_type` called on non-sequence value: {0}",
self))bug!("`sequence_element_type` called on non-sequence value: {}", self),
1300 }
1301 }
1302
1303 pub fn scalable_vector_parts(
1304 self,
1305 tcx: TyCtxt<'tcx>,
1306 ) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
1307 let Adt(def, args) = self.kind() else {
1308 return None;
1309 };
1310 let (num_vectors, vec_def) = match def.repr().scalable? {
1311 ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1312 ScalableElt::Container => (
1313 NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1314 def.non_enum_variant().fields[FieldIdx::ZERO]
1315 .ty(tcx, args)
1316 .skip_norm_wip()
1317 .ty_adt_def()?,
1318 ),
1319 };
1320 let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1321 return None;
1322 };
1323 let variant = vec_def.non_enum_variant();
1324 {
match (&variant.fields.len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(variant.fields.len(), 1);
1325 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1326 Some((element_count, field_ty.skip_norm_wip(), num_vectors))
1327 }
1328
1329 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1330 let Adt(def, args) = self.kind() else {
1331 crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1332 };
1333 if !def.repr().simd() {
{
::core::panicking::panic_fmt(format_args!("`simd_size_and_type` called on non-SIMD type"));
}
};assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1334 let variant = def.non_enum_variant();
1335 {
match (&variant.fields.len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(variant.fields.len(), 1);
1336 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1337 let Array(f0_elem_ty, f0_len) = field_ty.skip_norm_wip().kind() else {
1338 crate::util::bug::bug_fmt(format_args!("Simd type has non-array field type {0:?}",
field_ty))bug!("Simd type has non-array field type {field_ty:?}")
1339 };
1340 (
1345 f0_len
1346 .try_to_target_usize(tcx)
1347 .expect("expected SIMD field to have definite array size"),
1348 *f0_elem_ty,
1349 )
1350 }
1351
1352 #[inline]
1353 pub fn is_mutable_ptr(self) -> bool {
1354 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut) => true,
_ => false,
}matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1355 }
1356
1357 #[inline]
1359 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1360 match self.kind() {
1361 Ref(_, _, mutability) => Some(*mutability),
1362 _ => None,
1363 }
1364 }
1365
1366 #[inline]
1367 pub fn is_raw_ptr(self) -> bool {
1368 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
RawPtr(_, _) => true,
_ => false,
}matches!(self.kind(), RawPtr(_, _))
1369 }
1370
1371 #[inline]
1374 pub fn is_any_ptr(self) -> bool {
1375 self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1376 }
1377
1378 #[inline]
1379 pub fn is_box(self) -> bool {
1380 match self.kind() {
1381 Adt(def, _) => def.is_box(),
1382 _ => false,
1383 }
1384 }
1385
1386 #[inline]
1391 pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1392 match self.kind() {
1393 Adt(def, args) if def.is_box() => {
1394 let Some(alloc) = args.get(1) else {
1395 return true;
1397 };
1398 alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1399 tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1400 })
1401 }
1402 _ => false,
1403 }
1404 }
1405
1406 pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1407 match self.kind() {
1408 Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1409 _ => None,
1410 }
1411 }
1412
1413 pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1414 match self.kind() {
1415 Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1416 _ => None,
1417 }
1418 }
1419
1420 pub fn maybe_pinned_ref(
1429 self,
1430 ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1431 match self.kind() {
1432 Adt(def, args)
1433 if def.is_pin()
1434 && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1435 {
1436 Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1437 }
1438 &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1439 _ => None,
1440 }
1441 }
1442
1443 pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1445 self.boxed_ty()
1446 .unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("`expect_boxed_ty` is called on non-box type {0:?}",
self))bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1447 }
1448
1449 #[inline]
1453 pub fn is_scalar(self) -> bool {
1454 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
_ => false,
}matches!(
1455 self.kind(),
1456 Bool | Char
1457 | Int(_)
1458 | Float(_)
1459 | Uint(_)
1460 | FnDef(..)
1461 | FnPtr(..)
1462 | RawPtr(_, _)
1463 | Infer(IntVar(_) | FloatVar(_))
1464 )
1465 }
1466
1467 #[inline]
1469 pub fn is_floating_point(self) -> bool {
1470 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Float(_) | Infer(FloatVar(_)) => true,
_ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1471 }
1472
1473 #[inline]
1474 pub fn is_trait(self) -> bool {
1475 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Dynamic(_, _) => true,
_ => false,
}matches!(self.kind(), Dynamic(_, _))
1476 }
1477
1478 #[inline]
1479 pub fn is_enum(self) -> bool {
1480 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Adt(adt_def, _) if adt_def.is_enum() => true,
_ => false,
}matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1481 }
1482
1483 #[inline]
1484 pub fn is_union(self) -> bool {
1485 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Adt(adt_def, _) if adt_def.is_union() => true,
_ => false,
}matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1486 }
1487
1488 #[inline]
1489 pub fn is_closure(self) -> bool {
1490 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Closure(..) => true,
_ => false,
}matches!(self.kind(), Closure(..))
1491 }
1492
1493 #[inline]
1494 pub fn is_coroutine(self) -> bool {
1495 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Coroutine(..) => true,
_ => false,
}matches!(self.kind(), Coroutine(..))
1496 }
1497
1498 #[inline]
1499 pub fn is_coroutine_closure(self) -> bool {
1500 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
CoroutineClosure(..) => true,
_ => false,
}matches!(self.kind(), CoroutineClosure(..))
1501 }
1502
1503 #[inline]
1504 pub fn is_integral(self) -> bool {
1505 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(IntVar(_)) | Int(_) | Uint(_) => true,
_ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1506 }
1507
1508 #[inline]
1509 pub fn is_fresh_ty(self) -> bool {
1510 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(FreshTy(_)) => true,
_ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1511 }
1512
1513 #[inline]
1514 pub fn is_fresh(self) -> bool {
1515 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
_ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1516 }
1517
1518 #[inline]
1519 pub fn is_char(self) -> bool {
1520 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Char => true,
_ => false,
}matches!(self.kind(), Char)
1521 }
1522
1523 #[inline]
1524 pub fn is_numeric(self) -> bool {
1525 self.is_integral() || self.is_floating_point()
1526 }
1527
1528 #[inline]
1529 pub fn is_signed(self) -> bool {
1530 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Int(_) => true,
_ => false,
}matches!(self.kind(), Int(_))
1531 }
1532
1533 #[inline]
1534 pub fn is_ptr_sized_integral(self) -> bool {
1535 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize) => true,
_ => false,
}matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1536 }
1537
1538 #[inline]
1539 pub fn has_concrete_skeleton(self) -> bool {
1540 !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Param(_) | Infer(_) | Error(_) => true,
_ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1541 }
1542
1543 pub fn contains(self, other: Ty<'tcx>) -> bool {
1547 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1548
1549 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1550 type Result = ControlFlow<()>;
1551
1552 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1553 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1554 }
1555 }
1556
1557 let cf = self.visit_with(&mut ContainsTyVisitor(other));
1558 cf.is_break()
1559 }
1560
1561 pub fn contains_closure(self) -> bool {
1565 struct ContainsClosureVisitor;
1566
1567 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1568 type Result = ControlFlow<()>;
1569
1570 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1571 if let ty::Closure(..) = t.kind() {
1572 ControlFlow::Break(())
1573 } else {
1574 t.super_visit_with(self)
1575 }
1576 }
1577 }
1578
1579 let cf = self.visit_with(&mut ContainsClosureVisitor);
1580 cf.is_break()
1581 }
1582
1583 pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1588 self,
1589 tcx: TyCtxt<'tcx>,
1590 mut f: F,
1591 ) -> Ty<'tcx> {
1592 if !self.is_coroutine() {
::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1593 let mut cor_ty = self;
1594 let mut ty = cor_ty;
1595 loop {
1596 let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1597 cor_ty = ty;
1598 f(ty);
1599 if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1600 return cor_ty;
1601 }
1602 ty = args.first().unwrap().expect_ty();
1603 }
1604 }
1605
1606 pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1611 match *self.kind() {
1612 _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1613 Ref(_, ty, _) => Some(ty),
1614 RawPtr(ty, _) if explicit => Some(ty),
1615 _ => None,
1616 }
1617 }
1618
1619 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1621 match self.kind() {
1622 Array(ty, _) | Slice(ty) => Some(*ty),
1623 _ => None,
1624 }
1625 }
1626
1627 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("fn_sig",
"rustc_middle::ty::sty", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
::tracing_core::__macro_support::Option::Some(1627u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: PolyFnSig<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.kind().fn_sig(tcx) }
}
}#[tracing::instrument(level = "trace", skip(tcx))]
1628 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1629 self.kind().fn_sig(tcx)
1630 }
1631
1632 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("unnormalized_fn_sig",
"rustc_middle::ty::sty", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
::tracing_core::__macro_support::Option::Some(1632u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
ty::Unnormalized<'tcx, PolyFnSig<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{ self.kind().unnormalized_fn_sig(tcx) }
}
}#[tracing::instrument(level = "trace", skip(tcx))]
1633 pub fn unnormalized_fn_sig(self, tcx: TyCtxt<'tcx>) -> ty::Unnormalized<'tcx, PolyFnSig<'tcx>> {
1634 self.kind().unnormalized_fn_sig(tcx)
1635 }
1636
1637 #[inline]
1638 pub fn is_fn(self) -> bool {
1639 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
FnDef(..) | FnPtr(..) => true,
_ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1640 }
1641
1642 #[inline]
1643 pub fn is_fn_ptr(self) -> bool {
1644 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
FnPtr(..) => true,
_ => false,
}matches!(self.kind(), FnPtr(..))
1645 }
1646
1647 #[inline]
1648 pub fn is_opaque(self) -> bool {
1649 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => true,
_ => false,
}matches!(self.kind(), Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }))
1650 }
1651
1652 #[inline]
1653 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1654 match self.kind() {
1655 Adt(adt, _) => Some(*adt),
1656 _ => None,
1657 }
1658 }
1659
1660 #[inline]
1664 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1665 match self.kind() {
1666 Tuple(args) => args,
1667 _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
self))bug!("tuple_fields called on non-tuple: {self:?}"),
1668 }
1669 }
1670
1671 #[inline]
1673 pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1674 match self.kind() {
1675 Tuple(args) => Some(args),
1676 _ => None,
1677 }
1678 }
1679
1680 #[inline]
1684 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1685 match self.kind() {
1686 TyKind::Adt(adt, _) => Some(adt.variant_range()),
1687 TyKind::Coroutine(def_id, args) => {
1688 Some(args.as_coroutine().variant_range(*def_id, tcx))
1689 }
1690 TyKind::UnsafeBinder(bound_ty) => {
1691 tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1692 }
1693 _ => None,
1694 }
1695 }
1696
1697 #[inline]
1702 pub fn discriminant_for_variant(
1703 self,
1704 tcx: TyCtxt<'tcx>,
1705 variant_index: VariantIdx,
1706 ) -> Option<Discr<'tcx>> {
1707 match self.kind() {
1708 TyKind::Adt(adt, _) if adt.is_enum() => {
1709 Some(adt.discriminant_for_variant(tcx, variant_index))
1710 }
1711 TyKind::Coroutine(def_id, args) => {
1712 Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1713 }
1714 TyKind::UnsafeBinder(bound_ty) => tcx
1715 .instantiate_bound_regions_with_erased((*bound_ty).into())
1716 .discriminant_for_variant(tcx, variant_index),
1717 _ => None,
1718 }
1719 }
1720
1721 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1723 match self.kind() {
1724 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1725 ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1726
1727 ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1728 let assoc_items = tcx.associated_item_def_ids(
1729 tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1730 );
1731 Ty::new_projection_from_args(
1732 tcx,
1733 ty::IsRigid::No,
1734 assoc_items[0],
1735 tcx.mk_args(&[self.into()]),
1736 )
1737 }
1738
1739 ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1740 ty::UnsafeBinder(bound_ty) => {
1741 tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1742 }
1743
1744 ty::Bool
1745 | ty::Char
1746 | ty::Int(_)
1747 | ty::Uint(_)
1748 | ty::Float(_)
1749 | ty::Adt(..)
1750 | ty::Foreign(_)
1751 | ty::Str
1752 | ty::Array(..)
1753 | ty::Slice(_)
1754 | ty::RawPtr(_, _)
1755 | ty::Ref(..)
1756 | ty::FnDef(..)
1757 | ty::FnPtr(..)
1758 | ty::Dynamic(..)
1759 | ty::Closure(..)
1760 | ty::CoroutineClosure(..)
1761 | ty::CoroutineWitness(..)
1762 | ty::Never
1763 | ty::Tuple(_)
1764 | ty::Error(_)
1765 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1766
1767 ty::Bound(..)
1768 | ty::Placeholder(_)
1769 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1770 crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1771 }
1772 }
1773 }
1774
1775 pub fn ptr_metadata_ty_or_tail(
1778 self,
1779 tcx: TyCtxt<'tcx>,
1780 normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1781 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1782 let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1783 match tail.kind() {
1784 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1786 | ty::Uint(_)
1787 | ty::Int(_)
1788 | ty::Bool
1789 | ty::Float(_)
1790 | ty::FnDef(..)
1791 | ty::FnPtr(..)
1792 | ty::RawPtr(..)
1793 | ty::Char
1794 | ty::Ref(..)
1795 | ty::Coroutine(..)
1796 | ty::CoroutineWitness(..)
1797 | ty::Array(..)
1798 | ty::Closure(..)
1799 | ty::CoroutineClosure(..)
1800 | ty::Never
1801 | ty::Error(_) => Ok(tcx.types.unit),
1802 ty::Foreign(..) => Ok(tcx.types.unit),
1804 ty::Adt(..) => Ok(tcx.types.unit),
1807 ty::Tuple(..) => Ok(tcx.types.unit),
1810
1811 ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1812
1813 ty::Dynamic(_, _) => {
1814 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1815 Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]).skip_norm_wip())
1816 }
1817
1818 ty::Param(_) | ty::Alias(..) => Err(tail),
1821
1822 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
1823
1824 ty::Infer(ty::TyVar(_))
1825 | ty::Pat(..)
1826 | ty::Bound(..)
1827 | ty::Placeholder(..)
1828 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty_or_tail` applied to unexpected type: {0:?} (tail = {1:?})",
self, tail))bug!(
1829 "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1830 ),
1831 }
1832 }
1833
1834 pub fn ptr_metadata_ty(
1837 self,
1838 tcx: TyCtxt<'tcx>,
1839 normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1840 ) -> Ty<'tcx> {
1841 match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1842 Ok(metadata) => metadata,
1843 Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
self, tail))bug!(
1844 "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1845 ),
1846 }
1847 }
1848
1849 #[track_caller]
1858 pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1859 let Some(pointee_ty) = self.builtin_deref(true) else {
1860 crate::util::bug::bug_fmt(format_args!("Type {0:?} is not a pointer or reference type",
self))bug!("Type {self:?} is not a pointer or reference type")
1861 };
1862 if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1863 tcx.types.unit
1864 } else {
1865 match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x.skip_norm_wip()) {
1866 Ok(metadata_ty) => metadata_ty,
1867 Err(tail_ty) => {
1868 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1869 Ty::new_projection(tcx, ty::IsRigid::No, metadata_def_id, [tail_ty])
1870 }
1871 }
1872 }
1873 }
1874
1875 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1915 match self.kind() {
1916 Int(int_ty) => match int_ty {
1917 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1918 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1919 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1920 _ => crate::util::bug::bug_fmt(format_args!("cannot convert type `{0:?}` to a closure kind",
self))bug!("cannot convert type `{:?}` to a closure kind", self),
1921 },
1922
1923 Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1927
1928 Error(_) => Some(ty::ClosureKind::Fn),
1929
1930 _ => crate::util::bug::bug_fmt(format_args!("cannot convert type `{0:?}` to a closure kind",
self))bug!("cannot convert type `{:?}` to a closure kind", self),
1931 }
1932 }
1933
1934 pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1937 match kind {
1938 ty::ClosureKind::Fn => tcx.types.i8,
1939 ty::ClosureKind::FnMut => tcx.types.i16,
1940 ty::ClosureKind::FnOnce => tcx.types.i32,
1941 }
1942 }
1943
1944 pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1957 match kind {
1958 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1959 ty::ClosureKind::FnOnce => tcx.types.i32,
1960 }
1961 }
1962
1963 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("has_trivial_sizedness",
"rustc_middle::ty::sty", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/sty.rs"),
::tracing_core::__macro_support::Option::Some(1972u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sizedness")
}> =
::tracing::__macro_support::FieldName::new("sizedness");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
match self.kind() {
ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Uint(_) |
ty::Int(_) | ty::Bool | ty::Float(_) | ty::FnDef(..) |
ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::RawPtr(..) |
ty::Char | ty::Ref(..) | ty::Coroutine(..) |
ty::CoroutineWitness(..) | ty::Array(..) | ty::Pat(..) |
ty::Closure(..) | ty::CoroutineClosure(..) | ty::Never |
ty::Error(_) => true,
ty::Str | ty::Slice(_) | ty::Dynamic(_, _) =>
match sizedness {
SizedTraitKind::Sized => false,
SizedTraitKind::MetaSized => true,
},
ty::Foreign(..) =>
match sizedness {
SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
},
ty::Tuple(tys) =>
tys.last().is_none_or(|ty|
ty.has_trivial_sizedness(tcx, sizedness)),
ty::Adt(def, args) =>
def.sizedness_constraint(tcx,
sizedness).is_none_or(|ty|
{
ty.instantiate(tcx,
args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
}),
ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) |
ty::Bound(..) => false,
ty::Infer(ty::TyVar(_)) => false,
ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) |
ty::FreshFloatTy(_)) => {
crate::util::bug::bug_fmt(format_args!("`has_trivial_sizedness` applied to unexpected type: {0:?}",
self))
}
}
}
}
}#[instrument(skip(tcx), level = "debug")]
1973 pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1974 match self.kind() {
1975 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1976 | ty::Uint(_)
1977 | ty::Int(_)
1978 | ty::Bool
1979 | ty::Float(_)
1980 | ty::FnDef(..)
1981 | ty::FnPtr(..)
1982 | ty::UnsafeBinder(_)
1983 | ty::RawPtr(..)
1984 | ty::Char
1985 | ty::Ref(..)
1986 | ty::Coroutine(..)
1987 | ty::CoroutineWitness(..)
1988 | ty::Array(..)
1989 | ty::Pat(..)
1990 | ty::Closure(..)
1991 | ty::CoroutineClosure(..)
1992 | ty::Never
1993 | ty::Error(_) => true,
1994
1995 ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1996 SizedTraitKind::Sized => false,
1997 SizedTraitKind::MetaSized => true,
1998 },
1999
2000 ty::Foreign(..) => match sizedness {
2001 SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
2002 },
2003
2004 ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
2005
2006 ty::Adt(def, args) => def.sizedness_constraint(tcx, sizedness).is_none_or(|ty| {
2007 ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
2008 }),
2009
2010 ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
2011
2012 ty::Infer(ty::TyVar(_)) => false,
2013
2014 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2015 bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
2016 }
2017 }
2018 }
2019
2020 pub fn is_trivially_pure_clone_copy(self) -> bool {
2029 match self.kind() {
2030 ty::Bool | ty::Char | ty::Never => true,
2031
2032 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2034
2035 ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2036 | ty::Int(..)
2037 | ty::Uint(..)
2038 | ty::Float(..) => true,
2039
2040 ty::FnDef(..) => true,
2042
2043 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2044
2045 ty::Tuple(field_tys) => {
2047 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2048 }
2049
2050 ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
2051
2052 ty::FnPtr(..) => false,
2055
2056 ty::Ref(_, _, hir::Mutability::Mut) => false,
2058
2059 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2062
2063 ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2064
2065 ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2067
2068 ty::UnsafeBinder(_) => false,
2069
2070 ty::Alias(..) => false,
2072
2073 ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2074 false
2075 }
2076 }
2077 }
2078
2079 pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2080 match *self.kind() {
2081 ty::Bool
2082 | ty::Char
2083 | ty::Int(_)
2084 | ty::Uint(_)
2085 | ty::Float(_)
2086 | ty::Str
2087 | ty::Never
2088 | ty::Param(_)
2089 | ty::Placeholder(_)
2090 | ty::Bound(..) => true,
2091
2092 ty::Slice(ty) => {
2093 ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2094 }
2095 ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2096
2097 ty::FnPtr(sig_tys, _) => {
2098 sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2099 }
2100 ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2101
2102 ty::Infer(infer) => match infer {
2103 ty::TyVar(_) => false,
2104 ty::IntVar(_) | ty::FloatVar(_) => true,
2105 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2106 },
2107
2108 ty::Adt(_, _)
2109 | ty::Tuple(_)
2110 | ty::Array(..)
2111 | ty::Foreign(_)
2112 | ty::Pat(_, _)
2113 | ty::FnDef(..)
2114 | ty::UnsafeBinder(..)
2115 | ty::Dynamic(..)
2116 | ty::Closure(..)
2117 | ty::CoroutineClosure(..)
2118 | ty::Coroutine(..)
2119 | ty::CoroutineWitness(..)
2120 | ty::Alias(..)
2121 | ty::Error(_) => false,
2122 }
2123 }
2124
2125 pub fn primitive_symbol(self) -> Option<Symbol> {
2127 match self.kind() {
2128 ty::Bool => Some(sym::bool),
2129 ty::Char => Some(sym::char),
2130 ty::Float(f) => match f {
2131 ty::FloatTy::F16 => Some(sym::f16),
2132 ty::FloatTy::F32 => Some(sym::f32),
2133 ty::FloatTy::F64 => Some(sym::f64),
2134 ty::FloatTy::F128 => Some(sym::f128),
2135 },
2136 ty::Int(f) => match f {
2137 ty::IntTy::Isize => Some(sym::isize),
2138 ty::IntTy::I8 => Some(sym::i8),
2139 ty::IntTy::I16 => Some(sym::i16),
2140 ty::IntTy::I32 => Some(sym::i32),
2141 ty::IntTy::I64 => Some(sym::i64),
2142 ty::IntTy::I128 => Some(sym::i128),
2143 },
2144 ty::Uint(f) => match f {
2145 ty::UintTy::Usize => Some(sym::usize),
2146 ty::UintTy::U8 => Some(sym::u8),
2147 ty::UintTy::U16 => Some(sym::u16),
2148 ty::UintTy::U32 => Some(sym::u32),
2149 ty::UintTy::U64 => Some(sym::u64),
2150 ty::UintTy::U128 => Some(sym::u128),
2151 },
2152 ty::Str => Some(sym::str),
2153 _ => None,
2154 }
2155 }
2156
2157 pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2158 match self.kind() {
2159 ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2160 _ => false,
2161 }
2162 }
2163
2164 pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2165 match self.kind() {
2166 ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2167 _ => false,
2168 }
2169 }
2170
2171 pub fn is_known_rigid(self) -> bool {
2177 self.kind().is_known_rigid()
2178 }
2179
2180 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2191 TypeWalker::new(self.into())
2192 }
2193}
2194
2195impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2196 fn inputs(self) -> &'tcx [Ty<'tcx>] {
2197 self.split_last().unwrap().1
2198 }
2199
2200 fn output(self) -> Ty<'tcx> {
2201 *self.split_last().unwrap().0
2202 }
2203}
2204
2205impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2206 fn is_kw_underscore_lifetime(self) -> bool {
2207 self == kw::UnderscoreLifetime
2208 }
2209}
2210
2211#[cfg(target_pointer_width = "64")]
2213mod size_asserts {
2214 use rustc_data_structures::static_assert_size;
2215
2216 use super::*;
2217 const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2219 const _: [(); 40] =
[(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 40);
2220 }