1//! Miscellaneous type-system utilities that are too small to deserve their own modules.
23use std::{fmt, iter};
45use rustc_abi::{Float, Integer, IntegerType, Size};
6use rustc_apfloat::Floatas _;
7use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8use rustc_data_structures::stable_hash::{StableHash, StableHasher};
9use rustc_data_structures::stack::ensure_sufficient_stack;
10use rustc_errors::ErrorGuaranteed;
11use rustc_hashes::Hash128;
12use rustc_hir::def::{CtorOf, DefKind, Res};
13use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
14use rustc_hir::limit::Limit;
15use rustc_hir::{selfas hir, find_attr};
16use rustc_index::bit_set::GrowableBitSet;
17use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
18use rustc_span::sym;
19use rustc_type_ir::solve::SizedTraitKind;
20use smallvec::{SmallVec, smallvec};
21use tracing::{debug, instrument};
2223use super::TypingEnv;
24use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
25use crate::mir;
26use crate::query::Providers;
27use crate::traits::ObligationCause;
28use crate::ty::layout::{FloatExt, IntegerExt};
29use crate::ty::{
30self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
31TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized, Upcast,
32};
3334#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Discr<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for Discr<'tcx> {
#[inline]
fn clone(&self) -> Discr<'tcx> {
let _: ::core::clone::AssertParamIsClone<u128>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Discr<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Discr", "val",
&self.val, "ty", &&self.ty)
}
}Debug)]
35pub struct Discr<'tcx> {
36/// Bit representation of the discriminant (e.g., `-1i8` is `0xFF_u128`).
37pub val: u128,
38pub ty: Ty<'tcx>,
39}
4041/// Used as an input to [`TyCtxt::uses_unique_generic_params`].
42#[derive(#[automatically_derived]
impl ::core::marker::Copy for CheckRegions { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CheckRegions {
#[inline]
fn clone(&self) -> CheckRegions { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CheckRegions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CheckRegions::No => "No",
CheckRegions::OnlyParam => "OnlyParam",
CheckRegions::FromFunction => "FromFunction",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CheckRegions {
#[inline]
fn eq(&self, other: &CheckRegions) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CheckRegions {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
43pub enum CheckRegions {
44 No,
45/// Only permit parameter regions. This should be used
46 /// for everything apart from functions, which may use
47 /// `ReBound` to represent late-bound regions.
48OnlyParam,
49/// Check region parameters from a function definition.
50 /// Allows `ReEarlyParam` and `ReBound` to handle early
51 /// and late-bound region parameters.
52FromFunction,
53}
5455#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NotUniqueParam<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for NotUniqueParam<'tcx> {
#[inline]
fn clone(&self) -> NotUniqueParam<'tcx> {
let _: ::core::clone::AssertParamIsClone<ty::GenericArg<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ty::GenericArg<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for NotUniqueParam<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
NotUniqueParam::DuplicateParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DuplicateParam", &__self_0),
NotUniqueParam::NotParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NotParam", &__self_0),
}
}
}Debug)]
56pub enum NotUniqueParam<'tcx> {
57 DuplicateParam(ty::GenericArg<'tcx>),
58 NotParam(ty::GenericArg<'tcx>),
59}
6061impl<'tcx> fmt::Displayfor Discr<'tcx> {
62fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
63match *self.ty.kind() {
64 ty::Int(ity) => {
65let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
66let x = self.val;
67// sign extend the raw representation to be an i128
68let x = size.sign_extend(x) as i128;
69fmt.write_fmt(format_args!("{0}", x))write!(fmt, "{x}")70 }
71_ => fmt.write_fmt(format_args!("{0}", self.val))write!(fmt, "{}", self.val),
72 }
73 }
74}
7576impl<'tcx> Discr<'tcx> {
77/// Adds `1` to the value and wraps around if the maximum for the type is reached.
78pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
79self.checked_add(tcx, 1).0
80}
81pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
82let (size, signed) = self.ty.int_size_and_signed(tcx);
83let (val, oflo) = if signed {
84let min = size.signed_int_min();
85let max = size.signed_int_max();
86let val = size.sign_extend(self.val);
87if !(n < (i128::MAX as u128)) {
::core::panicking::panic("assertion failed: n < (i128::MAX as u128)")
};assert!(n < (i128::MAX as u128));
88let n = nas i128;
89let oflo = val > max - n;
90let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
91// zero the upper bits
92let val = valas u128;
93let val = size.truncate(val);
94 (val, oflo)
95 } else {
96let max = size.unsigned_int_max();
97let val = self.val;
98let oflo = val > max - n;
99let val = if oflo { n - (max - val) - 1 } else { val + n };
100 (val, oflo)
101 };
102 (Self { val, ty: self.ty }, oflo)
103 }
104}
105106impl IntTypeExt for IntegerType {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match self {
IntegerType::Pointer(true) => tcx.types.isize,
IntegerType::Pointer(false) => tcx.types.usize,
IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
}
}
fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
Discr { val: 0, ty: self.to_ty(tcx) }
}
fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>)
-> Option<Discr<'tcx>> {
if let Some(val) = val {
{
match (&self.to_ty(tcx), &val.ty) {
(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);
}
}
}
};
let (new, oflo) = val.checked_add(tcx, 1);
if oflo { None } else { Some(new) }
} else { Some(self.initial_discriminant(tcx)) }
}
}#[extension(pub trait IntTypeExt)]107impl IntegerType {
108fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
109match self {
110 IntegerType::Pointer(true) => tcx.types.isize,
111 IntegerType::Pointer(false) => tcx.types.usize,
112 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
113 }
114 }
115116fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
117Discr { val: 0, ty: self.to_ty(tcx) }
118 }
119120fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
121if let Some(val) = val {
122assert_eq!(self.to_ty(tcx), val.ty);
123let (new, oflo) = val.checked_add(tcx, 1);
124if oflo { None } else { Some(new) }
125 } else {
126Some(self.initial_discriminant(tcx))
127 }
128 }
129}
130131impl<'tcx> TyCtxt<'tcx> {
132/// Creates a hash of the type `Ty` which will be the same no matter what crate
133 /// context it's calculated within. This is used by the `type_id` intrinsic.
134pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash128 {
135// We don't have region information, so we erase all free regions. Equal types
136 // must have the same `TypeId`, so we must anonymize all bound regions as well.
137let ty = self.erase_and_anonymize_regions(ty);
138139self.with_stable_hashing_context(|mut hcx| {
140let mut hasher = StableHasher::new();
141hcx.while_hashing_spans(false, |hcx| ty.stable_hash(hcx, &mut hasher));
142hasher.finish()
143 })
144 }
145146pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
147match res {
148 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
149Some(self.parent(self.parent(def_id)))
150 }
151 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
152Some(self.parent(def_id))
153 }
154// Other `DefKind`s don't have generics and would ICE when calling
155 // `generics_of`.
156Res::Def(
157 DefKind::Struct158 | DefKind::Union159 | DefKind::Enum160 | DefKind::Trait161 | DefKind::OpaqueTy162 | DefKind::TyAlias163 | DefKind::ForeignTy164 | DefKind::TraitAlias165 | DefKind::AssocTy166 | DefKind::Fn167 | DefKind::AssocFn168 | DefKind::AssocConst { .. }
169 | DefKind::Impl { .. },
170 def_id,
171 ) => Some(def_id),
172 Res::Err => None,
173_ => None,
174 }
175 }
176177/// Checks whether `ty: Copy` holds while ignoring region constraints.
178 ///
179 /// This impacts whether values of `ty` are *moved* or *copied*
180 /// when referenced. This means that we may generate MIR which
181 /// does copies even when the type actually doesn't satisfy the
182 /// full requirements for the `Copy` trait (cc #29149) -- this
183 /// winds up being reported as an error during NLL borrow check.
184 ///
185 /// This function should not be used if there is an `InferCtxt` available.
186 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
187pub fn type_is_copy_modulo_regions(
188self,
189 typing_env: ty::TypingEnv<'tcx>,
190 ty: Ty<'tcx>,
191 ) -> bool {
192ty.is_trivially_pure_clone_copy() || self.is_copy_raw(typing_env.as_query_input(ty))
193 }
194195/// Checks whether `ty: UseCloned` holds while ignoring region constraints.
196 ///
197 /// This function should not be used if there is an `InferCtxt` available.
198 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
199pub fn type_is_use_cloned_modulo_regions(
200self,
201 typing_env: ty::TypingEnv<'tcx>,
202 ty: Ty<'tcx>,
203 ) -> bool {
204ty.is_trivially_pure_clone_copy() || self.is_use_cloned_raw(typing_env.as_query_input(ty))
205 }
206207/// Returns the deeply last field of nested structures, or the same type if
208 /// not a structure at all. Corresponds to the only possible unsized field,
209 /// and its type can be used to determine unsizing strategy.
210 ///
211 /// Should only be called if `ty` has no inference variables and does not
212 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
213 /// normalization attempt may cause compiler bugs.
214pub fn struct_tail_for_codegen(
215self,
216 ty: Ty<'tcx>,
217 typing_env: ty::TypingEnv<'tcx>,
218 ) -> Ty<'tcx> {
219self.assert_fully_normalized(typing_env, ty);
220self.struct_tail_raw(
221ty,
222&ObligationCause::dummy(),
223 |ty| self.normalize_erasing_regions(typing_env, ty),
224 || {},
225 )
226 }
227228/// Returns true if a type has metadata.
229pub fn type_has_metadata(self, ty: Ty<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
230if ty.is_sized(self, typing_env) {
231return false;
232 }
233234let tail = self.struct_tail_for_codegen(ty, typing_env);
235match tail.kind() {
236 ty::Foreign(..) => false,
237 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
238_ => crate::util::bug::bug_fmt(format_args!("unexpected unsized tail: {0:?}",
tail))bug!("unexpected unsized tail: {:?}", tail),
239 }
240 }
241242/// Returns the deeply last field of nested structures, or the same type if
243 /// not a structure at all. Corresponds to the only possible unsized field,
244 /// and its type can be used to determine unsizing strategy.
245 ///
246 /// This is parameterized over the normalization strategy (i.e. how to
247 /// handle `<T as Trait>::Assoc` and `impl Trait`). You almost certainly do
248 /// **NOT** want to pass the identity function here, unless you know what
249 /// you're doing, or you're within normalization code itself and will handle
250 /// an unnormalized tail recursively.
251 ///
252 /// See also `struct_tail_for_codegen`, which is suitable for use
253 /// during codegen.
254pub fn struct_tail_raw(
255self,
256mut ty: Ty<'tcx>,
257 cause: &ObligationCause<'tcx>,
258mut normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
259// This is currently used to allow us to walk a ValTree
260 // in lockstep with the type in order to get the ValTree branch that
261 // corresponds to an unsized field.
262mut f: impl FnMut() -> (),
263 ) -> Ty<'tcx> {
264let recursion_limit = self.recursion_limit();
265for iteration in 0.. {
266if !recursion_limit.value_within_limit(iteration) {
267let suggested_limit = match recursion_limit {
268 Limit(0) => Limit(2),
269 limit => limit * 2,
270 };
271let reported = self.dcx().emit_err(crate::error::RecursionLimitReached {
272 span: cause.span,
273 ty,
274 suggested_limit,
275 });
276return Ty::new_error(self, reported);
277 }
278match *ty.kind() {
279 ty::Adt(def, args) => {
280if !def.is_struct() {
281break;
282 }
283match def.non_enum_variant().tail_opt() {
284Some(field) => {
285 f();
286 ty = normalize(field.ty(self, args));
287 }
288None => break,
289 }
290 }
291292 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
293 f();
294 ty = last_ty;
295 }
296297 ty::Tuple(_) => break,
298299 ty::Pat(inner, _) => {
300 f();
301 ty = inner;
302 }
303304_ => {
305break;
306 }
307 }
308 }
309ty310 }
311312/// Same as applying `struct_tail` on `source` and `target`, but only
313 /// keeps going as long as the two types are instances of the same
314 /// structure definitions.
315 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
316 /// whereas struct_tail produces `T`, and `Trait`, respectively.
317 ///
318 /// Should only be called if the types have no inference variables and do
319 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
320 /// normalization attempt may cause compiler bugs.
321pub fn struct_lockstep_tails_for_codegen(
322self,
323 source: Ty<'tcx>,
324 target: Ty<'tcx>,
325 typing_env: ty::TypingEnv<'tcx>,
326 ) -> (Ty<'tcx>, Ty<'tcx>) {
327self.assert_fully_normalized(typing_env, (source, target));
328self.struct_lockstep_tails_raw(source, target, |ty| {
329self.normalize_erasing_regions(typing_env, ty)
330 })
331 }
332333/// Same as applying `struct_tail` on `source` and `target`, but only
334 /// keeps going as long as the two types are instances of the same
335 /// structure definitions.
336 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
337 /// whereas struct_tail produces `T`, and `Trait`, respectively.
338 ///
339 /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
340 /// during codegen.
341pub fn struct_lockstep_tails_raw(
342self,
343 source: Ty<'tcx>,
344 target: Ty<'tcx>,
345 normalize: impl Fn(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
346 ) -> (Ty<'tcx>, Ty<'tcx>) {
347let (mut a, mut b) = (source, target);
348loop {
349match (a.kind(), b.kind()) {
350 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
351if a_def == b_def && a_def.is_struct() =>
352 {
353if let Some(f) = a_def.non_enum_variant().tail_opt() {
354a = normalize(f.ty(self, a_args));
355b = normalize(f.ty(self, b_args));
356 } else {
357break;
358 }
359 }
360 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
361if let Some(&a_last) = a_tys.last() {
362a = a_last;
363b = *b_tys.last().unwrap();
364 } else {
365break;
366 }
367 }
368369_ => break,
370 }
371 }
372 (a, b)
373 }
374375/// Calculate the destructor of a given type.
376pub fn calculate_dtor(
377self,
378 adt_did: LocalDefId,
379 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
380 ) -> Option<ty::Destructor> {
381let drop_trait = self.lang_items().drop_trait()?;
382self.ensure_result().coherent_trait(drop_trait).ok()?;
383384let mut dtor_candidate = None;
385// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
386for &impl_did in self.local_trait_impls(drop_trait) {
387let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
388if adt_def.did() != adt_did.to_def_id() {
389continue;
390 }
391392if validate(self, impl_did).is_err() {
393// Already `ErrorGuaranteed`, no need to delay a span bug here.
394continue;
395 }
396397let Some(&item_id) = self.associated_item_def_ids(impl_did).first() else {
398self.dcx()
399 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
400continue;
401 };
402403if self.def_kind(item_id) != DefKind::AssocFn {
404self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
405continue;
406 }
407408if let Some(old_item_id) = dtor_candidate {
409self.dcx()
410 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
411 .with_span_note(self.def_span(old_item_id), "other impl here")
412 .delay_as_bug();
413 }
414415 dtor_candidate = Some(item_id);
416 }
417418let did = dtor_candidate?;
419Some(ty::Destructor { did })
420 }
421422/// Calculate the async destructor of a given type.
423pub fn calculate_async_dtor(
424self,
425 adt_did: LocalDefId,
426 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
427 ) -> Option<ty::AsyncDestructor> {
428let async_drop_trait = self.lang_items().async_drop_trait()?;
429self.ensure_result().coherent_trait(async_drop_trait).ok()?;
430431let mut dtor_candidate = None;
432// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
433for &impl_did in self.local_trait_impls(async_drop_trait) {
434let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
435if adt_def.did() != adt_did.to_def_id() {
436continue;
437 }
438439if validate(self, impl_did).is_err() {
440// Already `ErrorGuaranteed`, no need to delay a span bug here.
441continue;
442 }
443444if let Some(old_impl_did) = dtor_candidate {
445self.dcx()
446 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
447 .with_span_note(self.def_span(old_impl_did), "other impl here")
448 .delay_as_bug();
449 }
450451 dtor_candidate = Some(impl_did);
452 }
453454Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
455 }
456457/// Returns the set of types that are required to be alive in
458 /// order to run the destructor of `def` (see RFCs 769 and
459 /// 1238).
460 ///
461 /// Note that this returns only the constraints for the
462 /// destructor of `def` itself. For the destructors of the
463 /// contents, you need `adt_dtorck_constraint`.
464pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
465let dtor = match def.destructor(self) {
466None => {
467{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/util.rs:467",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(467u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("destructor_constraints({0:?}) - no dtor",
def.did()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("destructor_constraints({:?}) - no dtor", def.did());
468return ::alloc::vec::Vec::new()vec![];
469 }
470Some(dtor) => dtor.did,
471 };
472473let impl_def_id = self.parent(dtor);
474let impl_generics = self.generics_of(impl_def_id);
475476// We have a destructor - all the parameters that are not
477 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
478 // must be live.
479480 // We need to return the list of parameters from the ADTs
481 // generics/args that correspond to impure parameters on the
482 // impl's generics. This is a bit ugly, but conceptually simple:
483 //
484 // Suppose our ADT looks like the following
485 //
486 // struct S<X, Y, Z>(X, Y, Z);
487 //
488 // and the impl is
489 //
490 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
491 //
492 // We want to return the parameters (X, Y). For that, we match
493 // up the item-args <X, Y, Z> with the args on the impl ADT,
494 // <P1, P2, P0>, and then look up which of the impl args refer to
495 // parameters marked as pure.
496497let impl_args =
498match *self.type_of(impl_def_id).instantiate_identity().skip_norm_wip().kind() {
499 ty::Adt(def_, args) if def_ == def => args,
500_ => crate::util::bug::span_bug_fmt(self.def_span(impl_def_id),
format_args!("expected ADT for self type of `Drop` impl"))span_bug!(
501self.def_span(impl_def_id),
502"expected ADT for self type of `Drop` impl"
503),
504 };
505506let item_args = ty::GenericArgs::identity_for_item(self, def.did());
507508let result = iter::zip(item_args, impl_args)
509 .filter(|&(_, arg)| {
510match arg.kind() {
511GenericArgKind::Lifetime(region) => match region.kind() {
512 ty::ReEarlyParam(ebr) => {
513 !impl_generics.region_param(ebr, self).pure_wrt_drop
514 }
515// Error: not a region param
516_ => false,
517 },
518GenericArgKind::Type(ty) => match *ty.kind() {
519 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
520// Error: not a type param
521_ => false,
522 },
523GenericArgKind::Const(ct) => match ct.kind() {
524 ty::ConstKind::Param(pc) => {
525 !impl_generics.const_param(pc, self).pure_wrt_drop
526 }
527// Error: not a const param
528_ => false,
529 },
530 }
531 })
532 .map(|(item_param, _)| item_param)
533 .collect();
534{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/util.rs:534",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(534u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("destructor_constraint({0:?}) = {1:?}",
def.did(), result) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
535result536 }
537538/// Checks whether each generic argument is simply a unique generic parameter.
539pub fn uses_unique_generic_params(
540self,
541 args: &[ty::GenericArg<'tcx>],
542 ignore_regions: CheckRegions,
543 ) -> Result<(), NotUniqueParam<'tcx>> {
544let mut seen = GrowableBitSet::default();
545let mut seen_late = FxHashSet::default();
546for arg in args {
547match arg.kind() {
548 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
549 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
550if !seen_late.insert((di, reg)) {
551return Err(NotUniqueParam::DuplicateParam(lt.into()));
552 }
553 }
554 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
555if !seen.insert(p.index) {
556return Err(NotUniqueParam::DuplicateParam(lt.into()));
557 }
558 }
559 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
560return Err(NotUniqueParam::NotParam(lt.into()));
561 }
562 (CheckRegions::No, _) => {}
563 },
564 GenericArgKind::Type(t) => match t.kind() {
565 ty::Param(p) => {
566if !seen.insert(p.index) {
567return Err(NotUniqueParam::DuplicateParam(t.into()));
568 }
569 }
570_ => return Err(NotUniqueParam::NotParam(t.into())),
571 },
572 GenericArgKind::Const(c) => match c.kind() {
573 ty::ConstKind::Param(p) => {
574if !seen.insert(p.index) {
575return Err(NotUniqueParam::DuplicateParam(c.into()));
576 }
577 }
578_ => return Err(NotUniqueParam::NotParam(c.into())),
579 },
580 }
581 }
582583Ok(())
584 }
585586/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
587 /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
588 /// have the same `DefKind`.
589 ///
590 /// Note that closures have a `DefId`, but the closure *expression* also has a
591 /// `HirId` that is located within the context where the closure appears. The
592 /// parent of the closure's `DefId` will also be the context where it appears.
593pub fn is_closure_like(self, def_id: DefId) -> bool {
594#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)595 }
596597/// Returns `true` if `def_id` refers to a definition that does not have its own
598 /// type-checking context, i.e. closure, coroutine or inline const.
599pub fn is_typeck_child(self, def_id: DefId) -> bool {
600match self.def_kind(def_id) {
601 DefKind::AnonConst => {
602self.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline603 }
604 DefKind::Closure | DefKind::SyntheticCoroutineBody => true,
605 DefKind::Mod606 | DefKind::Struct607 | DefKind::Union608 | DefKind::Enum609 | DefKind::Variant610 | DefKind::Trait611 | DefKind::TyAlias612 | DefKind::ForeignTy613 | DefKind::TraitAlias614 | DefKind::AssocTy615 | DefKind::TyParam616 | DefKind::Fn617 | DefKind::Const { .. }
618 | DefKind::ConstParam619 | DefKind::Static { .. }
620 | DefKind::Ctor(_, _)
621 | DefKind::AssocFn622 | DefKind::AssocConst { .. }
623 | DefKind::Macro(_)
624 | DefKind::ExternCrate625 | DefKind::Use626 | DefKind::ForeignMod627 | DefKind::OpaqueTy628 | DefKind::Field629 | DefKind::LifetimeParam630 | DefKind::GlobalAsm631 | DefKind::Impl { .. } => false,
632 }
633 }
634635/// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
636pub fn is_trait(self, def_id: DefId) -> bool {
637self.def_kind(def_id) == DefKind::Trait638 }
639640/// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
641 /// and `false` otherwise.
642pub fn is_trait_alias(self, def_id: DefId) -> bool {
643self.def_kind(def_id) == DefKind::TraitAlias644 }
645646/// Returns `true` if this `DefId` refers to the implicit constructor for
647 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
648pub fn is_constructor(self, def_id: DefId) -> bool {
649#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))650 }
651652/// Given the `DefId`, returns the `DefId` of the innermost item that
653 /// has its own type-checking context or "inference environment".
654 ///
655 /// For example, a closure has its own `DefId`, but it is type-checked
656 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
657 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
658pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
659let mut def_id = def_id;
660while self.is_typeck_child(def_id) {
661 def_id = self.parent(def_id);
662 }
663def_id664 }
665666/// Given the `LocalDefId`, returns the `LocalDefId` of the innermost item that
667 /// has its own type-checking context or "inference environment".
668 ///
669 /// For example, a closure has its own `LocalDefId`, but it is type-checked
670 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
671 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
672pub fn typeck_root_def_id_local(self, def_id: LocalDefId) -> LocalDefId {
673let mut def_id = def_id;
674while self.is_typeck_child(def_id.to_def_id()) {
675 def_id = self.local_parent(def_id);
676 }
677def_id678 }
679680/// Given the `DefId` and args a closure, creates the type of
681 /// `self` argument that the closure expects. For example, for a
682 /// `Fn` closure, this would return a reference type `&T` where
683 /// `T = closure_ty`.
684 ///
685 /// Returns `None` if this closure's kind has not yet been inferred.
686 /// This should only be possible during type checking.
687 ///
688 /// Note that the return value is a late-bound region and hence
689 /// wrapped in a binder.
690pub fn closure_env_ty(
691self,
692 closure_ty: Ty<'tcx>,
693 closure_kind: ty::ClosureKind,
694 env_region: ty::Region<'tcx>,
695 ) -> Ty<'tcx> {
696match closure_kind {
697 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
698 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
699 ty::ClosureKind::FnOnce => closure_ty,
700 }
701 }
702703/// Returns `true` if the node pointed to by `def_id` is a `static` item.
704#[inline]
705pub fn is_static(self, def_id: DefId) -> bool {
706#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })707 }
708709#[inline]
710pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
711if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
712Some(mutability)
713 } else {
714None715 }
716 }
717718/// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
719pub fn is_thread_local_static(self, def_id: DefId) -> bool {
720self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
721 }
722723/// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
724#[inline]
725pub fn is_mutable_static(self, def_id: DefId) -> bool {
726self.static_mutability(def_id) == Some(hir::Mutability::Mut)
727 }
728729/// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
730 /// thread local shim generated.
731#[inline]
732pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
733 !self.sess.target.dll_tls_export
734 && self.is_thread_local_static(def_id)
735 && !self.is_foreign_item(def_id)
736 }
737738/// Returns the type a reference to the thread local takes in MIR.
739pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
740let static_ty = self.type_of(def_id).instantiate_identity().skip_norm_wip();
741if self.is_mutable_static(def_id) {
742Ty::new_mut_ptr(self, static_ty)
743 } else if self.is_foreign_item(def_id) {
744Ty::new_imm_ptr(self, static_ty)
745 } else {
746// FIXME: These things don't *really* have 'static lifetime.
747Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
748 }
749 }
750751/// Get the type of the pointer to the static that we use in MIR.
752pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
753// Make sure that any constants in the static's type are evaluated.
754let static_ty =
755self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
756757// Make sure that accesses to unsafe statics end up using raw pointers.
758 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
759if self.is_mutable_static(def_id) {
760Ty::new_mut_ptr(self, static_ty)
761 } else if self.is_foreign_item(def_id) {
762Ty::new_imm_ptr(self, static_ty)
763 } else {
764Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
765 }
766 }
767768/// Expands the given impl trait type, stopping if the type is recursive.
769x;#[instrument(skip(self), level = "debug", ret)]770pub fn try_expand_impl_trait_type(
771self,
772 def_id: DefId,
773 args: GenericArgsRef<'tcx>,
774 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
775let mut visitor = OpaqueTypeExpander {
776 seen_opaque_tys: FxHashSet::default(),
777 expanded_cache: FxHashMap::default(),
778 primary_def_id: Some(def_id),
779 found_recursion: false,
780 found_any_recursion: false,
781 check_recursion: true,
782 tcx: self,
783 };
784785let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
786if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
787 }
788789/// Query and get an English description for the item's kind.
790pub fn def_descr(self, def_id: DefId) -> &'static str {
791self.def_kind_descr(self.def_kind(def_id), def_id)
792 }
793794/// Get an English description for the item's kind.
795pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
796match def_kind {
797 DefKind::AssocFnif self.associated_item(def_id).is_method() => "method",
798 DefKind::AssocTyif self.opt_rpitit_info(def_id).is_some() => "opaque type",
799 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
800match coroutine_kind {
801 hir::CoroutineKind::Desugared(
802 hir::CoroutineDesugaring::Async,
803 hir::CoroutineSource::Fn,
804 ) => "async fn",
805 hir::CoroutineKind::Desugared(
806 hir::CoroutineDesugaring::Async,
807 hir::CoroutineSource::Block,
808 ) => "async block",
809 hir::CoroutineKind::Desugared(
810 hir::CoroutineDesugaring::Async,
811 hir::CoroutineSource::Closure,
812 ) => "async closure",
813 hir::CoroutineKind::Desugared(
814 hir::CoroutineDesugaring::AsyncGen,
815 hir::CoroutineSource::Fn,
816 ) => "async gen fn",
817 hir::CoroutineKind::Desugared(
818 hir::CoroutineDesugaring::AsyncGen,
819 hir::CoroutineSource::Block,
820 ) => "async gen block",
821 hir::CoroutineKind::Desugared(
822 hir::CoroutineDesugaring::AsyncGen,
823 hir::CoroutineSource::Closure,
824 ) => "async gen closure",
825 hir::CoroutineKind::Desugared(
826 hir::CoroutineDesugaring::Gen,
827 hir::CoroutineSource::Fn,
828 ) => "gen fn",
829 hir::CoroutineKind::Desugared(
830 hir::CoroutineDesugaring::Gen,
831 hir::CoroutineSource::Block,
832 ) => "gen block",
833 hir::CoroutineKind::Desugared(
834 hir::CoroutineDesugaring::Gen,
835 hir::CoroutineSource::Closure,
836 ) => "gen closure",
837 hir::CoroutineKind::Coroutine(_) => "coroutine",
838 }
839 }
840_ => def_kind.descr(def_id),
841 }
842 }
843844/// Gets an English article for the [`TyCtxt::def_descr`].
845pub fn def_descr_article(self, def_id: DefId) -> &'static str {
846self.def_kind_descr_article(self.def_kind(def_id), def_id)
847 }
848849/// Gets an English article for the [`TyCtxt::def_kind_descr`].
850pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
851match def_kind {
852 DefKind::AssocFnif self.associated_item(def_id).is_method() => "a",
853 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
854match coroutine_kind {
855 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
856 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
857 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
858 hir::CoroutineKind::Coroutine(_) => "a",
859 }
860 }
861_ => def_kind.article(),
862 }
863 }
864865/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
866 /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
867 /// be shown in `impl` suggestions.
868 ///
869 /// [public]: TyCtxt::is_private_dep
870 /// [direct]: rustc_session::cstore::ExternCrate::is_direct
871pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
872// `#![rustc_private]` overrides defaults to make private dependencies usable.
873if self.features().enabled(sym::rustc_private) {
874return true;
875 }
876877// | Private | Direct | Visible | |
878 // |---------|--------|---------|--------------------|
879 // | Yes | Yes | Yes | !true || true |
880 // | No | Yes | Yes | !false || true |
881 // | Yes | No | No | !true || false |
882 // | No | No | Yes | !false || false |
883!self.is_private_dep(key)
884// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
885 // Treat that kind of crate as "indirect", since it's an implementation detail of
886 // the language.
887|| self.extern_crate(key).is_some_and(|e| e.is_direct())
888 }
889890/// Expand any [free alias types][free] contained within the given `value`.
891 ///
892 /// This should be used over other normalization routines in situations where
893 /// it's important not to normalize other alias types and where the predicates
894 /// on the corresponding type alias shouldn't be taken into consideration.
895 ///
896 /// Whenever possible **prefer not to use this function**! Instead, use standard
897 /// normalization routines or if feasible don't normalize at all.
898 ///
899 /// This function comes in handy if you want to mimic the behavior of eager
900 /// type alias expansion in a localized manner.
901 ///
902 /// <div class="warning">
903 /// This delays a bug on overflow! Therefore you need to be certain that the
904 /// contained types get fully normalized at a later stage. Note that even on
905 /// overflow all well-behaved free alias types get expanded correctly, so the
906 /// result is still useful.
907 /// </div>
908 ///
909 /// [free]: ty::Free
910pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
911value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
912 }
913914/// Peel off all [free alias types] in this type until there are none left.
915 ///
916 /// This only expands free alias types in “head” / outermost positions. It can
917 /// be used over [expand_free_alias_tys] as an optimization in situations where
918 /// one only really cares about the *kind* of the final aliased type but not
919 /// the types the other constituent types alias.
920 ///
921 /// <div class="warning">
922 /// This delays a bug on overflow! Therefore you need to be certain that the
923 /// type gets fully normalized at a later stage.
924 /// </div>
925 ///
926 /// [free]: ty::Free
927 /// [expand_free_alias_tys]: Self::expand_free_alias_tys
928pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
929let ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) = ty.kind() else {
930return ty;
931 };
932933let limit = self.recursion_limit();
934let mut depth = 0;
935936while let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() {
937if !limit.value_within_limit(depth) {
938let guar = self.dcx().delayed_bug("overflow expanding free alias type");
939return Ty::new_error(self, guar);
940 }
941942 ty = self.type_of(def_id).instantiate(self, args).skip_normalization();
943 depth += 1;
944 }
945946ty947 }
948949// Computes the variances for an alias (opaque or RPITIT) that represent
950 // its (un)captured regions.
951pub fn opt_alias_variances(
952self,
953 kind: impl Into<ty::AliasTermKind<'tcx>>,
954 ) -> Option<&'tcx [ty::Variance]> {
955match kind.into() {
956 ty::AliasTermKind::ProjectionTy { def_id } => {
957if self.is_impl_trait_in_trait(def_id) {
958Some(self.variances_of(def_id))
959 } else {
960None961 }
962 }
963 ty::AliasTermKind::OpaqueTy { def_id } => Some(self.variances_of(def_id)),
964 ty::AliasTermKind::InherentTy { .. }
965 | ty::AliasTermKind::InherentConst { .. }
966 | ty::AliasTermKind::FreeTy { .. }
967 | ty::AliasTermKind::FreeConst { .. }
968 | ty::AliasTermKind::AnonConst { .. }
969 | ty::AliasTermKind::ProjectionConst { .. } => None,
970 }
971 }
972}
973974struct OpaqueTypeExpander<'tcx> {
975// Contains the DefIds of the opaque types that are currently being
976 // expanded. When we expand an opaque type we insert the DefId of
977 // that type, and when we finish expanding that type we remove the
978 // its DefId.
979seen_opaque_tys: FxHashSet<DefId>,
980// Cache of all expansions we've seen so far. This is a critical
981 // optimization for some large types produced by async fn trees.
982expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
983 primary_def_id: Option<DefId>,
984 found_recursion: bool,
985 found_any_recursion: bool,
986/// Whether or not to check for recursive opaque types.
987 /// This is `true` when we're explicitly checking for opaque type
988 /// recursion, and 'false' otherwise to avoid unnecessary work.
989check_recursion: bool,
990 tcx: TyCtxt<'tcx>,
991}
992993impl<'tcx> OpaqueTypeExpander<'tcx> {
994fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
995if self.found_any_recursion {
996return None;
997 }
998let args = args.fold_with(self);
999if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
1000let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
1001Some(expanded_ty) => *expanded_ty,
1002None => {
1003let generic_ty = self.tcx.type_of(def_id);
1004let concrete_ty = generic_ty.instantiate(self.tcx, args).skip_normalization();
1005let expanded_ty = self.fold_ty(concrete_ty);
1006self.expanded_cache.insert((def_id, args), expanded_ty);
1007expanded_ty1008 }
1009 };
1010if self.check_recursion {
1011self.seen_opaque_tys.remove(&def_id);
1012 }
1013Some(expanded_ty)
1014 } else {
1015// If another opaque type that we contain is recursive, then it
1016 // will report the error, so we don't have to.
1017self.found_any_recursion = true;
1018self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1019None1020 }
1021 }
1022}
10231024impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1025fn cx(&self) -> TyCtxt<'tcx> {
1026self.tcx
1027 }
10281029fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1030if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *t.kind() {
1031self.expand_opaque_ty(def_id, args).unwrap_or(t)
1032 } else if t.has_opaque_types() {
1033t.super_fold_with(self)
1034 } else {
1035t1036 }
1037 }
10381039fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1040if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1041 && let ty::ClauseKind::Projection(projection_pred) = clause1042 {
1043p.kind()
1044 .rebind(ty::ProjectionPredicate {
1045 projection_term: projection_pred.projection_term.fold_with(self),
1046// Don't fold the term on the RHS of the projection predicate.
1047 // This is because for default trait methods with RPITITs, we
1048 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1049 // predicate, which would trivially cause a cycle when we do
1050 // anything that requires `TypingEnv::with_post_analysis_normalized`.
1051term: projection_pred.term,
1052 })
1053 .upcast(self.tcx)
1054 } else {
1055p.super_fold_with(self)
1056 }
1057 }
1058}
10591060struct FreeAliasTypeExpander<'tcx> {
1061 tcx: TyCtxt<'tcx>,
1062 depth: usize,
1063}
10641065impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1066fn cx(&self) -> TyCtxt<'tcx> {
1067self.tcx
1068 }
10691070fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1071if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1072return ty;
1073 }
1074let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() else {
1075return ty.super_fold_with(self);
1076 };
1077if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1078let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1079return Ty::new_error(self.tcx, guar);
1080 }
10811082self.depth += 1;
1083let ty = ensure_sufficient_stack(|| {
1084self.tcx
1085 .type_of(def_id)
1086 .instantiate(self.tcx, args)
1087 .skip_normalization()
1088 .fold_with(self)
1089 });
1090self.depth -= 1;
1091ty1092 }
10931094fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1095if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1096return ct;
1097 }
1098ct.super_fold_with(self)
1099 }
1100}
11011102impl<'tcx> Ty<'tcx> {
1103/// Returns the `Size` for primitive types (bool, uint, int, char, float).
1104pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1105match *self.kind() {
1106 ty::Bool => Size::from_bytes(1),
1107 ty::Char => Size::from_bytes(4),
1108 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1109 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1110 ty::Float(fty) => Float::from_float_ty(fty).size(),
1111_ => crate::util::bug::bug_fmt(format_args!("non primitive type"))bug!("non primitive type"),
1112 }
1113 }
11141115pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1116match *self.kind() {
1117 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1118 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1119_ => crate::util::bug::bug_fmt(format_args!("non integer discriminant"))bug!("non integer discriminant"),
1120 }
1121 }
11221123/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1124 /// returns `None` if the type is not numeric.
1125pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1126use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1127Some(match self.kind() {
1128 ty::Int(_) | ty::Uint(_) => {
1129let (size, signed) = self.int_size_and_signed(tcx);
1130let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1131let max =
1132if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1133 (min, max)
1134 }
1135 ty::Char => (0, std::char::MAXas u128),
1136 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1137 ty::Float(ty::FloatTy::F32) => {
1138 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1139 }
1140 ty::Float(ty::FloatTy::F64) => {
1141 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1142 }
1143 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1144_ => return None,
1145 })
1146 }
11471148/// Returns the maximum value for the given numeric type (including `char`s)
1149 /// or returns `None` if the type is not numeric.
1150pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1151let typing_env = TypingEnv::fully_monomorphized();
1152self.numeric_min_and_max_as_bits(tcx)
1153 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1154 }
11551156/// Returns the minimum value for the given numeric type (including `char`s)
1157 /// or returns `None` if the type is not numeric.
1158pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1159let typing_env = TypingEnv::fully_monomorphized();
1160self.numeric_min_and_max_as_bits(tcx)
1161 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1162 }
11631164/// Checks whether values of this type `T` have a size known at
1165 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1166 /// for the purposes of this check, so it can be an
1167 /// over-approximation in generic contexts, where one can have
1168 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1169 /// actually carry lifetime requirements.
1170pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1171self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1172 || tcx.is_sized_raw(typing_env.as_query_input(self))
1173 }
11741175/// Checks whether values of this type `T` implement the `Freeze`
1176 /// trait -- frozen types are those that do not contain an
1177 /// `UnsafeCell` anywhere. This is a language concept used to
1178 /// distinguish "true immutability", which is relevant to
1179 /// optimization as well as the rules around static values. Note
1180 /// that the `Freeze` trait is not exposed to end users and is
1181 /// effectively an implementation detail.
1182pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1183self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1184 }
11851186/// Fast path helper for testing if a type is `Freeze`.
1187 ///
1188 /// Returning true means the type is known to be `Freeze`. Returning
1189 /// `false` means nothing -- could be `Freeze`, might not be.
1190pub fn is_trivially_freeze(self) -> bool {
1191match self.kind() {
1192 ty::Int(_)
1193 | ty::Uint(_)
1194 | ty::Float(_)
1195 | ty::Bool1196 | ty::Char1197 | ty::Str1198 | ty::Never1199 | ty::Ref(..)
1200 | ty::RawPtr(_, _)
1201 | ty::FnDef(..)
1202 | ty::Error(_)
1203 | ty::FnPtr(..) => true,
1204 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1205 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1206 ty::Adt(..)
1207 | ty::Bound(..)
1208 | ty::Closure(..)
1209 | ty::CoroutineClosure(..)
1210 | ty::Dynamic(..)
1211 | ty::Foreign(_)
1212 | ty::Coroutine(..)
1213 | ty::CoroutineWitness(..)
1214 | ty::UnsafeBinder(_)
1215 | ty::Infer(_)
1216 | ty::Alias(..)
1217 | ty::Param(_)
1218 | ty::Placeholder(_) => false,
1219 }
1220 }
12211222/// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1223pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1224self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1225 }
12261227/// Checks whether values of this type `T` implement the `Unpin` trait.
1228 ///
1229 /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1230 /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1231 /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1232pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1233self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1234 }
12351236/// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1237 ///
1238 /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1239 /// `false` means nothing -- could be `Unpin`, might not be.
1240fn is_trivially_unpin(self) -> bool {
1241match self.kind() {
1242 ty::Int(_)
1243 | ty::Uint(_)
1244 | ty::Float(_)
1245 | ty::Bool1246 | ty::Char1247 | ty::Str1248 | ty::Never1249 | ty::Ref(..)
1250 | ty::RawPtr(_, _)
1251 | ty::FnDef(..)
1252 | ty::Error(_)
1253 | ty::FnPtr(..) => true,
1254 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1255 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1256 ty::Adt(..)
1257 | ty::Bound(..)
1258 | ty::Closure(..)
1259 | ty::CoroutineClosure(..)
1260 | ty::Dynamic(..)
1261 | ty::Foreign(_)
1262 | ty::Coroutine(..)
1263 | ty::CoroutineWitness(..)
1264 | ty::UnsafeBinder(_)
1265 | ty::Infer(_)
1266 | ty::Alias(..)
1267 | ty::Param(_)
1268 | ty::Placeholder(_) => false,
1269 }
1270 }
12711272/// Checks whether this type is an ADT that has unsafe fields.
1273pub fn has_unsafe_fields(self) -> bool {
1274if let ty::Adt(adt_def, ..) = self.kind() {
1275adt_def.all_fields().any(|x| x.safety.is_unsafe())
1276 } else {
1277false
1278}
1279 }
12801281/// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1282pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1283 !self.is_trivially_not_async_drop()
1284 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1285 }
12861287/// Fast path helper for testing if a type is `AsyncDrop`.
1288 ///
1289 /// Returning true means the type is known to be `!AsyncDrop`. Returning
1290 /// `false` means nothing -- could be `AsyncDrop`, might not be.
1291fn is_trivially_not_async_drop(self) -> bool {
1292match self.kind() {
1293 ty::Int(_)
1294 | ty::Uint(_)
1295 | ty::Float(_)
1296 | ty::Bool1297 | ty::Char1298 | ty::Str1299 | ty::Never1300 | ty::Ref(..)
1301 | ty::RawPtr(..)
1302 | ty::FnDef(..)
1303 | ty::Error(_)
1304 | ty::FnPtr(..) => true,
1305// FIXME(unsafe_binders):
1306 ty::UnsafeBinder(_) => ::core::panicking::panic("not implemented")unimplemented!(),
1307 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1308 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1309elem_ty.is_trivially_not_async_drop()
1310 }
1311 ty::Adt(..)
1312 | ty::Bound(..)
1313 | ty::Closure(..)
1314 | ty::CoroutineClosure(..)
1315 | ty::Dynamic(..)
1316 | ty::Foreign(_)
1317 | ty::Coroutine(..)
1318 | ty::CoroutineWitness(..)
1319 | ty::Infer(_)
1320 | ty::Alias(..)
1321 | ty::Param(_)
1322 | ty::Placeholder(_) => false,
1323 }
1324 }
13251326/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1327 /// non-copy and *might* have a destructor attached; if it returns
1328 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1329 ///
1330 /// (Note that this implies that if `ty` has a destructor attached,
1331 /// then `needs_drop` will definitely return `true` for `ty`.)
1332 ///
1333 /// Note that this method is used to check eligible types in unions.
1334#[inline]
1335pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1336// Avoid querying in simple cases.
1337match needs_drop_components(tcx, self) {
1338Err(AlwaysRequiresDrop) => true,
1339Ok(components) => {
1340let query_ty = match *components {
1341 [] => return false,
1342// If we've got a single component, call the query with that
1343 // to increase the chance that we hit the query cache.
1344[component_ty] => component_ty,
1345_ => self,
1346 };
13471348// This doesn't depend on regions, so try to minimize distinct
1349 // query keys used. If normalization fails, we just use `query_ty`.
1350if true {
if !!typing_env.param_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.param_env.has_infer()")
};
};debug_assert!(!typing_env.param_env.has_infer());
1351let query_ty = tcx1352 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1353 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13541355tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1356 }
1357 }
1358 }
13591360/// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1361 /// non-copy and *might* have a async destructor attached; if it returns
1362 /// `false`, then `ty` definitely has no async destructor (i.e., no async
1363 /// drop glue).
1364 ///
1365 /// (Note that this implies that if `ty` has an async destructor attached,
1366 /// then `needs_async_drop` will definitely return `true` for `ty`.)
1367 ///
1368// FIXME(zetanumbers): Note that this method is used to check eligible types
1369 // in unions.
1370#[inline]
1371pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1372// Avoid querying in simple cases.
1373match needs_drop_components(tcx, self) {
1374Err(AlwaysRequiresDrop) => true,
1375Ok(components) => {
1376let query_ty = match *components {
1377 [] => return false,
1378// If we've got a single component, call the query with that
1379 // to increase the chance that we hit the query cache.
1380[component_ty] => component_ty,
1381_ => self,
1382 };
13831384// This doesn't depend on regions, so try to minimize distinct
1385 // query keys used.
1386 // If normalization fails, we just use `query_ty`.
1387if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1388let query_ty = tcx1389 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1390 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13911392tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1393 }
1394 }
1395 }
13961397/// Checks if `ty` has a significant drop.
1398 ///
1399 /// Note that this method can return false even if `ty` has a destructor
1400 /// attached; even if that is the case then the adt has been marked with
1401 /// the attribute `rustc_insignificant_dtor`.
1402 ///
1403 /// Note that this method is used to check for change in drop order for
1404 /// 2229 drop reorder migration analysis.
1405#[inline]
1406pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1407// Avoid querying in simple cases.
1408match needs_drop_components(tcx, self) {
1409Err(AlwaysRequiresDrop) => true,
1410Ok(components) => {
1411let query_ty = match *components {
1412 [] => return false,
1413// If we've got a single component, call the query with that
1414 // to increase the chance that we hit the query cache.
1415[component_ty] => component_ty,
1416_ => self,
1417 };
14181419// FIXME
1420 // We should be canonicalizing, or else moving this to a method of inference
1421 // context, or *something* like that,
1422 // but for now just avoid passing inference variables
1423 // to queries that can't cope with them.
1424 // Instead, conservatively return "true" (may change drop order).
1425if query_ty.has_infer() {
1426return true;
1427 }
14281429// This doesn't depend on regions, so try to minimize distinct
1430 // query keys used.
1431 // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1432tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1433 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1434 .unwrap_or(true)
1435 }
1436 }
1437 }
14381439/// Returns `true` if equality for this type is both reflexive and structural.
1440 ///
1441 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1442 ///
1443 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1444 /// types, equality for the type as a whole is structural when it is the same as equality
1445 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1446 /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1447 ///
1448 /// This function is "shallow" because it may return `true` for a composite type whose fields
1449 /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1450 /// because equality for arrays is determined by the equality of each array element. If you
1451 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1452 /// down, you will need to use a type visitor.
1453#[inline]
1454pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1455match self.kind() {
1456// Look for an impl of `StructuralPartialEq`.
1457ty::Adt(..) => tcx.has_structural_eq_impl(self),
14581459// Primitive types that satisfy `Eq`.
1460ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
14611462// Composite types that satisfy `Eq` when all of their fields do.
1463 //
1464 // Because this function is "shallow", we return `true` for these composites regardless
1465 // of the type(s) contained within.
1466ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
14671468// Raw pointers use bitwise comparison.
1469ty::RawPtr(_, _) | ty::FnPtr(..) => true,
14701471// Floating point numbers are not `Eq`.
1472ty::Float(_) => false,
14731474// Conservatively return `false` for all others...
14751476 // Anonymous function types
1477ty::FnDef(..)
1478 | ty::Closure(..)
1479 | ty::CoroutineClosure(..)
1480 | ty::Dynamic(..)
1481 | ty::Coroutine(..) => false,
14821483// Generic or inferred types
1484 //
1485 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1486 // called for known, fully-monomorphized types.
1487ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1488false
1489}
14901491 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1492 }
1493 }
14941495/// Peel off all reference types in this type until there are none left.
1496 ///
1497 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1498 ///
1499 /// # Examples
1500 ///
1501 /// - `u8` -> `u8`
1502 /// - `&'a mut u8` -> `u8`
1503 /// - `&'a &'b u8` -> `u8`
1504 /// - `&'a *const &'b u8 -> *const &'b u8`
1505pub fn peel_refs(self) -> Ty<'tcx> {
1506let mut ty = self;
1507while let ty::Ref(_, inner_ty, _) = ty.kind() {
1508 ty = *inner_ty;
1509 }
1510ty1511 }
1512}
15131514/// Returns a list of types such that the given type needs drop if and only if
1515/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1516/// this type always needs drop.
1517//
1518// FIXME(zetanumbers): consider replacing this with only
1519// `needs_drop_components_with_async`
1520#[inline]
1521pub fn needs_drop_components<'tcx>(
1522 tcx: TyCtxt<'tcx>,
1523 ty: Ty<'tcx>,
1524) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1525needs_drop_components_with_async(tcx, ty, Asyncness::No)
1526}
15271528/// Returns a list of types such that the given type needs drop if and only if
1529/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1530/// this type always needs drop.
1531pub fn needs_drop_components_with_async<'tcx>(
1532 tcx: TyCtxt<'tcx>,
1533 ty: Ty<'tcx>,
1534 asyncness: Asyncness,
1535) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1536match *ty.kind() {
1537 ty::Infer(ty::FreshIntTy(_))
1538 | ty::Infer(ty::FreshFloatTy(_))
1539 | ty::Bool1540 | ty::Int(_)
1541 | ty::Uint(_)
1542 | ty::Float(_)
1543 | ty::Never1544 | ty::FnDef(..)
1545 | ty::FnPtr(..)
1546 | ty::Char1547 | ty::RawPtr(_, _)
1548 | ty::Ref(..)
1549 | ty::Str => Ok(SmallVec::new()),
15501551// Foreign types can never have destructors.
1552ty::Foreign(..) => Ok(SmallVec::new()),
15531554// FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1555ty::Dynamic(..) | ty::Error(_) => {
1556if asyncness.is_async() {
1557Ok(SmallVec::new())
1558 } else {
1559Err(AlwaysRequiresDrop)
1560 }
1561 }
15621563 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1564 ty::Array(elem_ty, size) => {
1565match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1566Ok(v) if v.is_empty() => Ok(v),
1567 res => match size.try_to_target_usize(tcx) {
1568// Arrays of size zero don't need drop, even if their element
1569 // type does.
1570Some(0) => Ok(SmallVec::new()),
1571Some(_) => res,
1572// We don't know which of the cases above we are in, so
1573 // return the whole type and let the caller decide what to
1574 // do.
1575None => Ok({
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(ty);
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ty])))
}
}smallvec![ty]),
1576 },
1577 }
1578 }
1579// If any field needs drop, then the whole tuple does.
1580ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1581acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1582Ok(acc)
1583 }),
15841585// These require checking for `Copy` bounds or `Adt` destructors.
1586ty::Adt(..)
1587 | ty::Alias(..)
1588 | ty::Param(_)
1589 | ty::Bound(..)
1590 | ty::Placeholder(..)
1591 | ty::Infer(_)
1592 | ty::Closure(..)
1593 | ty::CoroutineClosure(..)
1594 | ty::Coroutine(..)
1595 | ty::CoroutineWitness(..)
1596 | ty::UnsafeBinder(_) => Ok({
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(ty);
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ty])))
}
}smallvec![ty]),
1597 }
1598}
15991600/// Does the equivalent of
1601/// ```ignore (illustrative)
1602/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1603/// folder.tcx().intern_*(&v)
1604/// ```
1605pub fn fold_list<'tcx, F, L, T>(
1606 list: L,
1607 folder: &mut F,
1608 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1609) -> L
1610where
1611F: TypeFolder<TyCtxt<'tcx>>,
1612 L: AsRef<[T]>,
1613 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1614{
1615let slice = list.as_ref();
1616let mut iter = slice.iter().copied();
1617// Look for the first element that changed
1618match iter.by_ref().enumerate().find_map(|(i, t)| {
1619let new_t = t.fold_with(folder);
1620if new_t != t { Some((i, new_t)) } else { None }
1621 }) {
1622Some((i, new_t)) => {
1623// An element changed, prepare to intern the resulting list
1624let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1625new_list.extend_from_slice(&slice[..i]);
1626new_list.push(new_t);
1627for t in iter {
1628 new_list.push(t.fold_with(folder))
1629 }
1630intern(folder.cx(), &new_list)
1631 }
1632None => list,
1633 }
1634}
16351636/// Does the equivalent of
1637/// ```ignore (illustrative)
1638/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1639/// folder.tcx().intern_*(&v)
1640/// ```
1641pub fn try_fold_list<'tcx, F, L, T>(
1642 list: L,
1643 folder: &mut F,
1644 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1645) -> Result<L, F::Error>
1646where
1647F: FallibleTypeFolder<TyCtxt<'tcx>>,
1648 L: AsRef<[T]>,
1649 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1650{
1651let slice = list.as_ref();
1652let mut iter = slice.iter().copied();
1653// Look for the first element that changed
1654match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1655Ok(new_t) if new_t == t => None,
1656 new_t => Some((i, new_t)),
1657 }) {
1658Some((i, Ok(new_t))) => {
1659// An element changed, prepare to intern the resulting list
1660let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1661new_list.extend_from_slice(&slice[..i]);
1662new_list.push(new_t);
1663for t in iter {
1664 new_list.push(t.try_fold_with(folder)?)
1665 }
1666Ok(intern(folder.cx(), &new_list))
1667 }
1668Some((_, Err(err))) => {
1669return Err(err);
1670 }
1671None => Ok(list),
1672 }
1673}
16741675#[derive(#[automatically_derived]
impl ::core::marker::Copy for AlwaysRequiresDrop { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AlwaysRequiresDrop {
#[inline]
fn clone(&self) -> AlwaysRequiresDrop { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AlwaysRequiresDrop {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "AlwaysRequiresDrop")
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
AlwaysRequiresDrop {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self { AlwaysRequiresDrop => {} }
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for AlwaysRequiresDrop {
fn encode(&self, __encoder: &mut __E) {
match *self { AlwaysRequiresDrop => {} }
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for AlwaysRequiresDrop {
fn decode(__decoder: &mut __D) -> Self { AlwaysRequiresDrop }
}
};TyDecodable)]
1676pub struct AlwaysRequiresDrop;
16771678/// Reveals all opaque types in the given value, replacing them
1679/// with their underlying types.
1680pub fn reveal_opaque_types_in_bounds<'tcx>(
1681 tcx: TyCtxt<'tcx>,
1682 val: ty::Clauses<'tcx>,
1683) -> ty::Clauses<'tcx> {
1684if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1685let mut visitor = OpaqueTypeExpander {
1686 seen_opaque_tys: FxHashSet::default(),
1687 expanded_cache: FxHashMap::default(),
1688 primary_def_id: None,
1689 found_recursion: false,
1690 found_any_recursion: false,
1691 check_recursion: false,
1692tcx,
1693 };
1694val.fold_with(&mut visitor)
1695}
16961697/// Determines whether an item is directly annotated with `doc(hidden)`.
1698fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1699{
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Doc(doc)) if
doc.hidden.is_some() => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, Doc(doc) if doc.hidden.is_some())1700}
17011702/// Determines whether an item is annotated with `doc(notable_trait)`.
1703pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1704{
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Doc(doc)) if
doc.notable_trait.is_some() => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, Doc(doc) if doc.notable_trait.is_some())1705}
17061707/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1708///
1709/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1710/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1711/// cause an ICE that we otherwise may want to prevent.
1712pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1713if tcx.features().intrinsics() && {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcIntrinsic) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcIntrinsic) {
1714let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1715 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1716 !has_body1717 }
1718_ => true,
1719 };
1720Some(ty::IntrinsicDef {
1721 name: tcx.item_name(def_id),
1722must_be_overridden,
1723 const_stable: {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcIntrinsicConstStableIndirect)
=> {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcIntrinsicConstStableIndirect),
1724 })
1725 } else {
1726None1727 }
1728}
17291730pub fn provide(providers: &mut Providers) {
1731*providers = Providers {
1732reveal_opaque_types_in_bounds,
1733is_doc_hidden,
1734is_doc_notable_trait,
1735intrinsic_raw,
1736 ..*providers1737 }
1738}