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::Limit;
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_data_structures::stable_hash::{StableHash, StableHasher};
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::{selfas hir, find_attr};
15use rustc_index::bit_set::GrowableBitSet;
16use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
17use rustc_span::sym;
18use rustc_type_ir::solve::SizedTraitKind;
19use smallvec::{SmallVec, smallvec};
20use tracing::{debug, instrument};
2122use super::TypingEnv;
23use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
24use crate::mir;
25use crate::query::Providers;
26use crate::traits::ObligationCause;
27use crate::ty::layout::{FloatExt, IntegerExt};
28use crate::ty::{
29self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
30TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized, Upcast,
31};
3233#[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)]
34pub struct Discr<'tcx> {
35/// Bit representation of the discriminant (e.g., `-1i8` is `0xFF_u128`).
36pub val: u128,
37pub ty: Ty<'tcx>,
38}
3940/// Used as an input to [`TyCtxt::uses_unique_generic_params`].
41#[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)]
42pub enum CheckRegions {
43 No,
44/// Only permit parameter regions. This should be used
45 /// for everything apart from functions, which may use
46 /// `ReBound` to represent late-bound regions.
47OnlyParam,
48/// Check region parameters from a function definition.
49 /// Allows `ReEarlyParam` and `ReBound` to handle early
50 /// and late-bound region parameters.
51FromFunction,
52}
5354#[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)]
55pub enum NotUniqueParam<'tcx> {
56 DuplicateParam(ty::GenericArg<'tcx>),
57 NotParam(ty::GenericArg<'tcx>),
58}
5960impl<'tcx> fmt::Displayfor Discr<'tcx> {
61fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
62match *self.ty.kind() {
63 ty::Int(ity) => {
64let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
65let x = self.val;
66// sign extend the raw representation to be an i128
67let x = size.sign_extend(x) as i128;
68fmt.write_fmt(format_args!("{0}", x))write!(fmt, "{x}")69 }
70_ => fmt.write_fmt(format_args!("{0}", self.val))write!(fmt, "{}", self.val),
71 }
72 }
73}
7475impl<'tcx> Discr<'tcx> {
76/// Adds `1` to the value and wraps around if the maximum for the type is reached.
77pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
78self.checked_add(tcx, 1).0
79}
80pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
81let (size, signed) = self.ty.int_size_and_signed(tcx);
82let (val, oflo) = if signed {
83let min = size.signed_int_min();
84let max = size.signed_int_max();
85let val = size.sign_extend(self.val);
86if !(n < (i128::MAX as u128)) {
::core::panicking::panic("assertion failed: n < (i128::MAX as u128)")
};assert!(n < (i128::MAX as u128));
87let n = nas i128;
88let oflo = val > max - n;
89let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
90// zero the upper bits
91let val = valas u128;
92let val = size.truncate(val);
93 (val, oflo)
94 } else {
95let max = size.unsigned_int_max();
96let val = self.val;
97let oflo = val > max - n;
98let val = if oflo { n - (max - val) - 1 } else { val + n };
99 (val, oflo)
100 };
101 (Self { val, ty: self.ty }, oflo)
102 }
103}
104105impl 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)]106impl IntegerType {
107fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
108match self {
109 IntegerType::Pointer(true) => tcx.types.isize,
110 IntegerType::Pointer(false) => tcx.types.usize,
111 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
112 }
113 }
114115fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
116Discr { val: 0, ty: self.to_ty(tcx) }
117 }
118119fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
120if let Some(val) = val {
121assert_eq!(self.to_ty(tcx), val.ty);
122let (new, oflo) = val.checked_add(tcx, 1);
123if oflo { None } else { Some(new) }
124 } else {
125Some(self.initial_discriminant(tcx))
126 }
127 }
128}
129130impl<'tcx> TyCtxt<'tcx> {
131/// Creates a hash of the type `Ty` which will be the same no matter what crate
132 /// context it's calculated within. This is used by the `type_id` intrinsic.
133pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash128 {
134// We don't have region information, so we erase all free regions. Equal types
135 // must have the same `TypeId`, so we must anonymize all bound regions as well.
136let ty = self.erase_and_anonymize_regions(ty);
137138self.with_stable_hashing_context(|mut hcx| {
139let mut hasher = StableHasher::new();
140hcx.while_hashing_spans(false, |hcx| ty.stable_hash(hcx, &mut hasher));
141hasher.finish()
142 })
143 }
144145pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
146match res {
147 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
148Some(self.parent(self.parent(def_id)))
149 }
150 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
151Some(self.parent(def_id))
152 }
153// Other `DefKind`s don't have generics and would ICE when calling
154 // `generics_of`.
155Res::Def(
156 DefKind::Struct157 | DefKind::Union158 | DefKind::Enum159 | DefKind::Trait160 | DefKind::OpaqueTy161 | DefKind::TyAlias162 | DefKind::ForeignTy163 | DefKind::TraitAlias164 | DefKind::AssocTy165 | DefKind::Fn166 | DefKind::AssocFn167 | DefKind::AssocConst { .. }
168 | DefKind::Impl { .. },
169 def_id,
170 ) => Some(def_id),
171 Res::Err => None,
172_ => None,
173 }
174 }
175176/// Checks whether `ty: Copy` holds while ignoring region constraints.
177 ///
178 /// This impacts whether values of `ty` are *moved* or *copied*
179 /// when referenced. This means that we may generate MIR which
180 /// does copies even when the type actually doesn't satisfy the
181 /// full requirements for the `Copy` trait (cc #29149) -- this
182 /// winds up being reported as an error during NLL borrow check.
183 ///
184 /// This function should not be used if there is an `InferCtxt` available.
185 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
186pub fn type_is_copy_modulo_regions(
187self,
188 typing_env: ty::TypingEnv<'tcx>,
189 ty: Ty<'tcx>,
190 ) -> bool {
191ty.is_trivially_pure_clone_copy() || self.is_copy_raw(typing_env.as_query_input(ty))
192 }
193194/// Checks whether `ty: UseCloned` holds while ignoring region constraints.
195 ///
196 /// This function should not be used if there is an `InferCtxt` available.
197 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
198pub fn type_is_use_cloned_modulo_regions(
199self,
200 typing_env: ty::TypingEnv<'tcx>,
201 ty: Ty<'tcx>,
202 ) -> bool {
203ty.is_trivially_pure_clone_copy() || self.is_use_cloned_raw(typing_env.as_query_input(ty))
204 }
205206/// Returns the deeply last field of nested structures, or the same type if
207 /// not a structure at all. Corresponds to the only possible unsized field,
208 /// and its type can be used to determine unsizing strategy.
209 ///
210 /// Should only be called if `ty` has no inference variables and does not
211 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
212 /// normalization attempt may cause compiler bugs.
213pub fn struct_tail_for_codegen(
214self,
215 ty: Ty<'tcx>,
216 typing_env: ty::TypingEnv<'tcx>,
217 ) -> Ty<'tcx> {
218self.assert_fully_normalized(typing_env, ty);
219self.struct_tail_raw(
220ty,
221&ObligationCause::dummy(),
222 |ty| self.normalize_erasing_regions(typing_env, ty),
223 || {},
224 )
225 }
226227/// Returns true if a type has metadata.
228pub fn type_has_metadata(self, ty: Ty<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
229if ty.is_sized(self, typing_env) {
230return false;
231 }
232233let tail = self.struct_tail_for_codegen(ty, typing_env);
234match tail.kind() {
235 ty::Foreign(..) => false,
236 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
237_ => crate::util::bug::bug_fmt(format_args!("unexpected unsized tail: {0:?}",
tail))bug!("unexpected unsized tail: {:?}", tail),
238 }
239 }
240241/// Returns the deeply last field of nested structures, or the same type if
242 /// not a structure at all. Corresponds to the only possible unsized field,
243 /// and its type can be used to determine unsizing strategy.
244 ///
245 /// This is parameterized over the normalization strategy (i.e. how to
246 /// handle `<T as Trait>::Assoc` and `impl Trait`). You almost certainly do
247 /// **NOT** want to pass the identity function here, unless you know what
248 /// you're doing, or you're within normalization code itself and will handle
249 /// an unnormalized tail recursively.
250 ///
251 /// See also `struct_tail_for_codegen`, which is suitable for use
252 /// during codegen.
253pub fn struct_tail_raw(
254self,
255mut ty: Ty<'tcx>,
256 cause: &ObligationCause<'tcx>,
257mut normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
258// This is currently used to allow us to walk a ValTree
259 // in lockstep with the type in order to get the ValTree branch that
260 // corresponds to an unsized field.
261mut f: impl FnMut() -> (),
262 ) -> Ty<'tcx> {
263let recursion_limit = self.recursion_limit();
264for iteration in 0.. {
265if !recursion_limit.value_within_limit(iteration) {
266let suggested_limit = match recursion_limit {
267 Limit(0) => Limit(2),
268 limit => limit * 2,
269 };
270let reported = self.dcx().emit_err(crate::diagnostics::RecursionLimitReached {
271 span: cause.span,
272 ty,
273 suggested_limit,
274 });
275return Ty::new_error(self, reported);
276 }
277match *ty.kind() {
278 ty::Adt(def, args) => {
279if !def.is_struct() {
280break;
281 }
282match def.non_enum_variant().tail_opt() {
283Some(field) => {
284 f();
285 ty = normalize(field.ty(self, args));
286 }
287None => break,
288 }
289 }
290291 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
292 f();
293 ty = last_ty;
294 }
295296 ty::Tuple(_) => break,
297298 ty::Pat(inner, _) => {
299 f();
300 ty = inner;
301 }
302303_ => {
304break;
305 }
306 }
307 }
308ty309 }
310311/// Same as applying `struct_tail` on `source` and `target`, but only
312 /// keeps going as long as the two types are instances of the same
313 /// structure definitions.
314 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
315 /// whereas struct_tail produces `T`, and `Trait`, respectively.
316 ///
317 /// Should only be called if the types have no inference variables and do
318 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
319 /// normalization attempt may cause compiler bugs.
320pub fn struct_lockstep_tails_for_codegen(
321self,
322 source: Ty<'tcx>,
323 target: Ty<'tcx>,
324 typing_env: ty::TypingEnv<'tcx>,
325 ) -> (Ty<'tcx>, Ty<'tcx>) {
326self.assert_fully_normalized(typing_env, (source, target));
327self.struct_lockstep_tails_raw(source, target, |ty| {
328self.normalize_erasing_regions(typing_env, ty)
329 })
330 }
331332/// Same as applying `struct_tail` on `source` and `target`, but only
333 /// keeps going as long as the two types are instances of the same
334 /// structure definitions.
335 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
336 /// whereas struct_tail produces `T`, and `Trait`, respectively.
337 ///
338 /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
339 /// during codegen.
340pub fn struct_lockstep_tails_raw(
341self,
342 source: Ty<'tcx>,
343 target: Ty<'tcx>,
344 normalize: impl Fn(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
345 ) -> (Ty<'tcx>, Ty<'tcx>) {
346let (mut a, mut b) = (source, target);
347loop {
348match (a.kind(), b.kind()) {
349 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
350if a_def == b_def && a_def.is_struct() =>
351 {
352if let Some(f) = a_def.non_enum_variant().tail_opt() {
353a = normalize(f.ty(self, a_args));
354b = normalize(f.ty(self, b_args));
355 } else {
356break;
357 }
358 }
359 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
360if let Some(&a_last) = a_tys.last() {
361a = a_last;
362b = *b_tys.last().unwrap();
363 } else {
364break;
365 }
366 }
367368_ => break,
369 }
370 }
371 (a, b)
372 }
373374/// Calculate the destructor of a given type.
375pub fn calculate_dtor(
376self,
377 adt_did: LocalDefId,
378 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
379 ) -> Option<ty::Destructor> {
380let drop_trait = self.lang_items().drop_trait()?;
381self.ensure_result().coherent_trait(drop_trait).ok()?;
382383let mut dtor_candidate = None;
384// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
385for &impl_did in self.local_trait_impls(drop_trait) {
386let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
387if adt_def.did() != adt_did.to_def_id() {
388continue;
389 }
390391if validate(self, impl_did).is_err() {
392// Already `ErrorGuaranteed`, no need to delay a span bug here.
393continue;
394 }
395396let Some(&item_id) = self.associated_item_def_ids(impl_did).first() else {
397self.dcx()
398 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
399continue;
400 };
401402if self.def_kind(item_id) != DefKind::AssocFn {
403self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
404continue;
405 }
406407if let Some(old_item_id) = dtor_candidate {
408self.dcx()
409 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
410 .with_span_note(self.def_span(old_item_id), "other impl here")
411 .delay_as_bug();
412 }
413414 dtor_candidate = Some(item_id);
415 }
416417let did = dtor_candidate?;
418Some(ty::Destructor { did })
419 }
420421/// Calculate the async destructor of a given type.
422pub fn calculate_async_dtor(
423self,
424 adt_did: LocalDefId,
425 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
426 ) -> Option<ty::AsyncDestructor> {
427let async_drop_trait = self.lang_items().async_drop_trait()?;
428self.ensure_result().coherent_trait(async_drop_trait).ok()?;
429430let mut dtor_candidate = None;
431// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
432for &impl_did in self.local_trait_impls(async_drop_trait) {
433let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
434if adt_def.did() != adt_did.to_def_id() {
435continue;
436 }
437438if validate(self, impl_did).is_err() {
439// Already `ErrorGuaranteed`, no need to delay a span bug here.
440continue;
441 }
442443if let Some(old_impl_did) = dtor_candidate {
444self.dcx()
445 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
446 .with_span_note(self.def_span(old_impl_did), "other impl here")
447 .delay_as_bug();
448 }
449450 dtor_candidate = Some(impl_did);
451 }
452453Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
454 }
455456/// Returns the set of types that are required to be alive in
457 /// order to run the destructor of `def` (see RFCs 769 and
458 /// 1238).
459 ///
460 /// Note that this returns only the constraints for the
461 /// destructor of `def` itself. For the destructors of the
462 /// contents, you need `adt_dtorck_constraint`.
463pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
464let dtor = match def.destructor(self) {
465None => {
466{
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:466",
"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(466u32),
::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());
467return ::alloc::vec::Vec::new()vec![];
468 }
469Some(dtor) => dtor.did,
470 };
471472let impl_def_id = self.parent(dtor);
473let impl_generics = self.generics_of(impl_def_id);
474475// We have a destructor - all the parameters that are not
476 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
477 // must be live.
478479 // We need to return the list of parameters from the ADTs
480 // generics/args that correspond to impure parameters on the
481 // impl's generics. This is a bit ugly, but conceptually simple:
482 //
483 // Suppose our ADT looks like the following
484 //
485 // struct S<X, Y, Z>(X, Y, Z);
486 //
487 // and the impl is
488 //
489 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
490 //
491 // We want to return the parameters (X, Y). For that, we match
492 // up the item-args <X, Y, Z> with the args on the impl ADT,
493 // <P1, P2, P0>, and then look up which of the impl args refer to
494 // parameters marked as pure.
495496let impl_args =
497match *self.type_of(impl_def_id).instantiate_identity().skip_norm_wip().kind() {
498 ty::Adt(def_, args) if def_ == def => args,
499_ => crate::util::bug::span_bug_fmt(self.def_span(impl_def_id),
format_args!("expected ADT for self type of `Drop` impl"))span_bug!(
500self.def_span(impl_def_id),
501"expected ADT for self type of `Drop` impl"
502),
503 };
504505let item_args = ty::GenericArgs::identity_for_item(self, def.did());
506507let result = iter::zip(item_args, impl_args)
508 .filter(|&(_, arg)| {
509match arg.kind() {
510GenericArgKind::Lifetime(region) => match region.kind() {
511 ty::ReEarlyParam(ebr) => {
512 !impl_generics.region_param(ebr, self).pure_wrt_drop
513 }
514// Error: not a region param
515_ => false,
516 },
517GenericArgKind::Type(ty) => match *ty.kind() {
518 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
519// Error: not a type param
520_ => false,
521 },
522GenericArgKind::Const(ct) => match ct.kind() {
523 ty::ConstKind::Param(pc) => {
524 !impl_generics.const_param(pc, self).pure_wrt_drop
525 }
526// Error: not a const param
527_ => false,
528 },
529 }
530 })
531 .map(|(item_param, _)| item_param)
532 .collect();
533{
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:533",
"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(533u32),
::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);
534result535 }
536537/// Checks whether each generic argument is simply a unique generic parameter.
538pub fn uses_unique_generic_params(
539self,
540 args: &[ty::GenericArg<'tcx>],
541 ignore_regions: CheckRegions,
542 ) -> Result<(), NotUniqueParam<'tcx>> {
543let mut seen = GrowableBitSet::default();
544let mut seen_late = FxHashSet::default();
545for arg in args {
546match arg.kind() {
547 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
548 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
549if !seen_late.insert((di, reg)) {
550return Err(NotUniqueParam::DuplicateParam(lt.into()));
551 }
552 }
553 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
554if !seen.insert(p.index) {
555return Err(NotUniqueParam::DuplicateParam(lt.into()));
556 }
557 }
558 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
559return Err(NotUniqueParam::NotParam(lt.into()));
560 }
561 (CheckRegions::No, _) => {}
562 },
563 GenericArgKind::Type(t) => match t.kind() {
564 ty::Param(p) => {
565if !seen.insert(p.index) {
566return Err(NotUniqueParam::DuplicateParam(t.into()));
567 }
568 }
569_ => return Err(NotUniqueParam::NotParam(t.into())),
570 },
571 GenericArgKind::Const(c) => match c.kind() {
572 ty::ConstKind::Param(p) => {
573if !seen.insert(p.index) {
574return Err(NotUniqueParam::DuplicateParam(c.into()));
575 }
576 }
577_ => return Err(NotUniqueParam::NotParam(c.into())),
578 },
579 }
580 }
581582Ok(())
583 }
584585/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
586 /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
587 /// have the same `DefKind`.
588 ///
589 /// Note that closures have a `DefId`, but the closure *expression* also has a
590 /// `HirId` that is located within the context where the closure appears. The
591 /// parent of the closure's `DefId` will also be the context where it appears.
592pub fn is_closure_like(self, def_id: DefId) -> bool {
593#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)594 }
595596/// Returns `true` if `def_id` refers to a definition that does not have its own
597 /// type-checking context, i.e. closure, coroutine or inline const.
598pub fn is_typeck_child(self, def_id: DefId) -> bool {
599match self.def_kind(def_id) {
600 DefKind::AnonConst => {
601self.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline602 }
603 DefKind::Closure | DefKind::SyntheticCoroutineBody => true,
604 DefKind::Mod605 | DefKind::Struct606 | DefKind::Union607 | DefKind::Enum608 | DefKind::Variant609 | DefKind::Trait610 | DefKind::TyAlias611 | DefKind::ForeignTy612 | DefKind::TraitAlias613 | DefKind::AssocTy614 | DefKind::TyParam615 | DefKind::Fn616 | DefKind::Const { .. }
617 | DefKind::ConstParam618 | DefKind::Static { .. }
619 | DefKind::Ctor(_, _)
620 | DefKind::AssocFn621 | DefKind::AssocConst { .. }
622 | DefKind::Macro(_)
623 | DefKind::ExternCrate624 | DefKind::Use625 | DefKind::ForeignMod626 | DefKind::OpaqueTy627 | DefKind::Field628 | DefKind::LifetimeParam629 | DefKind::GlobalAsm630 | DefKind::Impl { .. } => false,
631 }
632 }
633634/// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
635pub fn is_trait(self, def_id: DefId) -> bool {
636self.def_kind(def_id) == DefKind::Trait637 }
638639/// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
640 /// and `false` otherwise.
641pub fn is_trait_alias(self, def_id: DefId) -> bool {
642self.def_kind(def_id) == DefKind::TraitAlias643 }
644645/// Returns `true` if this `DefId` refers to the implicit constructor for
646 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
647pub fn is_constructor(self, def_id: DefId) -> bool {
648#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))649 }
650651/// Given the `DefId`, returns the `DefId` of the innermost item that
652 /// has its own type-checking context or "inference environment".
653 ///
654 /// For example, a closure has its own `DefId`, but it is type-checked
655 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
656 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
657pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
658let mut def_id = def_id;
659while self.is_typeck_child(def_id) {
660 def_id = self.parent(def_id);
661 }
662def_id663 }
664665/// Given the `LocalDefId`, returns the `LocalDefId` of the innermost item that
666 /// has its own type-checking context or "inference environment".
667 ///
668 /// For example, a closure has its own `LocalDefId`, but it is type-checked
669 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
670 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
671pub fn typeck_root_def_id_local(self, def_id: LocalDefId) -> LocalDefId {
672let mut def_id = def_id;
673while self.is_typeck_child(def_id.to_def_id()) {
674 def_id = self.local_parent(def_id);
675 }
676def_id677 }
678679/// Given the `DefId` and args a closure, creates the type of
680 /// `self` argument that the closure expects. For example, for a
681 /// `Fn` closure, this would return a reference type `&T` where
682 /// `T = closure_ty`.
683 ///
684 /// Returns `None` if this closure's kind has not yet been inferred.
685 /// This should only be possible during type checking.
686 ///
687 /// Note that the return value is a late-bound region and hence
688 /// wrapped in a binder.
689pub fn closure_env_ty(
690self,
691 closure_ty: Ty<'tcx>,
692 closure_kind: ty::ClosureKind,
693 env_region: ty::Region<'tcx>,
694 ) -> Ty<'tcx> {
695match closure_kind {
696 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
697 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
698 ty::ClosureKind::FnOnce => closure_ty,
699 }
700 }
701702/// Returns `true` if the node pointed to by `def_id` is a `static` item.
703#[inline]
704pub fn is_static(self, def_id: DefId) -> bool {
705#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })706 }
707708#[inline]
709pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
710if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
711Some(mutability)
712 } else {
713None714 }
715 }
716717/// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
718pub fn is_thread_local_static(self, def_id: DefId) -> bool {
719self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
720 }
721722/// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
723#[inline]
724pub fn is_mutable_static(self, def_id: DefId) -> bool {
725self.static_mutability(def_id) == Some(hir::Mutability::Mut)
726 }
727728/// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
729 /// thread local shim generated.
730#[inline]
731pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
732 !self.sess.target.dll_tls_export
733 && self.is_thread_local_static(def_id)
734 && !self.is_foreign_item(def_id)
735 }
736737/// Returns the type a reference to the thread local takes in MIR.
738pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
739let static_ty = self.type_of(def_id).instantiate_identity().skip_norm_wip();
740if self.is_mutable_static(def_id) {
741Ty::new_mut_ptr(self, static_ty)
742 } else if self.is_foreign_item(def_id) {
743Ty::new_imm_ptr(self, static_ty)
744 } else {
745// FIXME: These things don't *really* have 'static lifetime.
746Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
747 }
748 }
749750/// Get the type of the pointer to the static that we use in MIR.
751pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
752// Make sure that any constants in the static's type are evaluated.
753let static_ty =
754self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
755756// Make sure that accesses to unsafe statics end up using raw pointers.
757 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
758if self.is_mutable_static(def_id) {
759Ty::new_mut_ptr(self, static_ty)
760 } else if self.is_foreign_item(def_id) {
761Ty::new_imm_ptr(self, static_ty)
762 } else {
763Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
764 }
765 }
766767/// Expands the given impl trait type, stopping if the type is recursive.
768x;#[instrument(skip(self), level = "debug", ret)]769pub fn try_expand_impl_trait_type(
770self,
771 def_id: DefId,
772 args: GenericArgsRef<'tcx>,
773 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
774let mut visitor = OpaqueTypeExpander {
775 seen_opaque_tys: FxHashSet::default(),
776 expanded_cache: FxHashMap::default(),
777 primary_def_id: Some(def_id),
778 found_recursion: false,
779 found_any_recursion: false,
780 check_recursion: true,
781 tcx: self,
782 };
783784let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
785if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
786 }
787788/// Query and get an English description for the item's kind.
789pub fn def_descr(self, def_id: DefId) -> &'static str {
790self.def_kind_descr(self.def_kind(def_id), def_id)
791 }
792793/// Get an English description for the item's kind.
794pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
795match def_kind {
796 DefKind::AssocFnif self.associated_item(def_id).is_method() => "method",
797 DefKind::AssocTyif self.opt_rpitit_info(def_id).is_some() => "opaque type",
798 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
799match coroutine_kind {
800 hir::CoroutineKind::Desugared(
801 hir::CoroutineDesugaring::Async,
802 hir::CoroutineSource::Fn,
803 ) => "async fn",
804 hir::CoroutineKind::Desugared(
805 hir::CoroutineDesugaring::Async,
806 hir::CoroutineSource::Block,
807 ) => "async block",
808 hir::CoroutineKind::Desugared(
809 hir::CoroutineDesugaring::Async,
810 hir::CoroutineSource::Closure,
811 ) => "async closure",
812 hir::CoroutineKind::Desugared(
813 hir::CoroutineDesugaring::AsyncGen,
814 hir::CoroutineSource::Fn,
815 ) => "async gen fn",
816 hir::CoroutineKind::Desugared(
817 hir::CoroutineDesugaring::AsyncGen,
818 hir::CoroutineSource::Block,
819 ) => "async gen block",
820 hir::CoroutineKind::Desugared(
821 hir::CoroutineDesugaring::AsyncGen,
822 hir::CoroutineSource::Closure,
823 ) => "async gen closure",
824 hir::CoroutineKind::Desugared(
825 hir::CoroutineDesugaring::Gen,
826 hir::CoroutineSource::Fn,
827 ) => "gen fn",
828 hir::CoroutineKind::Desugared(
829 hir::CoroutineDesugaring::Gen,
830 hir::CoroutineSource::Block,
831 ) => "gen block",
832 hir::CoroutineKind::Desugared(
833 hir::CoroutineDesugaring::Gen,
834 hir::CoroutineSource::Closure,
835 ) => "gen closure",
836 hir::CoroutineKind::Coroutine(_) => "coroutine",
837 }
838 }
839_ => def_kind.descr(def_id),
840 }
841 }
842843/// Gets an English article for the [`TyCtxt::def_descr`].
844pub fn def_descr_article(self, def_id: DefId) -> &'static str {
845self.def_kind_descr_article(self.def_kind(def_id), def_id)
846 }
847848/// Gets an English article for the [`TyCtxt::def_kind_descr`].
849pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
850match def_kind {
851 DefKind::AssocFnif self.associated_item(def_id).is_method() => "a",
852 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
853match coroutine_kind {
854 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
855 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
856 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
857 hir::CoroutineKind::Coroutine(_) => "a",
858 }
859 }
860_ => def_kind.article(),
861 }
862 }
863864/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
865 /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
866 /// be shown in `impl` suggestions.
867 ///
868 /// [public]: TyCtxt::is_private_dep
869 /// [direct]: rustc_crate_store::ExternCrate::is_direct
870pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
871// `#![rustc_private]` overrides defaults to make private dependencies usable.
872if self.features().enabled(sym::rustc_private) {
873return true;
874 }
875876// | Private | Direct | Visible | |
877 // |---------|--------|---------|--------------------|
878 // | Yes | Yes | Yes | !true || true |
879 // | No | Yes | Yes | !false || true |
880 // | Yes | No | No | !true || false |
881 // | No | No | Yes | !false || false |
882!self.is_private_dep(key)
883// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
884 // Treat that kind of crate as "indirect", since it's an implementation detail of
885 // the language.
886|| self.extern_crate(key).is_some_and(|e| e.is_direct())
887 }
888889/// Expand any [free alias types][free] contained within the given `value`.
890 ///
891 /// This should be used over other normalization routines in situations where
892 /// it's important not to normalize other alias types and where the predicates
893 /// on the corresponding type alias shouldn't be taken into consideration.
894 ///
895 /// Whenever possible **prefer not to use this function**! Instead, use standard
896 /// normalization routines or if feasible don't normalize at all.
897 ///
898 /// This function comes in handy if you want to mimic the behavior of eager
899 /// type alias expansion in a localized manner.
900 ///
901 /// <div class="warning">
902 /// This delays a bug on overflow! Therefore you need to be certain that the
903 /// contained types get fully normalized at a later stage. Note that even on
904 /// overflow all well-behaved free alias types get expanded correctly, so the
905 /// result is still useful.
906 /// </div>
907 ///
908 /// [free]: ty::Free
909pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
910value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
911 }
912913/// Peel off all [free alias types] in this type until there are none left.
914 ///
915 /// This only expands free alias types in “head” / outermost positions. It can
916 /// be used over [expand_free_alias_tys] as an optimization in situations where
917 /// one only really cares about the *kind* of the final aliased type but not
918 /// the types the other constituent types alias.
919 ///
920 /// <div class="warning">
921 /// This delays a bug on overflow! Therefore you need to be certain that the
922 /// type gets fully normalized at a later stage.
923 /// </div>
924 ///
925 /// [free]: ty::Free
926 /// [expand_free_alias_tys]: Self::expand_free_alias_tys
927pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
928let ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) = ty.kind() else {
929return ty;
930 };
931932let limit = self.recursion_limit();
933let mut depth = 0;
934935while let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() {
936if !limit.value_within_limit(depth) {
937let guar = self.dcx().delayed_bug("overflow expanding free alias type");
938return Ty::new_error(self, guar);
939 }
940941 ty = self.type_of(def_id).instantiate(self, args).skip_normalization();
942 depth += 1;
943 }
944945ty946 }
947948// Computes the variances for an alias (opaque or RPITIT) that represent
949 // its (un)captured regions.
950pub fn opt_alias_variances(
951self,
952 kind: impl Into<ty::AliasTermKind<'tcx>>,
953 ) -> Option<&'tcx [ty::Variance]> {
954match kind.into() {
955 ty::AliasTermKind::ProjectionTy { def_id } => {
956if self.is_impl_trait_in_trait(def_id) {
957Some(self.variances_of(def_id))
958 } else {
959None960 }
961 }
962 ty::AliasTermKind::OpaqueTy { def_id } => Some(self.variances_of(def_id)),
963 ty::AliasTermKind::InherentTy { .. }
964 | ty::AliasTermKind::InherentConst { .. }
965 | ty::AliasTermKind::FreeTy { .. }
966 | ty::AliasTermKind::FreeConst { .. }
967 | ty::AliasTermKind::AnonConst { .. }
968 | ty::AliasTermKind::ProjectionConst { .. } => None,
969 }
970 }
971}
972973struct OpaqueTypeExpander<'tcx> {
974// Contains the DefIds of the opaque types that are currently being
975 // expanded. When we expand an opaque type we insert the DefId of
976 // that type, and when we finish expanding that type we remove the
977 // its DefId.
978seen_opaque_tys: FxHashSet<DefId>,
979// Cache of all expansions we've seen so far. This is a critical
980 // optimization for some large types produced by async fn trees.
981expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
982 primary_def_id: Option<DefId>,
983 found_recursion: bool,
984 found_any_recursion: bool,
985/// Whether or not to check for recursive opaque types.
986 /// This is `true` when we're explicitly checking for opaque type
987 /// recursion, and 'false' otherwise to avoid unnecessary work.
988check_recursion: bool,
989 tcx: TyCtxt<'tcx>,
990}
991992impl<'tcx> OpaqueTypeExpander<'tcx> {
993fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
994if self.found_any_recursion {
995return None;
996 }
997let args = args.fold_with(self);
998if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
999let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
1000Some(expanded_ty) => *expanded_ty,
1001None => {
1002let generic_ty = self.tcx.type_of(def_id);
1003let concrete_ty = generic_ty.instantiate(self.tcx, args).skip_normalization();
1004let expanded_ty = self.fold_ty(concrete_ty);
1005self.expanded_cache.insert((def_id, args), expanded_ty);
1006expanded_ty1007 }
1008 };
1009if self.check_recursion {
1010self.seen_opaque_tys.remove(&def_id);
1011 }
1012Some(expanded_ty)
1013 } else {
1014// If another opaque type that we contain is recursive, then it
1015 // will report the error, so we don't have to.
1016self.found_any_recursion = true;
1017self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1018None1019 }
1020 }
1021}
10221023impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1024fn cx(&self) -> TyCtxt<'tcx> {
1025self.tcx
1026 }
10271028fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1029if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *t.kind() {
1030self.expand_opaque_ty(def_id, args).unwrap_or(t)
1031 } else if t.has_opaque_types() {
1032t.super_fold_with(self)
1033 } else {
1034t1035 }
1036 }
10371038fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1039if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1040 && let ty::ClauseKind::Projection(projection_pred) = clause1041 {
1042p.kind()
1043 .rebind(ty::ProjectionPredicate {
1044 projection_term: projection_pred.projection_term.fold_with(self),
1045// Don't fold the term on the RHS of the projection predicate.
1046 // This is because for default trait methods with RPITITs, we
1047 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1048 // predicate, which would trivially cause a cycle when we do
1049 // anything that requires `TypingEnv::with_post_analysis_normalized`.
1050term: projection_pred.term,
1051 })
1052 .upcast(self.tcx)
1053 } else {
1054p.super_fold_with(self)
1055 }
1056 }
1057}
10581059struct FreeAliasTypeExpander<'tcx> {
1060 tcx: TyCtxt<'tcx>,
1061 depth: usize,
1062}
10631064impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1065fn cx(&self) -> TyCtxt<'tcx> {
1066self.tcx
1067 }
10681069fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1070if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1071return ty;
1072 }
1073let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() else {
1074return ty.super_fold_with(self);
1075 };
1076if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1077let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1078return Ty::new_error(self.tcx, guar);
1079 }
10801081self.depth += 1;
1082let ty = self1083 .tcx
1084 .type_of(def_id)
1085 .instantiate(self.tcx, args)
1086 .skip_normalization()
1087 .fold_with(self);
1088self.depth -= 1;
1089ty1090 }
10911092fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1093if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1094return ct;
1095 }
1096ct.super_fold_with(self)
1097 }
1098}
10991100impl<'tcx> Ty<'tcx> {
1101/// Returns the `Size` for primitive types (bool, uint, int, char, float).
1102pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1103match *self.kind() {
1104 ty::Bool => Size::from_bytes(1),
1105 ty::Char => Size::from_bytes(4),
1106 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1107 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1108 ty::Float(fty) => Float::from_float_ty(fty).size(),
1109_ => crate::util::bug::bug_fmt(format_args!("non primitive type"))bug!("non primitive type"),
1110 }
1111 }
11121113pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1114match *self.kind() {
1115 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1116 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1117_ => crate::util::bug::bug_fmt(format_args!("non integer discriminant"))bug!("non integer discriminant"),
1118 }
1119 }
11201121/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1122 /// returns `None` if the type is not numeric.
1123pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1124use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1125Some(match self.kind() {
1126 ty::Int(_) | ty::Uint(_) => {
1127let (size, signed) = self.int_size_and_signed(tcx);
1128let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1129let max =
1130if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1131 (min, max)
1132 }
1133 ty::Char => (0, std::char::MAXas u128),
1134 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1135 ty::Float(ty::FloatTy::F32) => {
1136 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1137 }
1138 ty::Float(ty::FloatTy::F64) => {
1139 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1140 }
1141 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1142_ => return None,
1143 })
1144 }
11451146/// Returns the maximum value for the given numeric type (including `char`s)
1147 /// or returns `None` if the type is not numeric.
1148pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1149let typing_env = TypingEnv::fully_monomorphized();
1150self.numeric_min_and_max_as_bits(tcx)
1151 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1152 }
11531154/// Returns the minimum value for the given numeric type (including `char`s)
1155 /// or returns `None` if the type is not numeric.
1156pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1157let typing_env = TypingEnv::fully_monomorphized();
1158self.numeric_min_and_max_as_bits(tcx)
1159 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1160 }
11611162/// Checks whether values of this type `T` have a size known at
1163 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1164 /// for the purposes of this check, so it can be an
1165 /// over-approximation in generic contexts, where one can have
1166 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1167 /// actually carry lifetime requirements.
1168pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1169self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1170 || tcx.is_sized_raw(typing_env.as_query_input(self))
1171 }
11721173/// Checks whether values of this type `T` implement the `Freeze`
1174 /// trait -- frozen types are those that do not contain an
1175 /// `UnsafeCell` anywhere. This is a language concept used to
1176 /// distinguish "true immutability", which is relevant to
1177 /// optimization as well as the rules around static values. Note
1178 /// that the `Freeze` trait is not exposed to end users and is
1179 /// effectively an implementation detail.
1180pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1181self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1182 }
11831184/// Fast path helper for testing if a type is `Freeze`.
1185 ///
1186 /// Returning true means the type is known to be `Freeze`. Returning
1187 /// `false` means nothing -- could be `Freeze`, might not be.
1188pub fn is_trivially_freeze(self) -> bool {
1189match self.kind() {
1190 ty::Int(_)
1191 | ty::Uint(_)
1192 | ty::Float(_)
1193 | ty::Bool1194 | ty::Char1195 | ty::Str1196 | ty::Never1197 | ty::Ref(..)
1198 | ty::RawPtr(_, _)
1199 | ty::FnDef(..)
1200 | ty::Error(_)
1201 | ty::FnPtr(..) => true,
1202 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1203 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1204 ty::Adt(..)
1205 | ty::Bound(..)
1206 | ty::Closure(..)
1207 | ty::CoroutineClosure(..)
1208 | ty::Dynamic(..)
1209 | ty::Foreign(_)
1210 | ty::Coroutine(..)
1211 | ty::CoroutineWitness(..)
1212 | ty::UnsafeBinder(_)
1213 | ty::Infer(_)
1214 | ty::Alias(..)
1215 | ty::Param(_)
1216 | ty::Placeholder(_) => false,
1217 }
1218 }
12191220/// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1221pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1222self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1223 }
12241225/// Checks whether values of this type `T` implement the `Unpin` trait.
1226 ///
1227 /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1228 /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1229 /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1230pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1231self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1232 }
12331234/// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1235 ///
1236 /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1237 /// `false` means nothing -- could be `Unpin`, might not be.
1238fn is_trivially_unpin(self) -> bool {
1239match self.kind() {
1240 ty::Int(_)
1241 | ty::Uint(_)
1242 | ty::Float(_)
1243 | ty::Bool1244 | ty::Char1245 | ty::Str1246 | ty::Never1247 | ty::Ref(..)
1248 | ty::RawPtr(_, _)
1249 | ty::FnDef(..)
1250 | ty::Error(_)
1251 | ty::FnPtr(..) => true,
1252 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1253 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1254 ty::Adt(..)
1255 | ty::Bound(..)
1256 | ty::Closure(..)
1257 | ty::CoroutineClosure(..)
1258 | ty::Dynamic(..)
1259 | ty::Foreign(_)
1260 | ty::Coroutine(..)
1261 | ty::CoroutineWitness(..)
1262 | ty::UnsafeBinder(_)
1263 | ty::Infer(_)
1264 | ty::Alias(..)
1265 | ty::Param(_)
1266 | ty::Placeholder(_) => false,
1267 }
1268 }
12691270/// Checks whether this type is an ADT that has unsafe fields.
1271pub fn has_unsafe_fields(self) -> bool {
1272if let ty::Adt(adt_def, ..) = self.kind() {
1273adt_def.all_fields().any(|x| x.safety.is_unsafe())
1274 } else {
1275false
1276}
1277 }
12781279/// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1280pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1281 !self.is_trivially_not_async_drop()
1282 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1283 }
12841285/// Fast path helper for testing if a type is `AsyncDrop`.
1286 ///
1287 /// Returning true means the type is known to be `!AsyncDrop`. Returning
1288 /// `false` means nothing -- could be `AsyncDrop`, might not be.
1289fn is_trivially_not_async_drop(self) -> bool {
1290match self.kind() {
1291 ty::Int(_)
1292 | ty::Uint(_)
1293 | ty::Float(_)
1294 | ty::Bool1295 | ty::Char1296 | ty::Str1297 | ty::Never1298 | ty::Ref(..)
1299 | ty::RawPtr(..)
1300 | ty::FnDef(..)
1301 | ty::Error(_)
1302 | ty::FnPtr(..) => true,
1303// FIXME(unsafe_binders):
1304 ty::UnsafeBinder(_) => ::core::panicking::panic("not implemented")unimplemented!(),
1305 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1306 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1307elem_ty.is_trivially_not_async_drop()
1308 }
1309 ty::Adt(..)
1310 | ty::Bound(..)
1311 | ty::Closure(..)
1312 | ty::CoroutineClosure(..)
1313 | ty::Dynamic(..)
1314 | ty::Foreign(_)
1315 | ty::Coroutine(..)
1316 | ty::CoroutineWitness(..)
1317 | ty::Infer(_)
1318 | ty::Alias(..)
1319 | ty::Param(_)
1320 | ty::Placeholder(_) => false,
1321 }
1322 }
13231324/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1325 /// non-copy and *might* have a destructor attached; if it returns
1326 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1327 ///
1328 /// (Note that this implies that if `ty` has a destructor attached,
1329 /// then `needs_drop` will definitely return `true` for `ty`.)
1330 ///
1331 /// Note that this method is used to check eligible types in unions.
1332#[inline]
1333pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1334// Avoid querying in simple cases.
1335match needs_drop_components(tcx, self) {
1336Err(AlwaysRequiresDrop) => true,
1337Ok(components) => {
1338let query_ty = match *components {
1339 [] => return false,
1340// If we've got a single component, call the query with that
1341 // to increase the chance that we hit the query cache.
1342[component_ty] => component_ty,
1343_ => self,
1344 };
13451346// This doesn't depend on regions, so try to minimize distinct
1347 // query keys used. If normalization fails, we just use `query_ty`.
1348if 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());
1349let query_ty = tcx1350 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1351 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13521353tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1354 }
1355 }
1356 }
13571358/// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1359 /// non-copy and *might* have a async destructor attached; if it returns
1360 /// `false`, then `ty` definitely has no async destructor (i.e., no async
1361 /// drop glue).
1362 ///
1363 /// (Note that this implies that if `ty` has an async destructor attached,
1364 /// then `needs_async_drop` will definitely return `true` for `ty`.)
1365 ///
1366// FIXME(zetanumbers): Note that this method is used to check eligible types
1367 // in unions.
1368#[inline]
1369pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1370// Avoid querying in simple cases.
1371match needs_drop_components(tcx, self) {
1372Err(AlwaysRequiresDrop) => true,
1373Ok(components) => {
1374let query_ty = match *components {
1375 [] => return false,
1376// If we've got a single component, call the query with that
1377 // to increase the chance that we hit the query cache.
1378[component_ty] => component_ty,
1379_ => self,
1380 };
13811382// This doesn't depend on regions, so try to minimize distinct
1383 // query keys used.
1384 // If normalization fails, we just use `query_ty`.
1385if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1386let query_ty = tcx1387 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1388 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13891390tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1391 }
1392 }
1393 }
13941395/// Checks if `ty` has a significant drop.
1396 ///
1397 /// Note that this method can return false even if `ty` has a destructor
1398 /// attached; even if that is the case then the adt has been marked with
1399 /// the attribute `rustc_insignificant_dtor`.
1400 ///
1401 /// Note that this method is used to check for change in drop order for
1402 /// 2229 drop reorder migration analysis.
1403#[inline]
1404pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1405// Avoid querying in simple cases.
1406match needs_drop_components(tcx, self) {
1407Err(AlwaysRequiresDrop) => true,
1408Ok(components) => {
1409let query_ty = match *components {
1410 [] => return false,
1411// If we've got a single component, call the query with that
1412 // to increase the chance that we hit the query cache.
1413[component_ty] => component_ty,
1414_ => self,
1415 };
14161417// FIXME
1418 // We should be canonicalizing, or else moving this to a method of inference
1419 // context, or *something* like that,
1420 // but for now just avoid passing inference variables
1421 // to queries that can't cope with them.
1422 // Instead, conservatively return "true" (may change drop order).
1423if query_ty.has_infer() {
1424return true;
1425 }
14261427// This doesn't depend on regions, so try to minimize distinct
1428 // query keys used.
1429 // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1430tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1431 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1432 .unwrap_or(true)
1433 }
1434 }
1435 }
14361437/// Returns `true` if equality for this type is both reflexive and structural.
1438 ///
1439 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1440 ///
1441 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1442 /// types, equality for the type as a whole is structural when it is the same as equality
1443 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1444 /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1445 ///
1446 /// This function is "shallow" because it may return `true` for a composite type whose fields
1447 /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1448 /// because equality for arrays is determined by the equality of each array element. If you
1449 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1450 /// down, you will need to use a type visitor.
1451#[inline]
1452pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1453match self.kind() {
1454// Look for an impl of `StructuralPartialEq`.
1455ty::Adt(..) => tcx.has_structural_eq_impl(self),
14561457// Primitive types that satisfy `Eq`.
1458ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
14591460// Composite types that satisfy `Eq` when all of their fields do.
1461 //
1462 // Because this function is "shallow", we return `true` for these composites regardless
1463 // of the type(s) contained within.
1464ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
14651466// Raw pointers use bitwise comparison.
1467ty::RawPtr(_, _) | ty::FnPtr(..) => true,
14681469// Floating point numbers are not `Eq`.
1470ty::Float(_) => false,
14711472// Conservatively return `false` for all others...
14731474 // Anonymous function types
1475ty::FnDef(..)
1476 | ty::Closure(..)
1477 | ty::CoroutineClosure(..)
1478 | ty::Dynamic(..)
1479 | ty::Coroutine(..) => false,
14801481// Generic or inferred types
1482 //
1483 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1484 // called for known, fully-monomorphized types.
1485ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1486false
1487}
14881489 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1490 }
1491 }
14921493/// Peel off all reference types in this type until there are none left.
1494 ///
1495 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1496 ///
1497 /// # Examples
1498 ///
1499 /// - `u8` -> `u8`
1500 /// - `&'a mut u8` -> `u8`
1501 /// - `&'a &'b u8` -> `u8`
1502 /// - `&'a *const &'b u8 -> *const &'b u8`
1503pub fn peel_refs(self) -> Ty<'tcx> {
1504let mut ty = self;
1505while let ty::Ref(_, inner_ty, _) = ty.kind() {
1506 ty = *inner_ty;
1507 }
1508ty1509 }
1510}
15111512/// Returns a list of types such that the given type needs drop if and only if
1513/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1514/// this type always needs drop.
1515//
1516// FIXME(zetanumbers): consider replacing this with only
1517// `needs_drop_components_with_async`
1518#[inline]
1519pub fn needs_drop_components<'tcx>(
1520 tcx: TyCtxt<'tcx>,
1521 ty: Ty<'tcx>,
1522) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1523needs_drop_components_with_async(tcx, ty, Asyncness::No)
1524}
15251526/// Returns a list of types such that the given type needs drop if and only if
1527/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1528/// this type always needs drop.
1529pub fn needs_drop_components_with_async<'tcx>(
1530 tcx: TyCtxt<'tcx>,
1531 ty: Ty<'tcx>,
1532 asyncness: Asyncness,
1533) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1534match *ty.kind() {
1535 ty::Infer(ty::FreshIntTy(_))
1536 | ty::Infer(ty::FreshFloatTy(_))
1537 | ty::Bool1538 | ty::Int(_)
1539 | ty::Uint(_)
1540 | ty::Float(_)
1541 | ty::Never1542 | ty::FnDef(..)
1543 | ty::FnPtr(..)
1544 | ty::Char1545 | ty::RawPtr(_, _)
1546 | ty::Ref(..)
1547 | ty::Str => Ok(SmallVec::new()),
15481549// Foreign types can never have destructors.
1550ty::Foreign(..) => Ok(SmallVec::new()),
15511552// FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1553ty::Dynamic(..) | ty::Error(_) => {
1554if asyncness.is_async() {
1555Ok(SmallVec::new())
1556 } else {
1557Err(AlwaysRequiresDrop)
1558 }
1559 }
15601561 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1562 ty::Array(elem_ty, size) => {
1563match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1564Ok(v) if v.is_empty() => Ok(v),
1565 res => match size.try_to_target_usize(tcx) {
1566// Arrays of size zero don't need drop, even if their element
1567 // type does.
1568Some(0) => Ok(SmallVec::new()),
1569Some(_) => res,
1570// We don't know which of the cases above we are in, so
1571 // return the whole type and let the caller decide what to
1572 // do.
1573None => 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]),
1574 },
1575 }
1576 }
1577// If any field needs drop, then the whole tuple does.
1578ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1579acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1580Ok(acc)
1581 }),
15821583// These require checking for `Copy` bounds or `Adt` destructors.
1584ty::Adt(..)
1585 | ty::Alias(..)
1586 | ty::Param(_)
1587 | ty::Bound(..)
1588 | ty::Placeholder(..)
1589 | ty::Infer(_)
1590 | ty::Closure(..)
1591 | ty::CoroutineClosure(..)
1592 | ty::Coroutine(..)
1593 | ty::CoroutineWitness(..)
1594 | 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]),
1595 }
1596}
15971598/// Does the equivalent of
1599/// ```ignore (illustrative)
1600/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1601/// folder.tcx().intern_*(&v)
1602/// ```
1603pub fn fold_list<'tcx, F, L, T>(
1604 list: L,
1605 folder: &mut F,
1606 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1607) -> L
1608where
1609F: TypeFolder<TyCtxt<'tcx>>,
1610 L: AsRef<[T]>,
1611 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1612{
1613let slice = list.as_ref();
1614let mut iter = slice.iter().copied();
1615// Look for the first element that changed
1616match iter.by_ref().enumerate().find_map(|(i, t)| {
1617let new_t = t.fold_with(folder);
1618if new_t != t { Some((i, new_t)) } else { None }
1619 }) {
1620Some((i, new_t)) => {
1621// An element changed, prepare to intern the resulting list
1622let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1623new_list.extend_from_slice(&slice[..i]);
1624new_list.push(new_t);
1625for t in iter {
1626 new_list.push(t.fold_with(folder))
1627 }
1628intern(folder.cx(), &new_list)
1629 }
1630None => list,
1631 }
1632}
16331634/// Does the equivalent of
1635/// ```ignore (illustrative)
1636/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1637/// folder.tcx().intern_*(&v)
1638/// ```
1639pub fn try_fold_list<'tcx, F, L, T>(
1640 list: L,
1641 folder: &mut F,
1642 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1643) -> Result<L, F::Error>
1644where
1645F: FallibleTypeFolder<TyCtxt<'tcx>>,
1646 L: AsRef<[T]>,
1647 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1648{
1649let slice = list.as_ref();
1650let mut iter = slice.iter().copied();
1651// Look for the first element that changed
1652match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1653Ok(new_t) if new_t == t => None,
1654 new_t => Some((i, new_t)),
1655 }) {
1656Some((i, Ok(new_t))) => {
1657// An element changed, prepare to intern the resulting list
1658let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1659new_list.extend_from_slice(&slice[..i]);
1660new_list.push(new_t);
1661for t in iter {
1662 new_list.push(t.try_fold_with(folder)?)
1663 }
1664Ok(intern(folder.cx(), &new_list))
1665 }
1666Some((_, Err(err))) => {
1667return Err(err);
1668 }
1669None => Ok(list),
1670 }
1671}
16721673#[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)]
1674pub struct AlwaysRequiresDrop;
16751676/// Reveals all opaque types in the given value, replacing them
1677/// with their underlying types.
1678pub fn reveal_opaque_types_in_bounds<'tcx>(
1679 tcx: TyCtxt<'tcx>,
1680 val: ty::Clauses<'tcx>,
1681) -> ty::Clauses<'tcx> {
1682if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1683let mut visitor = OpaqueTypeExpander {
1684 seen_opaque_tys: FxHashSet::default(),
1685 expanded_cache: FxHashMap::default(),
1686 primary_def_id: None,
1687 found_recursion: false,
1688 found_any_recursion: false,
1689 check_recursion: false,
1690tcx,
1691 };
1692val.fold_with(&mut visitor)
1693}
16941695/// Determines whether an item is directly annotated with `doc(hidden)`.
1696fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1697{
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Doc(doc)) if
doc.hidden.is_some() => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, Doc(doc) if doc.hidden.is_some())1698}
16991700/// Determines whether an item is annotated with `doc(notable_trait)`.
1701pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1702{
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Doc(doc)) if
doc.notable_trait.is_some() => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, Doc(doc) if doc.notable_trait.is_some())1703}
17041705/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1706///
1707/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1708/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1709/// cause an ICE that we otherwise may want to prevent.
1710pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1711if tcx.features().intrinsics() && {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcIntrinsic) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcIntrinsic) {
1712let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1713 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1714 !has_body1715 }
1716_ => true,
1717 };
1718Some(ty::IntrinsicDef {
1719 name: tcx.item_name(def_id),
1720must_be_overridden,
1721 const_stable: {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcIntrinsicConstStableIndirect)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcIntrinsicConstStableIndirect),
1722 })
1723 } else {
1724None1725 }
1726}
17271728pub fn provide(providers: &mut Providers) {
1729*providers = Providers {
1730reveal_opaque_types_in_bounds,
1731is_doc_hidden,
1732is_doc_notable_trait,
1733intrinsic_raw,
1734 ..*providers1735 }
1736}