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_hasher::{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> {
219let tcx = self;
220tcx.struct_tail_raw(
221ty,
222&ObligationCause::dummy(),
223 |ty| tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(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(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 = 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 ty::Alias(..) => {
305let normalized = normalize(ty);
306if ty == normalized {
307return ty;
308 } else {
309 ty = normalized;
310 }
311 }
312313_ => {
314break;
315 }
316 }
317 }
318ty319 }
320321/// Same as applying `struct_tail` on `source` and `target`, but only
322 /// keeps going as long as the two types are instances of the same
323 /// structure definitions.
324 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
325 /// whereas struct_tail produces `T`, and `Trait`, respectively.
326 ///
327 /// Should only be called if the types have no inference variables and do
328 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
329 /// normalization attempt may cause compiler bugs.
330pub fn struct_lockstep_tails_for_codegen(
331self,
332 source: Ty<'tcx>,
333 target: Ty<'tcx>,
334 typing_env: ty::TypingEnv<'tcx>,
335 ) -> (Ty<'tcx>, Ty<'tcx>) {
336let tcx = self;
337tcx.struct_lockstep_tails_raw(source, target, |ty| {
338tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty))
339 })
340 }
341342/// Same as applying `struct_tail` on `source` and `target`, but only
343 /// keeps going as long as the two types are instances of the same
344 /// structure definitions.
345 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
346 /// whereas struct_tail produces `T`, and `Trait`, respectively.
347 ///
348 /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
349 /// during codegen.
350pub fn struct_lockstep_tails_raw(
351self,
352 source: Ty<'tcx>,
353 target: Ty<'tcx>,
354 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
355 ) -> (Ty<'tcx>, Ty<'tcx>) {
356let (mut a, mut b) = (source, target);
357loop {
358match (a.kind(), b.kind()) {
359 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
360if a_def == b_def && a_def.is_struct() =>
361 {
362if let Some(f) = a_def.non_enum_variant().tail_opt() {
363a = f.ty(self, a_args);
364b = f.ty(self, b_args);
365 } else {
366break;
367 }
368 }
369 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
370if let Some(&a_last) = a_tys.last() {
371a = a_last;
372b = *b_tys.last().unwrap();
373 } else {
374break;
375 }
376 }
377 (ty::Alias(..), _) | (_, ty::Alias(..)) => {
378// If either side is a projection, attempt to
379 // progress via normalization. (Should be safe to
380 // apply to both sides as normalization is
381 // idempotent.)
382let a_norm = normalize(a);
383let b_norm = normalize(b);
384if a == a_norm && b == b_norm {
385break;
386 } else {
387a = a_norm;
388b = b_norm;
389 }
390 }
391392_ => break,
393 }
394 }
395 (a, b)
396 }
397398/// Calculate the destructor of a given type.
399pub fn calculate_dtor(
400self,
401 adt_did: LocalDefId,
402 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
403 ) -> Option<ty::Destructor> {
404let drop_trait = self.lang_items().drop_trait()?;
405self.ensure_result().coherent_trait(drop_trait).ok()?;
406407let mut dtor_candidate = None;
408// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
409for &impl_did in self.local_trait_impls(drop_trait) {
410let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
411if adt_def.did() != adt_did.to_def_id() {
412continue;
413 }
414415if validate(self, impl_did).is_err() {
416// Already `ErrorGuaranteed`, no need to delay a span bug here.
417continue;
418 }
419420let Some(&item_id) = self.associated_item_def_ids(impl_did).first() else {
421self.dcx()
422 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
423continue;
424 };
425426if self.def_kind(item_id) != DefKind::AssocFn {
427self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
428continue;
429 }
430431if let Some(old_item_id) = dtor_candidate {
432self.dcx()
433 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
434 .with_span_note(self.def_span(old_item_id), "other impl here")
435 .delay_as_bug();
436 }
437438 dtor_candidate = Some(item_id);
439 }
440441let did = dtor_candidate?;
442Some(ty::Destructor { did })
443 }
444445/// Calculate the async destructor of a given type.
446pub fn calculate_async_dtor(
447self,
448 adt_did: LocalDefId,
449 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
450 ) -> Option<ty::AsyncDestructor> {
451let async_drop_trait = self.lang_items().async_drop_trait()?;
452self.ensure_result().coherent_trait(async_drop_trait).ok()?;
453454let mut dtor_candidate = None;
455// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
456for &impl_did in self.local_trait_impls(async_drop_trait) {
457let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
458if adt_def.did() != adt_did.to_def_id() {
459continue;
460 }
461462if validate(self, impl_did).is_err() {
463// Already `ErrorGuaranteed`, no need to delay a span bug here.
464continue;
465 }
466467if let Some(old_impl_did) = dtor_candidate {
468self.dcx()
469 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
470 .with_span_note(self.def_span(old_impl_did), "other impl here")
471 .delay_as_bug();
472 }
473474 dtor_candidate = Some(impl_did);
475 }
476477Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
478 }
479480/// Returns the set of types that are required to be alive in
481 /// order to run the destructor of `def` (see RFCs 769 and
482 /// 1238).
483 ///
484 /// Note that this returns only the constraints for the
485 /// destructor of `def` itself. For the destructors of the
486 /// contents, you need `adt_dtorck_constraint`.
487pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
488let dtor = match def.destructor(self) {
489None => {
490{
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:490",
"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(490u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("destructor_constraints({0:?}) - no dtor",
def.did()) as &dyn Value))])
});
} else { ; }
};debug!("destructor_constraints({:?}) - no dtor", def.did());
491return ::alloc::vec::Vec::new()vec![];
492 }
493Some(dtor) => dtor.did,
494 };
495496let impl_def_id = self.parent(dtor);
497let impl_generics = self.generics_of(impl_def_id);
498499// We have a destructor - all the parameters that are not
500 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
501 // must be live.
502503 // We need to return the list of parameters from the ADTs
504 // generics/args that correspond to impure parameters on the
505 // impl's generics. This is a bit ugly, but conceptually simple:
506 //
507 // Suppose our ADT looks like the following
508 //
509 // struct S<X, Y, Z>(X, Y, Z);
510 //
511 // and the impl is
512 //
513 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
514 //
515 // We want to return the parameters (X, Y). For that, we match
516 // up the item-args <X, Y, Z> with the args on the impl ADT,
517 // <P1, P2, P0>, and then look up which of the impl args refer to
518 // parameters marked as pure.
519520let impl_args =
521match *self.type_of(impl_def_id).instantiate_identity().skip_norm_wip().kind() {
522 ty::Adt(def_, args) if def_ == def => args,
523_ => crate::util::bug::span_bug_fmt(self.def_span(impl_def_id),
format_args!("expected ADT for self type of `Drop` impl"))span_bug!(
524self.def_span(impl_def_id),
525"expected ADT for self type of `Drop` impl"
526),
527 };
528529let item_args = ty::GenericArgs::identity_for_item(self, def.did());
530531let result = iter::zip(item_args, impl_args)
532 .filter(|&(_, arg)| {
533match arg.kind() {
534GenericArgKind::Lifetime(region) => match region.kind() {
535 ty::ReEarlyParam(ebr) => {
536 !impl_generics.region_param(ebr, self).pure_wrt_drop
537 }
538// Error: not a region param
539_ => false,
540 },
541GenericArgKind::Type(ty) => match *ty.kind() {
542 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
543// Error: not a type param
544_ => false,
545 },
546GenericArgKind::Const(ct) => match ct.kind() {
547 ty::ConstKind::Param(pc) => {
548 !impl_generics.const_param(pc, self).pure_wrt_drop
549 }
550// Error: not a const param
551_ => false,
552 },
553 }
554 })
555 .map(|(item_param, _)| item_param)
556 .collect();
557{
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:557",
"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(557u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("destructor_constraint({0:?}) = {1:?}",
def.did(), result) as &dyn Value))])
});
} else { ; }
};debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
558result559 }
560561/// Checks whether each generic argument is simply a unique generic parameter.
562pub fn uses_unique_generic_params(
563self,
564 args: &[ty::GenericArg<'tcx>],
565 ignore_regions: CheckRegions,
566 ) -> Result<(), NotUniqueParam<'tcx>> {
567let mut seen = GrowableBitSet::default();
568let mut seen_late = FxHashSet::default();
569for arg in args {
570match arg.kind() {
571 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
572 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
573if !seen_late.insert((di, reg)) {
574return Err(NotUniqueParam::DuplicateParam(lt.into()));
575 }
576 }
577 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
578if !seen.insert(p.index) {
579return Err(NotUniqueParam::DuplicateParam(lt.into()));
580 }
581 }
582 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
583return Err(NotUniqueParam::NotParam(lt.into()));
584 }
585 (CheckRegions::No, _) => {}
586 },
587 GenericArgKind::Type(t) => match t.kind() {
588 ty::Param(p) => {
589if !seen.insert(p.index) {
590return Err(NotUniqueParam::DuplicateParam(t.into()));
591 }
592 }
593_ => return Err(NotUniqueParam::NotParam(t.into())),
594 },
595 GenericArgKind::Const(c) => match c.kind() {
596 ty::ConstKind::Param(p) => {
597if !seen.insert(p.index) {
598return Err(NotUniqueParam::DuplicateParam(c.into()));
599 }
600 }
601_ => return Err(NotUniqueParam::NotParam(c.into())),
602 },
603 }
604 }
605606Ok(())
607 }
608609/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
610 /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
611 /// have the same `DefKind`.
612 ///
613 /// Note that closures have a `DefId`, but the closure *expression* also has a
614 /// `HirId` that is located within the context where the closure appears. The
615 /// parent of the closure's `DefId` will also be the context where it appears.
616pub fn is_closure_like(self, def_id: DefId) -> bool {
617#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)618 }
619620/// Returns `true` if `def_id` refers to a definition that does not have its own
621 /// type-checking context, i.e. closure, coroutine or inline const.
622pub fn is_typeck_child(self, def_id: DefId) -> bool {
623self.def_kind(def_id).is_typeck_child()
624 }
625626/// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
627pub fn is_trait(self, def_id: DefId) -> bool {
628self.def_kind(def_id) == DefKind::Trait629 }
630631/// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
632 /// and `false` otherwise.
633pub fn is_trait_alias(self, def_id: DefId) -> bool {
634self.def_kind(def_id) == DefKind::TraitAlias635 }
636637/// Returns `true` if this `DefId` refers to the implicit constructor for
638 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
639pub fn is_constructor(self, def_id: DefId) -> bool {
640#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))641 }
642643/// Given the `DefId`, returns the `DefId` of the innermost item that
644 /// has its own type-checking context or "inference environment".
645 ///
646 /// For example, a closure has its own `DefId`, but it is type-checked
647 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
648 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
649pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
650let mut def_id = def_id;
651while self.is_typeck_child(def_id) {
652 def_id = self.parent(def_id);
653 }
654def_id655 }
656657/// Given the `LocalDefId`, returns the `LocalDefId` of the innermost item that
658 /// has its own type-checking context or "inference environment".
659 ///
660 /// For example, a closure has its own `LocalDefId`, but it is type-checked
661 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
662 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
663pub fn typeck_root_def_id_local(self, def_id: LocalDefId) -> LocalDefId {
664let mut def_id = def_id;
665while self.is_typeck_child(def_id.to_def_id()) {
666 def_id = self.local_parent(def_id);
667 }
668def_id669 }
670671/// Given the `DefId` and args a closure, creates the type of
672 /// `self` argument that the closure expects. For example, for a
673 /// `Fn` closure, this would return a reference type `&T` where
674 /// `T = closure_ty`.
675 ///
676 /// Returns `None` if this closure's kind has not yet been inferred.
677 /// This should only be possible during type checking.
678 ///
679 /// Note that the return value is a late-bound region and hence
680 /// wrapped in a binder.
681pub fn closure_env_ty(
682self,
683 closure_ty: Ty<'tcx>,
684 closure_kind: ty::ClosureKind,
685 env_region: ty::Region<'tcx>,
686 ) -> Ty<'tcx> {
687match closure_kind {
688 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
689 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
690 ty::ClosureKind::FnOnce => closure_ty,
691 }
692 }
693694/// Returns `true` if the node pointed to by `def_id` is a `static` item.
695#[inline]
696pub fn is_static(self, def_id: DefId) -> bool {
697#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })698 }
699700#[inline]
701pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
702if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
703Some(mutability)
704 } else {
705None706 }
707 }
708709/// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
710pub fn is_thread_local_static(self, def_id: DefId) -> bool {
711self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
712 }
713714/// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
715#[inline]
716pub fn is_mutable_static(self, def_id: DefId) -> bool {
717self.static_mutability(def_id) == Some(hir::Mutability::Mut)
718 }
719720/// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
721 /// thread local shim generated.
722#[inline]
723pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
724 !self.sess.target.dll_tls_export
725 && self.is_thread_local_static(def_id)
726 && !self.is_foreign_item(def_id)
727 }
728729/// Returns the type a reference to the thread local takes in MIR.
730pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
731let static_ty = self.type_of(def_id).instantiate_identity().skip_norm_wip();
732if self.is_mutable_static(def_id) {
733Ty::new_mut_ptr(self, static_ty)
734 } else if self.is_foreign_item(def_id) {
735Ty::new_imm_ptr(self, static_ty)
736 } else {
737// FIXME: These things don't *really* have 'static lifetime.
738Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
739 }
740 }
741742/// Get the type of the pointer to the static that we use in MIR.
743pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
744// Make sure that any constants in the static's type are evaluated.
745let static_ty =
746self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
747748// Make sure that accesses to unsafe statics end up using raw pointers.
749 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
750if self.is_mutable_static(def_id) {
751Ty::new_mut_ptr(self, static_ty)
752 } else if self.is_foreign_item(def_id) {
753Ty::new_imm_ptr(self, static_ty)
754 } else {
755Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
756 }
757 }
758759/// Expands the given impl trait type, stopping if the type is recursive.
760x;#[instrument(skip(self), level = "debug", ret)]761pub fn try_expand_impl_trait_type(
762self,
763 def_id: DefId,
764 args: GenericArgsRef<'tcx>,
765 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
766let mut visitor = OpaqueTypeExpander {
767 seen_opaque_tys: FxHashSet::default(),
768 expanded_cache: FxHashMap::default(),
769 primary_def_id: Some(def_id),
770 found_recursion: false,
771 found_any_recursion: false,
772 check_recursion: true,
773 tcx: self,
774 };
775776let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
777if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
778 }
779780/// Query and get an English description for the item's kind.
781pub fn def_descr(self, def_id: DefId) -> &'static str {
782self.def_kind_descr(self.def_kind(def_id), def_id)
783 }
784785/// Get an English description for the item's kind.
786pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
787match def_kind {
788 DefKind::AssocFnif self.associated_item(def_id).is_method() => "method",
789 DefKind::AssocTyif self.opt_rpitit_info(def_id).is_some() => "opaque type",
790 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
791match coroutine_kind {
792 hir::CoroutineKind::Desugared(
793 hir::CoroutineDesugaring::Async,
794 hir::CoroutineSource::Fn,
795 ) => "async fn",
796 hir::CoroutineKind::Desugared(
797 hir::CoroutineDesugaring::Async,
798 hir::CoroutineSource::Block,
799 ) => "async block",
800 hir::CoroutineKind::Desugared(
801 hir::CoroutineDesugaring::Async,
802 hir::CoroutineSource::Closure,
803 ) => "async closure",
804 hir::CoroutineKind::Desugared(
805 hir::CoroutineDesugaring::AsyncGen,
806 hir::CoroutineSource::Fn,
807 ) => "async gen fn",
808 hir::CoroutineKind::Desugared(
809 hir::CoroutineDesugaring::AsyncGen,
810 hir::CoroutineSource::Block,
811 ) => "async gen block",
812 hir::CoroutineKind::Desugared(
813 hir::CoroutineDesugaring::AsyncGen,
814 hir::CoroutineSource::Closure,
815 ) => "async gen closure",
816 hir::CoroutineKind::Desugared(
817 hir::CoroutineDesugaring::Gen,
818 hir::CoroutineSource::Fn,
819 ) => "gen fn",
820 hir::CoroutineKind::Desugared(
821 hir::CoroutineDesugaring::Gen,
822 hir::CoroutineSource::Block,
823 ) => "gen block",
824 hir::CoroutineKind::Desugared(
825 hir::CoroutineDesugaring::Gen,
826 hir::CoroutineSource::Closure,
827 ) => "gen closure",
828 hir::CoroutineKind::Coroutine(_) => "coroutine",
829 }
830 }
831_ => def_kind.descr(def_id),
832 }
833 }
834835/// Gets an English article for the [`TyCtxt::def_descr`].
836pub fn def_descr_article(self, def_id: DefId) -> &'static str {
837self.def_kind_descr_article(self.def_kind(def_id), def_id)
838 }
839840/// Gets an English article for the [`TyCtxt::def_kind_descr`].
841pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
842match def_kind {
843 DefKind::AssocFnif self.associated_item(def_id).is_method() => "a",
844 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
845match coroutine_kind {
846 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
847 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
848 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
849 hir::CoroutineKind::Coroutine(_) => "a",
850 }
851 }
852_ => def_kind.article(),
853 }
854 }
855856/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
857 /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
858 /// be shown in `impl` suggestions.
859 ///
860 /// [public]: TyCtxt::is_private_dep
861 /// [direct]: rustc_session::cstore::ExternCrate::is_direct
862pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
863// `#![rustc_private]` overrides defaults to make private dependencies usable.
864if self.features().enabled(sym::rustc_private) {
865return true;
866 }
867868// | Private | Direct | Visible | |
869 // |---------|--------|---------|--------------------|
870 // | Yes | Yes | Yes | !true || true |
871 // | No | Yes | Yes | !false || true |
872 // | Yes | No | No | !true || false |
873 // | No | No | Yes | !false || false |
874!self.is_private_dep(key)
875// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
876 // Treat that kind of crate as "indirect", since it's an implementation detail of
877 // the language.
878|| self.extern_crate(key).is_some_and(|e| e.is_direct())
879 }
880881/// Expand any [free alias types][free] contained within the given `value`.
882 ///
883 /// This should be used over other normalization routines in situations where
884 /// it's important not to normalize other alias types and where the predicates
885 /// on the corresponding type alias shouldn't be taken into consideration.
886 ///
887 /// Whenever possible **prefer not to use this function**! Instead, use standard
888 /// normalization routines or if feasible don't normalize at all.
889 ///
890 /// This function comes in handy if you want to mimic the behavior of eager
891 /// type alias expansion in a localized manner.
892 ///
893 /// <div class="warning">
894 /// This delays a bug on overflow! Therefore you need to be certain that the
895 /// contained types get fully normalized at a later stage. Note that even on
896 /// overflow all well-behaved free alias types get expanded correctly, so the
897 /// result is still useful.
898 /// </div>
899 ///
900 /// [free]: ty::Free
901pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
902value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
903 }
904905/// Peel off all [free alias types] in this type until there are none left.
906 ///
907 /// This only expands free alias types in “head” / outermost positions. It can
908 /// be used over [expand_free_alias_tys] as an optimization in situations where
909 /// one only really cares about the *kind* of the final aliased type but not
910 /// the types the other constituent types alias.
911 ///
912 /// <div class="warning">
913 /// This delays a bug on overflow! Therefore you need to be certain that the
914 /// type gets fully normalized at a later stage.
915 /// </div>
916 ///
917 /// [free]: ty::Free
918 /// [expand_free_alias_tys]: Self::expand_free_alias_tys
919pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
920let ty::Alias(ty::AliasTy { kind: ty::Free { .. }, .. }) = ty.kind() else { return ty };
921922let limit = self.recursion_limit();
923let mut depth = 0;
924925while let &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() {
926if !limit.value_within_limit(depth) {
927let guar = self.dcx().delayed_bug("overflow expanding free alias type");
928return Ty::new_error(self, guar);
929 }
930931 ty = self.type_of(def_id).instantiate(self, args).skip_norm_wip();
932 depth += 1;
933 }
934935ty936 }
937938// Computes the variances for an alias (opaque or RPITIT) that represent
939 // its (un)captured regions.
940pub fn opt_alias_variances(
941self,
942 kind: impl Into<ty::AliasTermKind<'tcx>>,
943 ) -> Option<&'tcx [ty::Variance]> {
944match kind.into() {
945 ty::AliasTermKind::ProjectionTy { def_id } => {
946if self.is_impl_trait_in_trait(def_id) {
947Some(self.variances_of(def_id))
948 } else {
949None950 }
951 }
952 ty::AliasTermKind::OpaqueTy { def_id } => Some(self.variances_of(def_id)),
953 ty::AliasTermKind::InherentTy { .. }
954 | ty::AliasTermKind::InherentConst { .. }
955 | ty::AliasTermKind::FreeTy { .. }
956 | ty::AliasTermKind::FreeConst { .. }
957 | ty::AliasTermKind::UnevaluatedConst { .. }
958 | ty::AliasTermKind::ProjectionConst { .. } => None,
959 }
960 }
961}
962963struct OpaqueTypeExpander<'tcx> {
964// Contains the DefIds of the opaque types that are currently being
965 // expanded. When we expand an opaque type we insert the DefId of
966 // that type, and when we finish expanding that type we remove the
967 // its DefId.
968seen_opaque_tys: FxHashSet<DefId>,
969// Cache of all expansions we've seen so far. This is a critical
970 // optimization for some large types produced by async fn trees.
971expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
972 primary_def_id: Option<DefId>,
973 found_recursion: bool,
974 found_any_recursion: bool,
975/// Whether or not to check for recursive opaque types.
976 /// This is `true` when we're explicitly checking for opaque type
977 /// recursion, and 'false' otherwise to avoid unnecessary work.
978check_recursion: bool,
979 tcx: TyCtxt<'tcx>,
980}
981982impl<'tcx> OpaqueTypeExpander<'tcx> {
983fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
984if self.found_any_recursion {
985return None;
986 }
987let args = args.fold_with(self);
988if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
989let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
990Some(expanded_ty) => *expanded_ty,
991None => {
992let generic_ty = self.tcx.type_of(def_id);
993let concrete_ty = generic_ty.instantiate(self.tcx, args).skip_norm_wip();
994let expanded_ty = self.fold_ty(concrete_ty);
995self.expanded_cache.insert((def_id, args), expanded_ty);
996expanded_ty997 }
998 };
999if self.check_recursion {
1000self.seen_opaque_tys.remove(&def_id);
1001 }
1002Some(expanded_ty)
1003 } else {
1004// If another opaque type that we contain is recursive, then it
1005 // will report the error, so we don't have to.
1006self.found_any_recursion = true;
1007self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1008None1009 }
1010 }
1011}
10121013impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1014fn cx(&self) -> TyCtxt<'tcx> {
1015self.tcx
1016 }
10171018fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1019if let ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *t.kind() {
1020self.expand_opaque_ty(def_id, args).unwrap_or(t)
1021 } else if t.has_opaque_types() {
1022t.super_fold_with(self)
1023 } else {
1024t1025 }
1026 }
10271028fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1029if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1030 && let ty::ClauseKind::Projection(projection_pred) = clause1031 {
1032p.kind()
1033 .rebind(ty::ProjectionPredicate {
1034 projection_term: projection_pred.projection_term.fold_with(self),
1035// Don't fold the term on the RHS of the projection predicate.
1036 // This is because for default trait methods with RPITITs, we
1037 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1038 // predicate, which would trivially cause a cycle when we do
1039 // anything that requires `TypingEnv::with_post_analysis_normalized`.
1040term: projection_pred.term,
1041 })
1042 .upcast(self.tcx)
1043 } else {
1044p.super_fold_with(self)
1045 }
1046 }
1047}
10481049struct FreeAliasTypeExpander<'tcx> {
1050 tcx: TyCtxt<'tcx>,
1051 depth: usize,
1052}
10531054impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1055fn cx(&self) -> TyCtxt<'tcx> {
1056self.tcx
1057 }
10581059fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1060if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1061return ty;
1062 }
1063let &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() else {
1064return ty.super_fold_with(self);
1065 };
1066if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1067let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1068return Ty::new_error(self.tcx, guar);
1069 }
10701071self.depth += 1;
1072let ty = ensure_sufficient_stack(|| {
1073self.tcx.type_of(def_id).instantiate(self.tcx, args).skip_norm_wip().fold_with(self)
1074 });
1075self.depth -= 1;
1076ty1077 }
10781079fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1080if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1081return ct;
1082 }
1083ct.super_fold_with(self)
1084 }
1085}
10861087impl<'tcx> Ty<'tcx> {
1088/// Returns the `Size` for primitive types (bool, uint, int, char, float).
1089pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1090match *self.kind() {
1091 ty::Bool => Size::from_bytes(1),
1092 ty::Char => Size::from_bytes(4),
1093 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1094 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1095 ty::Float(fty) => Float::from_float_ty(fty).size(),
1096_ => crate::util::bug::bug_fmt(format_args!("non primitive type"))bug!("non primitive type"),
1097 }
1098 }
10991100pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1101match *self.kind() {
1102 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1103 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1104_ => crate::util::bug::bug_fmt(format_args!("non integer discriminant"))bug!("non integer discriminant"),
1105 }
1106 }
11071108/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1109 /// returns `None` if the type is not numeric.
1110pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1111use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1112Some(match self.kind() {
1113 ty::Int(_) | ty::Uint(_) => {
1114let (size, signed) = self.int_size_and_signed(tcx);
1115let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1116let max =
1117if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1118 (min, max)
1119 }
1120 ty::Char => (0, std::char::MAXas u128),
1121 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1122 ty::Float(ty::FloatTy::F32) => {
1123 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1124 }
1125 ty::Float(ty::FloatTy::F64) => {
1126 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1127 }
1128 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1129_ => return None,
1130 })
1131 }
11321133/// Returns the maximum value for the given numeric type (including `char`s)
1134 /// or returns `None` if the type is not numeric.
1135pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1136let typing_env = TypingEnv::fully_monomorphized();
1137self.numeric_min_and_max_as_bits(tcx)
1138 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1139 }
11401141/// Returns the minimum value for the given numeric type (including `char`s)
1142 /// or returns `None` if the type is not numeric.
1143pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1144let typing_env = TypingEnv::fully_monomorphized();
1145self.numeric_min_and_max_as_bits(tcx)
1146 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1147 }
11481149/// Checks whether values of this type `T` have a size known at
1150 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1151 /// for the purposes of this check, so it can be an
1152 /// over-approximation in generic contexts, where one can have
1153 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1154 /// actually carry lifetime requirements.
1155pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1156self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1157 || tcx.is_sized_raw(typing_env.as_query_input(self))
1158 }
11591160/// Checks whether values of this type `T` implement the `Freeze`
1161 /// trait -- frozen types are those that do not contain an
1162 /// `UnsafeCell` anywhere. This is a language concept used to
1163 /// distinguish "true immutability", which is relevant to
1164 /// optimization as well as the rules around static values. Note
1165 /// that the `Freeze` trait is not exposed to end users and is
1166 /// effectively an implementation detail.
1167pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1168self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1169 }
11701171/// Fast path helper for testing if a type is `Freeze`.
1172 ///
1173 /// Returning true means the type is known to be `Freeze`. Returning
1174 /// `false` means nothing -- could be `Freeze`, might not be.
1175pub fn is_trivially_freeze(self) -> bool {
1176match self.kind() {
1177 ty::Int(_)
1178 | ty::Uint(_)
1179 | ty::Float(_)
1180 | ty::Bool1181 | ty::Char1182 | ty::Str1183 | ty::Never1184 | ty::Ref(..)
1185 | ty::RawPtr(_, _)
1186 | ty::FnDef(..)
1187 | ty::Error(_)
1188 | ty::FnPtr(..) => true,
1189 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1190 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1191 ty::Adt(..)
1192 | ty::Bound(..)
1193 | ty::Closure(..)
1194 | ty::CoroutineClosure(..)
1195 | ty::Dynamic(..)
1196 | ty::Foreign(_)
1197 | ty::Coroutine(..)
1198 | ty::CoroutineWitness(..)
1199 | ty::UnsafeBinder(_)
1200 | ty::Infer(_)
1201 | ty::Alias(..)
1202 | ty::Param(_)
1203 | ty::Placeholder(_) => false,
1204 }
1205 }
12061207/// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1208pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1209self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1210 }
12111212/// Checks whether values of this type `T` implement the `Unpin` trait.
1213 ///
1214 /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1215 /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1216 /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1217pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1218self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1219 }
12201221/// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1222 ///
1223 /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1224 /// `false` means nothing -- could be `Unpin`, might not be.
1225fn is_trivially_unpin(self) -> bool {
1226match self.kind() {
1227 ty::Int(_)
1228 | ty::Uint(_)
1229 | ty::Float(_)
1230 | ty::Bool1231 | ty::Char1232 | ty::Str1233 | ty::Never1234 | ty::Ref(..)
1235 | ty::RawPtr(_, _)
1236 | ty::FnDef(..)
1237 | ty::Error(_)
1238 | ty::FnPtr(..) => true,
1239 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1240 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1241 ty::Adt(..)
1242 | ty::Bound(..)
1243 | ty::Closure(..)
1244 | ty::CoroutineClosure(..)
1245 | ty::Dynamic(..)
1246 | ty::Foreign(_)
1247 | ty::Coroutine(..)
1248 | ty::CoroutineWitness(..)
1249 | ty::UnsafeBinder(_)
1250 | ty::Infer(_)
1251 | ty::Alias(..)
1252 | ty::Param(_)
1253 | ty::Placeholder(_) => false,
1254 }
1255 }
12561257/// Checks whether this type is an ADT that has unsafe fields.
1258pub fn has_unsafe_fields(self) -> bool {
1259if let ty::Adt(adt_def, ..) = self.kind() {
1260adt_def.all_fields().any(|x| x.safety.is_unsafe())
1261 } else {
1262false
1263}
1264 }
12651266/// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1267pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1268 !self.is_trivially_not_async_drop()
1269 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1270 }
12711272/// Fast path helper for testing if a type is `AsyncDrop`.
1273 ///
1274 /// Returning true means the type is known to be `!AsyncDrop`. Returning
1275 /// `false` means nothing -- could be `AsyncDrop`, might not be.
1276fn is_trivially_not_async_drop(self) -> bool {
1277match self.kind() {
1278 ty::Int(_)
1279 | ty::Uint(_)
1280 | ty::Float(_)
1281 | ty::Bool1282 | ty::Char1283 | ty::Str1284 | ty::Never1285 | ty::Ref(..)
1286 | ty::RawPtr(..)
1287 | ty::FnDef(..)
1288 | ty::Error(_)
1289 | ty::FnPtr(..) => true,
1290// FIXME(unsafe_binders):
1291 ty::UnsafeBinder(_) => ::core::panicking::panic("not yet implemented")todo!(),
1292 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1293 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1294elem_ty.is_trivially_not_async_drop()
1295 }
1296 ty::Adt(..)
1297 | ty::Bound(..)
1298 | ty::Closure(..)
1299 | ty::CoroutineClosure(..)
1300 | ty::Dynamic(..)
1301 | ty::Foreign(_)
1302 | ty::Coroutine(..)
1303 | ty::CoroutineWitness(..)
1304 | ty::Infer(_)
1305 | ty::Alias(..)
1306 | ty::Param(_)
1307 | ty::Placeholder(_) => false,
1308 }
1309 }
13101311/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1312 /// non-copy and *might* have a destructor attached; if it returns
1313 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1314 ///
1315 /// (Note that this implies that if `ty` has a destructor attached,
1316 /// then `needs_drop` will definitely return `true` for `ty`.)
1317 ///
1318 /// Note that this method is used to check eligible types in unions.
1319#[inline]
1320pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1321// Avoid querying in simple cases.
1322match needs_drop_components(tcx, self) {
1323Err(AlwaysRequiresDrop) => true,
1324Ok(components) => {
1325let query_ty = match *components {
1326 [] => return false,
1327// If we've got a single component, call the query with that
1328 // to increase the chance that we hit the query cache.
1329[component_ty] => component_ty,
1330_ => self,
1331 };
13321333// This doesn't depend on regions, so try to minimize distinct
1334 // query keys used. If normalization fails, we just use `query_ty`.
1335if 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());
1336let query_ty = tcx1337 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1338 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13391340tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1341 }
1342 }
1343 }
13441345/// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1346 /// non-copy and *might* have a async destructor attached; if it returns
1347 /// `false`, then `ty` definitely has no async destructor (i.e., no async
1348 /// drop glue).
1349 ///
1350 /// (Note that this implies that if `ty` has an async destructor attached,
1351 /// then `needs_async_drop` will definitely return `true` for `ty`.)
1352 ///
1353// FIXME(zetanumbers): Note that this method is used to check eligible types
1354 // in unions.
1355#[inline]
1356pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1357// Avoid querying in simple cases.
1358match needs_drop_components(tcx, self) {
1359Err(AlwaysRequiresDrop) => true,
1360Ok(components) => {
1361let query_ty = match *components {
1362 [] => return false,
1363// If we've got a single component, call the query with that
1364 // to increase the chance that we hit the query cache.
1365[component_ty] => component_ty,
1366_ => self,
1367 };
13681369// This doesn't depend on regions, so try to minimize distinct
1370 // query keys used.
1371 // If normalization fails, we just use `query_ty`.
1372if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1373let query_ty = tcx1374 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1375 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13761377tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1378 }
1379 }
1380 }
13811382/// Checks if `ty` has a significant drop.
1383 ///
1384 /// Note that this method can return false even if `ty` has a destructor
1385 /// attached; even if that is the case then the adt has been marked with
1386 /// the attribute `rustc_insignificant_dtor`.
1387 ///
1388 /// Note that this method is used to check for change in drop order for
1389 /// 2229 drop reorder migration analysis.
1390#[inline]
1391pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1392// Avoid querying in simple cases.
1393match needs_drop_components(tcx, self) {
1394Err(AlwaysRequiresDrop) => true,
1395Ok(components) => {
1396let query_ty = match *components {
1397 [] => return false,
1398// If we've got a single component, call the query with that
1399 // to increase the chance that we hit the query cache.
1400[component_ty] => component_ty,
1401_ => self,
1402 };
14031404// FIXME
1405 // We should be canonicalizing, or else moving this to a method of inference
1406 // context, or *something* like that,
1407 // but for now just avoid passing inference variables
1408 // to queries that can't cope with them.
1409 // Instead, conservatively return "true" (may change drop order).
1410if query_ty.has_infer() {
1411return true;
1412 }
14131414// This doesn't depend on regions, so try to minimize distinct
1415 // query keys used.
1416 // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1417tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1418 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1419 .unwrap_or(true)
1420 }
1421 }
1422 }
14231424/// Returns `true` if equality for this type is both reflexive and structural.
1425 ///
1426 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1427 ///
1428 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1429 /// types, equality for the type as a whole is structural when it is the same as equality
1430 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1431 /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1432 ///
1433 /// This function is "shallow" because it may return `true` for a composite type whose fields
1434 /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1435 /// because equality for arrays is determined by the equality of each array element. If you
1436 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1437 /// down, you will need to use a type visitor.
1438#[inline]
1439pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1440match self.kind() {
1441// Look for an impl of `StructuralPartialEq`.
1442ty::Adt(..) => tcx.has_structural_eq_impl(self),
14431444// Primitive types that satisfy `Eq`.
1445ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
14461447// Composite types that satisfy `Eq` when all of their fields do.
1448 //
1449 // Because this function is "shallow", we return `true` for these composites regardless
1450 // of the type(s) contained within.
1451ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
14521453// Raw pointers use bitwise comparison.
1454ty::RawPtr(_, _) | ty::FnPtr(..) => true,
14551456// Floating point numbers are not `Eq`.
1457ty::Float(_) => false,
14581459// Conservatively return `false` for all others...
14601461 // Anonymous function types
1462ty::FnDef(..)
1463 | ty::Closure(..)
1464 | ty::CoroutineClosure(..)
1465 | ty::Dynamic(..)
1466 | ty::Coroutine(..) => false,
14671468// Generic or inferred types
1469 //
1470 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1471 // called for known, fully-monomorphized types.
1472ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1473false
1474}
14751476 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1477 }
1478 }
14791480/// Peel off all reference types in this type until there are none left.
1481 ///
1482 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1483 ///
1484 /// # Examples
1485 ///
1486 /// - `u8` -> `u8`
1487 /// - `&'a mut u8` -> `u8`
1488 /// - `&'a &'b u8` -> `u8`
1489 /// - `&'a *const &'b u8 -> *const &'b u8`
1490pub fn peel_refs(self) -> Ty<'tcx> {
1491let mut ty = self;
1492while let ty::Ref(_, inner_ty, _) = ty.kind() {
1493 ty = *inner_ty;
1494 }
1495ty1496 }
1497}
14981499/// Returns a list of types such that the given type needs drop if and only if
1500/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1501/// this type always needs drop.
1502//
1503// FIXME(zetanumbers): consider replacing this with only
1504// `needs_drop_components_with_async`
1505#[inline]
1506pub fn needs_drop_components<'tcx>(
1507 tcx: TyCtxt<'tcx>,
1508 ty: Ty<'tcx>,
1509) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1510needs_drop_components_with_async(tcx, ty, Asyncness::No)
1511}
15121513/// Returns a list of types such that the given type needs drop if and only if
1514/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1515/// this type always needs drop.
1516pub fn needs_drop_components_with_async<'tcx>(
1517 tcx: TyCtxt<'tcx>,
1518 ty: Ty<'tcx>,
1519 asyncness: Asyncness,
1520) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1521match *ty.kind() {
1522 ty::Infer(ty::FreshIntTy(_))
1523 | ty::Infer(ty::FreshFloatTy(_))
1524 | ty::Bool1525 | ty::Int(_)
1526 | ty::Uint(_)
1527 | ty::Float(_)
1528 | ty::Never1529 | ty::FnDef(..)
1530 | ty::FnPtr(..)
1531 | ty::Char1532 | ty::RawPtr(_, _)
1533 | ty::Ref(..)
1534 | ty::Str => Ok(SmallVec::new()),
15351536// Foreign types can never have destructors.
1537ty::Foreign(..) => Ok(SmallVec::new()),
15381539// FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1540ty::Dynamic(..) | ty::Error(_) => {
1541if asyncness.is_async() {
1542Ok(SmallVec::new())
1543 } else {
1544Err(AlwaysRequiresDrop)
1545 }
1546 }
15471548 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1549 ty::Array(elem_ty, size) => {
1550match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1551Ok(v) if v.is_empty() => Ok(v),
1552 res => match size.try_to_target_usize(tcx) {
1553// Arrays of size zero don't need drop, even if their element
1554 // type does.
1555Some(0) => Ok(SmallVec::new()),
1556Some(_) => res,
1557// We don't know which of the cases above we are in, so
1558 // return the whole type and let the caller decide what to
1559 // do.
1560None => 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]),
1561 },
1562 }
1563 }
1564// If any field needs drop, then the whole tuple does.
1565ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1566acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1567Ok(acc)
1568 }),
15691570// These require checking for `Copy` bounds or `Adt` destructors.
1571ty::Adt(..)
1572 | ty::Alias(..)
1573 | ty::Param(_)
1574 | ty::Bound(..)
1575 | ty::Placeholder(..)
1576 | ty::Infer(_)
1577 | ty::Closure(..)
1578 | ty::CoroutineClosure(..)
1579 | ty::Coroutine(..)
1580 | ty::CoroutineWitness(..)
1581 | 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]),
1582 }
1583}
15841585/// Does the equivalent of
1586/// ```ignore (illustrative)
1587/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1588/// folder.tcx().intern_*(&v)
1589/// ```
1590pub fn fold_list<'tcx, F, L, T>(
1591 list: L,
1592 folder: &mut F,
1593 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1594) -> L
1595where
1596F: TypeFolder<TyCtxt<'tcx>>,
1597 L: AsRef<[T]>,
1598 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1599{
1600let slice = list.as_ref();
1601let mut iter = slice.iter().copied();
1602// Look for the first element that changed
1603match iter.by_ref().enumerate().find_map(|(i, t)| {
1604let new_t = t.fold_with(folder);
1605if new_t != t { Some((i, new_t)) } else { None }
1606 }) {
1607Some((i, new_t)) => {
1608// An element changed, prepare to intern the resulting list
1609let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1610new_list.extend_from_slice(&slice[..i]);
1611new_list.push(new_t);
1612for t in iter {
1613 new_list.push(t.fold_with(folder))
1614 }
1615intern(folder.cx(), &new_list)
1616 }
1617None => list,
1618 }
1619}
16201621/// Does the equivalent of
1622/// ```ignore (illustrative)
1623/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1624/// folder.tcx().intern_*(&v)
1625/// ```
1626pub fn try_fold_list<'tcx, F, L, T>(
1627 list: L,
1628 folder: &mut F,
1629 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1630) -> Result<L, F::Error>
1631where
1632F: FallibleTypeFolder<TyCtxt<'tcx>>,
1633 L: AsRef<[T]>,
1634 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1635{
1636let slice = list.as_ref();
1637let mut iter = slice.iter().copied();
1638// Look for the first element that changed
1639match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1640Ok(new_t) if new_t == t => None,
1641 new_t => Some((i, new_t)),
1642 }) {
1643Some((i, Ok(new_t))) => {
1644// An element changed, prepare to intern the resulting list
1645let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1646new_list.extend_from_slice(&slice[..i]);
1647new_list.push(new_t);
1648for t in iter {
1649 new_list.push(t.try_fold_with(folder)?)
1650 }
1651Ok(intern(folder.cx(), &new_list))
1652 }
1653Some((_, Err(err))) => {
1654return Err(err);
1655 }
1656None => Ok(list),
1657 }
1658}
16591660#[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_hasher::StableHash for
AlwaysRequiresDrop {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hasher::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)]
1661pub struct AlwaysRequiresDrop;
16621663/// Reveals all opaque types in the given value, replacing them
1664/// with their underlying types.
1665pub fn reveal_opaque_types_in_bounds<'tcx>(
1666 tcx: TyCtxt<'tcx>,
1667 val: ty::Clauses<'tcx>,
1668) -> ty::Clauses<'tcx> {
1669if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1670let mut visitor = OpaqueTypeExpander {
1671 seen_opaque_tys: FxHashSet::default(),
1672 expanded_cache: FxHashMap::default(),
1673 primary_def_id: None,
1674 found_recursion: false,
1675 found_any_recursion: false,
1676 check_recursion: false,
1677tcx,
1678 };
1679val.fold_with(&mut visitor)
1680}
16811682/// Determines whether an item is directly annotated with `doc(hidden)`.
1683fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1684{
{
'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())1685}
16861687/// Determines whether an item is annotated with `doc(notable_trait)`.
1688pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1689{
{
'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())1690}
16911692/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1693///
1694/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1695/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1696/// cause an ICE that we otherwise may want to prevent.
1697pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1698if 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) {
1699let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1700 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1701 !has_body1702 }
1703_ => true,
1704 };
1705Some(ty::IntrinsicDef {
1706 name: tcx.item_name(def_id),
1707must_be_overridden,
1708 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),
1709 })
1710 } else {
1711None1712 }
1713}
17141715pub fn provide(providers: &mut Providers) {
1716*providers = Providers {
1717reveal_opaque_types_in_bounds,
1718is_doc_hidden,
1719is_doc_notable_trait,
1720intrinsic_raw,
1721 ..*providers1722 }
1723}