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