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_attr_ir::find_attr;
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_hiras hir;
13use rustc_hir::def::{CtorOf, DefKind, Res};
14use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
15use rustc_index::bit_set::GrowableBitSet;
16use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
17use rustc_span::{bug, span_bug, sym};
18use rustc_structures::Limit;
19use rustc_type_ir::PredicateProxy;
20use rustc_type_ir::solve::SizedTraitKind;
21use smallvec::{SmallVec, smallvec};
22use tracing::{debug, instrument};
2324use super::TypingEnv;
25use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
26use crate::mir;
27use crate::query::Providers;
28use crate::traits::ObligationCause;
29use crate::ty::layout::{FloatExt, IntegerExt};
30use crate::ty::{
31self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
32TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized,
33};
3435#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Discr<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for Discr<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Discr<'tcx> {
#[inline]
fn clone(&self) -> Self {
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)]
36pub struct Discr<'tcx> {
37/// Bit representation of the discriminant (e.g., `-1i8` is `0xFF_u128`).
38pub val: u128,
39pub ty: Ty<'tcx>,
40}
4142/// Used as an input to [`TyCtxt::uses_unique_generic_params`].
43#[derive(#[automatically_derived]
impl ::core::marker::Copy for CheckRegions { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CheckRegions { }
#[automatically_derived]
impl ::core::clone::Clone for CheckRegions {
#[inline]
fn clone(&self) -> Self { *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::marker::StructuralPartialEq for CheckRegions { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CheckRegions {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CheckRegions { }Eq)]
44pub enum CheckRegions {
45 No,
46/// Only permit parameter regions. This should be used
47 /// for everything apart from functions, which may use
48 /// `ReBound` to represent late-bound regions.
49OnlyParam,
50/// Check region parameters from a function definition.
51 /// Allows `ReEarlyParam` and `ReBound` to handle early
52 /// and late-bound region parameters.
53FromFunction,
54}
5556#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NotUniqueParam<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for NotUniqueParam<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for NotUniqueParam<'tcx> {
#[inline]
fn clone(&self) -> Self {
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 {
Self::DuplicateParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DuplicateParam", &__self_0),
Self::NotParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NotParam", &__self_0),
}
}
}Debug)]
57pub enum NotUniqueParam<'tcx> {
58 DuplicateParam(ty::GenericArg<'tcx>),
59 NotParam(ty::GenericArg<'tcx>),
60}
6162impl<'tcx> fmt::Displayfor Discr<'tcx> {
63fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
64match *self.ty.kind() {
65 ty::Int(ity) => {
66let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
67let x = self.val;
68// sign extend the raw representation to be an i128
69let x = size.sign_extend(x) as i128;
70fmt.write_fmt(format_args!("{0}", x))write!(fmt, "{x}")71 }
72_ => fmt.write_fmt(format_args!("{0}", self.val))write!(fmt, "{}", self.val),
73 }
74 }
75}
7677impl<'tcx> Discr<'tcx> {
78/// Adds `1` to the value and wraps around if the maximum for the type is reached.
79pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
80self.checked_add(tcx, 1).0
81}
82pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
83let (size, signed) = self.ty.int_size_and_signed(tcx);
84let (val, oflo) = if signed {
85let min = size.signed_int_min();
86let max = size.signed_int_max();
87let val = size.sign_extend(self.val);
88if !(n < (i128::MAX as u128)) {
::core::panicking::panic("assertion failed: n < (i128::MAX as u128)")
};assert!(n < (i128::MAX as u128));
89let n = nas i128;
90let oflo = val > max - n;
91let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
92// zero the upper bits
93let val = valas u128;
94let val = size.truncate(val);
95 (val, oflo)
96 } else {
97let max = size.unsigned_int_max();
98let val = self.val;
99let oflo = val > max - n;
100let val = if oflo { n - (max - val) - 1 } else { val + n };
101 (val, oflo)
102 };
103 (Self { val, ty: self.ty }, oflo)
104 }
105}
106107pub trait IntTypeExt {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
-> Ty<'tcx>;
fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>)
-> Discr<'tcx>;
fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>)
-> Option<Discr<'tcx>>;
}
impl 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)]108impl IntegerType {
109fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
110match self {
111 IntegerType::Pointer(true) => tcx.types.isize,
112 IntegerType::Pointer(false) => tcx.types.usize,
113 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
114 }
115 }
116117fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
118Discr { val: 0, ty: self.to_ty(tcx) }
119 }
120121fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
122if let Some(val) = val {
123assert_eq!(self.to_ty(tcx), val.ty);
124let (new, oflo) = val.checked_add(tcx, 1);
125if oflo { None } else { Some(new) }
126 } else {
127Some(self.initial_discriminant(tcx))
128 }
129 }
130}
131132impl<'tcx> TyCtxt<'tcx> {
133/// Creates a hash of the type `Ty` which will be the same no matter what crate
134 /// context it's calculated within. This is used by the `type_id` intrinsic.
135pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash128 {
136// We don't have region information, so we erase all free regions. Equal types
137 // must have the same `TypeId`, so we must anonymize all bound regions as well.
138let ty = self.erase_and_anonymize_regions(ty);
139140self.with_stable_hashing_context(|mut hcx| {
141let mut hasher = StableHasher::new();
142hcx.while_hashing_spans(false, |hcx| ty.stable_hash(hcx, &mut hasher));
143hasher.finish()
144 })
145 }
146147pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
148match res {
149 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
150Some(self.parent(self.parent(def_id)))
151 }
152 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
153Some(self.parent(def_id))
154 }
155// Other `DefKind`s don't have generics and would ICE when calling
156 // `generics_of`.
157Res::Def(
158 DefKind::Struct159 | DefKind::Union160 | DefKind::Enum161 | DefKind::Trait162 | DefKind::OpaqueTy163 | DefKind::TyAlias164 | DefKind::ForeignTy165 | DefKind::TraitAlias166 | DefKind::AssocTy167 | DefKind::Fn168 | DefKind::AssocFn169 | DefKind::AssocConst170 | DefKind::Impl { .. },
171 def_id,
172 ) => Some(def_id),
173 Res::Err => None,
174_ => None,
175 }
176 }
177178/// Checks whether `ty: Copy` holds while ignoring region constraints.
179 ///
180 /// This impacts whether values of `ty` are *moved* or *copied*
181 /// when referenced. This means that we may generate MIR which
182 /// does copies even when the type actually doesn't satisfy the
183 /// full requirements for the `Copy` trait (cc #29149) -- this
184 /// winds up being reported as an error during NLL borrow check.
185 ///
186 /// This function should not be used if there is an `InferCtxt` available.
187 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
188pub fn type_is_copy_modulo_regions(
189self,
190 typing_env: ty::TypingEnv<'tcx>,
191 ty: Ty<'tcx>,
192 ) -> bool {
193ty.is_trivially_pure_clone_copy() || self.is_copy_raw(typing_env.as_query_input(ty))
194 }
195196/// Checks whether `ty: UseCloned` holds while ignoring region constraints.
197 ///
198 /// This function should not be used if there is an `InferCtxt` available.
199 /// Use `InferCtxt::type_is_copy_modulo_regions` instead.
200pub fn type_is_use_cloned_modulo_regions(
201self,
202 typing_env: ty::TypingEnv<'tcx>,
203 ty: Ty<'tcx>,
204 ) -> bool {
205ty.is_trivially_pure_clone_copy() || self.is_use_cloned_raw(typing_env.as_query_input(ty))
206 }
207208/// Returns the deeply last field of nested structures, or the same type if
209 /// not a structure at all. Corresponds to the only possible unsized field,
210 /// and its type can be used to determine unsizing strategy.
211 ///
212 /// Should only be called if `ty` has no inference variables and does not
213 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
214 /// normalization attempt may cause compiler bugs.
215pub fn struct_tail_for_codegen(
216self,
217 ty: Ty<'tcx>,
218 typing_env: ty::TypingEnv<'tcx>,
219 ) -> Ty<'tcx> {
220self.assert_fully_normalized(typing_env, ty);
221self.struct_tail_raw(
222ty,
223&ObligationCause::dummy(),
224 |ty| self.normalize_erasing_regions(typing_env, ty),
225 || {},
226 )
227 }
228229/// Returns true if a type has metadata.
230pub fn type_has_metadata(self, ty: Ty<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
231if ty.is_sized(self, typing_env) {
232return false;
233 }
234235let tail = self.struct_tail_for_codegen(ty, typing_env);
236match tail.kind() {
237 ty::Foreign(..) => false,
238 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
239_ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected unsized tail: {0:?}", tail), Location::caller())bug!("unexpected unsized tail: {:?}", tail),
240 }
241 }
242243/// Returns the deeply last field of nested structures, or the same type if
244 /// not a structure at all. Corresponds to the only possible unsized field,
245 /// and its type can be used to determine unsizing strategy.
246 ///
247 /// This is parameterized over the normalization strategy (i.e. how to
248 /// handle `<T as Trait>::Assoc` and `impl Trait`). You almost certainly do
249 /// **NOT** want to pass the identity function here, unless you know what
250 /// you're doing, or you're within normalization code itself and will handle
251 /// an unnormalized tail recursively.
252 ///
253 /// See also `struct_tail_for_codegen`, which is suitable for use
254 /// during codegen.
255pub fn struct_tail_raw(
256self,
257mut ty: Ty<'tcx>,
258 cause: &ObligationCause<'tcx>,
259mut normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
260// This is currently used to allow us to walk a ValTree
261 // in lockstep with the type in order to get the ValTree branch that
262 // corresponds to an unsized field.
263mut f: impl FnMut() -> (),
264 ) -> Ty<'tcx> {
265let recursion_limit = self.recursion_limit();
266for iteration in 0.. {
267if !recursion_limit.value_within_limit(iteration) {
268let suggested_limit = match recursion_limit {
269 Limit(0) => Limit(2),
270 limit => limit * 2,
271 };
272let reported = self.dcx().emit_err(crate::diagnostics::RecursionLimitReached {
273 span: cause.span,
274 ty,
275 suggested_limit,
276 });
277return Ty::new_error(self, reported);
278 }
279match *ty.kind() {
280 ty::Adt(def, args) => {
281if !def.is_struct() {
282break;
283 }
284match def.non_enum_variant().tail_opt() {
285Some(field) => {
286 f();
287 ty = normalize(field.ty(self, args));
288 }
289None => break,
290 }
291 }
292293 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
294 f();
295 ty = last_ty;
296 }
297298 ty::Tuple(_) => break,
299300 ty::Pat(inner, _) => {
301 f();
302 ty = inner;
303 }
304305_ => {
306break;
307 }
308 }
309 }
310ty311 }
312313/// Same as applying `struct_tail` on `source` and `target`, but only
314 /// keeps going as long as the two types are instances of the same
315 /// structure definitions.
316 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
317 /// whereas struct_tail produces `T`, and `Trait`, respectively.
318 ///
319 /// Should only be called if the types have no inference variables and do
320 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
321 /// normalization attempt may cause compiler bugs.
322pub fn struct_lockstep_tails_for_codegen(
323self,
324 source: Ty<'tcx>,
325 target: Ty<'tcx>,
326 typing_env: ty::TypingEnv<'tcx>,
327 ) -> (Ty<'tcx>, Ty<'tcx>) {
328self.assert_fully_normalized(typing_env, (source, target));
329self.struct_lockstep_tails_raw(source, target, |ty| {
330self.normalize_erasing_regions(typing_env, ty)
331 })
332 }
333334/// Same as applying `struct_tail` on `source` and `target`, but only
335 /// keeps going as long as the two types are instances of the same
336 /// structure definitions.
337 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
338 /// whereas struct_tail produces `T`, and `Trait`, respectively.
339 ///
340 /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
341 /// during codegen.
342pub fn struct_lockstep_tails_raw(
343self,
344 source: Ty<'tcx>,
345 target: Ty<'tcx>,
346 normalize: impl Fn(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
347 ) -> (Ty<'tcx>, Ty<'tcx>) {
348let (mut a, mut b) = (source, target);
349loop {
350match (a.kind(), b.kind()) {
351 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
352if a_def == b_def && a_def.is_struct() =>
353 {
354if let Some(f) = a_def.non_enum_variant().tail_opt() {
355a = normalize(f.ty(self, a_args));
356b = normalize(f.ty(self, b_args));
357 } else {
358break;
359 }
360 }
361 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
362if let Some(&a_last) = a_tys.last() {
363a = a_last;
364b = *b_tys.last().unwrap();
365 } else {
366break;
367 }
368 }
369370_ => break,
371 }
372 }
373 (a, b)
374 }
375376/// Calculate the destructor of a given type.
377pub fn calculate_dtor(
378self,
379 adt_did: LocalDefId,
380 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
381 ) -> Option<ty::Destructor> {
382let drop_trait = self.lang_items().drop_trait()?;
383self.ensure_result().coherent_trait(drop_trait).ok()?;
384385let mut dtor_candidate = None;
386// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
387for &impl_did in self.local_trait_impls(drop_trait) {
388let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
389if adt_def.did() != adt_did.to_def_id() {
390continue;
391 }
392393if validate(self, impl_did).is_err() {
394// Already `ErrorGuaranteed`, no need to delay a span bug here.
395continue;
396 }
397398let Some(&item_id) = self.associated_item_def_ids(impl_did).first() else {
399self.dcx()
400 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
401continue;
402 };
403404if self.def_kind(item_id) != DefKind::AssocFn {
405self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
406continue;
407 }
408409if let Some(old_item_id) = dtor_candidate {
410self.dcx()
411 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
412 .with_span_note(self.def_span(old_item_id), "other impl here")
413 .delay_as_bug();
414 }
415416 dtor_candidate = Some(item_id);
417 }
418419let did = dtor_candidate?;
420Some(ty::Destructor { did })
421 }
422423/// Calculate the async destructor of a given type.
424pub fn calculate_async_dtor(
425self,
426 adt_did: LocalDefId,
427 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
428 ) -> Option<ty::AsyncDestructor> {
429let async_drop_trait = self.lang_items().async_drop_trait()?;
430self.ensure_result().coherent_trait(async_drop_trait).ok()?;
431432let mut dtor_candidate = None;
433// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
434for &impl_did in self.local_trait_impls(async_drop_trait) {
435let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
436if adt_def.did() != adt_did.to_def_id() {
437continue;
438 }
439440if validate(self, impl_did).is_err() {
441// Already `ErrorGuaranteed`, no need to delay a span bug here.
442continue;
443 }
444445if let Some(old_impl_did) = dtor_candidate {
446self.dcx()
447 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
448 .with_span_note(self.def_span(old_impl_did), "other impl here")
449 .delay_as_bug();
450 }
451452 dtor_candidate = Some(impl_did);
453 }
454455Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
456 }
457458/// Returns the set of types that are required to be alive in
459 /// order to run the destructor of `def` (see RFCs 769 and
460 /// 1238).
461 ///
462 /// Note that this returns only the constraints for the
463 /// destructor of `def` itself. For the destructors of the
464 /// contents, you need `adt_dtorck_constraint`.
465pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
466let dtor = match def.destructor(self) {
467None => {
468{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs:468",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(468u32),
::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());
469return ::alloc::vec::Vec::new()vec![];
470 }
471Some(dtor) => dtor.did,
472 };
473474let impl_def_id = self.parent(dtor);
475let impl_generics = self.generics_of(impl_def_id);
476477// We have a destructor - all the parameters that are not
478 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
479 // must be live.
480481 // We need to return the list of parameters from the ADTs
482 // generics/args that correspond to impure parameters on the
483 // impl's generics. This is a bit ugly, but conceptually simple:
484 //
485 // Suppose our ADT looks like the following
486 //
487 // struct S<X, Y, Z>(X, Y, Z);
488 //
489 // and the impl is
490 //
491 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
492 //
493 // We want to return the parameters (X, Y). For that, we match
494 // up the item-args <X, Y, Z> with the args on the impl ADT,
495 // <P1, P2, P0>, and then look up which of the impl args refer to
496 // parameters marked as pure.
497498let impl_args =
499match *self.type_of(impl_def_id).instantiate_identity().skip_norm_wip().kind() {
500 ty::Adt(def_, args) if def_ == def => args,
501_ => ::rustc_span::macros::bug_impl(Some(self.def_span(impl_def_id)),
format_args!("expected ADT for self type of `Drop` impl"),
Location::caller())span_bug!(
502self.def_span(impl_def_id),
503"expected ADT for self type of `Drop` impl"
504),
505 };
506507let item_args = ty::GenericArgs::identity_for_item(self, def.did());
508509let result = iter::zip(item_args, impl_args)
510 .filter(|&(_, arg)| {
511match arg.kind() {
512GenericArgKind::Lifetime(region) => match region.kind() {
513 ty::ReEarlyParam(ebr) => {
514 !impl_generics.region_param(ebr, self).pure_wrt_drop
515 }
516// Error: not a region param
517_ => false,
518 },
519GenericArgKind::Type(ty) => match *ty.kind() {
520 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
521// Error: not a type param
522_ => false,
523 },
524GenericArgKind::Const(ct) => match ct.kind() {
525 ty::ConstKind::Param(pc) => {
526 !impl_generics.const_param(pc, self).pure_wrt_drop
527 }
528// Error: not a const param
529_ => false,
530 },
531 }
532 })
533 .map(|(item_param, _)| item_param)
534 .collect();
535{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs:535",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(535u32),
::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);
536result537 }
538539/// Checks whether each generic argument is simply a unique generic parameter.
540pub fn uses_unique_generic_params(
541self,
542 args: &[ty::GenericArg<'tcx>],
543 ignore_regions: CheckRegions,
544 ) -> Result<(), NotUniqueParam<'tcx>> {
545let mut seen = GrowableBitSet::default();
546let mut seen_late = FxHashSet::default();
547for arg in args {
548match arg.kind() {
549 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
550 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
551if !seen_late.insert((di, reg)) {
552return Err(NotUniqueParam::DuplicateParam(lt.into()));
553 }
554 }
555 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
556if !seen.insert(p.index) {
557return Err(NotUniqueParam::DuplicateParam(lt.into()));
558 }
559 }
560 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
561return Err(NotUniqueParam::NotParam(lt.into()));
562 }
563 (CheckRegions::No, _) => {}
564 },
565 GenericArgKind::Type(t) => match t.kind() {
566 ty::Param(p) => {
567if !seen.insert(p.index) {
568return Err(NotUniqueParam::DuplicateParam(t.into()));
569 }
570 }
571_ => return Err(NotUniqueParam::NotParam(t.into())),
572 },
573 GenericArgKind::Const(c) => match c.kind() {
574 ty::ConstKind::Param(p) => {
575if !seen.insert(p.index) {
576return Err(NotUniqueParam::DuplicateParam(c.into()));
577 }
578 }
579_ => return Err(NotUniqueParam::NotParam(c.into())),
580 },
581 }
582 }
583584Ok(())
585 }
586587/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
588 /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
589 /// have the same `DefKind`.
590 ///
591 /// Note that closures have a `DefId`, but the closure *expression* also has a
592 /// `HirId` that is located within the context where the closure appears. The
593 /// parent of the closure's `DefId` will also be the context where it appears.
594pub fn is_closure_like(self, def_id: DefId) -> bool {
595#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)596 }
597598/// Returns `true` if `def_id` refers to a definition that does not have its own
599 /// type-checking context, i.e. closure, coroutine or inline const.
600pub fn is_typeck_child(self, def_id: DefId) -> bool {
601match self.def_kind(def_id) {
602 DefKind::AnonConst => {
603self.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline604 }
605 DefKind::Closure | DefKind::SyntheticCoroutineBody => true,
606 DefKind::Mod607 | DefKind::Struct608 | DefKind::Union609 | DefKind::Enum610 | DefKind::Variant611 | DefKind::Trait612 | DefKind::TyAlias613 | DefKind::ForeignTy614 | DefKind::TraitAlias615 | DefKind::AssocTy616 | DefKind::TyParam617 | DefKind::Fn618 | DefKind::Const619 | DefKind::ConstParam620 | DefKind::Static { .. }
621 | DefKind::Ctor(_, _)
622 | DefKind::AssocFn623 | DefKind::AssocConst624 | DefKind::Macro(_)
625 | DefKind::ExternCrate626 | DefKind::Use627 | DefKind::ForeignMod628 | DefKind::OpaqueTy629 | DefKind::Field630 | DefKind::LifetimeParam631 | DefKind::GlobalAsm632 | DefKind::Impl { .. }
633 | DefKind::TestBinderConstraints => false,
634 }
635 }
636637/// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
638pub fn is_trait(self, def_id: DefId) -> bool {
639self.def_kind(def_id) == DefKind::Trait640 }
641642/// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
643 /// and `false` otherwise.
644pub fn is_trait_alias(self, def_id: DefId) -> bool {
645self.def_kind(def_id) == DefKind::TraitAlias646 }
647648/// Returns `true` if this `DefId` refers to the implicit constructor for
649 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
650pub fn is_constructor(self, def_id: DefId) -> bool {
651#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))652 }
653654/// Given the `DefId`, returns the `DefId` of the innermost item that
655 /// has its own type-checking context or "inference environment".
656 ///
657 /// For example, a closure has its own `DefId`, but it is type-checked
658 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
659 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
660pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
661let mut def_id = def_id;
662while self.is_typeck_child(def_id) {
663 def_id = self.parent(def_id);
664 }
665def_id666 }
667668/// Given the `LocalDefId`, returns the `LocalDefId` of the innermost item that
669 /// has its own type-checking context or "inference environment".
670 ///
671 /// For example, a closure has its own `LocalDefId`, but it is type-checked
672 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
673 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
674pub fn typeck_root_def_id_local(self, def_id: LocalDefId) -> LocalDefId {
675let mut def_id = def_id;
676while self.is_typeck_child(def_id.to_def_id()) {
677 def_id = self.local_parent(def_id);
678 }
679def_id680 }
681682/// Given the `DefId` and args a closure, creates the type of
683 /// `self` argument that the closure expects. For example, for a
684 /// `Fn` closure, this would return a reference type `&T` where
685 /// `T = closure_ty`.
686 ///
687 /// Returns `None` if this closure's kind has not yet been inferred.
688 /// This should only be possible during type checking.
689 ///
690 /// Note that the return value is a late-bound region and hence
691 /// wrapped in a binder.
692pub fn closure_env_ty(
693self,
694 closure_ty: Ty<'tcx>,
695 closure_kind: ty::ClosureKind,
696 env_region: ty::Region<'tcx>,
697 ) -> Ty<'tcx> {
698match closure_kind {
699 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
700 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
701 ty::ClosureKind::FnOnce => closure_ty,
702 }
703 }
704705/// Returns `true` if the node pointed to by `def_id` is a `static` item.
706#[inline]
707pub fn is_static(self, def_id: DefId) -> bool {
708#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })709 }
710711#[inline]
712pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
713if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
714Some(mutability)
715 } else {
716None717 }
718 }
719720/// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
721pub fn is_thread_local_static(self, def_id: DefId) -> bool {
722self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
723 }
724725/// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
726#[inline]
727pub fn is_mutable_static(self, def_id: DefId) -> bool {
728self.static_mutability(def_id) == Some(hir::Mutability::Mut)
729 }
730731/// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
732 /// thread local shim generated.
733#[inline]
734pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
735 !self.sess.target.dll_tls_export
736 && self.is_thread_local_static(def_id)
737 && !self.is_foreign_item(def_id)
738 }
739740/// Returns the type a reference to the thread local takes in MIR.
741pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
742let static_ty = self.type_of(def_id).instantiate_identity().skip_norm_wip();
743if self.is_mutable_static(def_id) {
744Ty::new_mut_ptr(self, static_ty)
745 } else if self.is_foreign_item(def_id) {
746Ty::new_imm_ptr(self, static_ty)
747 } else {
748// FIXME: These things don't *really* have 'static lifetime.
749Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
750 }
751 }
752753/// Get the type of the pointer to the static that we use in MIR.
754pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
755// Make sure that any constants in the static's type are evaluated.
756let static_ty =
757self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
758759// Make sure that accesses to unsafe statics end up using raw pointers.
760 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
761if self.is_mutable_static(def_id) {
762Ty::new_mut_ptr(self, static_ty)
763 } else if self.is_foreign_item(def_id) {
764Ty::new_imm_ptr(self, static_ty)
765 } else {
766Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
767 }
768 }
769770/// Expands the given impl trait type, stopping if the type is recursive.
771{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_expand_impl_trait_type",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(771u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("args")
}> =
::tracing::__macro_support::FieldName::new("args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<Ty<'tcx>, Ty<'tcx>> =
loop {};
return __tracing_attr_fake_return;
}
{
let mut visitor =
OpaqueTypeExpander {
seen_opaque_tys: FxHashSet::default(),
expanded_cache: FxHashMap::default(),
primary_def_id: Some(def_id),
found_recursion: false,
found_any_recursion: false,
check_recursion: true,
tcx: self,
};
let expanded_type =
visitor.expand_opaque_ty(def_id, args).unwrap();
if visitor.found_recursion {
Err(expanded_type)
} else { Ok(expanded_type) }
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs:771",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/07e526db9df34143c99ec8064acc8ad543f69b30/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(771u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(skip(self), level = "debug", ret)]772pub fn try_expand_impl_trait_type(
773self,
774 def_id: DefId,
775 args: GenericArgsRef<'tcx>,
776 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
777let mut visitor = OpaqueTypeExpander {
778 seen_opaque_tys: FxHashSet::default(),
779 expanded_cache: FxHashMap::default(),
780 primary_def_id: Some(def_id),
781 found_recursion: false,
782 found_any_recursion: false,
783 check_recursion: true,
784 tcx: self,
785 };
786787let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
788if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
789 }
790791/// Query and get an English description for the item's kind.
792pub fn def_descr(self, def_id: DefId) -> &'static str {
793self.def_kind_descr(self.def_kind(def_id), def_id)
794 }
795796/// Get an English description for the item's kind.
797pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
798match def_kind {
799 DefKind::AssocFnif self.associated_item(def_id).is_method() => "method",
800 DefKind::AssocTyif self.opt_rpitit_info(def_id).is_some() => "opaque type",
801 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
802match coroutine_kind {
803 hir::CoroutineKind::Desugared(
804 hir::CoroutineDesugaring::Async,
805 hir::CoroutineSource::Fn,
806 ) => "async fn",
807 hir::CoroutineKind::Desugared(
808 hir::CoroutineDesugaring::Async,
809 hir::CoroutineSource::Block,
810 ) => "async block",
811 hir::CoroutineKind::Desugared(
812 hir::CoroutineDesugaring::Async,
813 hir::CoroutineSource::Closure,
814 ) => "async closure",
815 hir::CoroutineKind::Desugared(
816 hir::CoroutineDesugaring::AsyncGen,
817 hir::CoroutineSource::Fn,
818 ) => "async gen fn",
819 hir::CoroutineKind::Desugared(
820 hir::CoroutineDesugaring::AsyncGen,
821 hir::CoroutineSource::Block,
822 ) => "async gen block",
823 hir::CoroutineKind::Desugared(
824 hir::CoroutineDesugaring::AsyncGen,
825 hir::CoroutineSource::Closure,
826 ) => "async gen closure",
827 hir::CoroutineKind::Desugared(
828 hir::CoroutineDesugaring::Gen,
829 hir::CoroutineSource::Fn,
830 ) => "gen fn",
831 hir::CoroutineKind::Desugared(
832 hir::CoroutineDesugaring::Gen,
833 hir::CoroutineSource::Block,
834 ) => "gen block",
835 hir::CoroutineKind::Desugared(
836 hir::CoroutineDesugaring::Gen,
837 hir::CoroutineSource::Closure,
838 ) => "gen closure",
839 hir::CoroutineKind::Coroutine(_) => "coroutine",
840 }
841 }
842_ => def_kind.descr(def_id),
843 }
844 }
845846/// Gets an English article for the [`TyCtxt::def_descr`].
847pub fn def_descr_article(self, def_id: DefId) -> &'static str {
848self.def_kind_descr_article(self.def_kind(def_id), def_id)
849 }
850851/// Gets an English article for the [`TyCtxt::def_kind_descr`].
852pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
853match def_kind {
854 DefKind::AssocFnif self.associated_item(def_id).is_method() => "a",
855 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
856match coroutine_kind {
857 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
858 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
859 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
860 hir::CoroutineKind::Coroutine(_) => "a",
861 }
862 }
863_ => def_kind.article(),
864 }
865 }
866867/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
868 /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
869 /// be shown in `impl` suggestions.
870 ///
871 /// [public]: TyCtxt::is_private_dep
872 /// [direct]: rustc_crate_store::ExternCrate::is_direct
873pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
874// `#![rustc_private]` overrides defaults to make private dependencies usable.
875if self.features().enabled(sym::rustc_private) {
876return true;
877 }
878879// | Private | Direct | Visible | |
880 // |---------|--------|---------|--------------------|
881 // | Yes | Yes | Yes | !true || true |
882 // | No | Yes | Yes | !false || true |
883 // | Yes | No | No | !true || false |
884 // | No | No | Yes | !false || false |
885!self.is_private_dep(key)
886// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
887 // Treat that kind of crate as "indirect", since it's an implementation detail of
888 // the language.
889|| self.extern_crate(key).is_some_and(|e| e.is_direct())
890 }
891892/// Expand any [free alias types][free] contained within the given `value`.
893 ///
894 /// This should be used over other normalization routines in situations where
895 /// it's important not to normalize other alias types and where the predicates
896 /// on the corresponding type alias shouldn't be taken into consideration.
897 ///
898 /// Whenever possible **prefer not to use this function**! Instead, use standard
899 /// normalization routines or if feasible don't normalize at all.
900 ///
901 /// This function comes in handy if you want to mimic the behavior of eager
902 /// type alias expansion in a localized manner.
903 ///
904 /// <div class="warning">
905 /// This delays a bug on overflow! Therefore you need to be certain that the
906 /// contained types get fully normalized at a later stage. Note that even on
907 /// overflow all well-behaved free alias types get expanded correctly, so the
908 /// result is still useful.
909 /// </div>
910 ///
911 /// [free]: ty::Free
912pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
913value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
914 }
915916/// Peel off all [free alias types] in this type until there are none left.
917 ///
918 /// This only expands free alias types in “head” / outermost positions. It can
919 /// be used over [expand_free_alias_tys] as an optimization in situations where
920 /// one only really cares about the *kind* of the final aliased type but not
921 /// the types the other constituent types alias.
922 ///
923 /// <div class="warning">
924 /// This delays a bug on overflow! Therefore you need to be certain that the
925 /// type gets fully normalized at a later stage.
926 /// </div>
927 ///
928 /// [free]: ty::Free
929 /// [expand_free_alias_tys]: Self::expand_free_alias_tys
930pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
931let ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) = ty.kind() else {
932return ty;
933 };
934935let limit = self.recursion_limit();
936let mut depth = 0;
937938while let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() {
939if !limit.value_within_limit(depth) {
940let guar = self.dcx().delayed_bug("overflow expanding free alias type");
941return Ty::new_error(self, guar);
942 }
943944 ty = self.type_of(def_id).instantiate(self, args).skip_normalization();
945 depth += 1;
946 }
947948ty949 }
950951// Computes the variances for an alias (opaque or RPITIT) that represent
952 // its (un)captured regions.
953pub fn opt_alias_variances(
954self,
955 kind: impl Into<ty::AliasTermKind<'tcx>>,
956 ) -> Option<&'tcx [ty::Variance]> {
957match kind.into() {
958 ty::AliasTermKind::ProjectionTy { def_id } => {
959if self.is_impl_trait_in_trait(def_id) {
960Some(self.variances_of(def_id))
961 } else {
962None963 }
964 }
965 ty::AliasTermKind::OpaqueTy { def_id } => Some(self.variances_of(def_id)),
966 ty::AliasTermKind::InherentTy { .. }
967 | ty::AliasTermKind::InherentConstSelf { .. }
968 | ty::AliasTermKind::InherentConstImpl { .. }
969 | ty::AliasTermKind::FreeTy { .. }
970 | ty::AliasTermKind::FreeConst { .. }
971 | ty::AliasTermKind::AnonConst { .. }
972 | ty::AliasTermKind::ProjectionConst { .. } => None,
973 }
974 }
975}
976977struct OpaqueTypeExpander<'tcx> {
978// Contains the DefIds of the opaque types that are currently being
979 // expanded. When we expand an opaque type we insert the DefId of
980 // that type, and when we finish expanding that type we remove the
981 // its DefId.
982seen_opaque_tys: FxHashSet<DefId>,
983// Cache of all expansions we've seen so far. This is a critical
984 // optimization for some large types produced by async fn trees.
985expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
986 primary_def_id: Option<DefId>,
987 found_recursion: bool,
988 found_any_recursion: bool,
989/// Whether or not to check for recursive opaque types.
990 /// This is `true` when we're explicitly checking for opaque type
991 /// recursion, and 'false' otherwise to avoid unnecessary work.
992check_recursion: bool,
993 tcx: TyCtxt<'tcx>,
994}
995996impl<'tcx> OpaqueTypeExpander<'tcx> {
997fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
998if self.found_any_recursion {
999return None;
1000 }
1001let args = args.fold_with(self);
1002if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
1003let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
1004Some(expanded_ty) => *expanded_ty,
1005None => {
1006let generic_ty = self.tcx.type_of(def_id);
1007let concrete_ty = generic_ty.instantiate(self.tcx, args).skip_normalization();
1008let expanded_ty = self.fold_ty(concrete_ty);
1009self.expanded_cache.insert((def_id, args), expanded_ty);
1010expanded_ty1011 }
1012 };
1013if self.check_recursion {
1014self.seen_opaque_tys.remove(&def_id);
1015 }
1016Some(expanded_ty)
1017 } else {
1018// If another opaque type that we contain is recursive, then it
1019 // will report the error, so we don't have to.
1020self.found_any_recursion = true;
1021self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1022None1023 }
1024 }
1025}
10261027impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1028fn cx(&self) -> TyCtxt<'tcx> {
1029self.tcx
1030 }
10311032fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1033if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *t.kind() {
1034self.expand_opaque_ty(def_id, args).unwrap_or(t)
1035 } else if t.has_opaque_types() {
1036t.super_fold_with(self)
1037 } else {
1038t1039 }
1040 }
10411042fn fold_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> P {
1043// We use `map_projection` to execute the closure only if `p` is a projection clause,
1044 // to implement the logic described below (i.e. avoid folding the `term`).
1045 // In all other cases, fold recursively, as normal.
1046p.map_projection(self.tcx, |bound_clause| {
1047let projection_clause = bound_clause.skip_binder();
1048bound_clause.rebind(ty::ProjectionClause {
1049 projection_term: projection_clause.projection_term.fold_with(self),
1050// Don't fold the term on the RHS of the projection predicate.
1051 // This is because for default trait methods with RPITITs, we
1052 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1053 // predicate, which would trivially cause a cycle when we do
1054 // anything that requires `TypingEnv::with_post_analysis_normalized`.
1055term: projection_clause.term,
1056 })
1057 })
1058 .unwrap_or_else(|| p.super_fold_with(self))
1059 }
1060}
10611062struct FreeAliasTypeExpander<'tcx> {
1063 tcx: TyCtxt<'tcx>,
1064 depth: usize,
1065}
10661067impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1068fn cx(&self) -> TyCtxt<'tcx> {
1069self.tcx
1070 }
10711072fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1073if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1074return ty;
1075 }
1076let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() else {
1077return ty.super_fold_with(self);
1078 };
1079if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1080let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1081return Ty::new_error(self.tcx, guar);
1082 }
10831084self.depth += 1;
1085let ty = self1086 .tcx
1087 .type_of(def_id)
1088 .instantiate(self.tcx, args)
1089 .skip_normalization()
1090 .fold_with(self);
1091self.depth -= 1;
1092ty1093 }
10941095fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1096if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1097return ct;
1098 }
1099ct.super_fold_with(self)
1100 }
1101}
11021103impl<'tcx> Ty<'tcx> {
1104/// Returns the `Size` for primitive types (bool, uint, int, char, float).
1105pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1106match *self.kind() {
1107 ty::Bool => Size::from_bytes(1),
1108 ty::Char => Size::from_bytes(4),
1109 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1110 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1111 ty::Float(fty) => Float::from_float_ty(fty).size(),
1112_ => ::rustc_span::macros::bug_impl(None, format_args!("non primitive type"),
Location::caller())bug!("non primitive type"),
1113 }
1114 }
11151116pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1117match *self.kind() {
1118 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1119 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1120_ => ::rustc_span::macros::bug_impl(None, format_args!("non integer discriminant"),
Location::caller())bug!("non integer discriminant"),
1121 }
1122 }
11231124/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1125 /// returns `None` if the type is not numeric.
1126pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1127use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1128Some(match self.kind() {
1129 ty::Int(_) | ty::Uint(_) => {
1130let (size, signed) = self.int_size_and_signed(tcx);
1131let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1132let max =
1133if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1134 (min, max)
1135 }
1136 ty::Char => (0, std::char::MAXas u128),
1137 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1138 ty::Float(ty::FloatTy::F32) => {
1139 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1140 }
1141 ty::Float(ty::FloatTy::F64) => {
1142 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1143 }
1144 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1145_ => return None,
1146 })
1147 }
11481149/// Returns the maximum value for the given numeric type (including `char`s)
1150 /// or returns `None` if the type is not numeric.
1151pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1152let typing_env = TypingEnv::fully_monomorphized();
1153self.numeric_min_and_max_as_bits(tcx)
1154 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1155 }
11561157/// Returns the minimum value for the given numeric type (including `char`s)
1158 /// or returns `None` if the type is not numeric.
1159pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1160let typing_env = TypingEnv::fully_monomorphized();
1161self.numeric_min_and_max_as_bits(tcx)
1162 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1163 }
11641165/// Checks whether values of this type `T` have a size known at
1166 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1167 /// for the purposes of this check, so it can be an
1168 /// over-approximation in generic contexts, where one can have
1169 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1170 /// actually carry lifetime requirements.
1171pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1172self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1173 || tcx.is_sized_raw(typing_env.as_query_input(self))
1174 }
11751176/// Checks whether values of this type `T` implement the `Freeze`
1177 /// trait -- frozen types are those that do not contain an
1178 /// `UnsafeCell` anywhere. This is a language concept used to
1179 /// distinguish "true immutability", which is relevant to
1180 /// optimization as well as the rules around static values. Note
1181 /// that the `Freeze` trait is not exposed to end users and is
1182 /// effectively an implementation detail.
1183pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1184self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1185 }
11861187/// Fast path helper for testing if a type is `Freeze`.
1188 ///
1189 /// Returning true means the type is known to be `Freeze`. Returning
1190 /// `false` means nothing -- could be `Freeze`, might not be.
1191pub fn is_trivially_freeze(self) -> bool {
1192match self.kind() {
1193 ty::Int(_)
1194 | ty::Uint(_)
1195 | ty::Float(_)
1196 | ty::Bool1197 | ty::Char1198 | ty::Str1199 | ty::Never1200 | ty::Ref(..)
1201 | ty::RawPtr(_, _)
1202 | ty::FnDef(..)
1203 | ty::Error(_)
1204 | ty::FnPtr(..) => true,
1205 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1206 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1207 ty::Adt(..)
1208 | ty::Bound(..)
1209 | ty::Closure(..)
1210 | ty::CoroutineClosure(..)
1211 | ty::Dynamic(..)
1212 | ty::Foreign(_)
1213 | ty::Coroutine(..)
1214 | ty::CoroutineWitness(..)
1215 | ty::UnsafeBinder(_)
1216 | ty::Infer(_)
1217 | ty::Alias(..)
1218 | ty::Param(_)
1219 | ty::Placeholder(_) => false,
1220 }
1221 }
12221223/// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1224pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1225self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1226 }
12271228/// Checks whether values of this type `T` implement the `Unpin` trait.
1229 ///
1230 /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1231 /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1232 /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1233pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1234self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1235 }
12361237/// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1238 ///
1239 /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1240 /// `false` means nothing -- could be `Unpin`, might not be.
1241fn is_trivially_unpin(self) -> bool {
1242match self.kind() {
1243 ty::Int(_)
1244 | ty::Uint(_)
1245 | ty::Float(_)
1246 | ty::Bool1247 | ty::Char1248 | ty::Str1249 | ty::Never1250 | ty::Ref(..)
1251 | ty::RawPtr(_, _)
1252 | ty::FnDef(..)
1253 | ty::Error(_)
1254 | ty::FnPtr(..) => true,
1255 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1256 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1257 ty::Adt(..)
1258 | ty::Bound(..)
1259 | ty::Closure(..)
1260 | ty::CoroutineClosure(..)
1261 | ty::Dynamic(..)
1262 | ty::Foreign(_)
1263 | ty::Coroutine(..)
1264 | ty::CoroutineWitness(..)
1265 | ty::UnsafeBinder(_)
1266 | ty::Infer(_)
1267 | ty::Alias(..)
1268 | ty::Param(_)
1269 | ty::Placeholder(_) => false,
1270 }
1271 }
12721273/// Checks whether this type is an ADT that has unsafe fields.
1274pub fn has_unsafe_fields(self) -> bool {
1275if let ty::Adt(adt_def, ..) = self.kind() {
1276adt_def.all_fields().any(|x| x.safety.is_unsafe())
1277 } else {
1278false
1279}
1280 }
12811282/// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1283pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1284 !self.is_trivially_not_async_drop()
1285 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1286 }
12871288/// Fast path helper for testing if a type is `AsyncDrop`.
1289 ///
1290 /// Returning true means the type is known to be `!AsyncDrop`. Returning
1291 /// `false` means nothing -- could be `AsyncDrop`, might not be.
1292fn is_trivially_not_async_drop(self) -> bool {
1293match self.kind() {
1294 ty::Int(_)
1295 | ty::Uint(_)
1296 | ty::Float(_)
1297 | ty::Bool1298 | ty::Char1299 | ty::Str1300 | ty::Never1301 | ty::Ref(..)
1302 | ty::RawPtr(..)
1303 | ty::FnDef(..)
1304 | ty::Error(_)
1305 | ty::FnPtr(..) => true,
1306// FIXME(unsafe_binders):
1307 ty::UnsafeBinder(_) => ::core::panicking::panic("not implemented")unimplemented!(),
1308 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1309 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1310elem_ty.is_trivially_not_async_drop()
1311 }
1312 ty::Adt(..)
1313 | ty::Bound(..)
1314 | ty::Closure(..)
1315 | ty::CoroutineClosure(..)
1316 | ty::Dynamic(..)
1317 | ty::Foreign(_)
1318 | ty::Coroutine(..)
1319 | ty::CoroutineWitness(..)
1320 | ty::Infer(_)
1321 | ty::Alias(..)
1322 | ty::Param(_)
1323 | ty::Placeholder(_) => false,
1324 }
1325 }
13261327/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1328 /// non-copy and *might* have a destructor attached; if it returns
1329 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1330 ///
1331 /// (Note that this implies that if `ty` has a destructor attached,
1332 /// then `needs_drop` will definitely return `true` for `ty`.)
1333 ///
1334 /// Note that this method is used to check eligible types in unions.
1335#[inline]
1336pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1337// Avoid querying in simple cases.
1338match needs_drop_components(tcx, self) {
1339Err(AlwaysRequiresDrop) => true,
1340Ok(components) => {
1341let query_ty = match *components {
1342 [] => return false,
1343// If we've got a single component, call the query with that
1344 // to increase the chance that we hit the query cache.
1345[component_ty] => component_ty,
1346_ => self,
1347 };
13481349// This doesn't depend on regions, so try to minimize distinct
1350 // query keys used. If normalization fails, we just use `query_ty`.
1351if 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());
1352let query_ty = tcx1353 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1354 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13551356tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1357 }
1358 }
1359 }
13601361/// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1362 /// non-copy and *might* have a async destructor attached; if it returns
1363 /// `false`, then `ty` definitely has no async destructor (i.e., no async
1364 /// drop glue).
1365 ///
1366 /// (Note that this implies that if `ty` has an async destructor attached,
1367 /// then `needs_async_drop` will definitely return `true` for `ty`.)
1368 ///
1369// FIXME(zetanumbers): Note that this method is used to check eligible types
1370 // in unions.
1371#[inline]
1372pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1373// Avoid querying in simple cases.
1374match needs_drop_components(tcx, self) {
1375Err(AlwaysRequiresDrop) => true,
1376Ok(components) => {
1377let query_ty = match *components {
1378 [] => return false,
1379// If we've got a single component, call the query with that
1380 // to increase the chance that we hit the query cache.
1381[component_ty] => component_ty,
1382_ => self,
1383 };
13841385// This doesn't depend on regions, so try to minimize distinct
1386 // query keys used.
1387 // If normalization fails, we just use `query_ty`.
1388if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1389let query_ty = tcx1390 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1391 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13921393tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1394 }
1395 }
1396 }
13971398/// Checks if `ty` has a significant drop.
1399 ///
1400 /// Note that this method can return false even if `ty` has a destructor
1401 /// attached; even if that is the case then the adt has been marked with
1402 /// the attribute `rustc_insignificant_dtor`.
1403 ///
1404 /// Note that this method is used to check for change in drop order for
1405 /// 2229 drop reorder migration analysis.
1406#[inline]
1407pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1408// Avoid querying in simple cases.
1409match needs_drop_components(tcx, self) {
1410Err(AlwaysRequiresDrop) => true,
1411Ok(components) => {
1412let query_ty = match *components {
1413 [] => return false,
1414// If we've got a single component, call the query with that
1415 // to increase the chance that we hit the query cache.
1416[component_ty] => component_ty,
1417_ => self,
1418 };
14191420// FIXME
1421 // We should be canonicalizing, or else moving this to a method of inference
1422 // context, or *something* like that,
1423 // but for now just avoid passing inference variables
1424 // to queries that can't cope with them.
1425 // Instead, conservatively return "true" (may change drop order).
1426if query_ty.has_infer() {
1427return true;
1428 }
14291430// This doesn't depend on regions, so try to minimize distinct
1431 // query keys used.
1432 // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1433tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1434 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1435 .unwrap_or(true)
1436 }
1437 }
1438 }
14391440/// Returns `true` if equality for this type is both reflexive and structural.
1441 ///
1442 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1443 ///
1444 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1445 /// types, equality for the type as a whole is structural when it is the same as equality
1446 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1447 /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1448 ///
1449 /// This function is "shallow" because it may return `true` for a composite type whose fields
1450 /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1451 /// because equality for arrays is determined by the equality of each array element. If you
1452 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1453 /// down, you will need to use a type visitor.
1454#[inline]
1455pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1456match self.kind() {
1457// Look for an impl of `StructuralPartialEq`.
1458ty::Adt(..) => tcx.has_structural_eq_impl(self),
14591460// Primitive types that satisfy `Eq`.
1461ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
14621463// Composite types that satisfy `Eq` when all of their fields do.
1464 //
1465 // Because this function is "shallow", we return `true` for these composites regardless
1466 // of the type(s) contained within.
1467ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
14681469// Raw pointers use bitwise comparison.
1470ty::RawPtr(_, _) | ty::FnPtr(..) => true,
14711472// Floating point numbers are not `Eq`.
1473ty::Float(_) => false,
14741475// Conservatively return `false` for all others...
14761477 // Anonymous function types
1478ty::FnDef(..)
1479 | ty::Closure(..)
1480 | ty::CoroutineClosure(..)
1481 | ty::Dynamic(..)
1482 | ty::Coroutine(..) => false,
14831484// Generic or inferred types
1485 //
1486 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1487 // called for known, fully-monomorphized types.
1488ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1489false
1490}
14911492 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1493 }
1494 }
14951496/// Peel off all reference types in this type until there are none left.
1497 ///
1498 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1499 ///
1500 /// # Examples
1501 ///
1502 /// - `u8` -> `u8`
1503 /// - `&'a mut u8` -> `u8`
1504 /// - `&'a &'b u8` -> `u8`
1505 /// - `&'a *const &'b u8 -> *const &'b u8`
1506pub fn peel_refs(self) -> Ty<'tcx> {
1507let mut ty = self;
1508while let ty::Ref(_, inner_ty, _) = ty.kind() {
1509 ty = *inner_ty;
1510 }
1511ty1512 }
1513}
15141515/// Returns a list of types such that the given type needs drop if and only if
1516/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1517/// this type always needs drop.
1518//
1519// FIXME(zetanumbers): consider replacing this with only
1520// `needs_drop_components_with_async`
1521#[inline]
1522pub fn needs_drop_components<'tcx>(
1523 tcx: TyCtxt<'tcx>,
1524 ty: Ty<'tcx>,
1525) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1526needs_drop_components_with_async(tcx, ty, Asyncness::No)
1527}
15281529/// Returns a list of types such that the given type needs drop if and only if
1530/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1531/// this type always needs drop.
1532pub fn needs_drop_components_with_async<'tcx>(
1533 tcx: TyCtxt<'tcx>,
1534 ty: Ty<'tcx>,
1535 asyncness: Asyncness,
1536) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1537match *ty.kind() {
1538 ty::Infer(ty::FreshIntTy(_))
1539 | ty::Infer(ty::FreshFloatTy(_))
1540 | ty::Bool1541 | ty::Int(_)
1542 | ty::Uint(_)
1543 | ty::Float(_)
1544 | ty::Never1545 | ty::FnDef(..)
1546 | ty::FnPtr(..)
1547 | ty::Char1548 | ty::RawPtr(_, _)
1549 | ty::Ref(..)
1550 | ty::Str => Ok(SmallVec::new()),
15511552// Foreign types can never have destructors.
1553ty::Foreign(..) => Ok(SmallVec::new()),
15541555// FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1556ty::Dynamic(..) | ty::Error(_) => {
1557if asyncness.is_async() {
1558Ok(SmallVec::new())
1559 } else {
1560Err(AlwaysRequiresDrop)
1561 }
1562 }
15631564 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1565 ty::Array(elem_ty, size) => {
1566match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1567Ok(v) if v.is_empty() => Ok(v),
1568 res => match size.try_to_target_usize(tcx) {
1569// Arrays of size zero don't need drop, even if their element
1570 // type does.
1571Some(0) => Ok(SmallVec::new()),
1572Some(_) => res,
1573// We don't know which of the cases above we are in, so
1574 // return the whole type and let the caller decide what to
1575 // do.
1576None => 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]),
1577 },
1578 }
1579 }
1580// If any field needs drop, then the whole tuple does.
1581ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1582acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1583Ok(acc)
1584 }),
15851586// These require checking for `Copy` bounds or `Adt` destructors.
1587ty::Adt(..)
1588 | ty::Alias(..)
1589 | ty::Param(_)
1590 | ty::Bound(..)
1591 | ty::Placeholder(..)
1592 | ty::Infer(_)
1593 | ty::Closure(..)
1594 | ty::CoroutineClosure(..)
1595 | ty::Coroutine(..)
1596 | ty::CoroutineWitness(..)
1597 | 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]),
1598 }
1599}
16001601/// Does the equivalent of
1602/// ```ignore (illustrative)
1603/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1604/// folder.tcx().intern_*(&v)
1605/// ```
1606pub fn fold_list<'tcx, F, L, T>(
1607 list: L,
1608 folder: &mut F,
1609 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1610) -> L
1611where
1612F: TypeFolder<TyCtxt<'tcx>>,
1613 L: AsRef<[T]>,
1614 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1615{
1616let slice = list.as_ref();
1617let mut iter = slice.iter().copied();
1618// Look for the first element that changed
1619match iter.by_ref().enumerate().find_map(|(i, t)| {
1620let new_t = t.fold_with(folder);
1621if new_t != t { Some((i, new_t)) } else { None }
1622 }) {
1623Some((i, new_t)) => {
1624// An element changed, prepare to intern the resulting list
1625let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1626new_list.extend_from_slice(&slice[..i]);
1627new_list.push(new_t);
1628for t in iter {
1629 new_list.push(t.fold_with(folder))
1630 }
1631intern(folder.cx(), &new_list)
1632 }
1633None => list,
1634 }
1635}
16361637/// Does the equivalent of
1638/// ```ignore (illustrative)
1639/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1640/// folder.tcx().intern_*(&v)
1641/// ```
1642pub fn try_fold_list<'tcx, F, L, T>(
1643 list: L,
1644 folder: &mut F,
1645 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1646) -> Result<L, F::Error>
1647where
1648F: FallibleTypeFolder<TyCtxt<'tcx>>,
1649 L: AsRef<[T]>,
1650 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1651{
1652let slice = list.as_ref();
1653let mut iter = slice.iter().copied();
1654// Look for the first element that changed
1655match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1656Ok(new_t) if new_t == t => None,
1657 new_t => Some((i, new_t)),
1658 }) {
1659Some((i, Ok(new_t))) => {
1660// An element changed, prepare to intern the resulting list
1661let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1662new_list.extend_from_slice(&slice[..i]);
1663new_list.push(new_t);
1664for t in iter {
1665 new_list.push(t.try_fold_with(folder)?)
1666 }
1667Ok(intern(folder.cx(), &new_list))
1668 }
1669Some((_, Err(err))) => {
1670return Err(err);
1671 }
1672None => Ok(list),
1673 }
1674}
16751676#[derive(#[automatically_derived]
impl ::core::marker::Copy for AlwaysRequiresDrop { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AlwaysRequiresDrop { }
#[automatically_derived]
impl ::core::clone::Clone for AlwaysRequiresDrop {
#[inline]
fn clone(&self) -> Self { *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) {}
}
};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)]
1677pub struct AlwaysRequiresDrop;
16781679/// Reveals all opaque types in the given value, replacing them
1680/// with their underlying types.
1681pub fn reveal_opaque_types_in_bounds<'tcx>(
1682 tcx: TyCtxt<'tcx>,
1683 val: ty::Clauses<'tcx>,
1684) -> ty::Clauses<'tcx> {
1685if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1686let mut visitor = OpaqueTypeExpander {
1687 seen_opaque_tys: FxHashSet::default(),
1688 expanded_cache: FxHashMap::default(),
1689 primary_def_id: None,
1690 found_recursion: false,
1691 found_any_recursion: false,
1692 check_recursion: false,
1693tcx,
1694 };
1695val.fold_with(&mut visitor)
1696}
16971698/// Determines whether an item is directly annotated with `doc(hidden)`.
1699fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1700{
{
'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())1701}
17021703/// Determines whether an item is annotated with `doc(notable_trait)`.
1704pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1705{
{
'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())1706}
17071708/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1709///
1710/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1711/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1712/// cause an ICE that we otherwise may want to prevent.
1713pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1714if 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) {
1715let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1716 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1717 !has_body1718 }
1719_ => true,
1720 };
1721Some(ty::IntrinsicDef {
1722 name: tcx.item_name(def_id),
1723must_be_overridden,
1724 const_stable_indirect: {
{
'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),
1725 })
1726 } else {
1727None1728 }
1729}
17301731pub fn provide(providers: &mut Providers) {
1732*providers = Providers {
1733reveal_opaque_types_in_bounds,
1734is_doc_hidden,
1735is_doc_notable_trait,
1736intrinsic_raw,
1737 ..*providers1738 }
1739}