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