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_ast::attr::AttributeExt;
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_errors::ErrorGuaranteed;
12use rustc_hashes::Hash128;
13use rustc_hir::attrs::AttributeKind;
14use rustc_hir::def::{CtorOf, DefKind, Res};
15use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
16use rustc_hir::limit::Limit;
17use rustc_hir::{selfas hir, find_attr};
18use rustc_index::bit_set::GrowableBitSet;
19use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension};
20use rustc_span::sym;
21use rustc_type_ir::solve::SizedTraitKind;
22use smallvec::{SmallVec, smallvec};
23use tracing::{debug, instrument};
2425use super::TypingEnv;
26use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
27use crate::mir;
28use crate::query::Providers;
29use crate::traits::ObligationCause;
30use crate::ty::layout::{FloatExt, IntegerExt};
31use crate::ty::{
32self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
33TypeFolder, TypeSuperFoldable, TypeVisitableExt, Upcast,
34};
3536#[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)]
37pub struct Discr<'tcx> {
38/// Bit representation of the discriminant (e.g., `-1i8` is `0xFF_u128`).
39pub val: u128,
40pub ty: Ty<'tcx>,
41}
4243/// Used as an input to [`TyCtxt::uses_unique_generic_params`].
44#[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_receiver_is_total_eq(&self) {}
}Eq)]
45pub enum CheckRegions {
46 No,
47/// Only permit parameter regions. This should be used
48 /// for everything apart from functions, which may use
49 /// `ReBound` to represent late-bound regions.
50OnlyParam,
51/// Check region parameters from a function definition.
52 /// Allows `ReEarlyParam` and `ReBound` to handle early
53 /// and late-bound region parameters.
54FromFunction,
55}
5657#[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)]
58pub enum NotUniqueParam<'tcx> {
59 DuplicateParam(ty::GenericArg<'tcx>),
60 NotParam(ty::GenericArg<'tcx>),
61}
6263impl<'tcx> fmt::Displayfor Discr<'tcx> {
64fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
65match *self.ty.kind() {
66 ty::Int(ity) => {
67let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
68let x = self.val;
69// sign extend the raw representation to be an i128
70let x = size.sign_extend(x) as i128;
71fmt.write_fmt(format_args!("{0}", x))write!(fmt, "{x}")72 }
73_ => fmt.write_fmt(format_args!("{0}", self.val))write!(fmt, "{}", self.val),
74 }
75 }
76}
7778impl<'tcx> Discr<'tcx> {
79/// Adds `1` to the value and wraps around if the maximum for the type is reached.
80pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
81self.checked_add(tcx, 1).0
82}
83pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
84let (size, signed) = self.ty.int_size_and_signed(tcx);
85let (val, oflo) = if signed {
86let min = size.signed_int_min();
87let max = size.signed_int_max();
88let val = size.sign_extend(self.val);
89if !(n < (i128::MAX as u128)) {
::core::panicking::panic("assertion failed: n < (i128::MAX as u128)")
};assert!(n < (i128::MAX as u128));
90let n = nas i128;
91let oflo = val > max - n;
92let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
93// zero the upper bits
94let val = valas u128;
95let val = size.truncate(val);
96 (val, oflo)
97 } else {
98let max = size.unsigned_int_max();
99let val = self.val;
100let oflo = val > max - n;
101let val = if oflo { n - (max - val) - 1 } else { val + n };
102 (val, oflo)
103 };
104 (Self { val, ty: self.ty }, oflo)
105 }
106}
107108impl 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)]109impl IntegerType {
110fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
111match self {
112 IntegerType::Pointer(true) => tcx.types.isize,
113 IntegerType::Pointer(false) => tcx.types.usize,
114 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
115 }
116 }
117118fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
119Discr { val: 0, ty: self.to_ty(tcx) }
120 }
121122fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
123if let Some(val) = val {
124assert_eq!(self.to_ty(tcx), val.ty);
125let (new, oflo) = val.checked_add(tcx, 1);
126if oflo { None } else { Some(new) }
127 } else {
128Some(self.initial_discriminant(tcx))
129 }
130 }
131}
132133impl<'tcx> TyCtxt<'tcx> {
134/// Creates a hash of the type `Ty` which will be the same no matter what crate
135 /// context it's calculated within. This is used by the `type_id` intrinsic.
136pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash128 {
137// We don't have region information, so we erase all free regions. Equal types
138 // must have the same `TypeId`, so we must anonymize all bound regions as well.
139let ty = self.erase_and_anonymize_regions(ty);
140141self.with_stable_hashing_context(|mut hcx| {
142let mut hasher = StableHasher::new();
143hcx.while_hashing_spans(false, |hcx| ty.hash_stable(hcx, &mut hasher));
144hasher.finish()
145 })
146 }
147148pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
149match res {
150 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
151Some(self.parent(self.parent(def_id)))
152 }
153 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
154Some(self.parent(def_id))
155 }
156// Other `DefKind`s don't have generics and would ICE when calling
157 // `generics_of`.
158Res::Def(
159 DefKind::Struct160 | DefKind::Union161 | DefKind::Enum162 | DefKind::Trait163 | DefKind::OpaqueTy164 | DefKind::TyAlias165 | DefKind::ForeignTy166 | DefKind::TraitAlias167 | DefKind::AssocTy168 | DefKind::Fn169 | DefKind::AssocFn170 | DefKind::AssocConst171 | DefKind::Impl { .. },
172 def_id,
173 ) => Some(def_id),
174 Res::Err => None,
175_ => None,
176 }
177 }
178179/// Checks whether `ty: Copy` holds while ignoring region constraints.
180 ///
181 /// This impacts whether values of `ty` are *moved* or *copied*
182 /// when referenced. This means that we may generate MIR which
183 /// does copies even when the type actually doesn't satisfy the
184 /// full requirements for the `Copy` trait (cc #29149) -- this
185 /// winds up being reported as an error during NLL borrow check.
186 ///
187 /// This function should not be used if there is an `InferCtxt` available.
188 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
189pub fn type_is_copy_modulo_regions(
190self,
191 typing_env: ty::TypingEnv<'tcx>,
192 ty: Ty<'tcx>,
193 ) -> bool {
194ty.is_trivially_pure_clone_copy() || self.is_copy_raw(typing_env.as_query_input(ty))
195 }
196197/// Checks whether `ty: UseCloned` holds while ignoring region constraints.
198 ///
199 /// This function should not be used if there is an `InferCtxt` available.
200 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
201pub fn type_is_use_cloned_modulo_regions(
202self,
203 typing_env: ty::TypingEnv<'tcx>,
204 ty: Ty<'tcx>,
205 ) -> bool {
206ty.is_trivially_pure_clone_copy() || self.is_use_cloned_raw(typing_env.as_query_input(ty))
207 }
208209/// Returns the deeply last field of nested structures, or the same type if
210 /// not a structure at all. Corresponds to the only possible unsized field,
211 /// and its type can be used to determine unsizing strategy.
212 ///
213 /// Should only be called if `ty` has no inference variables and does not
214 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
215 /// normalization attempt may cause compiler bugs.
216pub fn struct_tail_for_codegen(
217self,
218 ty: Ty<'tcx>,
219 typing_env: ty::TypingEnv<'tcx>,
220 ) -> Ty<'tcx> {
221let tcx = self;
222tcx.struct_tail_raw(
223ty,
224&ObligationCause::dummy(),
225 |ty| tcx.normalize_erasing_regions(typing_env, ty),
226 || {},
227 )
228 }
229230/// Returns true if a type has metadata.
231pub fn type_has_metadata(self, ty: Ty<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
232if ty.is_sized(self, typing_env) {
233return false;
234 }
235236let tail = self.struct_tail_for_codegen(ty, typing_env);
237match tail.kind() {
238 ty::Foreign(..) => false,
239 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
240_ => crate::util::bug::bug_fmt(format_args!("unexpected unsized tail: {0:?}",
tail))bug!("unexpected unsized tail: {:?}", tail),
241 }
242 }
243244/// Returns the deeply last field of nested structures, or the same type if
245 /// not a structure at all. Corresponds to the only possible unsized field,
246 /// and its type can be used to determine unsizing strategy.
247 ///
248 /// This is parameterized over the normalization strategy (i.e. how to
249 /// handle `<T as Trait>::Assoc` and `impl Trait`). You almost certainly do
250 /// **NOT** want to pass the identity function here, unless you know what
251 /// you're doing, or you're within normalization code itself and will handle
252 /// an unnormalized tail recursively.
253 ///
254 /// See also `struct_tail_for_codegen`, which is suitable for use
255 /// during codegen.
256pub fn struct_tail_raw(
257self,
258mut ty: Ty<'tcx>,
259 cause: &ObligationCause<'tcx>,
260mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
261// This is currently used to allow us to walk a ValTree
262 // in lockstep with the type in order to get the ValTree branch that
263 // corresponds to an unsized field.
264mut f: impl FnMut() -> (),
265 ) -> Ty<'tcx> {
266let recursion_limit = self.recursion_limit();
267for iteration in 0.. {
268if !recursion_limit.value_within_limit(iteration) {
269let suggested_limit = match recursion_limit {
270 Limit(0) => Limit(2),
271 limit => limit * 2,
272 };
273let reported = self.dcx().emit_err(crate::error::RecursionLimitReached {
274 span: cause.span,
275 ty,
276 suggested_limit,
277 });
278return Ty::new_error(self, reported);
279 }
280match *ty.kind() {
281 ty::Adt(def, args) => {
282if !def.is_struct() {
283break;
284 }
285match def.non_enum_variant().tail_opt() {
286Some(field) => {
287 f();
288 ty = field.ty(self, args);
289 }
290None => break,
291 }
292 }
293294 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
295 f();
296 ty = last_ty;
297 }
298299 ty::Tuple(_) => break,
300301 ty::Pat(inner, _) => {
302 f();
303 ty = inner;
304 }
305306 ty::Alias(..) => {
307let normalized = normalize(ty);
308if ty == normalized {
309return ty;
310 } else {
311 ty = normalized;
312 }
313 }
314315_ => {
316break;
317 }
318 }
319 }
320ty321 }
322323/// Same as applying `struct_tail` on `source` and `target`, but only
324 /// keeps going as long as the two types are instances of the same
325 /// structure definitions.
326 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
327 /// whereas struct_tail produces `T`, and `Trait`, respectively.
328 ///
329 /// Should only be called if the types have no inference variables and do
330 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
331 /// normalization attempt may cause compiler bugs.
332pub fn struct_lockstep_tails_for_codegen(
333self,
334 source: Ty<'tcx>,
335 target: Ty<'tcx>,
336 typing_env: ty::TypingEnv<'tcx>,
337 ) -> (Ty<'tcx>, Ty<'tcx>) {
338let tcx = self;
339tcx.struct_lockstep_tails_raw(source, target, |ty| {
340tcx.normalize_erasing_regions(typing_env, ty)
341 })
342 }
343344/// Same as applying `struct_tail` on `source` and `target`, but only
345 /// keeps going as long as the two types are instances of the same
346 /// structure definitions.
347 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
348 /// whereas struct_tail produces `T`, and `Trait`, respectively.
349 ///
350 /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
351 /// during codegen.
352pub fn struct_lockstep_tails_raw(
353self,
354 source: Ty<'tcx>,
355 target: Ty<'tcx>,
356 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
357 ) -> (Ty<'tcx>, Ty<'tcx>) {
358let (mut a, mut b) = (source, target);
359loop {
360match (a.kind(), b.kind()) {
361 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
362if a_def == b_def && a_def.is_struct() =>
363 {
364if let Some(f) = a_def.non_enum_variant().tail_opt() {
365a = f.ty(self, a_args);
366b = f.ty(self, b_args);
367 } else {
368break;
369 }
370 }
371 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
372if let Some(&a_last) = a_tys.last() {
373a = a_last;
374b = *b_tys.last().unwrap();
375 } else {
376break;
377 }
378 }
379 (ty::Alias(..), _) | (_, ty::Alias(..)) => {
380// If either side is a projection, attempt to
381 // progress via normalization. (Should be safe to
382 // apply to both sides as normalization is
383 // idempotent.)
384let a_norm = normalize(a);
385let b_norm = normalize(b);
386if a == a_norm && b == b_norm {
387break;
388 } else {
389a = a_norm;
390b = b_norm;
391 }
392 }
393394_ => break,
395 }
396 }
397 (a, b)
398 }
399400/// Calculate the destructor of a given type.
401pub fn calculate_dtor(
402self,
403 adt_did: LocalDefId,
404 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
405 ) -> Option<ty::Destructor> {
406let drop_trait = self.lang_items().drop_trait()?;
407self.ensure_ok().coherent_trait(drop_trait).ok()?;
408409let mut dtor_candidate = None;
410// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
411for &impl_did in self.local_trait_impls(drop_trait) {
412let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
413if adt_def.did() != adt_did.to_def_id() {
414continue;
415 }
416417if validate(self, impl_did).is_err() {
418// Already `ErrorGuaranteed`, no need to delay a span bug here.
419continue;
420 }
421422let Some(item_id) = self.associated_item_def_ids(impl_did).first() else {
423self.dcx()
424 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
425continue;
426 };
427428if self.def_kind(item_id) != DefKind::AssocFn {
429self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
430continue;
431 }
432433if let Some(old_item_id) = dtor_candidate {
434self.dcx()
435 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
436 .with_span_note(self.def_span(old_item_id), "other impl here")
437 .delay_as_bug();
438 }
439440 dtor_candidate = Some(*item_id);
441 }
442443let did = dtor_candidate?;
444Some(ty::Destructor { did })
445 }
446447/// Calculate the async destructor of a given type.
448pub fn calculate_async_dtor(
449self,
450 adt_did: LocalDefId,
451 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
452 ) -> Option<ty::AsyncDestructor> {
453let async_drop_trait = self.lang_items().async_drop_trait()?;
454self.ensure_ok().coherent_trait(async_drop_trait).ok()?;
455456let mut dtor_candidate = None;
457// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
458for &impl_did in self.local_trait_impls(async_drop_trait) {
459let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
460if adt_def.did() != adt_did.to_def_id() {
461continue;
462 }
463464if validate(self, impl_did).is_err() {
465// Already `ErrorGuaranteed`, no need to delay a span bug here.
466continue;
467 }
468469if let Some(old_impl_did) = dtor_candidate {
470self.dcx()
471 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
472 .with_span_note(self.def_span(old_impl_did), "other impl here")
473 .delay_as_bug();
474 }
475476 dtor_candidate = Some(impl_did);
477 }
478479Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
480 }
481482/// Returns the set of types that are required to be alive in
483 /// order to run the destructor of `def` (see RFCs 769 and
484 /// 1238).
485 ///
486 /// Note that this returns only the constraints for the
487 /// destructor of `def` itself. For the destructors of the
488 /// contents, you need `adt_dtorck_constraint`.
489pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
490let dtor = match def.destructor(self) {
491None => {
492{
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:492",
"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(492u32),
::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());
493return ::alloc::vec::Vec::new()vec![];
494 }
495Some(dtor) => dtor.did,
496 };
497498let impl_def_id = self.parent(dtor);
499let impl_generics = self.generics_of(impl_def_id);
500501// We have a destructor - all the parameters that are not
502 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
503 // must be live.
504505 // We need to return the list of parameters from the ADTs
506 // generics/args that correspond to impure parameters on the
507 // impl's generics. This is a bit ugly, but conceptually simple:
508 //
509 // Suppose our ADT looks like the following
510 //
511 // struct S<X, Y, Z>(X, Y, Z);
512 //
513 // and the impl is
514 //
515 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
516 //
517 // We want to return the parameters (X, Y). For that, we match
518 // up the item-args <X, Y, Z> with the args on the impl ADT,
519 // <P1, P2, P0>, and then look up which of the impl args refer to
520 // parameters marked as pure.
521522let impl_args = match *self.type_of(impl_def_id).instantiate_identity().kind() {
523 ty::Adt(def_, args) if def_ == def => args,
524_ => crate::util::bug::span_bug_fmt(self.def_span(impl_def_id),
format_args!("expected ADT for self type of `Drop` impl"))span_bug!(self.def_span(impl_def_id), "expected ADT for self type of `Drop` impl"),
525 };
526527let item_args = ty::GenericArgs::identity_for_item(self, def.did());
528529let result = iter::zip(item_args, impl_args)
530 .filter(|&(_, arg)| {
531match arg.kind() {
532GenericArgKind::Lifetime(region) => match region.kind() {
533 ty::ReEarlyParam(ebr) => {
534 !impl_generics.region_param(ebr, self).pure_wrt_drop
535 }
536// Error: not a region param
537_ => false,
538 },
539GenericArgKind::Type(ty) => match *ty.kind() {
540 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
541// Error: not a type param
542_ => false,
543 },
544GenericArgKind::Const(ct) => match ct.kind() {
545 ty::ConstKind::Param(pc) => {
546 !impl_generics.const_param(pc, self).pure_wrt_drop
547 }
548// Error: not a const param
549_ => false,
550 },
551 }
552 })
553 .map(|(item_param, _)| item_param)
554 .collect();
555{
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:555",
"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(555u32),
::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);
556result557 }
558559/// Checks whether each generic argument is simply a unique generic parameter.
560pub fn uses_unique_generic_params(
561self,
562 args: &[ty::GenericArg<'tcx>],
563 ignore_regions: CheckRegions,
564 ) -> Result<(), NotUniqueParam<'tcx>> {
565let mut seen = GrowableBitSet::default();
566let mut seen_late = FxHashSet::default();
567for arg in args {
568match arg.kind() {
569 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
570 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
571if !seen_late.insert((di, reg)) {
572return Err(NotUniqueParam::DuplicateParam(lt.into()));
573 }
574 }
575 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
576if !seen.insert(p.index) {
577return Err(NotUniqueParam::DuplicateParam(lt.into()));
578 }
579 }
580 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
581return Err(NotUniqueParam::NotParam(lt.into()));
582 }
583 (CheckRegions::No, _) => {}
584 },
585 GenericArgKind::Type(t) => match t.kind() {
586 ty::Param(p) => {
587if !seen.insert(p.index) {
588return Err(NotUniqueParam::DuplicateParam(t.into()));
589 }
590 }
591_ => return Err(NotUniqueParam::NotParam(t.into())),
592 },
593 GenericArgKind::Const(c) => match c.kind() {
594 ty::ConstKind::Param(p) => {
595if !seen.insert(p.index) {
596return Err(NotUniqueParam::DuplicateParam(c.into()));
597 }
598 }
599_ => return Err(NotUniqueParam::NotParam(c.into())),
600 },
601 }
602 }
603604Ok(())
605 }
606607/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
608 /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
609 /// have the same `DefKind`.
610 ///
611 /// Note that closures have a `DefId`, but the closure *expression* also has a
612 /// `HirId` that is located within the context where the closure appears. The
613 /// parent of the closure's `DefId` will also be the context where it appears.
614pub fn is_closure_like(self, def_id: DefId) -> bool {
615#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)616 }
617618/// Returns `true` if `def_id` refers to a definition that does not have its own
619 /// type-checking context, i.e. closure, coroutine or inline const.
620pub fn is_typeck_child(self, def_id: DefId) -> bool {
621self.def_kind(def_id).is_typeck_child()
622 }
623624/// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
625pub fn is_trait(self, def_id: DefId) -> bool {
626self.def_kind(def_id) == DefKind::Trait627 }
628629/// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
630 /// and `false` otherwise.
631pub fn is_trait_alias(self, def_id: DefId) -> bool {
632self.def_kind(def_id) == DefKind::TraitAlias633 }
634635/// Returns `true` if this `DefId` refers to the implicit constructor for
636 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
637pub fn is_constructor(self, def_id: DefId) -> bool {
638#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))639 }
640641/// Given the `DefId`, returns the `DefId` of the innermost item that
642 /// has its own type-checking context or "inference environment".
643 ///
644 /// For example, a closure has its own `DefId`, but it is type-checked
645 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
646 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
647pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
648let mut def_id = def_id;
649while self.is_typeck_child(def_id) {
650 def_id = self.parent(def_id);
651 }
652def_id653 }
654655/// Given the `DefId` and args a closure, creates the type of
656 /// `self` argument that the closure expects. For example, for a
657 /// `Fn` closure, this would return a reference type `&T` where
658 /// `T = closure_ty`.
659 ///
660 /// Returns `None` if this closure's kind has not yet been inferred.
661 /// This should only be possible during type checking.
662 ///
663 /// Note that the return value is a late-bound region and hence
664 /// wrapped in a binder.
665pub fn closure_env_ty(
666self,
667 closure_ty: Ty<'tcx>,
668 closure_kind: ty::ClosureKind,
669 env_region: ty::Region<'tcx>,
670 ) -> Ty<'tcx> {
671match closure_kind {
672 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
673 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
674 ty::ClosureKind::FnOnce => closure_ty,
675 }
676 }
677678/// Returns `true` if the node pointed to by `def_id` is a `static` item.
679#[inline]
680pub fn is_static(self, def_id: DefId) -> bool {
681#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })682 }
683684#[inline]
685pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
686if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
687Some(mutability)
688 } else {
689None690 }
691 }
692693/// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
694pub fn is_thread_local_static(self, def_id: DefId) -> bool {
695self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
696 }
697698/// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
699#[inline]
700pub fn is_mutable_static(self, def_id: DefId) -> bool {
701self.static_mutability(def_id) == Some(hir::Mutability::Mut)
702 }
703704/// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
705 /// thread local shim generated.
706#[inline]
707pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
708 !self.sess.target.dll_tls_export
709 && self.is_thread_local_static(def_id)
710 && !self.is_foreign_item(def_id)
711 }
712713/// Returns the type a reference to the thread local takes in MIR.
714pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
715let static_ty = self.type_of(def_id).instantiate_identity();
716if self.is_mutable_static(def_id) {
717Ty::new_mut_ptr(self, static_ty)
718 } else if self.is_foreign_item(def_id) {
719Ty::new_imm_ptr(self, static_ty)
720 } else {
721// FIXME: These things don't *really* have 'static lifetime.
722Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
723 }
724 }
725726/// Get the type of the pointer to the static that we use in MIR.
727pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
728// Make sure that any constants in the static's type are evaluated.
729let static_ty =
730self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
731732// Make sure that accesses to unsafe statics end up using raw pointers.
733 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
734if self.is_mutable_static(def_id) {
735Ty::new_mut_ptr(self, static_ty)
736 } else if self.is_foreign_item(def_id) {
737Ty::new_imm_ptr(self, static_ty)
738 } else {
739Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
740 }
741 }
742743/// Expands the given impl trait type, stopping if the type is recursive.
744x;#[instrument(skip(self), level = "debug", ret)]745pub fn try_expand_impl_trait_type(
746self,
747 def_id: DefId,
748 args: GenericArgsRef<'tcx>,
749 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
750let mut visitor = OpaqueTypeExpander {
751 seen_opaque_tys: FxHashSet::default(),
752 expanded_cache: FxHashMap::default(),
753 primary_def_id: Some(def_id),
754 found_recursion: false,
755 found_any_recursion: false,
756 check_recursion: true,
757 tcx: self,
758 };
759760let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
761if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
762 }
763764/// Query and get an English description for the item's kind.
765pub fn def_descr(self, def_id: DefId) -> &'static str {
766self.def_kind_descr(self.def_kind(def_id), def_id)
767 }
768769/// Get an English description for the item's kind.
770pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
771match def_kind {
772 DefKind::AssocFnif self.associated_item(def_id).is_method() => "method",
773 DefKind::AssocTyif self.opt_rpitit_info(def_id).is_some() => "opaque type",
774 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
775match coroutine_kind {
776 hir::CoroutineKind::Desugared(
777 hir::CoroutineDesugaring::Async,
778 hir::CoroutineSource::Fn,
779 ) => "async fn",
780 hir::CoroutineKind::Desugared(
781 hir::CoroutineDesugaring::Async,
782 hir::CoroutineSource::Block,
783 ) => "async block",
784 hir::CoroutineKind::Desugared(
785 hir::CoroutineDesugaring::Async,
786 hir::CoroutineSource::Closure,
787 ) => "async closure",
788 hir::CoroutineKind::Desugared(
789 hir::CoroutineDesugaring::AsyncGen,
790 hir::CoroutineSource::Fn,
791 ) => "async gen fn",
792 hir::CoroutineKind::Desugared(
793 hir::CoroutineDesugaring::AsyncGen,
794 hir::CoroutineSource::Block,
795 ) => "async gen block",
796 hir::CoroutineKind::Desugared(
797 hir::CoroutineDesugaring::AsyncGen,
798 hir::CoroutineSource::Closure,
799 ) => "async gen closure",
800 hir::CoroutineKind::Desugared(
801 hir::CoroutineDesugaring::Gen,
802 hir::CoroutineSource::Fn,
803 ) => "gen fn",
804 hir::CoroutineKind::Desugared(
805 hir::CoroutineDesugaring::Gen,
806 hir::CoroutineSource::Block,
807 ) => "gen block",
808 hir::CoroutineKind::Desugared(
809 hir::CoroutineDesugaring::Gen,
810 hir::CoroutineSource::Closure,
811 ) => "gen closure",
812 hir::CoroutineKind::Coroutine(_) => "coroutine",
813 }
814 }
815_ => def_kind.descr(def_id),
816 }
817 }
818819/// Gets an English article for the [`TyCtxt::def_descr`].
820pub fn def_descr_article(self, def_id: DefId) -> &'static str {
821self.def_kind_descr_article(self.def_kind(def_id), def_id)
822 }
823824/// Gets an English article for the [`TyCtxt::def_kind_descr`].
825pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
826match def_kind {
827 DefKind::AssocFnif self.associated_item(def_id).is_method() => "a",
828 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
829match coroutine_kind {
830 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
831 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
832 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
833 hir::CoroutineKind::Coroutine(_) => "a",
834 }
835 }
836_ => def_kind.article(),
837 }
838 }
839840/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
841 /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
842 /// be shown in `impl` suggestions.
843 ///
844 /// [public]: TyCtxt::is_private_dep
845 /// [direct]: rustc_session::cstore::ExternCrate::is_direct
846pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
847// `#![rustc_private]` overrides defaults to make private dependencies usable.
848if self.features().enabled(sym::rustc_private) {
849return true;
850 }
851852// | Private | Direct | Visible | |
853 // |---------|--------|---------|--------------------|
854 // | Yes | Yes | Yes | !true || true |
855 // | No | Yes | Yes | !false || true |
856 // | Yes | No | No | !true || false |
857 // | No | No | Yes | !false || false |
858!self.is_private_dep(key)
859// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
860 // Treat that kind of crate as "indirect", since it's an implementation detail of
861 // the language.
862|| self.extern_crate(key).is_some_and(|e| e.is_direct())
863 }
864865/// Expand any [free alias types][free] contained within the given `value`.
866 ///
867 /// This should be used over other normalization routines in situations where
868 /// it's important not to normalize other alias types and where the predicates
869 /// on the corresponding type alias shouldn't be taken into consideration.
870 ///
871 /// Whenever possible **prefer not to use this function**! Instead, use standard
872 /// normalization routines or if feasible don't normalize at all.
873 ///
874 /// This function comes in handy if you want to mimic the behavior of eager
875 /// type alias expansion in a localized manner.
876 ///
877 /// <div class="warning">
878 /// This delays a bug on overflow! Therefore you need to be certain that the
879 /// contained types get fully normalized at a later stage. Note that even on
880 /// overflow all well-behaved free alias types get expanded correctly, so the
881 /// result is still useful.
882 /// </div>
883 ///
884 /// [free]: ty::Free
885pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
886value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
887 }
888889/// Peel off all [free alias types] in this type until there are none left.
890 ///
891 /// This only expands free alias types in “head” / outermost positions. It can
892 /// be used over [expand_free_alias_tys] as an optimization in situations where
893 /// one only really cares about the *kind* of the final aliased type but not
894 /// the types the other constituent types alias.
895 ///
896 /// <div class="warning">
897 /// This delays a bug on overflow! Therefore you need to be certain that the
898 /// type gets fully normalized at a later stage.
899 /// </div>
900 ///
901 /// [free]: ty::Free
902 /// [expand_free_alias_tys]: Self::expand_free_alias_tys
903pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
904let ty::Alias(ty::Free, _) = ty.kind() else { return ty };
905906let limit = self.recursion_limit();
907let mut depth = 0;
908909while let ty::Alias(ty::Free, alias) = ty.kind() {
910if !limit.value_within_limit(depth) {
911let guar = self.dcx().delayed_bug("overflow expanding free alias type");
912return Ty::new_error(self, guar);
913 }
914915 ty = self.type_of(alias.def_id).instantiate(self, alias.args);
916 depth += 1;
917 }
918919ty920 }
921922// Computes the variances for an alias (opaque or RPITIT) that represent
923 // its (un)captured regions.
924pub fn opt_alias_variances(
925self,
926 kind: impl Into<ty::AliasTermKind>,
927 def_id: DefId,
928 ) -> Option<&'tcx [ty::Variance]> {
929match kind.into() {
930 ty::AliasTermKind::ProjectionTy => {
931if self.is_impl_trait_in_trait(def_id) {
932Some(self.variances_of(def_id))
933 } else {
934None935 }
936 }
937 ty::AliasTermKind::OpaqueTy => Some(self.variances_of(def_id)),
938 ty::AliasTermKind::InherentTy939 | ty::AliasTermKind::InherentConst940 | ty::AliasTermKind::FreeTy941 | ty::AliasTermKind::FreeConst942 | ty::AliasTermKind::UnevaluatedConst943 | ty::AliasTermKind::ProjectionConst => None,
944 }
945 }
946}
947948struct OpaqueTypeExpander<'tcx> {
949// Contains the DefIds of the opaque types that are currently being
950 // expanded. When we expand an opaque type we insert the DefId of
951 // that type, and when we finish expanding that type we remove the
952 // its DefId.
953seen_opaque_tys: FxHashSet<DefId>,
954// Cache of all expansions we've seen so far. This is a critical
955 // optimization for some large types produced by async fn trees.
956expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
957 primary_def_id: Option<DefId>,
958 found_recursion: bool,
959 found_any_recursion: bool,
960/// Whether or not to check for recursive opaque types.
961 /// This is `true` when we're explicitly checking for opaque type
962 /// recursion, and 'false' otherwise to avoid unnecessary work.
963check_recursion: bool,
964 tcx: TyCtxt<'tcx>,
965}
966967impl<'tcx> OpaqueTypeExpander<'tcx> {
968fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
969if self.found_any_recursion {
970return None;
971 }
972let args = args.fold_with(self);
973if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
974let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
975Some(expanded_ty) => *expanded_ty,
976None => {
977let generic_ty = self.tcx.type_of(def_id);
978let concrete_ty = generic_ty.instantiate(self.tcx, args);
979let expanded_ty = self.fold_ty(concrete_ty);
980self.expanded_cache.insert((def_id, args), expanded_ty);
981expanded_ty982 }
983 };
984if self.check_recursion {
985self.seen_opaque_tys.remove(&def_id);
986 }
987Some(expanded_ty)
988 } else {
989// If another opaque type that we contain is recursive, then it
990 // will report the error, so we don't have to.
991self.found_any_recursion = true;
992self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
993None994 }
995 }
996}
997998impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
999fn cx(&self) -> TyCtxt<'tcx> {
1000self.tcx
1001 }
10021003fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1004if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *t.kind() {
1005self.expand_opaque_ty(def_id, args).unwrap_or(t)
1006 } else if t.has_opaque_types() {
1007t.super_fold_with(self)
1008 } else {
1009t1010 }
1011 }
10121013fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1014if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1015 && let ty::ClauseKind::Projection(projection_pred) = clause1016 {
1017p.kind()
1018 .rebind(ty::ProjectionPredicate {
1019 projection_term: projection_pred.projection_term.fold_with(self),
1020// Don't fold the term on the RHS of the projection predicate.
1021 // This is because for default trait methods with RPITITs, we
1022 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1023 // predicate, which would trivially cause a cycle when we do
1024 // anything that requires `TypingEnv::with_post_analysis_normalized`.
1025term: projection_pred.term,
1026 })
1027 .upcast(self.tcx)
1028 } else {
1029p.super_fold_with(self)
1030 }
1031 }
1032}
10331034struct FreeAliasTypeExpander<'tcx> {
1035 tcx: TyCtxt<'tcx>,
1036 depth: usize,
1037}
10381039impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1040fn cx(&self) -> TyCtxt<'tcx> {
1041self.tcx
1042 }
10431044fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1045if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1046return ty;
1047 }
1048let ty::Alias(ty::Free, alias) = ty.kind() else {
1049return ty.super_fold_with(self);
1050 };
1051if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1052let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1053return Ty::new_error(self.tcx, guar);
1054 }
10551056self.depth += 1;
1057let ty = ensure_sufficient_stack(|| {
1058self.tcx.type_of(alias.def_id).instantiate(self.tcx, alias.args).fold_with(self)
1059 });
1060self.depth -= 1;
1061ty1062 }
10631064fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1065if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1066return ct;
1067 }
1068ct.super_fold_with(self)
1069 }
1070}
10711072impl<'tcx> Ty<'tcx> {
1073/// Returns the `Size` for primitive types (bool, uint, int, char, float).
1074pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1075match *self.kind() {
1076 ty::Bool => Size::from_bytes(1),
1077 ty::Char => Size::from_bytes(4),
1078 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1079 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1080 ty::Float(fty) => Float::from_float_ty(fty).size(),
1081_ => crate::util::bug::bug_fmt(format_args!("non primitive type"))bug!("non primitive type"),
1082 }
1083 }
10841085pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1086match *self.kind() {
1087 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1088 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1089_ => crate::util::bug::bug_fmt(format_args!("non integer discriminant"))bug!("non integer discriminant"),
1090 }
1091 }
10921093/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1094 /// returns `None` if the type is not numeric.
1095pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1096use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1097Some(match self.kind() {
1098 ty::Int(_) | ty::Uint(_) => {
1099let (size, signed) = self.int_size_and_signed(tcx);
1100let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1101let max =
1102if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1103 (min, max)
1104 }
1105 ty::Char => (0, std::char::MAXas u128),
1106 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1107 ty::Float(ty::FloatTy::F32) => {
1108 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1109 }
1110 ty::Float(ty::FloatTy::F64) => {
1111 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1112 }
1113 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1114_ => return None,
1115 })
1116 }
11171118/// Returns the maximum value for the given numeric type (including `char`s)
1119 /// or returns `None` if the type is not numeric.
1120pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1121let typing_env = TypingEnv::fully_monomorphized();
1122self.numeric_min_and_max_as_bits(tcx)
1123 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1124 }
11251126/// Returns the minimum value for the given numeric type (including `char`s)
1127 /// or returns `None` if the type is not numeric.
1128pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1129let typing_env = TypingEnv::fully_monomorphized();
1130self.numeric_min_and_max_as_bits(tcx)
1131 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1132 }
11331134/// Checks whether values of this type `T` have a size known at
1135 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1136 /// for the purposes of this check, so it can be an
1137 /// over-approximation in generic contexts, where one can have
1138 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1139 /// actually carry lifetime requirements.
1140pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1141self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1142 || tcx.is_sized_raw(typing_env.as_query_input(self))
1143 }
11441145/// Checks whether values of this type `T` implement the `Freeze`
1146 /// trait -- frozen types are those that do not contain an
1147 /// `UnsafeCell` anywhere. This is a language concept used to
1148 /// distinguish "true immutability", which is relevant to
1149 /// optimization as well as the rules around static values. Note
1150 /// that the `Freeze` trait is not exposed to end users and is
1151 /// effectively an implementation detail.
1152pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1153self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1154 }
11551156/// Fast path helper for testing if a type is `Freeze`.
1157 ///
1158 /// Returning true means the type is known to be `Freeze`. Returning
1159 /// `false` means nothing -- could be `Freeze`, might not be.
1160pub fn is_trivially_freeze(self) -> bool {
1161match self.kind() {
1162 ty::Int(_)
1163 | ty::Uint(_)
1164 | ty::Float(_)
1165 | ty::Bool1166 | ty::Char1167 | ty::Str1168 | ty::Never1169 | ty::Ref(..)
1170 | ty::RawPtr(_, _)
1171 | ty::FnDef(..)
1172 | ty::Error(_)
1173 | ty::FnPtr(..) => true,
1174 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1175 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1176 ty::Adt(..)
1177 | ty::Bound(..)
1178 | ty::Closure(..)
1179 | ty::CoroutineClosure(..)
1180 | ty::Dynamic(..)
1181 | ty::Foreign(_)
1182 | ty::Coroutine(..)
1183 | ty::CoroutineWitness(..)
1184 | ty::UnsafeBinder(_)
1185 | ty::Infer(_)
1186 | ty::Alias(..)
1187 | ty::Param(_)
1188 | ty::Placeholder(_) => false,
1189 }
1190 }
11911192/// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1193pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1194self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1195 }
11961197/// Checks whether values of this type `T` implement the `Unpin` trait.
1198 ///
1199 /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1200 /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1201 /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1202pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1203self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1204 }
12051206/// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1207 ///
1208 /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1209 /// `false` means nothing -- could be `Unpin`, might not be.
1210fn is_trivially_unpin(self) -> bool {
1211match self.kind() {
1212 ty::Int(_)
1213 | ty::Uint(_)
1214 | ty::Float(_)
1215 | ty::Bool1216 | ty::Char1217 | ty::Str1218 | ty::Never1219 | ty::Ref(..)
1220 | ty::RawPtr(_, _)
1221 | ty::FnDef(..)
1222 | ty::Error(_)
1223 | ty::FnPtr(..) => true,
1224 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1225 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1226 ty::Adt(..)
1227 | ty::Bound(..)
1228 | ty::Closure(..)
1229 | ty::CoroutineClosure(..)
1230 | ty::Dynamic(..)
1231 | ty::Foreign(_)
1232 | ty::Coroutine(..)
1233 | ty::CoroutineWitness(..)
1234 | ty::UnsafeBinder(_)
1235 | ty::Infer(_)
1236 | ty::Alias(..)
1237 | ty::Param(_)
1238 | ty::Placeholder(_) => false,
1239 }
1240 }
12411242/// Checks whether this type is an ADT that has unsafe fields.
1243pub fn has_unsafe_fields(self) -> bool {
1244if let ty::Adt(adt_def, ..) = self.kind() {
1245adt_def.all_fields().any(|x| x.safety.is_unsafe())
1246 } else {
1247false
1248}
1249 }
12501251/// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1252pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1253 !self.is_trivially_not_async_drop()
1254 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1255 }
12561257/// Fast path helper for testing if a type is `AsyncDrop`.
1258 ///
1259 /// Returning true means the type is known to be `!AsyncDrop`. Returning
1260 /// `false` means nothing -- could be `AsyncDrop`, might not be.
1261fn is_trivially_not_async_drop(self) -> bool {
1262match self.kind() {
1263 ty::Int(_)
1264 | ty::Uint(_)
1265 | ty::Float(_)
1266 | ty::Bool1267 | ty::Char1268 | ty::Str1269 | ty::Never1270 | ty::Ref(..)
1271 | ty::RawPtr(..)
1272 | ty::FnDef(..)
1273 | ty::Error(_)
1274 | ty::FnPtr(..) => true,
1275// FIXME(unsafe_binders):
1276 ty::UnsafeBinder(_) => ::core::panicking::panic("not yet implemented")todo!(),
1277 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1278 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1279elem_ty.is_trivially_not_async_drop()
1280 }
1281 ty::Adt(..)
1282 | ty::Bound(..)
1283 | ty::Closure(..)
1284 | ty::CoroutineClosure(..)
1285 | ty::Dynamic(..)
1286 | ty::Foreign(_)
1287 | ty::Coroutine(..)
1288 | ty::CoroutineWitness(..)
1289 | ty::Infer(_)
1290 | ty::Alias(..)
1291 | ty::Param(_)
1292 | ty::Placeholder(_) => false,
1293 }
1294 }
12951296/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1297 /// non-copy and *might* have a destructor attached; if it returns
1298 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1299 ///
1300 /// (Note that this implies that if `ty` has a destructor attached,
1301 /// then `needs_drop` will definitely return `true` for `ty`.)
1302 ///
1303 /// Note that this method is used to check eligible types in unions.
1304#[inline]
1305pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1306// Avoid querying in simple cases.
1307match needs_drop_components(tcx, self) {
1308Err(AlwaysRequiresDrop) => true,
1309Ok(components) => {
1310let query_ty = match *components {
1311 [] => return false,
1312// If we've got a single component, call the query with that
1313 // to increase the chance that we hit the query cache.
1314[component_ty] => component_ty,
1315_ => self,
1316 };
13171318// This doesn't depend on regions, so try to minimize distinct
1319 // query keys used. If normalization fails, we just use `query_ty`.
1320if 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());
1321let query_ty = tcx1322 .try_normalize_erasing_regions(typing_env, query_ty)
1323 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13241325tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1326 }
1327 }
1328 }
13291330/// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1331 /// non-copy and *might* have a async destructor attached; if it returns
1332 /// `false`, then `ty` definitely has no async destructor (i.e., no async
1333 /// drop glue).
1334 ///
1335 /// (Note that this implies that if `ty` has an async destructor attached,
1336 /// then `needs_async_drop` will definitely return `true` for `ty`.)
1337 ///
1338// FIXME(zetanumbers): Note that this method is used to check eligible types
1339 // in unions.
1340#[inline]
1341pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1342// Avoid querying in simple cases.
1343match needs_drop_components(tcx, self) {
1344Err(AlwaysRequiresDrop) => true,
1345Ok(components) => {
1346let query_ty = match *components {
1347 [] => return false,
1348// If we've got a single component, call the query with that
1349 // to increase the chance that we hit the query cache.
1350[component_ty] => component_ty,
1351_ => self,
1352 };
13531354// This doesn't depend on regions, so try to minimize distinct
1355 // query keys used.
1356 // If normalization fails, we just use `query_ty`.
1357if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1358let query_ty = tcx1359 .try_normalize_erasing_regions(typing_env, query_ty)
1360 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13611362tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1363 }
1364 }
1365 }
13661367/// Checks if `ty` has a significant drop.
1368 ///
1369 /// Note that this method can return false even if `ty` has a destructor
1370 /// attached; even if that is the case then the adt has been marked with
1371 /// the attribute `rustc_insignificant_dtor`.
1372 ///
1373 /// Note that this method is used to check for change in drop order for
1374 /// 2229 drop reorder migration analysis.
1375#[inline]
1376pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1377// Avoid querying in simple cases.
1378match needs_drop_components(tcx, self) {
1379Err(AlwaysRequiresDrop) => true,
1380Ok(components) => {
1381let query_ty = match *components {
1382 [] => return false,
1383// If we've got a single component, call the query with that
1384 // to increase the chance that we hit the query cache.
1385[component_ty] => component_ty,
1386_ => self,
1387 };
13881389// FIXME
1390 // We should be canonicalizing, or else moving this to a method of inference
1391 // context, or *something* like that,
1392 // but for now just avoid passing inference variables
1393 // to queries that can't cope with them.
1394 // Instead, conservatively return "true" (may change drop order).
1395if query_ty.has_infer() {
1396return true;
1397 }
13981399// This doesn't depend on regions, so try to minimize distinct
1400 // query keys used.
1401 // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1402tcx.try_normalize_erasing_regions(typing_env, query_ty)
1403 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1404 .unwrap_or(true)
1405 }
1406 }
1407 }
14081409/// Returns `true` if equality for this type is both reflexive and structural.
1410 ///
1411 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1412 ///
1413 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1414 /// types, equality for the type as a whole is structural when it is the same as equality
1415 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1416 /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1417 ///
1418 /// This function is "shallow" because it may return `true` for a composite type whose fields
1419 /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1420 /// because equality for arrays is determined by the equality of each array element. If you
1421 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1422 /// down, you will need to use a type visitor.
1423#[inline]
1424pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1425match self.kind() {
1426// Look for an impl of `StructuralPartialEq`.
1427ty::Adt(..) => tcx.has_structural_eq_impl(self),
14281429// Primitive types that satisfy `Eq`.
1430ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
14311432// Composite types that satisfy `Eq` when all of their fields do.
1433 //
1434 // Because this function is "shallow", we return `true` for these composites regardless
1435 // of the type(s) contained within.
1436ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
14371438// Raw pointers use bitwise comparison.
1439ty::RawPtr(_, _) | ty::FnPtr(..) => true,
14401441// Floating point numbers are not `Eq`.
1442ty::Float(_) => false,
14431444// Conservatively return `false` for all others...
14451446 // Anonymous function types
1447ty::FnDef(..)
1448 | ty::Closure(..)
1449 | ty::CoroutineClosure(..)
1450 | ty::Dynamic(..)
1451 | ty::Coroutine(..) => false,
14521453// Generic or inferred types
1454 //
1455 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1456 // called for known, fully-monomorphized types.
1457ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1458false
1459}
14601461 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1462 }
1463 }
14641465/// Peel off all reference types in this type until there are none left.
1466 ///
1467 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1468 ///
1469 /// # Examples
1470 ///
1471 /// - `u8` -> `u8`
1472 /// - `&'a mut u8` -> `u8`
1473 /// - `&'a &'b u8` -> `u8`
1474 /// - `&'a *const &'b u8 -> *const &'b u8`
1475pub fn peel_refs(self) -> Ty<'tcx> {
1476let mut ty = self;
1477while let ty::Ref(_, inner_ty, _) = ty.kind() {
1478 ty = *inner_ty;
1479 }
1480ty1481 }
14821483// FIXME(compiler-errors): Think about removing this.
1484#[inline]
1485pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
1486self.0.outer_exclusive_binder
1487 }
1488}
14891490/// Returns a list of types such that the given type needs drop if and only if
1491/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1492/// this type always needs drop.
1493//
1494// FIXME(zetanumbers): consider replacing this with only
1495// `needs_drop_components_with_async`
1496#[inline]
1497pub fn needs_drop_components<'tcx>(
1498 tcx: TyCtxt<'tcx>,
1499 ty: Ty<'tcx>,
1500) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1501needs_drop_components_with_async(tcx, ty, Asyncness::No)
1502}
15031504/// Returns a list of types such that the given type needs drop if and only if
1505/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1506/// this type always needs drop.
1507pub fn needs_drop_components_with_async<'tcx>(
1508 tcx: TyCtxt<'tcx>,
1509 ty: Ty<'tcx>,
1510 asyncness: Asyncness,
1511) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1512match *ty.kind() {
1513 ty::Infer(ty::FreshIntTy(_))
1514 | ty::Infer(ty::FreshFloatTy(_))
1515 | ty::Bool1516 | ty::Int(_)
1517 | ty::Uint(_)
1518 | ty::Float(_)
1519 | ty::Never1520 | ty::FnDef(..)
1521 | ty::FnPtr(..)
1522 | ty::Char1523 | ty::RawPtr(_, _)
1524 | ty::Ref(..)
1525 | ty::Str => Ok(SmallVec::new()),
15261527// Foreign types can never have destructors.
1528ty::Foreign(..) => Ok(SmallVec::new()),
15291530// FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1531ty::Dynamic(..) | ty::Error(_) => {
1532if asyncness.is_async() {
1533Ok(SmallVec::new())
1534 } else {
1535Err(AlwaysRequiresDrop)
1536 }
1537 }
15381539 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1540 ty::Array(elem_ty, size) => {
1541match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1542Ok(v) if v.is_empty() => Ok(v),
1543 res => match size.try_to_target_usize(tcx) {
1544// Arrays of size zero don't need drop, even if their element
1545 // type does.
1546Some(0) => Ok(SmallVec::new()),
1547Some(_) => res,
1548// We don't know which of the cases above we are in, so
1549 // return the whole type and let the caller decide what to
1550 // do.
1551None => 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(<[_]>::into_vec(::alloc::boxed::box_new([ty])))
}
}smallvec![ty]),
1552 },
1553 }
1554 }
1555// If any field needs drop, then the whole tuple does.
1556ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1557acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1558Ok(acc)
1559 }),
15601561// These require checking for `Copy` bounds or `Adt` destructors.
1562ty::Adt(..)
1563 | ty::Alias(..)
1564 | ty::Param(_)
1565 | ty::Bound(..)
1566 | ty::Placeholder(..)
1567 | ty::Infer(_)
1568 | ty::Closure(..)
1569 | ty::CoroutineClosure(..)
1570 | ty::Coroutine(..)
1571 | ty::CoroutineWitness(..)
1572 | 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(<[_]>::into_vec(::alloc::boxed::box_new([ty])))
}
}smallvec![ty]),
1573 }
1574}
15751576/// Does the equivalent of
1577/// ```ignore (illustrative)
1578/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1579/// folder.tcx().intern_*(&v)
1580/// ```
1581pub fn fold_list<'tcx, F, L, T>(
1582 list: L,
1583 folder: &mut F,
1584 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1585) -> L
1586where
1587F: TypeFolder<TyCtxt<'tcx>>,
1588 L: AsRef<[T]>,
1589 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1590{
1591let slice = list.as_ref();
1592let mut iter = slice.iter().copied();
1593// Look for the first element that changed
1594match iter.by_ref().enumerate().find_map(|(i, t)| {
1595let new_t = t.fold_with(folder);
1596if new_t != t { Some((i, new_t)) } else { None }
1597 }) {
1598Some((i, new_t)) => {
1599// An element changed, prepare to intern the resulting list
1600let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1601new_list.extend_from_slice(&slice[..i]);
1602new_list.push(new_t);
1603for t in iter {
1604 new_list.push(t.fold_with(folder))
1605 }
1606intern(folder.cx(), &new_list)
1607 }
1608None => list,
1609 }
1610}
16111612/// Does the equivalent of
1613/// ```ignore (illustrative)
1614/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1615/// folder.tcx().intern_*(&v)
1616/// ```
1617pub fn try_fold_list<'tcx, F, L, T>(
1618 list: L,
1619 folder: &mut F,
1620 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1621) -> Result<L, F::Error>
1622where
1623F: FallibleTypeFolder<TyCtxt<'tcx>>,
1624 L: AsRef<[T]>,
1625 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1626{
1627let slice = list.as_ref();
1628let mut iter = slice.iter().copied();
1629// Look for the first element that changed
1630match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1631Ok(new_t) if new_t == t => None,
1632 new_t => Some((i, new_t)),
1633 }) {
1634Some((i, Ok(new_t))) => {
1635// An element changed, prepare to intern the resulting list
1636let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1637new_list.extend_from_slice(&slice[..i]);
1638new_list.push(new_t);
1639for t in iter {
1640 new_list.push(t.try_fold_with(folder)?)
1641 }
1642Ok(intern(folder.cx(), &new_list))
1643 }
1644Some((_, Err(err))) => {
1645return Err(err);
1646 }
1647None => Ok(list),
1648 }
1649}
16501651#[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<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
for AlwaysRequiresDrop {
#[inline]
fn hash_stable(&self,
__hcx:
&mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self { AlwaysRequiresDrop => {} }
}
}
};HashStable, 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)]
1652pub struct AlwaysRequiresDrop;
16531654/// Reveals all opaque types in the given value, replacing them
1655/// with their underlying types.
1656pub fn reveal_opaque_types_in_bounds<'tcx>(
1657 tcx: TyCtxt<'tcx>,
1658 val: ty::Clauses<'tcx>,
1659) -> ty::Clauses<'tcx> {
1660if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1661let mut visitor = OpaqueTypeExpander {
1662 seen_opaque_tys: FxHashSet::default(),
1663 expanded_cache: FxHashMap::default(),
1664 primary_def_id: None,
1665 found_recursion: false,
1666 found_any_recursion: false,
1667 check_recursion: false,
1668tcx,
1669 };
1670val.fold_with(&mut visitor)
1671}
16721673/// Determines whether an item is directly annotated with `doc(hidden)`.
1674fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1675let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
1676attrs.iter().any(|attr| attr.is_doc_hidden())
1677}
16781679/// Determines whether an item is annotated with `doc(notable_trait)`.
1680pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1681let attrs = tcx.get_all_attrs(def_id);
1682attrs.iter().any(|attr| #[allow(non_exhaustive_omitted_patterns)] match attr {
hir::Attribute::Parsed(AttributeKind::Doc(doc)) if
doc.notable_trait.is_some() => true,
_ => false,
}matches!(attr, hir::Attribute::Parsed(AttributeKind::Doc(doc)) if doc.notable_trait.is_some()))
1683}
16841685/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1686///
1687/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1688/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1689/// cause an ICE that we otherwise may want to prevent.
1690pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1691if tcx.features().intrinsics()
1692 && {
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcIntrinsic)
=> {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcIntrinsic)1693 {
1694let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1695 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1696 !has_body1697 }
1698_ => true,
1699 };
1700Some(ty::IntrinsicDef {
1701 name: tcx.item_name(def_id),
1702must_be_overridden,
1703 const_stable: {
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcIntrinsicConstStableIndirect)
=> {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(
1704 tcx.get_all_attrs(def_id),
1705 AttributeKind::RustcIntrinsicConstStableIndirect
1706 ),
1707 })
1708 } else {
1709None1710 }
1711}
17121713pub fn provide(providers: &mut Providers) {
1714*providers = Providers {
1715reveal_opaque_types_in_bounds,
1716is_doc_hidden,
1717is_doc_notable_trait,
1718intrinsic_raw,
1719 ..*providers1720 }
1721}