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()
}
})
})
}
#[doc =
" This is the types of the fields of a coroutine which are not stored in a"]
#[doc = " variant."]
#[inline]
fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> { self.upvar_tys() }
}#[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 #[inline]
180 fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
181 self.upvar_tys()
182 }
183}
184
185#[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)]
186pub enum UpvarArgs<'tcx> {
187 Closure(GenericArgsRef<'tcx>),
188 Coroutine(GenericArgsRef<'tcx>),
189 CoroutineClosure(GenericArgsRef<'tcx>),
190}
191
192impl<'tcx> UpvarArgs<'tcx> {
193 #[inline]
197 pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
198 let tupled_tys = match self {
199 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
200 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
201 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
202 };
203
204 match tupled_tys.kind() {
205 TyKind::Error(_) => ty::List::empty(),
206 TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
207 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"),
208 ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
209 }
210 }
211
212 #[inline]
213 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
214 match self {
215 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
216 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
217 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
218 }
219 }
220}
221
222#[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)]
237pub struct InlineConstArgs<'tcx> {
238 pub args: GenericArgsRef<'tcx>,
241}
242
243pub struct InlineConstArgsParts<'tcx, T> {
245 pub parent_args: &'tcx [GenericArg<'tcx>],
246 pub ty: T,
247}
248
249impl<'tcx> InlineConstArgs<'tcx> {
250 pub fn new(
252 tcx: TyCtxt<'tcx>,
253 parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
254 ) -> InlineConstArgs<'tcx> {
255 InlineConstArgs {
256 args: tcx.mk_args_from_iter(
257 parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
258 ),
259 }
260 }
261
262 fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
265 match self.args[..] {
266 [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
267 _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
268 }
269 }
270
271 pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
273 self.split().parent_args
274 }
275
276 pub fn ty(self) -> Ty<'tcx> {
278 self.split().ty.expect_ty()
279 }
280}
281
282pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
283pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
284
285#[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)]
286#[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)]
287pub struct ParamTy {
288 pub index: u32,
289 pub name: Symbol,
290}
291
292impl rustc_type_ir::inherent::ParamLike for ParamTy {
293 fn index(self) -> u32 {
294 self.index
295 }
296}
297
298impl<'tcx> ParamTy {
299 pub fn new(index: u32, name: Symbol) -> ParamTy {
300 ParamTy { index, name }
301 }
302
303 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
304 ParamTy::new(def.index, def.name)
305 }
306
307 #[inline]
308 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
309 Ty::new_param(tcx, self.index, self.name)
310 }
311
312 pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
313 let generics = tcx.generics_of(item_with_generics);
314 let type_param = generics.type_param(self, tcx);
315 tcx.def_span(type_param.def_id)
316 }
317}
318
319#[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)]
320#[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)]
321pub struct ParamConst {
322 pub index: u32,
323 pub name: Symbol,
324}
325
326impl rustc_type_ir::inherent::ParamLike for ParamConst {
327 fn index(self) -> u32 {
328 self.index
329 }
330}
331
332impl ParamConst {
333 pub fn new(index: u32, name: Symbol) -> ParamConst {
334 ParamConst { index, name }
335 }
336
337 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
338 ParamConst::new(def.index, def.name)
339 }
340
341 #[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(341u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&["self", "env"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&env)
as &dyn 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")]
342 pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
343 let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
344 match clause.kind().skip_binder() {
346 ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
347 assert!(!(param_ct, ty).has_escaping_bound_vars());
348
349 match param_ct.kind() {
350 ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
351 _ => None,
352 }
353 }
354 _ => None,
355 }
356 });
357
358 let ty = candidates.next().unwrap_or_else(|| {
365 bug!("cannot find `{self:?}` in param-env: {env:#?}");
366 });
367 assert!(
368 candidates.next().is_none(),
369 "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
370 );
371 ty
372 }
373}
374
375impl<'tcx> Ty<'tcx> {
377 #[allow(rustc::usage_of_ty_tykind)]
380 #[inline]
381 fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
382 tcx.mk_ty_from_kind(st)
383 }
384
385 #[inline]
386 pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
387 Ty::new(tcx, TyKind::Infer(infer))
388 }
389
390 #[inline]
391 pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
392 tcx.types
394 .ty_vars
395 .get(v.as_usize())
396 .copied()
397 .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
398 }
399
400 #[inline]
401 pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
402 Ty::new_infer(tcx, IntVar(v))
403 }
404
405 #[inline]
406 pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
407 Ty::new_infer(tcx, FloatVar(v))
408 }
409
410 #[inline]
411 pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
412 tcx.types
414 .fresh_tys
415 .get(n as usize)
416 .copied()
417 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
418 }
419
420 #[inline]
421 pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
422 tcx.types
424 .fresh_int_tys
425 .get(n as usize)
426 .copied()
427 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
428 }
429
430 #[inline]
431 pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
432 tcx.types
434 .fresh_float_tys
435 .get(n as usize)
436 .copied()
437 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
438 }
439
440 #[inline]
441 pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
442 Ty::new(tcx, Param(ParamTy { index, name }))
443 }
444
445 #[inline]
446 pub fn new_bound(
447 tcx: TyCtxt<'tcx>,
448 index: ty::DebruijnIndex,
449 bound_ty: ty::BoundTy<'tcx>,
450 ) -> Ty<'tcx> {
451 if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
453 && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
454 && let Some(ty) = inner.get(var.as_usize()).copied()
455 {
456 ty
457 } else {
458 Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
459 }
460 }
461
462 #[inline]
463 pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
464 if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
466 ty
467 } else {
468 Ty::new(
469 tcx,
470 Bound(
471 ty::BoundVarIndexKind::Canonical,
472 ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
473 ),
474 )
475 }
476 }
477
478 #[inline]
479 pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
480 Ty::new(tcx, Placeholder(placeholder))
481 }
482
483 #[inline]
484 pub fn new_alias(
485 tcx: TyCtxt<'tcx>,
486 is_rigid: ty::IsRigid,
487 alias_ty: ty::AliasTy<'tcx>,
488 ) -> Ty<'tcx> {
489 if truecfg!(debug_assertions) {
490 match alias_ty.kind {
491 ty::AliasTyKind::Projection { def_id } => {
492 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)
493 }
494 ty::AliasTyKind::Inherent { def_id } => {
495 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)
496 }
497 ty::AliasTyKind::Opaque { def_id } => {
498 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)
499 }
500 ty::AliasTyKind::Free { def_id } => {
501 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)
502 }
503 }
504 }
505 Ty::new(tcx, Alias(is_rigid, alias_ty))
506 }
507
508 #[inline]
509 pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
510 Ty::new(tcx, Pat(base, pat))
511 }
512
513 #[inline]
514 pub fn new_field_representing_type(
515 tcx: TyCtxt<'tcx>,
516 base: Ty<'tcx>,
517 variant: VariantIdx,
518 field: FieldIdx,
519 ) -> Ty<'tcx> {
520 let Some(did) = tcx.lang_items().field_representing_type() else {
521 crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
522 };
523 let def = tcx.adt_def(did);
524 let args = tcx.mk_args(&[
525 base.into(),
526 Const::new_value(
527 tcx,
528 ValTree::from_scalar_int(tcx, variant.as_u32().into()),
529 tcx.types.u32,
530 )
531 .into(),
532 Const::new_value(
533 tcx,
534 ValTree::from_scalar_int(tcx, field.as_u32().into()),
535 tcx.types.u32,
536 )
537 .into(),
538 ]);
539 Ty::new_adt(tcx, def, args)
540 }
541
542 #[inline]
543 #[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(543u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&["is_rigid", "def_id",
"args"], ::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_rigid)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn 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))]
544 pub fn new_opaque(
545 tcx: TyCtxt<'tcx>,
546 is_rigid: ty::IsRigid,
547 def_id: DefId,
548 args: GenericArgsRef<'tcx>,
549 ) -> Ty<'tcx> {
550 Ty::new_alias(tcx, is_rigid, AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
551 }
552
553 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
555 Ty::new(tcx, Error(guar))
556 }
557
558 #[track_caller]
560 pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
561 Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
562 }
563
564 #[track_caller]
567 pub fn new_error_with_message<S: Into<MultiSpan>>(
568 tcx: TyCtxt<'tcx>,
569 span: S,
570 msg: impl Into<Cow<'static, str>>,
571 ) -> Ty<'tcx> {
572 let reported = tcx.dcx().span_delayed_bug(span, msg);
573 Ty::new(tcx, Error(reported))
574 }
575
576 #[inline]
577 pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
578 use ty::IntTy::*;
579 match i {
580 Isize => tcx.types.isize,
581 I8 => tcx.types.i8,
582 I16 => tcx.types.i16,
583 I32 => tcx.types.i32,
584 I64 => tcx.types.i64,
585 I128 => tcx.types.i128,
586 }
587 }
588
589 #[inline]
590 pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
591 use ty::UintTy::*;
592 match ui {
593 Usize => tcx.types.usize,
594 U8 => tcx.types.u8,
595 U16 => tcx.types.u16,
596 U32 => tcx.types.u32,
597 U64 => tcx.types.u64,
598 U128 => tcx.types.u128,
599 }
600 }
601
602 #[inline]
603 pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
604 use ty::FloatTy::*;
605 match f {
606 F16 => tcx.types.f16,
607 F32 => tcx.types.f32,
608 F64 => tcx.types.f64,
609 F128 => tcx.types.f128,
610 }
611 }
612
613 #[inline]
614 pub fn new_ref(
615 tcx: TyCtxt<'tcx>,
616 r: Region<'tcx>,
617 ty: Ty<'tcx>,
618 mutbl: ty::Mutability,
619 ) -> Ty<'tcx> {
620 Ty::new(tcx, Ref(r, ty, mutbl))
621 }
622
623 #[inline]
624 pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
625 Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
626 }
627
628 #[inline]
629 pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
630 Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
631 }
632
633 pub fn new_pinned_ref(
634 tcx: TyCtxt<'tcx>,
635 r: Region<'tcx>,
636 ty: Ty<'tcx>,
637 mutbl: ty::Mutability,
638 ) -> Ty<'tcx> {
639 let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
640 Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
641 }
642
643 #[inline]
644 pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
645 Ty::new(tcx, ty::RawPtr(ty, mutbl))
646 }
647
648 #[inline]
649 pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
650 Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
651 }
652
653 #[inline]
654 pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
655 Ty::new_ptr(tcx, ty, hir::Mutability::Not)
656 }
657
658 #[inline]
659 pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
660 tcx.debug_assert_args_compatible(def.did(), args);
661 if truecfg!(debug_assertions) {
662 match tcx.def_kind(def.did()) {
663 DefKind::Struct | DefKind::Union | DefKind::Enum => {}
664 DefKind::Mod
665 | DefKind::Variant
666 | DefKind::Trait
667 | DefKind::TyAlias
668 | DefKind::ForeignTy
669 | DefKind::TraitAlias
670 | DefKind::AssocTy
671 | DefKind::TyParam
672 | DefKind::Fn
673 | DefKind::Const { .. }
674 | DefKind::ConstParam
675 | DefKind::Static { .. }
676 | DefKind::Ctor(..)
677 | DefKind::AssocFn
678 | DefKind::AssocConst { .. }
679 | DefKind::Macro(..)
680 | DefKind::ExternCrate
681 | DefKind::Use
682 | DefKind::ForeignMod
683 | DefKind::AnonConst
684 | DefKind::OpaqueTy
685 | DefKind::Field
686 | DefKind::LifetimeParam
687 | DefKind::GlobalAsm
688 | DefKind::Impl { .. }
689 | DefKind::Closure
690 | DefKind::SyntheticCoroutineBody => {
691 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()))
692 }
693 }
694 }
695 Ty::new(tcx, Adt(def, args))
696 }
697
698 #[inline]
699 pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
700 Ty::new(tcx, Foreign(def_id))
701 }
702
703 #[inline]
704 pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
705 Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
706 }
707
708 #[inline]
709 pub fn new_array_with_const_len(
710 tcx: TyCtxt<'tcx>,
711 ty: Ty<'tcx>,
712 ct: ty::Const<'tcx>,
713 ) -> Ty<'tcx> {
714 Ty::new(tcx, Array(ty, ct))
715 }
716
717 #[inline]
718 pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
719 Ty::new(tcx, Slice(ty))
720 }
721
722 #[inline]
723 pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
724 if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
725 }
726
727 pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
728 where
729 I: Iterator<Item = T>,
730 T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
731 {
732 T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
733 }
734
735 #[inline]
736 pub fn new_fn_def(
737 tcx: TyCtxt<'tcx>,
738 def_id: DefId,
739 args: ty::Binder<'tcx, impl IntoIterator<Item: Into<GenericArg<'tcx>>>>,
740 ) -> Ty<'tcx> {
741 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!(
742 tcx.def_kind(def_id),
743 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
744 );
745 let args = args.map_bound(|args| tcx.check_and_mk_args(def_id, args));
747 Ty::new(tcx, FnDef(def_id, args))
748 }
749
750 #[inline]
751 pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
752 let (sig_tys, hdr) = fty.split();
753 Ty::new(tcx, FnPtr(sig_tys, hdr))
754 }
755
756 #[inline]
757 pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
758 Ty::new(tcx, UnsafeBinder(b.into()))
759 }
760
761 #[inline]
762 pub fn new_dynamic(
763 tcx: TyCtxt<'tcx>,
764 obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
765 reg: ty::Region<'tcx>,
766 ) -> Ty<'tcx> {
767 if truecfg!(debug_assertions) {
768 let projection_count = obj
769 .projection_bounds()
770 .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
771 .count();
772 let expected_count: usize = obj.principal_def_id().map_or(0, |principal_def_id| {
773 elaborate::supertraits(
775 tcx,
776 ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
777 )
778 .map(|principal| {
779 tcx.associated_items(principal.def_id())
780 .in_definition_order()
781 .filter(|item| item.is_type() || item.is_type_const())
782 .filter(|item| !item.is_impl_trait_in_trait())
783 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
784 .count()
785 })
786 .sum()
787 });
788 {
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!(
789 projection_count, expected_count,
790 "expected {obj:?} to have {expected_count} projections, \
791 but it has {projection_count}"
792 );
793 }
794 Ty::new(tcx, Dynamic(obj, reg))
795 }
796
797 #[inline]
798 pub fn new_projection_from_args(
799 tcx: TyCtxt<'tcx>,
800 is_rigid: ty::IsRigid,
801 item_def_id: DefId,
802 args: ty::GenericArgsRef<'tcx>,
803 ) -> Ty<'tcx> {
804 Ty::new_alias(
805 tcx,
806 is_rigid,
807 AliasTy::new_from_args(tcx, ty::Projection { def_id: item_def_id }, args),
808 )
809 }
810
811 #[inline]
812 pub fn new_projection(
813 tcx: TyCtxt<'tcx>,
814 is_rigid: ty::IsRigid,
815 item_def_id: DefId,
816 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
817 ) -> Ty<'tcx> {
818 Ty::new_alias(
819 tcx,
820 is_rigid,
821 AliasTy::new(tcx, ty::Projection { def_id: item_def_id }, args),
822 )
823 }
824
825 #[inline]
826 pub fn new_closure(
827 tcx: TyCtxt<'tcx>,
828 def_id: DefId,
829 closure_args: GenericArgsRef<'tcx>,
830 ) -> Ty<'tcx> {
831 tcx.debug_assert_args_compatible(def_id, closure_args);
832 Ty::new(tcx, Closure(def_id, closure_args))
833 }
834
835 #[inline]
836 pub fn new_coroutine_closure(
837 tcx: TyCtxt<'tcx>,
838 def_id: DefId,
839 closure_args: GenericArgsRef<'tcx>,
840 ) -> Ty<'tcx> {
841 tcx.debug_assert_args_compatible(def_id, closure_args);
842 Ty::new(tcx, CoroutineClosure(def_id, closure_args))
843 }
844
845 #[inline]
846 pub fn new_coroutine(
847 tcx: TyCtxt<'tcx>,
848 def_id: DefId,
849 coroutine_args: GenericArgsRef<'tcx>,
850 ) -> Ty<'tcx> {
851 tcx.debug_assert_args_compatible(def_id, coroutine_args);
852 Ty::new(tcx, Coroutine(def_id, coroutine_args))
853 }
854
855 #[inline]
856 pub fn new_coroutine_witness(
857 tcx: TyCtxt<'tcx>,
858 def_id: DefId,
859 args: GenericArgsRef<'tcx>,
860 ) -> Ty<'tcx> {
861 if truecfg!(debug_assertions) {
862 tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args);
863 }
864 Ty::new(tcx, CoroutineWitness(def_id, args))
865 }
866
867 pub fn new_coroutine_witness_for_coroutine(
868 tcx: TyCtxt<'tcx>,
869 def_id: DefId,
870 coroutine_args: GenericArgsRef<'tcx>,
871 ) -> Ty<'tcx> {
872 tcx.debug_assert_args_compatible(def_id, coroutine_args);
873 let args =
882 ty::GenericArgs::for_item(tcx, tcx.typeck_root_def_id(def_id), |def, _| {
883 match def.kind {
884 ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
885 ty::GenericParamDefKind::Type { .. }
886 | ty::GenericParamDefKind::Const { .. } => coroutine_args[def.index as usize],
887 }
888 });
889 Ty::new_coroutine_witness(tcx, def_id, args)
890 }
891
892 #[inline]
895 pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
896 Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
897 }
898
899 fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
902 let adt_def = tcx.adt_def(wrapper_def_id);
903 let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
904 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
905 GenericParamDefKind::Type { has_default, .. } => {
906 if param.index == 0 {
907 ty_param.into()
908 } else {
909 if !has_default { ::core::panicking::panic("assertion failed: has_default") };assert!(has_default);
910 tcx.type_of(param.def_id).instantiate(tcx, args).skip_norm_wip().into()
911 }
912 }
913 });
914 Ty::new_adt(tcx, adt_def, args)
915 }
916
917 #[inline]
918 pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
919 let def_id = tcx.lang_items().get(item)?;
920 Some(Ty::new_generic_adt(tcx, def_id, ty))
921 }
922
923 #[inline]
924 pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
925 let def_id = tcx.get_diagnostic_item(name)?;
926 Some(Ty::new_generic_adt(tcx, def_id, ty))
927 }
928
929 #[inline]
930 pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
931 let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
932 Ty::new_generic_adt(tcx, def_id, ty)
933 }
934
935 #[inline]
936 pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
937 let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
938 Ty::new_generic_adt(tcx, def_id, ty)
939 }
940
941 #[inline]
942 pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
943 let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
944 Ty::new_generic_adt(tcx, def_id, ty)
945 }
946
947 pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
949 let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
950 let context_adt_ref = tcx.adt_def(context_did);
951 let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
952 let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
953 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
954 }
955}
956
957impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
958 fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
959 tcx.types.bool
960 }
961
962 fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
963 tcx.types.u8
964 }
965
966 fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
967 Ty::new_infer(tcx, infer)
968 }
969
970 fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
971 Ty::new_var(tcx, vid)
972 }
973
974 fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
975 Ty::new_param(tcx, param.index, param.name)
976 }
977
978 fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Self {
979 Ty::new_placeholder(tcx, placeholder)
980 }
981
982 fn new_bound(
983 interner: TyCtxt<'tcx>,
984 debruijn: ty::DebruijnIndex,
985 var: ty::BoundTy<'tcx>,
986 ) -> Self {
987 Ty::new_bound(interner, debruijn, var)
988 }
989
990 fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
991 Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
992 }
993
994 fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
995 Ty::new_canonical_bound(tcx, var)
996 }
997
998 fn new_alias(
999 interner: TyCtxt<'tcx>,
1000 is_rigid: ty::IsRigid,
1001 alias_ty: ty::AliasTy<'tcx>,
1002 ) -> Self {
1003 Ty::new_alias(interner, is_rigid, alias_ty)
1004 }
1005
1006 fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
1007 Ty::new_error(interner, guar)
1008 }
1009
1010 fn new_adt(
1011 interner: TyCtxt<'tcx>,
1012 adt_def: ty::AdtDef<'tcx>,
1013 args: ty::GenericArgsRef<'tcx>,
1014 ) -> Self {
1015 Ty::new_adt(interner, adt_def, args)
1016 }
1017
1018 fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
1019 Ty::new_foreign(interner, def_id)
1020 }
1021
1022 fn new_dynamic(
1023 interner: TyCtxt<'tcx>,
1024 preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
1025 region: ty::Region<'tcx>,
1026 ) -> Self {
1027 Ty::new_dynamic(interner, preds, region)
1028 }
1029
1030 fn new_coroutine(
1031 interner: TyCtxt<'tcx>,
1032 def_id: DefId,
1033 args: ty::GenericArgsRef<'tcx>,
1034 ) -> Self {
1035 Ty::new_coroutine(interner, def_id, args)
1036 }
1037
1038 fn new_coroutine_closure(
1039 interner: TyCtxt<'tcx>,
1040 def_id: DefId,
1041 args: ty::GenericArgsRef<'tcx>,
1042 ) -> Self {
1043 Ty::new_coroutine_closure(interner, def_id, args)
1044 }
1045
1046 fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1047 Ty::new_closure(interner, def_id, args)
1048 }
1049
1050 fn new_coroutine_witness(
1051 interner: TyCtxt<'tcx>,
1052 def_id: DefId,
1053 args: ty::GenericArgsRef<'tcx>,
1054 ) -> Self {
1055 Ty::new_coroutine_witness(interner, def_id, args)
1056 }
1057
1058 fn new_coroutine_witness_for_coroutine(
1059 interner: TyCtxt<'tcx>,
1060 def_id: DefId,
1061 coroutine_args: ty::GenericArgsRef<'tcx>,
1062 ) -> Self {
1063 Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1064 }
1065
1066 fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1067 Ty::new_ptr(interner, ty, mutbl)
1068 }
1069
1070 fn new_ref(
1071 interner: TyCtxt<'tcx>,
1072 region: ty::Region<'tcx>,
1073 ty: Self,
1074 mutbl: hir::Mutability,
1075 ) -> Self {
1076 Ty::new_ref(interner, region, ty, mutbl)
1077 }
1078
1079 fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1080 Ty::new_array_with_const_len(interner, ty, len)
1081 }
1082
1083 fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1084 Ty::new_slice(interner, ty)
1085 }
1086
1087 fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1088 Ty::new_tup(interner, tys)
1089 }
1090
1091 fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1092 where
1093 It: Iterator<Item = T>,
1094 T: CollectAndApply<Self, Self>,
1095 {
1096 Ty::new_tup_from_iter(interner, iter)
1097 }
1098
1099 fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1100 self.tuple_fields()
1101 }
1102
1103 fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1104 self.to_opt_closure_kind()
1105 }
1106
1107 fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1108 Ty::from_closure_kind(interner, kind)
1109 }
1110
1111 fn from_coroutine_closure_kind(
1112 interner: TyCtxt<'tcx>,
1113 kind: rustc_type_ir::ClosureKind,
1114 ) -> Self {
1115 Ty::from_coroutine_closure_kind(interner, kind)
1116 }
1117
1118 fn new_fn_def(
1119 interner: TyCtxt<'tcx>,
1120 def_id: DefId,
1121 args: ty::Binder<'tcx, ty::GenericArgsRef<'tcx>>,
1122 ) -> Self {
1123 Ty::new_fn_def(interner, def_id, args)
1124 }
1125
1126 fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1127 Ty::new_fn_ptr(interner, sig)
1128 }
1129
1130 fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1131 Ty::new_pat(interner, ty, pat)
1132 }
1133
1134 fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1135 Ty::new_unsafe_binder(interner, ty)
1136 }
1137
1138 fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1139 interner.types.unit
1140 }
1141
1142 fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1143 interner.types.usize
1144 }
1145
1146 fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1147 self.discriminant_ty(interner)
1148 }
1149
1150 fn has_unsafe_fields(self) -> bool {
1151 Ty::has_unsafe_fields(self)
1152 }
1153}
1154
1155impl<'tcx> Ty<'tcx> {
1157 #[inline(always)]
1162 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1163 self.0.0
1164 }
1165
1166 #[inline]
1167 pub fn is_unit(self) -> bool {
1168 match self.kind() {
1169 Tuple(tys) => tys.is_empty(),
1170 _ => false,
1171 }
1172 }
1173
1174 #[inline]
1176 pub fn is_usize(self) -> bool {
1177 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Uint(UintTy::Usize) => true,
_ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1178 }
1179
1180 #[inline]
1182 pub fn is_usize_like(self) -> bool {
1183 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
_ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1184 }
1185
1186 #[inline]
1187 pub fn is_never(self) -> bool {
1188 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Never => true,
_ => false,
}matches!(self.kind(), Never)
1189 }
1190
1191 #[inline]
1192 pub fn is_primitive(self) -> bool {
1193 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Bool | Char | Int(_) | Uint(_) | Float(_) => true,
_ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1194 }
1195
1196 #[inline]
1197 pub fn is_adt(self) -> bool {
1198 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Adt(..) => true,
_ => false,
}matches!(self.kind(), Adt(..))
1199 }
1200
1201 #[inline]
1202 pub fn is_ref(self) -> bool {
1203 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Ref(..) => true,
_ => false,
}matches!(self.kind(), Ref(..))
1204 }
1205
1206 #[inline]
1207 pub fn is_ty_var(self) -> bool {
1208 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(TyVar(_)) => true,
_ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1209 }
1210
1211 #[inline]
1212 pub fn ty_vid(self) -> Option<ty::TyVid> {
1213 match self.kind() {
1214 &Infer(TyVar(vid)) => Some(vid),
1215 _ => None,
1216 }
1217 }
1218
1219 #[inline]
1220 pub fn float_vid(self) -> Option<ty::FloatVid> {
1221 match self.kind() {
1222 &Infer(FloatVar(vid)) => Some(vid),
1223 _ => None,
1224 }
1225 }
1226
1227 #[inline]
1228 pub fn is_ty_or_numeric_infer(self) -> bool {
1229 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(_) => true,
_ => false,
}matches!(self.kind(), Infer(_))
1230 }
1231
1232 #[inline]
1233 pub fn is_phantom_data(self) -> bool {
1234 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1235 }
1236
1237 #[inline]
1238 pub fn is_bool(self) -> bool {
1239 *self.kind() == Bool
1240 }
1241
1242 #[inline]
1244 pub fn is_str(self) -> bool {
1245 *self.kind() == Str
1246 }
1247
1248 #[inline]
1250 pub fn is_imm_ref_str(self) -> bool {
1251 #[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())
1252 }
1253
1254 #[inline]
1255 pub fn is_param(self, index: u32) -> bool {
1256 match self.kind() {
1257 ty::Param(data) => data.index == index,
1258 _ => false,
1259 }
1260 }
1261
1262 #[inline]
1263 pub fn is_slice(self) -> bool {
1264 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Slice(_) => true,
_ => false,
}matches!(self.kind(), Slice(_))
1265 }
1266
1267 #[inline]
1268 pub fn is_array_slice(self) -> bool {
1269 match self.kind() {
1270 Slice(_) => true,
1271 ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
Slice(_) => true,
_ => false,
}matches!(ty.kind(), Slice(_)),
1272 _ => false,
1273 }
1274 }
1275
1276 #[inline]
1277 pub fn is_array(self) -> bool {
1278 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Array(..) => true,
_ => false,
}matches!(self.kind(), Array(..))
1279 }
1280
1281 #[inline]
1282 pub fn is_simd(self) -> bool {
1283 match self.kind() {
1284 Adt(def, _) => def.repr().simd(),
1285 _ => false,
1286 }
1287 }
1288
1289 #[inline]
1290 pub fn is_scalable_vector(self) -> bool {
1291 match self.kind() {
1292 Adt(def, _) => def.repr().scalable(),
1293 _ => false,
1294 }
1295 }
1296
1297 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1298 match self.kind() {
1299 Array(ty, _) | Slice(ty) => *ty,
1300 Str => tcx.types.u8,
1301 _ => 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),
1302 }
1303 }
1304
1305 pub fn scalable_vector_parts(
1306 self,
1307 tcx: TyCtxt<'tcx>,
1308 ) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
1309 let Adt(def, args) = self.kind() else {
1310 return None;
1311 };
1312 let (num_vectors, vec_def) = match def.repr().scalable? {
1313 ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1314 ScalableElt::Container => (
1315 NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1316 def.non_enum_variant().fields[FieldIdx::ZERO]
1317 .ty(tcx, args)
1318 .skip_norm_wip()
1319 .ty_adt_def()?,
1320 ),
1321 };
1322 let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1323 return None;
1324 };
1325 let variant = vec_def.non_enum_variant();
1326 {
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);
1327 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1328 Some((element_count, field_ty.skip_norm_wip(), num_vectors))
1329 }
1330
1331 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1332 let Adt(def, args) = self.kind() else {
1333 crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1334 };
1335 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");
1336 let variant = def.non_enum_variant();
1337 {
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);
1338 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1339 let Array(f0_elem_ty, f0_len) = field_ty.skip_norm_wip().kind() else {
1340 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:?}")
1341 };
1342 (
1347 f0_len
1348 .try_to_target_usize(tcx)
1349 .expect("expected SIMD field to have definite array size"),
1350 *f0_elem_ty,
1351 )
1352 }
1353
1354 #[inline]
1355 pub fn is_mutable_ptr(self) -> bool {
1356 #[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))
1357 }
1358
1359 #[inline]
1361 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1362 match self.kind() {
1363 Ref(_, _, mutability) => Some(*mutability),
1364 _ => None,
1365 }
1366 }
1367
1368 #[inline]
1369 pub fn is_raw_ptr(self) -> bool {
1370 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
RawPtr(_, _) => true,
_ => false,
}matches!(self.kind(), RawPtr(_, _))
1371 }
1372
1373 #[inline]
1376 pub fn is_any_ptr(self) -> bool {
1377 self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1378 }
1379
1380 #[inline]
1381 pub fn is_box(self) -> bool {
1382 match self.kind() {
1383 Adt(def, _) => def.is_box(),
1384 _ => false,
1385 }
1386 }
1387
1388 #[inline]
1393 pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1394 match self.kind() {
1395 Adt(def, args) if def.is_box() => {
1396 let Some(alloc) = args.get(1) else {
1397 return true;
1399 };
1400 alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1401 tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1402 })
1403 }
1404 _ => false,
1405 }
1406 }
1407
1408 pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1409 match self.kind() {
1410 Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1411 _ => None,
1412 }
1413 }
1414
1415 pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1416 match self.kind() {
1417 Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1418 _ => None,
1419 }
1420 }
1421
1422 pub fn maybe_pinned_ref(
1431 self,
1432 ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1433 match self.kind() {
1434 Adt(def, args)
1435 if def.is_pin()
1436 && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1437 {
1438 Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1439 }
1440 &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1441 _ => None,
1442 }
1443 }
1444
1445 pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1447 self.boxed_ty()
1448 .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))
1449 }
1450
1451 #[inline]
1455 pub fn is_scalar(self) -> bool {
1456 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
_ => false,
}matches!(
1457 self.kind(),
1458 Bool | Char
1459 | Int(_)
1460 | Float(_)
1461 | Uint(_)
1462 | FnDef(..)
1463 | FnPtr(..)
1464 | RawPtr(_, _)
1465 | Infer(IntVar(_) | FloatVar(_))
1466 )
1467 }
1468
1469 #[inline]
1471 pub fn is_floating_point(self) -> bool {
1472 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Float(_) | Infer(FloatVar(_)) => true,
_ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1473 }
1474
1475 #[inline]
1476 pub fn is_trait(self) -> bool {
1477 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Dynamic(_, _) => true,
_ => false,
}matches!(self.kind(), Dynamic(_, _))
1478 }
1479
1480 #[inline]
1481 pub fn is_enum(self) -> bool {
1482 #[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())
1483 }
1484
1485 #[inline]
1486 pub fn is_union(self) -> bool {
1487 #[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())
1488 }
1489
1490 #[inline]
1491 pub fn is_closure(self) -> bool {
1492 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Closure(..) => true,
_ => false,
}matches!(self.kind(), Closure(..))
1493 }
1494
1495 #[inline]
1496 pub fn is_coroutine(self) -> bool {
1497 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Coroutine(..) => true,
_ => false,
}matches!(self.kind(), Coroutine(..))
1498 }
1499
1500 #[inline]
1501 pub fn is_coroutine_closure(self) -> bool {
1502 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
CoroutineClosure(..) => true,
_ => false,
}matches!(self.kind(), CoroutineClosure(..))
1503 }
1504
1505 #[inline]
1506 pub fn is_integral(self) -> bool {
1507 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(IntVar(_)) | Int(_) | Uint(_) => true,
_ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1508 }
1509
1510 #[inline]
1511 pub fn is_fresh_ty(self) -> bool {
1512 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(FreshTy(_)) => true,
_ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1513 }
1514
1515 #[inline]
1516 pub fn is_fresh(self) -> bool {
1517 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
_ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1518 }
1519
1520 #[inline]
1521 pub fn is_char(self) -> bool {
1522 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Char => true,
_ => false,
}matches!(self.kind(), Char)
1523 }
1524
1525 #[inline]
1526 pub fn is_numeric(self) -> bool {
1527 self.is_integral() || self.is_floating_point()
1528 }
1529
1530 #[inline]
1531 pub fn is_signed(self) -> bool {
1532 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Int(_) => true,
_ => false,
}matches!(self.kind(), Int(_))
1533 }
1534
1535 #[inline]
1536 pub fn is_ptr_sized_integral(self) -> bool {
1537 #[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))
1538 }
1539
1540 #[inline]
1541 pub fn has_concrete_skeleton(self) -> bool {
1542 !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Param(_) | Infer(_) | Error(_) => true,
_ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1543 }
1544
1545 pub fn contains(self, other: Ty<'tcx>) -> bool {
1549 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1550
1551 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1552 type Result = ControlFlow<()>;
1553
1554 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1555 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1556 }
1557 }
1558
1559 let cf = self.visit_with(&mut ContainsTyVisitor(other));
1560 cf.is_break()
1561 }
1562
1563 pub fn contains_closure(self) -> bool {
1567 struct ContainsClosureVisitor;
1568
1569 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1570 type Result = ControlFlow<()>;
1571
1572 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1573 if let ty::Closure(..) = t.kind() {
1574 ControlFlow::Break(())
1575 } else {
1576 t.super_visit_with(self)
1577 }
1578 }
1579 }
1580
1581 let cf = self.visit_with(&mut ContainsClosureVisitor);
1582 cf.is_break()
1583 }
1584
1585 pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1590 self,
1591 tcx: TyCtxt<'tcx>,
1592 mut f: F,
1593 ) -> Ty<'tcx> {
1594 if !self.is_coroutine() {
::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1595 let mut cor_ty = self;
1596 let mut ty = cor_ty;
1597 loop {
1598 let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1599 cor_ty = ty;
1600 f(ty);
1601 if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1602 return cor_ty;
1603 }
1604 ty = args.first().unwrap().expect_ty();
1605 }
1606 }
1607
1608 pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1613 match *self.kind() {
1614 _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1615 Ref(_, ty, _) => Some(ty),
1616 RawPtr(ty, _) if explicit => Some(ty),
1617 _ => None,
1618 }
1619 }
1620
1621 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1623 match self.kind() {
1624 Array(ty, _) | Slice(ty) => Some(*ty),
1625 _ => None,
1626 }
1627 }
1628
1629 #[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(1629u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&["self"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn 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))]
1630 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1631 self.kind().fn_sig(tcx)
1632 }
1633
1634 #[inline]
1635 pub fn is_fn(self) -> bool {
1636 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
FnDef(..) | FnPtr(..) => true,
_ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1637 }
1638
1639 #[inline]
1640 pub fn is_fn_ptr(self) -> bool {
1641 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
FnPtr(..) => true,
_ => false,
}matches!(self.kind(), FnPtr(..))
1642 }
1643
1644 #[inline]
1645 pub fn is_opaque(self) -> bool {
1646 #[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 { .. }, .. }))
1647 }
1648
1649 #[inline]
1650 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1651 match self.kind() {
1652 Adt(adt, _) => Some(*adt),
1653 _ => None,
1654 }
1655 }
1656
1657 #[inline]
1661 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1662 match self.kind() {
1663 Tuple(args) => args,
1664 _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
self))bug!("tuple_fields called on non-tuple: {self:?}"),
1665 }
1666 }
1667
1668 #[inline]
1670 pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1671 match self.kind() {
1672 Tuple(args) => Some(args),
1673 _ => None,
1674 }
1675 }
1676
1677 #[inline]
1681 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1682 match self.kind() {
1683 TyKind::Adt(adt, _) => Some(adt.variant_range()),
1684 TyKind::Coroutine(def_id, args) => {
1685 Some(args.as_coroutine().variant_range(*def_id, tcx))
1686 }
1687 TyKind::UnsafeBinder(bound_ty) => {
1688 tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1689 }
1690 _ => None,
1691 }
1692 }
1693
1694 #[inline]
1699 pub fn discriminant_for_variant(
1700 self,
1701 tcx: TyCtxt<'tcx>,
1702 variant_index: VariantIdx,
1703 ) -> Option<Discr<'tcx>> {
1704 match self.kind() {
1705 TyKind::Adt(adt, _) if adt.is_enum() => {
1706 Some(adt.discriminant_for_variant(tcx, variant_index))
1707 }
1708 TyKind::Coroutine(def_id, args) => {
1709 Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1710 }
1711 TyKind::UnsafeBinder(bound_ty) => tcx
1712 .instantiate_bound_regions_with_erased((*bound_ty).into())
1713 .discriminant_for_variant(tcx, variant_index),
1714 _ => None,
1715 }
1716 }
1717
1718 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1720 match self.kind() {
1721 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1722 ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1723
1724 ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1725 let assoc_items = tcx.associated_item_def_ids(
1726 tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1727 );
1728 Ty::new_projection_from_args(
1729 tcx,
1730 ty::IsRigid::No,
1731 assoc_items[0],
1732 tcx.mk_args(&[self.into()]),
1733 )
1734 }
1735
1736 ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1737 ty::UnsafeBinder(bound_ty) => {
1738 tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1739 }
1740
1741 ty::Bool
1742 | ty::Char
1743 | ty::Int(_)
1744 | ty::Uint(_)
1745 | ty::Float(_)
1746 | ty::Adt(..)
1747 | ty::Foreign(_)
1748 | ty::Str
1749 | ty::Array(..)
1750 | ty::Slice(_)
1751 | ty::RawPtr(_, _)
1752 | ty::Ref(..)
1753 | ty::FnDef(..)
1754 | ty::FnPtr(..)
1755 | ty::Dynamic(..)
1756 | ty::Closure(..)
1757 | ty::CoroutineClosure(..)
1758 | ty::CoroutineWitness(..)
1759 | ty::Never
1760 | ty::Tuple(_)
1761 | ty::Error(_)
1762 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1763
1764 ty::Bound(..)
1765 | ty::Placeholder(_)
1766 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1767 crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1768 }
1769 }
1770 }
1771
1772 pub fn ptr_metadata_ty_or_tail(
1775 self,
1776 tcx: TyCtxt<'tcx>,
1777 normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1778 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1779 let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1780 match tail.kind() {
1781 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1783 | ty::Uint(_)
1784 | ty::Int(_)
1785 | ty::Bool
1786 | ty::Float(_)
1787 | ty::FnDef(..)
1788 | ty::FnPtr(..)
1789 | ty::RawPtr(..)
1790 | ty::Char
1791 | ty::Ref(..)
1792 | ty::Coroutine(..)
1793 | ty::CoroutineWitness(..)
1794 | ty::Array(..)
1795 | ty::Closure(..)
1796 | ty::CoroutineClosure(..)
1797 | ty::Never
1798 | ty::Error(_) => Ok(tcx.types.unit),
1799 ty::Foreign(..) => Ok(tcx.types.unit),
1801 ty::Adt(..) => Ok(tcx.types.unit),
1804 ty::Tuple(..) => Ok(tcx.types.unit),
1807
1808 ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1809
1810 ty::Dynamic(_, _) => {
1811 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1812 Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]).skip_norm_wip())
1813 }
1814
1815 ty::Param(_) | ty::Alias(..) => Err(tail),
1818
1819 ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
1820
1821 ty::Infer(ty::TyVar(_))
1822 | ty::Pat(..)
1823 | ty::Bound(..)
1824 | ty::Placeholder(..)
1825 | 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!(
1826 "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1827 ),
1828 }
1829 }
1830
1831 pub fn ptr_metadata_ty(
1834 self,
1835 tcx: TyCtxt<'tcx>,
1836 normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1837 ) -> Ty<'tcx> {
1838 match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1839 Ok(metadata) => metadata,
1840 Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
self, tail))bug!(
1841 "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1842 ),
1843 }
1844 }
1845
1846 #[track_caller]
1855 pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1856 let Some(pointee_ty) = self.builtin_deref(true) else {
1857 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")
1858 };
1859 if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1860 tcx.types.unit
1861 } else {
1862 match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x.skip_norm_wip()) {
1863 Ok(metadata_ty) => metadata_ty,
1864 Err(tail_ty) => {
1865 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1866 Ty::new_projection(tcx, ty::IsRigid::No, metadata_def_id, [tail_ty])
1867 }
1868 }
1869 }
1870 }
1871
1872 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1912 match self.kind() {
1913 Int(int_ty) => match int_ty {
1914 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1915 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1916 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1917 _ => 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),
1918 },
1919
1920 Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1924
1925 Error(_) => Some(ty::ClosureKind::Fn),
1926
1927 _ => 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),
1928 }
1929 }
1930
1931 pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1934 match kind {
1935 ty::ClosureKind::Fn => tcx.types.i8,
1936 ty::ClosureKind::FnMut => tcx.types.i16,
1937 ty::ClosureKind::FnOnce => tcx.types.i32,
1938 }
1939 }
1940
1941 pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1954 match kind {
1955 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1956 ty::ClosureKind::FnOnce => tcx.types.i32,
1957 }
1958 }
1959
1960 #[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(1969u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&["self", "sizedness"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
as &dyn 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")]
1970 pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1971 match self.kind() {
1972 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1973 | ty::Uint(_)
1974 | ty::Int(_)
1975 | ty::Bool
1976 | ty::Float(_)
1977 | ty::FnDef(..)
1978 | ty::FnPtr(..)
1979 | ty::UnsafeBinder(_)
1980 | ty::RawPtr(..)
1981 | ty::Char
1982 | ty::Ref(..)
1983 | ty::Coroutine(..)
1984 | ty::CoroutineWitness(..)
1985 | ty::Array(..)
1986 | ty::Pat(..)
1987 | ty::Closure(..)
1988 | ty::CoroutineClosure(..)
1989 | ty::Never
1990 | ty::Error(_) => true,
1991
1992 ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1993 SizedTraitKind::Sized => false,
1994 SizedTraitKind::MetaSized => true,
1995 },
1996
1997 ty::Foreign(..) => match sizedness {
1998 SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1999 },
2000
2001 ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
2002
2003 ty::Adt(def, args) => def.sizedness_constraint(tcx, sizedness).is_none_or(|ty| {
2004 ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
2005 }),
2006
2007 ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
2008
2009 ty::Infer(ty::TyVar(_)) => false,
2010
2011 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2012 bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
2013 }
2014 }
2015 }
2016
2017 pub fn is_trivially_pure_clone_copy(self) -> bool {
2026 match self.kind() {
2027 ty::Bool | ty::Char | ty::Never => true,
2028
2029 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2031
2032 ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2033 | ty::Int(..)
2034 | ty::Uint(..)
2035 | ty::Float(..) => true,
2036
2037 ty::FnDef(..) => true,
2039
2040 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2041
2042 ty::Tuple(field_tys) => {
2044 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2045 }
2046
2047 ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
2048
2049 ty::FnPtr(..) => false,
2052
2053 ty::Ref(_, _, hir::Mutability::Mut) => false,
2055
2056 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2059
2060 ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2061
2062 ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2064
2065 ty::UnsafeBinder(_) => false,
2066
2067 ty::Alias(..) => false,
2069
2070 ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2071 false
2072 }
2073 }
2074 }
2075
2076 pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2077 match *self.kind() {
2078 ty::Bool
2079 | ty::Char
2080 | ty::Int(_)
2081 | ty::Uint(_)
2082 | ty::Float(_)
2083 | ty::Str
2084 | ty::Never
2085 | ty::Param(_)
2086 | ty::Placeholder(_)
2087 | ty::Bound(..) => true,
2088
2089 ty::Slice(ty) => {
2090 ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2091 }
2092 ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2093
2094 ty::FnPtr(sig_tys, _) => {
2095 sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2096 }
2097 ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2098
2099 ty::Infer(infer) => match infer {
2100 ty::TyVar(_) => false,
2101 ty::IntVar(_) | ty::FloatVar(_) => true,
2102 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2103 },
2104
2105 ty::Adt(_, _)
2106 | ty::Tuple(_)
2107 | ty::Array(..)
2108 | ty::Foreign(_)
2109 | ty::Pat(_, _)
2110 | ty::FnDef(..)
2111 | ty::UnsafeBinder(..)
2112 | ty::Dynamic(..)
2113 | ty::Closure(..)
2114 | ty::CoroutineClosure(..)
2115 | ty::Coroutine(..)
2116 | ty::CoroutineWitness(..)
2117 | ty::Alias(..)
2118 | ty::Error(_) => false,
2119 }
2120 }
2121
2122 pub fn primitive_symbol(self) -> Option<Symbol> {
2124 match self.kind() {
2125 ty::Bool => Some(sym::bool),
2126 ty::Char => Some(sym::char),
2127 ty::Float(f) => match f {
2128 ty::FloatTy::F16 => Some(sym::f16),
2129 ty::FloatTy::F32 => Some(sym::f32),
2130 ty::FloatTy::F64 => Some(sym::f64),
2131 ty::FloatTy::F128 => Some(sym::f128),
2132 },
2133 ty::Int(f) => match f {
2134 ty::IntTy::Isize => Some(sym::isize),
2135 ty::IntTy::I8 => Some(sym::i8),
2136 ty::IntTy::I16 => Some(sym::i16),
2137 ty::IntTy::I32 => Some(sym::i32),
2138 ty::IntTy::I64 => Some(sym::i64),
2139 ty::IntTy::I128 => Some(sym::i128),
2140 },
2141 ty::Uint(f) => match f {
2142 ty::UintTy::Usize => Some(sym::usize),
2143 ty::UintTy::U8 => Some(sym::u8),
2144 ty::UintTy::U16 => Some(sym::u16),
2145 ty::UintTy::U32 => Some(sym::u32),
2146 ty::UintTy::U64 => Some(sym::u64),
2147 ty::UintTy::U128 => Some(sym::u128),
2148 },
2149 ty::Str => Some(sym::str),
2150 _ => None,
2151 }
2152 }
2153
2154 pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2155 match self.kind() {
2156 ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2157 _ => false,
2158 }
2159 }
2160
2161 pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2162 match self.kind() {
2163 ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2164 _ => false,
2165 }
2166 }
2167
2168 pub fn is_known_rigid(self) -> bool {
2174 self.kind().is_known_rigid()
2175 }
2176
2177 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2188 TypeWalker::new(self.into())
2189 }
2190}
2191
2192impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2193 fn inputs(self) -> &'tcx [Ty<'tcx>] {
2194 self.split_last().unwrap().1
2195 }
2196
2197 fn output(self) -> Ty<'tcx> {
2198 *self.split_last().unwrap().0
2199 }
2200}
2201
2202impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2203 fn is_kw_underscore_lifetime(self) -> bool {
2204 self == kw::UnderscoreLifetime
2205 }
2206}
2207
2208#[cfg(target_pointer_width = "64")]
2210mod size_asserts {
2211 use rustc_data_structures::static_assert_size;
2212
2213 use super::*;
2214 const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2216 const _: [(); 40] =
[(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 40);
2217 }