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 FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
42pub type FnSigKind<'tcx> = ir::FnSigKind<TyCtxt<'tcx>>;
43pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
44pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
45pub type Unnormalized<'tcx, T> = ir::Unnormalized<TyCtxt<'tcx>, T>;
46pub type TypingMode<'tcx, S = MayBeErased> = ir::TypingMode<TyCtxt<'tcx>, S>;
47pub type TypingModeEqWrapper<'tcx> = ir::TypingModeEqWrapper<TyCtxt<'tcx>>;
48pub type Placeholder<'tcx, T> = ir::Placeholder<TyCtxt<'tcx>, T>;
49pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion<TyCtxt<'tcx>>;
50pub type PlaceholderType<'tcx> = ir::PlaceholderType<TyCtxt<'tcx>>;
51pub type PlaceholderConst<'tcx> = ir::PlaceholderConst<TyCtxt<'tcx>>;
52pub type BoundTy<'tcx> = ir::BoundTy<TyCtxt<'tcx>>;
53pub type BoundConst<'tcx> = ir::BoundConst<TyCtxt<'tcx>>;
54pub type BoundRegion<'tcx> = ir::BoundRegion<TyCtxt<'tcx>>;
55pub type BoundVariableKind<'tcx> = ir::BoundVariableKind<TyCtxt<'tcx>>;
56pub type BoundRegionKind<'tcx> = ir::BoundRegionKind<TyCtxt<'tcx>>;
57pub type BoundTyKind<'tcx> = ir::BoundTyKind<TyCtxt<'tcx>>;
58
59pub trait Article {
60 fn article(&self) -> &'static str;
61}
62
63impl<'tcx> Article for TyKind<'tcx> {
64 fn article(&self) -> &'static str {
66 match self {
67 Int(_) | Float(_) | Array(_, _) => "an",
68 Adt(def, _) if def.is_enum() => "an",
69 Error(_) => "a",
72 _ => "a",
73 }
74 }
75}
76
77impl<'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(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>)]
78impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
79 const UNRESUMED: usize = 0;
81 const RETURNED: usize = 1;
83 const POISONED: usize = 2;
85 const RESERVED_VARIANTS: usize = 3;
89
90 const UNRESUMED_NAME: &'static str = "Unresumed";
91 const RETURNED_NAME: &'static str = "Returned";
92 const POISONED_NAME: &'static str = "Panicked";
93
94 #[inline]
96 fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
97 FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
99 }
100
101 #[inline]
104 fn discriminant_for_variant(
105 &self,
106 def_id: DefId,
107 tcx: TyCtxt<'tcx>,
108 variant_index: VariantIdx,
109 ) -> Discr<'tcx> {
110 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
113 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
114 }
115
116 #[inline]
119 fn discriminants(
120 self,
121 def_id: DefId,
122 tcx: TyCtxt<'tcx>,
123 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
124 self.variant_range(def_id, tcx).map(move |index| {
125 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
126 })
127 }
128
129 fn variant_name(v: VariantIdx) -> Cow<'static, str> {
132 match v.as_usize() {
133 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
134 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
135 Self::POISONED => Cow::from(Self::POISONED_NAME),
136 _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
137 }
138 }
139
140 #[inline]
142 fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
143 tcx.types.u32
144 }
145
146 #[inline]
153 fn state_tys(
154 self,
155 def_id: DefId,
156 tcx: TyCtxt<'tcx>,
157 ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
158 let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
159 layout.variant_fields.iter().map(move |variant| {
160 variant.iter().map(move |field| {
161 if tcx.is_async_drop_in_place_coroutine(def_id) {
162 layout.field_tys[*field].ty
163 } else {
164 ty::EarlyBinder::bind(layout.field_tys[*field].ty)
165 .instantiate(tcx, self.args)
166 .skip_norm_wip()
167 }
168 })
169 })
170 }
171
172 #[inline]
175 fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
176 self.upvar_tys()
177 }
178}
179
180#[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)]
181pub enum UpvarArgs<'tcx> {
182 Closure(GenericArgsRef<'tcx>),
183 Coroutine(GenericArgsRef<'tcx>),
184 CoroutineClosure(GenericArgsRef<'tcx>),
185}
186
187impl<'tcx> UpvarArgs<'tcx> {
188 #[inline]
192 pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
193 let tupled_tys = match self {
194 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
195 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
196 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
197 };
198
199 match tupled_tys.kind() {
200 TyKind::Error(_) => ty::List::empty(),
201 TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
202 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"),
203 ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
204 }
205 }
206
207 #[inline]
208 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
209 match self {
210 UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
211 UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
212 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
213 }
214 }
215}
216
217#[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)]
232pub struct InlineConstArgs<'tcx> {
233 pub args: GenericArgsRef<'tcx>,
236}
237
238pub struct InlineConstArgsParts<'tcx, T> {
240 pub parent_args: &'tcx [GenericArg<'tcx>],
241 pub ty: T,
242}
243
244impl<'tcx> InlineConstArgs<'tcx> {
245 pub fn new(
247 tcx: TyCtxt<'tcx>,
248 parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
249 ) -> InlineConstArgs<'tcx> {
250 InlineConstArgs {
251 args: tcx.mk_args_from_iter(
252 parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
253 ),
254 }
255 }
256
257 fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
260 match self.args[..] {
261 [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
262 _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
263 }
264 }
265
266 pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
268 self.split().parent_args
269 }
270
271 pub fn ty(self) -> Ty<'tcx> {
273 self.split().ty.expect_ty()
274 }
275}
276
277pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
278pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
279
280#[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> {
match ::core::cmp::PartialOrd::partial_cmp(&self.index, &other.index)
{
::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name),
cmp => cmp,
}
}
}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)]
281#[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)]
282pub struct ParamTy {
283 pub index: u32,
284 pub name: Symbol,
285}
286
287impl rustc_type_ir::inherent::ParamLike for ParamTy {
288 fn index(self) -> u32 {
289 self.index
290 }
291}
292
293impl<'tcx> ParamTy {
294 pub fn new(index: u32, name: Symbol) -> ParamTy {
295 ParamTy { index, name }
296 }
297
298 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
299 ParamTy::new(def.index, def.name)
300 }
301
302 #[inline]
303 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
304 Ty::new_param(tcx, self.index, self.name)
305 }
306
307 pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
308 let generics = tcx.generics_of(item_with_generics);
309 let type_param = generics.type_param(self, tcx);
310 tcx.def_span(type_param.def_id)
311 }
312}
313
314#[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> {
match ::core::cmp::PartialOrd::partial_cmp(&self.index, &other.index)
{
::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name),
cmp => cmp,
}
}
}PartialOrd)]
315#[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)]
316pub struct ParamConst {
317 pub index: u32,
318 pub name: Symbol,
319}
320
321impl rustc_type_ir::inherent::ParamLike for ParamConst {
322 fn index(self) -> u32 {
323 self.index
324 }
325}
326
327impl ParamConst {
328 pub fn new(index: u32, name: Symbol) -> ParamConst {
329 ParamConst { index, name }
330 }
331
332 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
333 ParamConst::new(def.index, def.name)
334 }
335
336 #[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(336u32),
::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")]
337 pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
338 let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
339 match clause.kind().skip_binder() {
341 ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
342 assert!(!(param_ct, ty).has_escaping_bound_vars());
343
344 match param_ct.kind() {
345 ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
346 _ => None,
347 }
348 }
349 _ => None,
350 }
351 });
352
353 let ty = candidates.next().unwrap_or_else(|| {
360 bug!("cannot find `{self:?}` in param-env: {env:#?}");
361 });
362 assert!(
363 candidates.next().is_none(),
364 "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
365 );
366 ty
367 }
368}
369
370impl<'tcx> Ty<'tcx> {
372 #[allow(rustc::usage_of_ty_tykind)]
375 #[inline]
376 fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
377 tcx.mk_ty_from_kind(st)
378 }
379
380 #[inline]
381 pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
382 Ty::new(tcx, TyKind::Infer(infer))
383 }
384
385 #[inline]
386 pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
387 tcx.types
389 .ty_vars
390 .get(v.as_usize())
391 .copied()
392 .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
393 }
394
395 #[inline]
396 pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
397 Ty::new_infer(tcx, IntVar(v))
398 }
399
400 #[inline]
401 pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
402 Ty::new_infer(tcx, FloatVar(v))
403 }
404
405 #[inline]
406 pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
407 tcx.types
409 .fresh_tys
410 .get(n as usize)
411 .copied()
412 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
413 }
414
415 #[inline]
416 pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
417 tcx.types
419 .fresh_int_tys
420 .get(n as usize)
421 .copied()
422 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
423 }
424
425 #[inline]
426 pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
427 tcx.types
429 .fresh_float_tys
430 .get(n as usize)
431 .copied()
432 .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
433 }
434
435 #[inline]
436 pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
437 Ty::new(tcx, Param(ParamTy { index, name }))
438 }
439
440 #[inline]
441 pub fn new_bound(
442 tcx: TyCtxt<'tcx>,
443 index: ty::DebruijnIndex,
444 bound_ty: ty::BoundTy<'tcx>,
445 ) -> Ty<'tcx> {
446 if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
448 && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
449 && let Some(ty) = inner.get(var.as_usize()).copied()
450 {
451 ty
452 } else {
453 Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
454 }
455 }
456
457 #[inline]
458 pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
459 if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
461 ty
462 } else {
463 Ty::new(
464 tcx,
465 Bound(
466 ty::BoundVarIndexKind::Canonical,
467 ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
468 ),
469 )
470 }
471 }
472
473 #[inline]
474 pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
475 Ty::new(tcx, Placeholder(placeholder))
476 }
477
478 #[inline]
479 pub fn new_alias(tcx: TyCtxt<'tcx>, alias_ty: ty::AliasTy<'tcx>) -> Ty<'tcx> {
480 if true {
{
match (alias_ty.kind, tcx.def_kind(alias_ty.kind.def_id())) {
(ty::Opaque { .. }, DefKind::OpaqueTy) |
(ty::Projection { .. } | ty::Inherent { .. },
DefKind::AssocTy) | (ty::Free { .. }, DefKind::TyAlias) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"(ty::Opaque { .. }, DefKind::OpaqueTy) |\n(ty::Projection { .. } | ty::Inherent { .. }, DefKind::AssocTy) |\n(ty::Free { .. }, DefKind::TyAlias)",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
481 (alias_ty.kind, tcx.def_kind(alias_ty.kind.def_id())),
482 (ty::Opaque { .. }, DefKind::OpaqueTy)
483 | (ty::Projection { .. } | ty::Inherent { .. }, DefKind::AssocTy)
484 | (ty::Free { .. }, DefKind::TyAlias)
485 );
486 Ty::new(tcx, Alias(alias_ty))
487 }
488
489 #[inline]
490 pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
491 Ty::new(tcx, Pat(base, pat))
492 }
493
494 #[inline]
495 pub fn new_field_representing_type(
496 tcx: TyCtxt<'tcx>,
497 base: Ty<'tcx>,
498 variant: VariantIdx,
499 field: FieldIdx,
500 ) -> Ty<'tcx> {
501 let Some(did) = tcx.lang_items().field_representing_type() else {
502 crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
503 };
504 let def = tcx.adt_def(did);
505 let args = tcx.mk_args(&[
506 base.into(),
507 Const::new_value(
508 tcx,
509 ValTree::from_scalar_int(tcx, variant.as_u32().into()),
510 tcx.types.u32,
511 )
512 .into(),
513 Const::new_value(
514 tcx,
515 ValTree::from_scalar_int(tcx, field.as_u32().into()),
516 tcx.types.u32,
517 )
518 .into(),
519 ]);
520 Ty::new_adt(tcx, def, args)
521 }
522
523 #[inline]
524 #[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(524u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
::tracing_core::field::FieldSet::new(&["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(&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,
AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
}
}
}#[instrument(level = "debug", skip(tcx))]
525 pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
526 Ty::new_alias(tcx, AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
527 }
528
529 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
531 Ty::new(tcx, Error(guar))
532 }
533
534 #[track_caller]
536 pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
537 Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
538 }
539
540 #[track_caller]
543 pub fn new_error_with_message<S: Into<MultiSpan>>(
544 tcx: TyCtxt<'tcx>,
545 span: S,
546 msg: impl Into<Cow<'static, str>>,
547 ) -> Ty<'tcx> {
548 let reported = tcx.dcx().span_delayed_bug(span, msg);
549 Ty::new(tcx, Error(reported))
550 }
551
552 #[inline]
553 pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
554 use ty::IntTy::*;
555 match i {
556 Isize => tcx.types.isize,
557 I8 => tcx.types.i8,
558 I16 => tcx.types.i16,
559 I32 => tcx.types.i32,
560 I64 => tcx.types.i64,
561 I128 => tcx.types.i128,
562 }
563 }
564
565 #[inline]
566 pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
567 use ty::UintTy::*;
568 match ui {
569 Usize => tcx.types.usize,
570 U8 => tcx.types.u8,
571 U16 => tcx.types.u16,
572 U32 => tcx.types.u32,
573 U64 => tcx.types.u64,
574 U128 => tcx.types.u128,
575 }
576 }
577
578 #[inline]
579 pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
580 use ty::FloatTy::*;
581 match f {
582 F16 => tcx.types.f16,
583 F32 => tcx.types.f32,
584 F64 => tcx.types.f64,
585 F128 => tcx.types.f128,
586 }
587 }
588
589 #[inline]
590 pub fn new_ref(
591 tcx: TyCtxt<'tcx>,
592 r: Region<'tcx>,
593 ty: Ty<'tcx>,
594 mutbl: ty::Mutability,
595 ) -> Ty<'tcx> {
596 Ty::new(tcx, Ref(r, ty, mutbl))
597 }
598
599 #[inline]
600 pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
601 Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
602 }
603
604 #[inline]
605 pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
606 Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
607 }
608
609 pub fn new_pinned_ref(
610 tcx: TyCtxt<'tcx>,
611 r: Region<'tcx>,
612 ty: Ty<'tcx>,
613 mutbl: ty::Mutability,
614 ) -> Ty<'tcx> {
615 let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
616 Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
617 }
618
619 #[inline]
620 pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
621 Ty::new(tcx, ty::RawPtr(ty, mutbl))
622 }
623
624 #[inline]
625 pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
626 Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
627 }
628
629 #[inline]
630 pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
631 Ty::new_ptr(tcx, ty, hir::Mutability::Not)
632 }
633
634 #[inline]
635 pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
636 tcx.debug_assert_args_compatible(def.did(), args);
637 if truecfg!(debug_assertions) {
638 match tcx.def_kind(def.did()) {
639 DefKind::Struct | DefKind::Union | DefKind::Enum => {}
640 DefKind::Mod
641 | DefKind::Variant
642 | DefKind::Trait
643 | DefKind::TyAlias
644 | DefKind::ForeignTy
645 | DefKind::TraitAlias
646 | DefKind::AssocTy
647 | DefKind::TyParam
648 | DefKind::Fn
649 | DefKind::Const { .. }
650 | DefKind::ConstParam
651 | DefKind::Static { .. }
652 | DefKind::Ctor(..)
653 | DefKind::AssocFn
654 | DefKind::AssocConst { .. }
655 | DefKind::Macro(..)
656 | DefKind::ExternCrate
657 | DefKind::Use
658 | DefKind::ForeignMod
659 | DefKind::AnonConst
660 | DefKind::InlineConst
661 | DefKind::OpaqueTy
662 | DefKind::Field
663 | DefKind::LifetimeParam
664 | DefKind::GlobalAsm
665 | DefKind::Impl { .. }
666 | DefKind::Closure
667 | DefKind::SyntheticCoroutineBody => {
668 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()))
669 }
670 }
671 }
672 Ty::new(tcx, Adt(def, args))
673 }
674
675 #[inline]
676 pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
677 Ty::new(tcx, Foreign(def_id))
678 }
679
680 #[inline]
681 pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
682 Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
683 }
684
685 #[inline]
686 pub fn new_array_with_const_len(
687 tcx: TyCtxt<'tcx>,
688 ty: Ty<'tcx>,
689 ct: ty::Const<'tcx>,
690 ) -> Ty<'tcx> {
691 Ty::new(tcx, Array(ty, ct))
692 }
693
694 #[inline]
695 pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
696 Ty::new(tcx, Slice(ty))
697 }
698
699 #[inline]
700 pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
701 if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
702 }
703
704 pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
705 where
706 I: Iterator<Item = T>,
707 T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
708 {
709 T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
710 }
711
712 #[inline]
713 pub fn new_fn_def(
714 tcx: TyCtxt<'tcx>,
715 def_id: DefId,
716 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
717 ) -> Ty<'tcx> {
718 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!(
719 tcx.def_kind(def_id),
720 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
721 );
722 let args = tcx.check_and_mk_args(def_id, args);
723 Ty::new(tcx, FnDef(def_id, args))
724 }
725
726 #[inline]
727 pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
728 let (sig_tys, hdr) = fty.split();
729 Ty::new(tcx, FnPtr(sig_tys, hdr))
730 }
731
732 #[inline]
733 pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
734 Ty::new(tcx, UnsafeBinder(b.into()))
735 }
736
737 #[inline]
738 pub fn new_dynamic(
739 tcx: TyCtxt<'tcx>,
740 obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
741 reg: ty::Region<'tcx>,
742 ) -> Ty<'tcx> {
743 if truecfg!(debug_assertions) {
744 let projection_count = obj
745 .projection_bounds()
746 .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
747 .count();
748 let expected_count: usize = obj
749 .principal_def_id()
750 .into_iter()
751 .flat_map(|principal_def_id| {
752 elaborate::supertraits(
754 tcx,
755 ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
756 )
757 .map(|principal| {
758 tcx.associated_items(principal.def_id())
759 .in_definition_order()
760 .filter(|item| item.is_type() || item.is_type_const())
761 .filter(|item| !item.is_impl_trait_in_trait())
762 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
763 .count()
764 })
765 })
766 .sum();
767 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!(
768 projection_count, expected_count,
769 "expected {obj:?} to have {expected_count} projections, \
770 but it has {projection_count}"
771 );
772 }
773 Ty::new(tcx, Dynamic(obj, reg))
774 }
775
776 #[inline]
777 pub fn new_projection_from_args(
778 tcx: TyCtxt<'tcx>,
779 item_def_id: DefId,
780 args: ty::GenericArgsRef<'tcx>,
781 ) -> Ty<'tcx> {
782 Ty::new_alias(
783 tcx,
784 AliasTy::new_from_args(tcx, ty::Projection { def_id: item_def_id }, args),
785 )
786 }
787
788 #[inline]
789 pub fn new_projection(
790 tcx: TyCtxt<'tcx>,
791 item_def_id: DefId,
792 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
793 ) -> Ty<'tcx> {
794 Ty::new_alias(tcx, AliasTy::new(tcx, ty::Projection { def_id: item_def_id }, args))
795 }
796
797 #[inline]
798 pub fn new_closure(
799 tcx: TyCtxt<'tcx>,
800 def_id: DefId,
801 closure_args: GenericArgsRef<'tcx>,
802 ) -> Ty<'tcx> {
803 tcx.debug_assert_args_compatible(def_id, closure_args);
804 Ty::new(tcx, Closure(def_id, closure_args))
805 }
806
807 #[inline]
808 pub fn new_coroutine_closure(
809 tcx: TyCtxt<'tcx>,
810 def_id: DefId,
811 closure_args: GenericArgsRef<'tcx>,
812 ) -> Ty<'tcx> {
813 tcx.debug_assert_args_compatible(def_id, closure_args);
814 Ty::new(tcx, CoroutineClosure(def_id, closure_args))
815 }
816
817 #[inline]
818 pub fn new_coroutine(
819 tcx: TyCtxt<'tcx>,
820 def_id: DefId,
821 coroutine_args: GenericArgsRef<'tcx>,
822 ) -> Ty<'tcx> {
823 tcx.debug_assert_args_compatible(def_id, coroutine_args);
824 Ty::new(tcx, Coroutine(def_id, coroutine_args))
825 }
826
827 #[inline]
828 pub fn new_coroutine_witness(
829 tcx: TyCtxt<'tcx>,
830 def_id: DefId,
831 args: GenericArgsRef<'tcx>,
832 ) -> Ty<'tcx> {
833 if truecfg!(debug_assertions) {
834 tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args);
835 }
836 Ty::new(tcx, CoroutineWitness(def_id, args))
837 }
838
839 pub fn new_coroutine_witness_for_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 let args =
854 ty::GenericArgs::for_item(tcx, tcx.typeck_root_def_id(def_id), |def, _| {
855 match def.kind {
856 ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
857 ty::GenericParamDefKind::Type { .. }
858 | ty::GenericParamDefKind::Const { .. } => coroutine_args[def.index as usize],
859 }
860 });
861 Ty::new_coroutine_witness(tcx, def_id, args)
862 }
863
864 #[inline]
867 pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
868 Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
869 }
870
871 fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
874 let adt_def = tcx.adt_def(wrapper_def_id);
875 let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
876 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
877 GenericParamDefKind::Type { has_default, .. } => {
878 if param.index == 0 {
879 ty_param.into()
880 } else {
881 if !has_default { ::core::panicking::panic("assertion failed: has_default") };assert!(has_default);
882 tcx.type_of(param.def_id).instantiate(tcx, args).skip_norm_wip().into()
883 }
884 }
885 });
886 Ty::new_adt(tcx, adt_def, args)
887 }
888
889 #[inline]
890 pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
891 let def_id = tcx.lang_items().get(item)?;
892 Some(Ty::new_generic_adt(tcx, def_id, ty))
893 }
894
895 #[inline]
896 pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
897 let def_id = tcx.get_diagnostic_item(name)?;
898 Some(Ty::new_generic_adt(tcx, def_id, ty))
899 }
900
901 #[inline]
902 pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
903 let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
904 Ty::new_generic_adt(tcx, def_id, ty)
905 }
906
907 #[inline]
908 pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
909 let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
910 Ty::new_generic_adt(tcx, def_id, ty)
911 }
912
913 #[inline]
914 pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
915 let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
916 Ty::new_generic_adt(tcx, def_id, ty)
917 }
918
919 pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
921 let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
922 let context_adt_ref = tcx.adt_def(context_did);
923 let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
924 let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
925 Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
926 }
927}
928
929impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
930 fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
931 tcx.types.bool
932 }
933
934 fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
935 tcx.types.u8
936 }
937
938 fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
939 Ty::new_infer(tcx, infer)
940 }
941
942 fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
943 Ty::new_var(tcx, vid)
944 }
945
946 fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
947 Ty::new_param(tcx, param.index, param.name)
948 }
949
950 fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Self {
951 Ty::new_placeholder(tcx, placeholder)
952 }
953
954 fn new_bound(
955 interner: TyCtxt<'tcx>,
956 debruijn: ty::DebruijnIndex,
957 var: ty::BoundTy<'tcx>,
958 ) -> Self {
959 Ty::new_bound(interner, debruijn, var)
960 }
961
962 fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
963 Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
964 }
965
966 fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
967 Ty::new_canonical_bound(tcx, var)
968 }
969
970 fn new_alias(interner: TyCtxt<'tcx>, alias_ty: ty::AliasTy<'tcx>) -> Self {
971 Ty::new_alias(interner, alias_ty)
972 }
973
974 fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
975 Ty::new_error(interner, guar)
976 }
977
978 fn new_adt(
979 interner: TyCtxt<'tcx>,
980 adt_def: ty::AdtDef<'tcx>,
981 args: ty::GenericArgsRef<'tcx>,
982 ) -> Self {
983 Ty::new_adt(interner, adt_def, args)
984 }
985
986 fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
987 Ty::new_foreign(interner, def_id)
988 }
989
990 fn new_dynamic(
991 interner: TyCtxt<'tcx>,
992 preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
993 region: ty::Region<'tcx>,
994 ) -> Self {
995 Ty::new_dynamic(interner, preds, region)
996 }
997
998 fn new_coroutine(
999 interner: TyCtxt<'tcx>,
1000 def_id: DefId,
1001 args: ty::GenericArgsRef<'tcx>,
1002 ) -> Self {
1003 Ty::new_coroutine(interner, def_id, args)
1004 }
1005
1006 fn new_coroutine_closure(
1007 interner: TyCtxt<'tcx>,
1008 def_id: DefId,
1009 args: ty::GenericArgsRef<'tcx>,
1010 ) -> Self {
1011 Ty::new_coroutine_closure(interner, def_id, args)
1012 }
1013
1014 fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1015 Ty::new_closure(interner, def_id, args)
1016 }
1017
1018 fn new_coroutine_witness(
1019 interner: TyCtxt<'tcx>,
1020 def_id: DefId,
1021 args: ty::GenericArgsRef<'tcx>,
1022 ) -> Self {
1023 Ty::new_coroutine_witness(interner, def_id, args)
1024 }
1025
1026 fn new_coroutine_witness_for_coroutine(
1027 interner: TyCtxt<'tcx>,
1028 def_id: DefId,
1029 coroutine_args: ty::GenericArgsRef<'tcx>,
1030 ) -> Self {
1031 Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1032 }
1033
1034 fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1035 Ty::new_ptr(interner, ty, mutbl)
1036 }
1037
1038 fn new_ref(
1039 interner: TyCtxt<'tcx>,
1040 region: ty::Region<'tcx>,
1041 ty: Self,
1042 mutbl: hir::Mutability,
1043 ) -> Self {
1044 Ty::new_ref(interner, region, ty, mutbl)
1045 }
1046
1047 fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1048 Ty::new_array_with_const_len(interner, ty, len)
1049 }
1050
1051 fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1052 Ty::new_slice(interner, ty)
1053 }
1054
1055 fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1056 Ty::new_tup(interner, tys)
1057 }
1058
1059 fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1060 where
1061 It: Iterator<Item = T>,
1062 T: CollectAndApply<Self, Self>,
1063 {
1064 Ty::new_tup_from_iter(interner, iter)
1065 }
1066
1067 fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1068 self.tuple_fields()
1069 }
1070
1071 fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1072 self.to_opt_closure_kind()
1073 }
1074
1075 fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1076 Ty::from_closure_kind(interner, kind)
1077 }
1078
1079 fn from_coroutine_closure_kind(
1080 interner: TyCtxt<'tcx>,
1081 kind: rustc_type_ir::ClosureKind,
1082 ) -> Self {
1083 Ty::from_coroutine_closure_kind(interner, kind)
1084 }
1085
1086 fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1087 Ty::new_fn_def(interner, def_id, args)
1088 }
1089
1090 fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1091 Ty::new_fn_ptr(interner, sig)
1092 }
1093
1094 fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1095 Ty::new_pat(interner, ty, pat)
1096 }
1097
1098 fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1099 Ty::new_unsafe_binder(interner, ty)
1100 }
1101
1102 fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1103 interner.types.unit
1104 }
1105
1106 fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1107 interner.types.usize
1108 }
1109
1110 fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1111 self.discriminant_ty(interner)
1112 }
1113
1114 fn has_unsafe_fields(self) -> bool {
1115 Ty::has_unsafe_fields(self)
1116 }
1117}
1118
1119impl<'tcx> Ty<'tcx> {
1121 #[inline(always)]
1126 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1127 self.0.0
1128 }
1129
1130 #[inline]
1131 pub fn is_unit(self) -> bool {
1132 match self.kind() {
1133 Tuple(tys) => tys.is_empty(),
1134 _ => false,
1135 }
1136 }
1137
1138 #[inline]
1140 pub fn is_usize(self) -> bool {
1141 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Uint(UintTy::Usize) => true,
_ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1142 }
1143
1144 #[inline]
1146 pub fn is_usize_like(self) -> bool {
1147 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
_ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1148 }
1149
1150 #[inline]
1151 pub fn is_never(self) -> bool {
1152 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Never => true,
_ => false,
}matches!(self.kind(), Never)
1153 }
1154
1155 #[inline]
1156 pub fn is_primitive(self) -> bool {
1157 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Bool | Char | Int(_) | Uint(_) | Float(_) => true,
_ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1158 }
1159
1160 #[inline]
1161 pub fn is_adt(self) -> bool {
1162 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Adt(..) => true,
_ => false,
}matches!(self.kind(), Adt(..))
1163 }
1164
1165 #[inline]
1166 pub fn is_ref(self) -> bool {
1167 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Ref(..) => true,
_ => false,
}matches!(self.kind(), Ref(..))
1168 }
1169
1170 #[inline]
1171 pub fn is_ty_var(self) -> bool {
1172 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(TyVar(_)) => true,
_ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1173 }
1174
1175 #[inline]
1176 pub fn ty_vid(self) -> Option<ty::TyVid> {
1177 match self.kind() {
1178 &Infer(TyVar(vid)) => Some(vid),
1179 _ => None,
1180 }
1181 }
1182
1183 #[inline]
1184 pub fn float_vid(self) -> Option<ty::FloatVid> {
1185 match self.kind() {
1186 &Infer(FloatVar(vid)) => Some(vid),
1187 _ => None,
1188 }
1189 }
1190
1191 #[inline]
1192 pub fn is_ty_or_numeric_infer(self) -> bool {
1193 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(_) => true,
_ => false,
}matches!(self.kind(), Infer(_))
1194 }
1195
1196 #[inline]
1197 pub fn is_phantom_data(self) -> bool {
1198 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1199 }
1200
1201 #[inline]
1202 pub fn is_bool(self) -> bool {
1203 *self.kind() == Bool
1204 }
1205
1206 #[inline]
1208 pub fn is_str(self) -> bool {
1209 *self.kind() == Str
1210 }
1211
1212 #[inline]
1214 pub fn is_imm_ref_str(self) -> bool {
1215 #[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())
1216 }
1217
1218 #[inline]
1219 pub fn is_param(self, index: u32) -> bool {
1220 match self.kind() {
1221 ty::Param(data) => data.index == index,
1222 _ => false,
1223 }
1224 }
1225
1226 #[inline]
1227 pub fn is_slice(self) -> bool {
1228 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Slice(_) => true,
_ => false,
}matches!(self.kind(), Slice(_))
1229 }
1230
1231 #[inline]
1232 pub fn is_array_slice(self) -> bool {
1233 match self.kind() {
1234 Slice(_) => true,
1235 ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
Slice(_) => true,
_ => false,
}matches!(ty.kind(), Slice(_)),
1236 _ => false,
1237 }
1238 }
1239
1240 #[inline]
1241 pub fn is_array(self) -> bool {
1242 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Array(..) => true,
_ => false,
}matches!(self.kind(), Array(..))
1243 }
1244
1245 #[inline]
1246 pub fn is_simd(self) -> bool {
1247 match self.kind() {
1248 Adt(def, _) => def.repr().simd(),
1249 _ => false,
1250 }
1251 }
1252
1253 #[inline]
1254 pub fn is_scalable_vector(self) -> bool {
1255 match self.kind() {
1256 Adt(def, _) => def.repr().scalable(),
1257 _ => false,
1258 }
1259 }
1260
1261 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1262 match self.kind() {
1263 Array(ty, _) | Slice(ty) => *ty,
1264 Str => tcx.types.u8,
1265 _ => 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),
1266 }
1267 }
1268
1269 pub fn scalable_vector_parts(
1270 self,
1271 tcx: TyCtxt<'tcx>,
1272 ) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
1273 let Adt(def, args) = self.kind() else {
1274 return None;
1275 };
1276 let (num_vectors, vec_def) = match def.repr().scalable? {
1277 ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1278 ScalableElt::Container => (
1279 NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1280 def.non_enum_variant().fields[FieldIdx::ZERO]
1281 .ty(tcx, args)
1282 .skip_norm_wip()
1283 .ty_adt_def()?,
1284 ),
1285 };
1286 let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1287 return None;
1288 };
1289 let variant = vec_def.non_enum_variant();
1290 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);
1291 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1292 Some((element_count, field_ty.skip_norm_wip(), num_vectors))
1293 }
1294
1295 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1296 let Adt(def, args) = self.kind() else {
1297 crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1298 };
1299 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");
1300 let variant = def.non_enum_variant();
1301 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);
1302 let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1303 let Array(f0_elem_ty, f0_len) = field_ty.skip_norm_wip().kind() else {
1304 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:?}")
1305 };
1306 (
1311 f0_len
1312 .try_to_target_usize(tcx)
1313 .expect("expected SIMD field to have definite array size"),
1314 *f0_elem_ty,
1315 )
1316 }
1317
1318 #[inline]
1319 pub fn is_mutable_ptr(self) -> bool {
1320 #[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))
1321 }
1322
1323 #[inline]
1325 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1326 match self.kind() {
1327 Ref(_, _, mutability) => Some(*mutability),
1328 _ => None,
1329 }
1330 }
1331
1332 #[inline]
1333 pub fn is_raw_ptr(self) -> bool {
1334 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
RawPtr(_, _) => true,
_ => false,
}matches!(self.kind(), RawPtr(_, _))
1335 }
1336
1337 #[inline]
1340 pub fn is_any_ptr(self) -> bool {
1341 self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1342 }
1343
1344 #[inline]
1345 pub fn is_box(self) -> bool {
1346 match self.kind() {
1347 Adt(def, _) => def.is_box(),
1348 _ => false,
1349 }
1350 }
1351
1352 #[inline]
1357 pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1358 match self.kind() {
1359 Adt(def, args) if def.is_box() => {
1360 let Some(alloc) = args.get(1) else {
1361 return true;
1363 };
1364 alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1365 tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1366 })
1367 }
1368 _ => false,
1369 }
1370 }
1371
1372 pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1373 match self.kind() {
1374 Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1375 _ => None,
1376 }
1377 }
1378
1379 pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1380 match self.kind() {
1381 Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1382 _ => None,
1383 }
1384 }
1385
1386 pub fn maybe_pinned_ref(
1395 self,
1396 ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1397 match self.kind() {
1398 Adt(def, args)
1399 if def.is_pin()
1400 && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1401 {
1402 Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1403 }
1404 &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1405 _ => None,
1406 }
1407 }
1408
1409 pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1411 self.boxed_ty()
1412 .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))
1413 }
1414
1415 #[inline]
1419 pub fn is_scalar(self) -> bool {
1420 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
_ => false,
}matches!(
1421 self.kind(),
1422 Bool | Char
1423 | Int(_)
1424 | Float(_)
1425 | Uint(_)
1426 | FnDef(..)
1427 | FnPtr(..)
1428 | RawPtr(_, _)
1429 | Infer(IntVar(_) | FloatVar(_))
1430 )
1431 }
1432
1433 #[inline]
1435 pub fn is_floating_point(self) -> bool {
1436 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Float(_) | Infer(FloatVar(_)) => true,
_ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1437 }
1438
1439 #[inline]
1440 pub fn is_trait(self) -> bool {
1441 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Dynamic(_, _) => true,
_ => false,
}matches!(self.kind(), Dynamic(_, _))
1442 }
1443
1444 #[inline]
1445 pub fn is_enum(self) -> bool {
1446 #[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())
1447 }
1448
1449 #[inline]
1450 pub fn is_union(self) -> bool {
1451 #[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())
1452 }
1453
1454 #[inline]
1455 pub fn is_closure(self) -> bool {
1456 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Closure(..) => true,
_ => false,
}matches!(self.kind(), Closure(..))
1457 }
1458
1459 #[inline]
1460 pub fn is_coroutine(self) -> bool {
1461 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Coroutine(..) => true,
_ => false,
}matches!(self.kind(), Coroutine(..))
1462 }
1463
1464 #[inline]
1465 pub fn is_coroutine_closure(self) -> bool {
1466 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
CoroutineClosure(..) => true,
_ => false,
}matches!(self.kind(), CoroutineClosure(..))
1467 }
1468
1469 #[inline]
1470 pub fn is_integral(self) -> bool {
1471 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(IntVar(_)) | Int(_) | Uint(_) => true,
_ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1472 }
1473
1474 #[inline]
1475 pub fn is_fresh_ty(self) -> bool {
1476 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(FreshTy(_)) => true,
_ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1477 }
1478
1479 #[inline]
1480 pub fn is_fresh(self) -> bool {
1481 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
_ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1482 }
1483
1484 #[inline]
1485 pub fn is_char(self) -> bool {
1486 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Char => true,
_ => false,
}matches!(self.kind(), Char)
1487 }
1488
1489 #[inline]
1490 pub fn is_numeric(self) -> bool {
1491 self.is_integral() || self.is_floating_point()
1492 }
1493
1494 #[inline]
1495 pub fn is_signed(self) -> bool {
1496 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Int(_) => true,
_ => false,
}matches!(self.kind(), Int(_))
1497 }
1498
1499 #[inline]
1500 pub fn is_ptr_sized_integral(self) -> bool {
1501 #[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))
1502 }
1503
1504 #[inline]
1505 pub fn has_concrete_skeleton(self) -> bool {
1506 !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
Param(_) | Infer(_) | Error(_) => true,
_ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1507 }
1508
1509 pub fn contains(self, other: Ty<'tcx>) -> bool {
1513 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1514
1515 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1516 type Result = ControlFlow<()>;
1517
1518 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1519 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1520 }
1521 }
1522
1523 let cf = self.visit_with(&mut ContainsTyVisitor(other));
1524 cf.is_break()
1525 }
1526
1527 pub fn contains_closure(self) -> bool {
1531 struct ContainsClosureVisitor;
1532
1533 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1534 type Result = ControlFlow<()>;
1535
1536 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1537 if let ty::Closure(..) = t.kind() {
1538 ControlFlow::Break(())
1539 } else {
1540 t.super_visit_with(self)
1541 }
1542 }
1543 }
1544
1545 let cf = self.visit_with(&mut ContainsClosureVisitor);
1546 cf.is_break()
1547 }
1548
1549 pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1554 self,
1555 tcx: TyCtxt<'tcx>,
1556 mut f: F,
1557 ) -> Ty<'tcx> {
1558 if !self.is_coroutine() {
::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1559 let mut cor_ty = self;
1560 let mut ty = cor_ty;
1561 loop {
1562 let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1563 cor_ty = ty;
1564 f(ty);
1565 if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1566 return cor_ty;
1567 }
1568 ty = args.first().unwrap().expect_ty();
1569 }
1570 }
1571
1572 pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1577 match *self.kind() {
1578 _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1579 Ref(_, ty, _) => Some(ty),
1580 RawPtr(ty, _) if explicit => Some(ty),
1581 _ => None,
1582 }
1583 }
1584
1585 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1587 match self.kind() {
1588 Array(ty, _) | Slice(ty) => Some(*ty),
1589 _ => None,
1590 }
1591 }
1592
1593 #[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(1593u32),
::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))]
1594 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1595 self.kind().fn_sig(tcx)
1596 }
1597
1598 #[inline]
1599 pub fn is_fn(self) -> bool {
1600 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
FnDef(..) | FnPtr(..) => true,
_ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1601 }
1602
1603 #[inline]
1604 pub fn is_fn_ptr(self) -> bool {
1605 #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
FnPtr(..) => true,
_ => false,
}matches!(self.kind(), FnPtr(..))
1606 }
1607
1608 #[inline]
1609 pub fn is_opaque(self) -> bool {
1610 #[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 { .. }, .. }))
1611 }
1612
1613 #[inline]
1614 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1615 match self.kind() {
1616 Adt(adt, _) => Some(*adt),
1617 _ => None,
1618 }
1619 }
1620
1621 #[inline]
1625 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1626 match self.kind() {
1627 Tuple(args) => args,
1628 _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
self))bug!("tuple_fields called on non-tuple: {self:?}"),
1629 }
1630 }
1631
1632 #[inline]
1634 pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1635 match self.kind() {
1636 Tuple(args) => Some(args),
1637 _ => None,
1638 }
1639 }
1640
1641 #[inline]
1645 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1646 match self.kind() {
1647 TyKind::Adt(adt, _) => Some(adt.variant_range()),
1648 TyKind::Coroutine(def_id, args) => {
1649 Some(args.as_coroutine().variant_range(*def_id, tcx))
1650 }
1651 TyKind::UnsafeBinder(bound_ty) => {
1652 tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1653 }
1654 _ => None,
1655 }
1656 }
1657
1658 #[inline]
1663 pub fn discriminant_for_variant(
1664 self,
1665 tcx: TyCtxt<'tcx>,
1666 variant_index: VariantIdx,
1667 ) -> Option<Discr<'tcx>> {
1668 match self.kind() {
1669 TyKind::Adt(adt, _) if adt.is_enum() => {
1670 Some(adt.discriminant_for_variant(tcx, variant_index))
1671 }
1672 TyKind::Coroutine(def_id, args) => {
1673 Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1674 }
1675 TyKind::UnsafeBinder(bound_ty) => tcx
1676 .instantiate_bound_regions_with_erased((*bound_ty).into())
1677 .discriminant_for_variant(tcx, variant_index),
1678 _ => None,
1679 }
1680 }
1681
1682 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1684 match self.kind() {
1685 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1686 ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1687
1688 ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1689 let assoc_items = tcx.associated_item_def_ids(
1690 tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1691 );
1692 Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1693 }
1694
1695 ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1696 ty::UnsafeBinder(bound_ty) => {
1697 tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1698 }
1699
1700 ty::Bool
1701 | ty::Char
1702 | ty::Int(_)
1703 | ty::Uint(_)
1704 | ty::Float(_)
1705 | ty::Adt(..)
1706 | ty::Foreign(_)
1707 | ty::Str
1708 | ty::Array(..)
1709 | ty::Slice(_)
1710 | ty::RawPtr(_, _)
1711 | ty::Ref(..)
1712 | ty::FnDef(..)
1713 | ty::FnPtr(..)
1714 | ty::Dynamic(..)
1715 | ty::Closure(..)
1716 | ty::CoroutineClosure(..)
1717 | ty::CoroutineWitness(..)
1718 | ty::Never
1719 | ty::Tuple(_)
1720 | ty::Error(_)
1721 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1722
1723 ty::Bound(..)
1724 | ty::Placeholder(_)
1725 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1726 crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1727 }
1728 }
1729 }
1730
1731 pub fn ptr_metadata_ty_or_tail(
1734 self,
1735 tcx: TyCtxt<'tcx>,
1736 normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1737 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1738 let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1739 match tail.kind() {
1740 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1742 | ty::Uint(_)
1743 | ty::Int(_)
1744 | ty::Bool
1745 | ty::Float(_)
1746 | ty::FnDef(..)
1747 | ty::FnPtr(..)
1748 | ty::RawPtr(..)
1749 | ty::Char
1750 | ty::Ref(..)
1751 | ty::Coroutine(..)
1752 | ty::CoroutineWitness(..)
1753 | ty::Array(..)
1754 | ty::Closure(..)
1755 | ty::CoroutineClosure(..)
1756 | ty::Never
1757 | ty::Error(_)
1758 | ty::Foreign(..)
1760 | ty::Adt(..)
1763 | ty::Tuple(..) => Ok(tcx.types.unit),
1766
1767 ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1768
1769 ty::Dynamic(_, _) => {
1770 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1771 Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]).skip_norm_wip())
1772 }
1773
1774 ty::Param(_) | ty::Alias(..) => Err(tail),
1777
1778 | ty::UnsafeBinder(_) => {
::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
1779
1780 ty::Infer(ty::TyVar(_))
1781 | ty::Pat(..)
1782 | ty::Bound(..)
1783 | ty::Placeholder(..)
1784 | 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!(
1785 "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1786 ),
1787 }
1788 }
1789
1790 pub fn ptr_metadata_ty(
1793 self,
1794 tcx: TyCtxt<'tcx>,
1795 normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1796 ) -> Ty<'tcx> {
1797 match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1798 Ok(metadata) => metadata,
1799 Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
self, tail))bug!(
1800 "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1801 ),
1802 }
1803 }
1804
1805 #[track_caller]
1814 pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1815 let Some(pointee_ty) = self.builtin_deref(true) else {
1816 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")
1817 };
1818 if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1819 tcx.types.unit
1820 } else {
1821 match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x.skip_norm_wip()) {
1822 Ok(metadata_ty) => metadata_ty,
1823 Err(tail_ty) => {
1824 let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1825 Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1826 }
1827 }
1828 }
1829 }
1830
1831 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1871 match self.kind() {
1872 Int(int_ty) => match int_ty {
1873 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1874 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1875 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1876 _ => 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),
1877 },
1878
1879 Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1883
1884 Error(_) => Some(ty::ClosureKind::Fn),
1885
1886 _ => 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),
1887 }
1888 }
1889
1890 pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1893 match kind {
1894 ty::ClosureKind::Fn => tcx.types.i8,
1895 ty::ClosureKind::FnMut => tcx.types.i16,
1896 ty::ClosureKind::FnOnce => tcx.types.i32,
1897 }
1898 }
1899
1900 pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1913 match kind {
1914 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1915 ty::ClosureKind::FnOnce => tcx.types.i32,
1916 }
1917 }
1918
1919 #[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(1928u32),
::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")]
1929 pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1930 match self.kind() {
1931 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1932 | ty::Uint(_)
1933 | ty::Int(_)
1934 | ty::Bool
1935 | ty::Float(_)
1936 | ty::FnDef(..)
1937 | ty::FnPtr(..)
1938 | ty::UnsafeBinder(_)
1939 | ty::RawPtr(..)
1940 | ty::Char
1941 | ty::Ref(..)
1942 | ty::Coroutine(..)
1943 | ty::CoroutineWitness(..)
1944 | ty::Array(..)
1945 | ty::Pat(..)
1946 | ty::Closure(..)
1947 | ty::CoroutineClosure(..)
1948 | ty::Never
1949 | ty::Error(_) => true,
1950
1951 ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1952 SizedTraitKind::Sized => false,
1953 SizedTraitKind::MetaSized => true,
1954 },
1955
1956 ty::Foreign(..) => match sizedness {
1957 SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1958 },
1959
1960 ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1961
1962 ty::Adt(def, args) => def.sizedness_constraint(tcx, sizedness).is_none_or(|ty| {
1963 ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
1964 }),
1965
1966 ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1967
1968 ty::Infer(ty::TyVar(_)) => false,
1969
1970 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1971 bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1972 }
1973 }
1974 }
1975
1976 pub fn is_trivially_pure_clone_copy(self) -> bool {
1985 match self.kind() {
1986 ty::Bool | ty::Char | ty::Never => true,
1987
1988 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1990
1991 ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1992 | ty::Int(..)
1993 | ty::Uint(..)
1994 | ty::Float(..) => true,
1995
1996 ty::FnDef(..) => true,
1998
1999 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2000
2001 ty::Tuple(field_tys) => {
2003 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2004 }
2005
2006 ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
2007
2008 ty::FnPtr(..) => false,
2011
2012 ty::Ref(_, _, hir::Mutability::Mut) => false,
2014
2015 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2018
2019 ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2020
2021 ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2023
2024 ty::UnsafeBinder(_) => false,
2025
2026 ty::Alias(..) => false,
2028
2029 ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2030 false
2031 }
2032 }
2033 }
2034
2035 pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2036 match *self.kind() {
2037 ty::Bool
2038 | ty::Char
2039 | ty::Int(_)
2040 | ty::Uint(_)
2041 | ty::Float(_)
2042 | ty::Str
2043 | ty::Never
2044 | ty::Param(_)
2045 | ty::Placeholder(_)
2046 | ty::Bound(..) => true,
2047
2048 ty::Slice(ty) => {
2049 ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2050 }
2051 ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2052
2053 ty::FnPtr(sig_tys, _) => {
2054 sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2055 }
2056 ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2057
2058 ty::Infer(infer) => match infer {
2059 ty::TyVar(_) => false,
2060 ty::IntVar(_) | ty::FloatVar(_) => true,
2061 ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2062 },
2063
2064 ty::Adt(_, _)
2065 | ty::Tuple(_)
2066 | ty::Array(..)
2067 | ty::Foreign(_)
2068 | ty::Pat(_, _)
2069 | ty::FnDef(..)
2070 | ty::UnsafeBinder(..)
2071 | ty::Dynamic(..)
2072 | ty::Closure(..)
2073 | ty::CoroutineClosure(..)
2074 | ty::Coroutine(..)
2075 | ty::CoroutineWitness(..)
2076 | ty::Alias(..)
2077 | ty::Error(_) => false,
2078 }
2079 }
2080
2081 pub fn primitive_symbol(self) -> Option<Symbol> {
2083 match self.kind() {
2084 ty::Bool => Some(sym::bool),
2085 ty::Char => Some(sym::char),
2086 ty::Float(f) => match f {
2087 ty::FloatTy::F16 => Some(sym::f16),
2088 ty::FloatTy::F32 => Some(sym::f32),
2089 ty::FloatTy::F64 => Some(sym::f64),
2090 ty::FloatTy::F128 => Some(sym::f128),
2091 },
2092 ty::Int(f) => match f {
2093 ty::IntTy::Isize => Some(sym::isize),
2094 ty::IntTy::I8 => Some(sym::i8),
2095 ty::IntTy::I16 => Some(sym::i16),
2096 ty::IntTy::I32 => Some(sym::i32),
2097 ty::IntTy::I64 => Some(sym::i64),
2098 ty::IntTy::I128 => Some(sym::i128),
2099 },
2100 ty::Uint(f) => match f {
2101 ty::UintTy::Usize => Some(sym::usize),
2102 ty::UintTy::U8 => Some(sym::u8),
2103 ty::UintTy::U16 => Some(sym::u16),
2104 ty::UintTy::U32 => Some(sym::u32),
2105 ty::UintTy::U64 => Some(sym::u64),
2106 ty::UintTy::U128 => Some(sym::u128),
2107 },
2108 ty::Str => Some(sym::str),
2109 _ => None,
2110 }
2111 }
2112
2113 pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2114 match self.kind() {
2115 ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2116 _ => false,
2117 }
2118 }
2119
2120 pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2121 match self.kind() {
2122 ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2123 _ => false,
2124 }
2125 }
2126
2127 pub fn is_known_rigid(self) -> bool {
2133 self.kind().is_known_rigid()
2134 }
2135
2136 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2147 TypeWalker::new(self.into())
2148 }
2149}
2150
2151impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2152 fn inputs(self) -> &'tcx [Ty<'tcx>] {
2153 self.split_last().unwrap().1
2154 }
2155
2156 fn output(self) -> Ty<'tcx> {
2157 *self.split_last().unwrap().0
2158 }
2159}
2160
2161impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2162 fn is_kw_underscore_lifetime(self) -> bool {
2163 self == kw::UnderscoreLifetime
2164 }
2165}
2166
2167#[cfg(target_pointer_width = "64")]
2169mod size_asserts {
2170 use rustc_data_structures::static_assert_size;
2171
2172 use super::*;
2173 const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2175 const _: [(); 40] =
[(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 40);
2176 }