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::consts::ConstExt;
30use crate::ty::layout::{FloatExt, IntegerExt};
31use crate::ty::{
32self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
33TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized,
34};
3536#[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)]
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]
#[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)]
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]
#[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)]
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}
107108pub 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)]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.stable_hash(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> {
221self.assert_fully_normalized(typing_env, ty);
222self.struct_tail_raw(
223ty,
224&ObligationCause::dummy(),
225 |ty| self.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_ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected unsized tail: {0:?}", tail), Location::caller())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(Unnormalized<'tcx, 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::diagnostics::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 = normalize(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_ => {
307break;
308 }
309 }
310 }
311ty312 }
313314/// Same as applying `struct_tail` on `source` and `target`, but only
315 /// keeps going as long as the two types are instances of the same
316 /// structure definitions.
317 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
318 /// whereas struct_tail produces `T`, and `Trait`, respectively.
319 ///
320 /// Should only be called if the types have no inference variables and do
321 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
322 /// normalization attempt may cause compiler bugs.
323pub fn struct_lockstep_tails_for_codegen(
324self,
325 source: Ty<'tcx>,
326 target: Ty<'tcx>,
327 typing_env: ty::TypingEnv<'tcx>,
328 ) -> (Ty<'tcx>, Ty<'tcx>) {
329self.assert_fully_normalized(typing_env, (source, target));
330self.struct_lockstep_tails_raw(source, target, |ty| {
331self.normalize_erasing_regions(typing_env, ty)
332 })
333 }
334335/// Same as applying `struct_tail` on `source` and `target`, but only
336 /// keeps going as long as the two types are instances of the same
337 /// structure definitions.
338 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
339 /// whereas struct_tail produces `T`, and `Trait`, respectively.
340 ///
341 /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
342 /// during codegen.
343pub fn struct_lockstep_tails_raw(
344self,
345 source: Ty<'tcx>,
346 target: Ty<'tcx>,
347 normalize: impl Fn(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
348 ) -> (Ty<'tcx>, Ty<'tcx>) {
349let (mut a, mut b) = (source, target);
350loop {
351match (a.kind(), b.kind()) {
352 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
353if a_def == b_def && a_def.is_struct() =>
354 {
355if let Some(f) = a_def.non_enum_variant().tail_opt() {
356a = normalize(f.ty(self, a_args));
357b = normalize(f.ty(self, b_args));
358 } else {
359break;
360 }
361 }
362 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
363if let Some(&a_last) = a_tys.last() {
364a = a_last;
365b = *b_tys.last().unwrap();
366 } else {
367break;
368 }
369 }
370371_ => break,
372 }
373 }
374 (a, b)
375 }
376377/// Calculate the destructor of a given type.
378pub fn calculate_dtor(
379self,
380 adt_did: LocalDefId,
381 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
382 ) -> Option<ty::Destructor> {
383let drop_trait = self.lang_items().drop_trait()?;
384self.ensure_result().coherent_trait(drop_trait).ok()?;
385386let mut dtor_candidate = None;
387// `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
388for &impl_did in self.local_trait_impls(drop_trait) {
389let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
390if adt_def.did() != adt_did.to_def_id() {
391continue;
392 }
393394if validate(self, impl_did).is_err() {
395// Already `ErrorGuaranteed`, no need to delay a span bug here.
396continue;
397 }
398399let Some(&item_id) = self.associated_item_def_ids(impl_did).first() else {
400self.dcx()
401 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
402continue;
403 };
404405if self.def_kind(item_id) != DefKind::AssocFn {
406self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
407continue;
408 }
409410if let Some(old_item_id) = dtor_candidate {
411self.dcx()
412 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
413 .with_span_note(self.def_span(old_item_id), "other impl here")
414 .delay_as_bug();
415 }
416417 dtor_candidate = Some(item_id);
418 }
419420let did = dtor_candidate?;
421Some(ty::Destructor { did })
422 }
423424/// Calculate the async destructor of a given type.
425pub fn calculate_async_dtor(
426self,
427 adt_did: LocalDefId,
428 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
429 ) -> Option<ty::AsyncDestructor> {
430let async_drop_trait = self.lang_items().async_drop_trait()?;
431self.ensure_result().coherent_trait(async_drop_trait).ok()?;
432433let mut dtor_candidate = None;
434// `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
435for &impl_did in self.local_trait_impls(async_drop_trait) {
436let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
437if adt_def.did() != adt_did.to_def_id() {
438continue;
439 }
440441if validate(self, impl_did).is_err() {
442// Already `ErrorGuaranteed`, no need to delay a span bug here.
443continue;
444 }
445446if let Some(old_impl_did) = dtor_candidate {
447self.dcx()
448 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
449 .with_span_note(self.def_span(old_impl_did), "other impl here")
450 .delay_as_bug();
451 }
452453 dtor_candidate = Some(impl_did);
454 }
455456Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
457 }
458459/// Returns the set of types that are required to be alive in
460 /// order to run the destructor of `def` (see RFCs 769 and
461 /// 1238).
462 ///
463 /// Note that this returns only the constraints for the
464 /// destructor of `def` itself. For the destructors of the
465 /// contents, you need `adt_dtorck_constraint`.
466pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
467let dtor = match def.destructor(self) {
468None => {
469{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs:469",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(469u32),
::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());
470return ::alloc::vec::Vec::new()vec![];
471 }
472Some(dtor) => dtor.did,
473 };
474475let impl_def_id = self.parent(dtor);
476let impl_generics = self.generics_of(impl_def_id);
477478// We have a destructor - all the parameters that are not
479 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
480 // must be live.
481482 // We need to return the list of parameters from the ADTs
483 // generics/args that correspond to impure parameters on the
484 // impl's generics. This is a bit ugly, but conceptually simple:
485 //
486 // Suppose our ADT looks like the following
487 //
488 // struct S<X, Y, Z>(X, Y, Z);
489 //
490 // and the impl is
491 //
492 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
493 //
494 // We want to return the parameters (X, Y). For that, we match
495 // up the item-args <X, Y, Z> with the args on the impl ADT,
496 // <P1, P2, P0>, and then look up which of the impl args refer to
497 // parameters marked as pure.
498499let impl_args =
500match *self.type_of(impl_def_id).instantiate_identity().skip_norm_wip().kind() {
501 ty::Adt(def_, args) if def_ == def => args,
502_ => ::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!(
503self.def_span(impl_def_id),
504"expected ADT for self type of `Drop` impl"
505),
506 };
507508let item_args = ty::GenericArgs::identity_for_item(self, def.did());
509510let result = iter::zip(item_args, impl_args)
511 .filter(|&(_, arg)| {
512match arg.kind() {
513GenericArgKind::Lifetime(region) => match region.kind() {
514 ty::ReEarlyParam(ebr) => {
515 !impl_generics.region_param(ebr, self).pure_wrt_drop
516 }
517// Error: not a region param
518_ => false,
519 },
520GenericArgKind::Type(ty) => match *ty.kind() {
521 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
522// Error: not a type param
523_ => false,
524 },
525GenericArgKind::Const(ct) => match ct.kind() {
526 ty::ConstKind::Param(pc) => {
527 !impl_generics.const_param(pc, self).pure_wrt_drop
528 }
529// Error: not a const param
530_ => false,
531 },
532 }
533 })
534 .map(|(item_param, _)| item_param)
535 .collect();
536{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs:536",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(536u32),
::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);
537result538 }
539540/// Checks whether each generic argument is simply a unique generic parameter.
541pub fn uses_unique_generic_params(
542self,
543 args: &[ty::GenericArg<'tcx>],
544 ignore_regions: CheckRegions,
545 ) -> Result<(), NotUniqueParam<'tcx>> {
546let mut seen = GrowableBitSet::default();
547let mut seen_late = FxHashSet::default();
548for arg in args {
549match arg.kind() {
550 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
551 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
552if !seen_late.insert((di, reg)) {
553return Err(NotUniqueParam::DuplicateParam(lt.into()));
554 }
555 }
556 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
557if !seen.insert(p.index) {
558return Err(NotUniqueParam::DuplicateParam(lt.into()));
559 }
560 }
561 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
562return Err(NotUniqueParam::NotParam(lt.into()));
563 }
564 (CheckRegions::No, _) => {}
565 },
566 GenericArgKind::Type(t) => match t.kind() {
567 ty::Param(p) => {
568if !seen.insert(p.index) {
569return Err(NotUniqueParam::DuplicateParam(t.into()));
570 }
571 }
572_ => return Err(NotUniqueParam::NotParam(t.into())),
573 },
574 GenericArgKind::Const(c) => match c.kind() {
575 ty::ConstKind::Param(p) => {
576if !seen.insert(p.index) {
577return Err(NotUniqueParam::DuplicateParam(c.into()));
578 }
579 }
580_ => return Err(NotUniqueParam::NotParam(c.into())),
581 },
582 }
583 }
584585Ok(())
586 }
587588/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
589 /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
590 /// have the same `DefKind`.
591 ///
592 /// Note that closures have a `DefId`, but the closure *expression* also has a
593 /// `HirId` that is located within the context where the closure appears. The
594 /// parent of the closure's `DefId` will also be the context where it appears.
595pub fn is_closure_like(self, def_id: DefId) -> bool {
596#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)597 }
598599/// Returns `true` if `def_id` refers to a definition that does not have its own
600 /// type-checking context, i.e. closure, coroutine or inline const.
601pub fn is_typeck_child(self, def_id: DefId) -> bool {
602match self.def_kind(def_id) {
603 DefKind::AnonConst => {
604self.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline605 }
606 DefKind::Closure | DefKind::SyntheticCoroutineBody => true,
607 DefKind::Mod608 | DefKind::Struct609 | DefKind::Union610 | DefKind::Enum611 | DefKind::Variant612 | DefKind::Trait613 | DefKind::TyAlias614 | DefKind::ForeignTy615 | DefKind::TraitAlias616 | DefKind::AssocTy617 | DefKind::TyParam618 | DefKind::Fn619 | DefKind::Const620 | DefKind::ConstParam621 | DefKind::Static { .. }
622 | DefKind::Ctor(_, _)
623 | DefKind::AssocFn624 | DefKind::AssocConst625 | DefKind::Macro(_)
626 | DefKind::ExternCrate627 | DefKind::Use628 | DefKind::ForeignMod629 | DefKind::OpaqueTy630 | DefKind::Field631 | DefKind::LifetimeParam632 | DefKind::GlobalAsm633 | DefKind::Impl { .. }
634 | DefKind::TestBinderConstraints => false,
635 }
636 }
637638/// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
639pub fn is_trait(self, def_id: DefId) -> bool {
640self.def_kind(def_id) == DefKind::Trait641 }
642643/// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
644 /// and `false` otherwise.
645pub fn is_trait_alias(self, def_id: DefId) -> bool {
646self.def_kind(def_id) == DefKind::TraitAlias647 }
648649/// Returns `true` if this `DefId` refers to the implicit constructor for
650 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
651pub fn is_constructor(self, def_id: DefId) -> bool {
652#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))653 }
654655/// Given the `DefId`, returns the `DefId` of the innermost item that
656 /// has its own type-checking context or "inference environment".
657 ///
658 /// For example, a closure has its own `DefId`, but it is type-checked
659 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
660 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
661pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
662let mut def_id = def_id;
663while self.is_typeck_child(def_id) {
664 def_id = self.parent(def_id);
665 }
666def_id667 }
668669/// Given the `LocalDefId`, returns the `LocalDefId` of the innermost item that
670 /// has its own type-checking context or "inference environment".
671 ///
672 /// For example, a closure has its own `LocalDefId`, but it is type-checked
673 /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
674 /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
675pub fn typeck_root_def_id_local(self, def_id: LocalDefId) -> LocalDefId {
676let mut def_id = def_id;
677while self.is_typeck_child(def_id.to_def_id()) {
678 def_id = self.local_parent(def_id);
679 }
680def_id681 }
682683/// Given the `DefId` and args a closure, creates the type of
684 /// `self` argument that the closure expects. For example, for a
685 /// `Fn` closure, this would return a reference type `&T` where
686 /// `T = closure_ty`.
687 ///
688 /// Returns `None` if this closure's kind has not yet been inferred.
689 /// This should only be possible during type checking.
690 ///
691 /// Note that the return value is a late-bound region and hence
692 /// wrapped in a binder.
693pub fn closure_env_ty(
694self,
695 closure_ty: Ty<'tcx>,
696 closure_kind: ty::ClosureKind,
697 env_region: ty::Region<'tcx>,
698 ) -> Ty<'tcx> {
699match closure_kind {
700 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
701 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
702 ty::ClosureKind::FnOnce => closure_ty,
703 }
704 }
705706/// Returns `true` if the node pointed to by `def_id` is a `static` item.
707#[inline]
708pub fn is_static(self, def_id: DefId) -> bool {
709#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })710 }
711712#[inline]
713pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
714if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
715Some(mutability)
716 } else {
717None718 }
719 }
720721/// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
722pub fn is_thread_local_static(self, def_id: DefId) -> bool {
723self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
724 }
725726/// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
727#[inline]
728pub fn is_mutable_static(self, def_id: DefId) -> bool {
729self.static_mutability(def_id) == Some(hir::Mutability::Mut)
730 }
731732/// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
733 /// thread local shim generated.
734#[inline]
735pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
736 !self.sess.target.dll_tls_export
737 && self.is_thread_local_static(def_id)
738 && !self.is_foreign_item(def_id)
739 }
740741/// Returns the type a reference to the thread local takes in MIR.
742pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
743let static_ty = self.type_of(def_id).instantiate_identity().skip_norm_wip();
744if self.is_mutable_static(def_id) {
745Ty::new_mut_ptr(self, static_ty)
746 } else if self.is_foreign_item(def_id) {
747Ty::new_imm_ptr(self, static_ty)
748 } else {
749// FIXME: These things don't *really* have 'static lifetime.
750Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
751 }
752 }
753754/// Get the type of the pointer to the static that we use in MIR.
755pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
756// Make sure that any constants in the static's type are evaluated.
757let static_ty =
758self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
759760// Make sure that accesses to unsafe statics end up using raw pointers.
761 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
762if self.is_mutable_static(def_id) {
763Ty::new_mut_ptr(self, static_ty)
764 } else if self.is_foreign_item(def_id) {
765Ty::new_imm_ptr(self, static_ty)
766 } else {
767Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
768 }
769 }
770771/// Expands the given impl trait type, stopping if the type is recursive.
772{}
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/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(772u32),
::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/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs:772",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(772u32),
::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)]773pub fn try_expand_impl_trait_type(
774self,
775 def_id: DefId,
776 args: GenericArgsRef<'tcx>,
777 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
778let mut visitor = OpaqueTypeExpander {
779 seen_opaque_tys: FxHashSet::default(),
780 expanded_cache: FxHashMap::default(),
781 primary_def_id: Some(def_id),
782 found_recursion: false,
783 found_any_recursion: false,
784 check_recursion: true,
785 tcx: self,
786 };
787788let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
789if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
790 }
791792/// Query and get an English description for the item's kind.
793pub fn def_descr(self, def_id: DefId) -> &'static str {
794self.def_kind_descr(self.def_kind(def_id), def_id)
795 }
796797/// Get an English description for the item's kind.
798pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
799match def_kind {
800 DefKind::AssocFnif self.associated_item(def_id).is_method() => "method",
801 DefKind::AssocTyif self.opt_rpitit_info(def_id).is_some() => "opaque type",
802 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
803match coroutine_kind {
804 hir::CoroutineKind::Desugared(
805 hir::CoroutineDesugaring::Async,
806 hir::CoroutineSource::Fn,
807 ) => "async fn",
808 hir::CoroutineKind::Desugared(
809 hir::CoroutineDesugaring::Async,
810 hir::CoroutineSource::Block,
811 ) => "async block",
812 hir::CoroutineKind::Desugared(
813 hir::CoroutineDesugaring::Async,
814 hir::CoroutineSource::Closure,
815 ) => "async closure",
816 hir::CoroutineKind::Desugared(
817 hir::CoroutineDesugaring::AsyncGen,
818 hir::CoroutineSource::Fn,
819 ) => "async gen fn",
820 hir::CoroutineKind::Desugared(
821 hir::CoroutineDesugaring::AsyncGen,
822 hir::CoroutineSource::Block,
823 ) => "async gen block",
824 hir::CoroutineKind::Desugared(
825 hir::CoroutineDesugaring::AsyncGen,
826 hir::CoroutineSource::Closure,
827 ) => "async gen closure",
828 hir::CoroutineKind::Desugared(
829 hir::CoroutineDesugaring::Gen,
830 hir::CoroutineSource::Fn,
831 ) => "gen fn",
832 hir::CoroutineKind::Desugared(
833 hir::CoroutineDesugaring::Gen,
834 hir::CoroutineSource::Block,
835 ) => "gen block",
836 hir::CoroutineKind::Desugared(
837 hir::CoroutineDesugaring::Gen,
838 hir::CoroutineSource::Closure,
839 ) => "gen closure",
840 hir::CoroutineKind::Coroutine(_) => "coroutine",
841 }
842 }
843_ => def_kind.descr(def_id),
844 }
845 }
846847/// Gets an English article for the [`TyCtxt::def_descr`].
848pub fn def_descr_article(self, def_id: DefId) -> &'static str {
849self.def_kind_descr_article(self.def_kind(def_id), def_id)
850 }
851852/// Gets an English article for the [`TyCtxt::def_kind_descr`].
853pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
854match def_kind {
855 DefKind::AssocFnif self.associated_item(def_id).is_method() => "a",
856 DefKind::Closureif let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
857match coroutine_kind {
858 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
859 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
860 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
861 hir::CoroutineKind::Coroutine(_) => "a",
862 }
863 }
864_ => def_kind.article(),
865 }
866 }
867868/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
869 /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
870 /// be shown in `impl` suggestions.
871 ///
872 /// [public]: TyCtxt::is_private_dep
873 /// [direct]: rustc_crate_store::ExternCrate::is_direct
874pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
875// `#![rustc_private]` overrides defaults to make private dependencies usable.
876if self.features().enabled(sym::rustc_private) {
877return true;
878 }
879880// | Private | Direct | Visible | |
881 // |---------|--------|---------|--------------------|
882 // | Yes | Yes | Yes | !true || true |
883 // | No | Yes | Yes | !false || true |
884 // | Yes | No | No | !true || false |
885 // | No | No | Yes | !false || false |
886!self.is_private_dep(key)
887// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
888 // Treat that kind of crate as "indirect", since it's an implementation detail of
889 // the language.
890|| self.extern_crate(key).is_some_and(|e| e.is_direct())
891 }
892893/// Expand any [free alias types][free] contained within the given `value`.
894 ///
895 /// This should be used over other normalization routines in situations where
896 /// it's important not to normalize other alias types and where the predicates
897 /// on the corresponding type alias shouldn't be taken into consideration.
898 ///
899 /// Whenever possible **prefer not to use this function**! Instead, use standard
900 /// normalization routines or if feasible don't normalize at all.
901 ///
902 /// This function comes in handy if you want to mimic the behavior of eager
903 /// type alias expansion in a localized manner.
904 ///
905 /// <div class="warning">
906 /// This delays a bug on overflow! Therefore you need to be certain that the
907 /// contained types get fully normalized at a later stage. Note that even on
908 /// overflow all well-behaved free alias types get expanded correctly, so the
909 /// result is still useful.
910 /// </div>
911 ///
912 /// [free]: ty::Free
913pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
914value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
915 }
916917/// Peel off all [free alias types] in this type until there are none left.
918 ///
919 /// This only expands free alias types in “head” / outermost positions. It can
920 /// be used over [expand_free_alias_tys] as an optimization in situations where
921 /// one only really cares about the *kind* of the final aliased type but not
922 /// the types the other constituent types alias.
923 ///
924 /// <div class="warning">
925 /// This delays a bug on overflow! Therefore you need to be certain that the
926 /// type gets fully normalized at a later stage.
927 /// </div>
928 ///
929 /// [free]: ty::Free
930 /// [expand_free_alias_tys]: Self::expand_free_alias_tys
931pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
932let ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) = ty.kind() else {
933return ty;
934 };
935936let limit = self.recursion_limit();
937let mut depth = 0;
938939while let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() {
940if !limit.value_within_limit(depth) {
941let guar = self.dcx().delayed_bug("overflow expanding free alias type");
942return Ty::new_error(self, guar);
943 }
944945 ty = self.type_of(def_id).instantiate(self, args).skip_normalization();
946 depth += 1;
947 }
948949ty950 }
951952// Computes the variances for an alias (opaque or RPITIT) that represent
953 // its (un)captured regions.
954pub fn opt_alias_variances(
955self,
956 kind: impl Into<ty::AliasTermKind<'tcx>>,
957 ) -> Option<&'tcx [ty::Variance]> {
958match kind.into() {
959 ty::AliasTermKind::ProjectionTy { def_id } => {
960if self.is_impl_trait_in_trait(def_id) {
961Some(self.variances_of(def_id))
962 } else {
963None964 }
965 }
966 ty::AliasTermKind::OpaqueTy { def_id } => Some(self.variances_of(def_id)),
967 ty::AliasTermKind::InherentTy { .. }
968 | ty::AliasTermKind::InherentConstSelf { .. }
969 | ty::AliasTermKind::InherentConstImpl { .. }
970 | ty::AliasTermKind::FreeTy { .. }
971 | ty::AliasTermKind::FreeConst { .. }
972 | ty::AliasTermKind::AnonConst { .. }
973 | ty::AliasTermKind::ProjectionConst { .. } => None,
974 }
975 }
976}
977978struct OpaqueTypeExpander<'tcx> {
979// Contains the DefIds of the opaque types that are currently being
980 // expanded. When we expand an opaque type we insert the DefId of
981 // that type, and when we finish expanding that type we remove the
982 // its DefId.
983seen_opaque_tys: FxHashSet<DefId>,
984// Cache of all expansions we've seen so far. This is a critical
985 // optimization for some large types produced by async fn trees.
986expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
987 primary_def_id: Option<DefId>,
988 found_recursion: bool,
989 found_any_recursion: bool,
990/// Whether or not to check for recursive opaque types.
991 /// This is `true` when we're explicitly checking for opaque type
992 /// recursion, and 'false' otherwise to avoid unnecessary work.
993check_recursion: bool,
994 tcx: TyCtxt<'tcx>,
995}
996997impl<'tcx> OpaqueTypeExpander<'tcx> {
998fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
999if self.found_any_recursion {
1000return None;
1001 }
1002let args = args.fold_with(self);
1003if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
1004let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
1005Some(expanded_ty) => *expanded_ty,
1006None => {
1007let generic_ty = self.tcx.type_of(def_id);
1008let concrete_ty = generic_ty.instantiate(self.tcx, args).skip_normalization();
1009let expanded_ty = self.fold_ty(concrete_ty);
1010self.expanded_cache.insert((def_id, args), expanded_ty);
1011expanded_ty1012 }
1013 };
1014if self.check_recursion {
1015self.seen_opaque_tys.remove(&def_id);
1016 }
1017Some(expanded_ty)
1018 } else {
1019// If another opaque type that we contain is recursive, then it
1020 // will report the error, so we don't have to.
1021self.found_any_recursion = true;
1022self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1023None1024 }
1025 }
1026}
10271028impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1029fn cx(&self) -> TyCtxt<'tcx> {
1030self.tcx
1031 }
10321033fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1034if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *t.kind() {
1035self.expand_opaque_ty(def_id, args).unwrap_or(t)
1036 } else if t.has_opaque_types() {
1037t.super_fold_with(self)
1038 } else {
1039t1040 }
1041 }
10421043fn fold_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> P {
1044// We use `map_projection` to execute the closure only if `p` is a projection clause,
1045 // to implement the logic described below (i.e. avoid folding the `term`).
1046 // In all other cases, fold recursively, as normal.
1047p.map_projection(self.tcx, |bound_clause| {
1048let projection_clause = bound_clause.skip_binder();
1049bound_clause.rebind(ty::ProjectionClause {
1050 projection_term: projection_clause.projection_term.fold_with(self),
1051// Don't fold the term on the RHS of the projection predicate.
1052 // This is because for default trait methods with RPITITs, we
1053 // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1054 // predicate, which would trivially cause a cycle when we do
1055 // anything that requires `TypingEnv::with_post_analysis_normalized`.
1056term: projection_clause.term,
1057 })
1058 })
1059 .unwrap_or_else(|| p.super_fold_with(self))
1060 }
1061}
10621063struct FreeAliasTypeExpander<'tcx> {
1064 tcx: TyCtxt<'tcx>,
1065 depth: usize,
1066}
10671068impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1069fn cx(&self) -> TyCtxt<'tcx> {
1070self.tcx
1071 }
10721073fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1074if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1075return ty;
1076 }
1077let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() else {
1078return ty.super_fold_with(self);
1079 };
1080if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1081let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1082return Ty::new_error(self.tcx, guar);
1083 }
10841085self.depth += 1;
1086let ty = self1087 .tcx
1088 .type_of(def_id)
1089 .instantiate(self.tcx, args)
1090 .skip_normalization()
1091 .fold_with(self);
1092self.depth -= 1;
1093ty1094 }
10951096fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1097if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1098return ct;
1099 }
1100ct.super_fold_with(self)
1101 }
1102}
11031104impl<'tcx> Ty<'tcx> {
1105/// Returns the `Size` for primitive types (bool, uint, int, char, float).
1106pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1107match *self.kind() {
1108 ty::Bool => Size::from_bytes(1),
1109 ty::Char => Size::from_bytes(4),
1110 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1111 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1112 ty::Float(fty) => Float::from_float_ty(fty).size(),
1113_ => ::rustc_span::macros::bug_impl(None, format_args!("non primitive type"),
Location::caller())bug!("non primitive type"),
1114 }
1115 }
11161117pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1118match *self.kind() {
1119 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1120 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1121_ => ::rustc_span::macros::bug_impl(None, format_args!("non integer discriminant"),
Location::caller())bug!("non integer discriminant"),
1122 }
1123 }
11241125/// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1126 /// returns `None` if the type is not numeric.
1127pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1128use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1129Some(match self.kind() {
1130 ty::Int(_) | ty::Uint(_) => {
1131let (size, signed) = self.int_size_and_signed(tcx);
1132let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1133let max =
1134if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1135 (min, max)
1136 }
1137 ty::Char => (0, std::char::MAXas u128),
1138 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1139 ty::Float(ty::FloatTy::F32) => {
1140 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1141 }
1142 ty::Float(ty::FloatTy::F64) => {
1143 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1144 }
1145 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1146_ => return None,
1147 })
1148 }
11491150/// Returns the maximum value for the given numeric type (including `char`s)
1151 /// or returns `None` if the type is not numeric.
1152pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1153let typing_env = TypingEnv::fully_monomorphized();
1154self.numeric_min_and_max_as_bits(tcx)
1155 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1156 }
11571158/// Returns the minimum value for the given numeric type (including `char`s)
1159 /// or returns `None` if the type is not numeric.
1160pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1161let typing_env = TypingEnv::fully_monomorphized();
1162self.numeric_min_and_max_as_bits(tcx)
1163 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1164 }
11651166/// Checks whether values of this type `T` have a size known at
1167 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1168 /// for the purposes of this check, so it can be an
1169 /// over-approximation in generic contexts, where one can have
1170 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1171 /// actually carry lifetime requirements.
1172pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1173self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1174 || tcx.is_sized_raw(typing_env.as_query_input(self))
1175 }
11761177/// Checks whether values of this type `T` implement the `Freeze`
1178 /// trait -- frozen types are those that do not contain an
1179 /// `UnsafeCell` anywhere. This is a language concept used to
1180 /// distinguish "true immutability", which is relevant to
1181 /// optimization as well as the rules around static values. Note
1182 /// that the `Freeze` trait is not exposed to end users and is
1183 /// effectively an implementation detail.
1184pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1185self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1186 }
11871188/// Fast path helper for testing if a type is `Freeze`.
1189 ///
1190 /// Returning true means the type is known to be `Freeze`. Returning
1191 /// `false` means nothing -- could be `Freeze`, might not be.
1192pub fn is_trivially_freeze(self) -> bool {
1193match self.kind() {
1194 ty::Int(_)
1195 | ty::Uint(_)
1196 | ty::Float(_)
1197 | ty::Bool1198 | ty::Char1199 | ty::Str1200 | ty::Never1201 | ty::Ref(..)
1202 | ty::RawPtr(_, _)
1203 | ty::FnDef(..)
1204 | ty::Error(_)
1205 | ty::FnPtr(..) => true,
1206 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1207 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1208 ty::Adt(..)
1209 | ty::Bound(..)
1210 | ty::Closure(..)
1211 | ty::CoroutineClosure(..)
1212 | ty::Dynamic(..)
1213 | ty::Foreign(_)
1214 | ty::Coroutine(..)
1215 | ty::CoroutineWitness(..)
1216 | ty::UnsafeBinder(_)
1217 | ty::Infer(_)
1218 | ty::Alias(..)
1219 | ty::Param(_)
1220 | ty::Placeholder(_) => false,
1221 }
1222 }
12231224/// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1225pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1226self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1227 }
12281229/// Checks whether values of this type `T` implement the `Unpin` trait.
1230 ///
1231 /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1232 /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1233 /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1234pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1235self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1236 }
12371238/// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1239 ///
1240 /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1241 /// `false` means nothing -- could be `Unpin`, might not be.
1242fn is_trivially_unpin(self) -> bool {
1243match self.kind() {
1244 ty::Int(_)
1245 | ty::Uint(_)
1246 | ty::Float(_)
1247 | ty::Bool1248 | ty::Char1249 | ty::Str1250 | ty::Never1251 | ty::Ref(..)
1252 | ty::RawPtr(_, _)
1253 | ty::FnDef(..)
1254 | ty::Error(_)
1255 | ty::FnPtr(..) => true,
1256 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1257 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1258 ty::Adt(..)
1259 | ty::Bound(..)
1260 | ty::Closure(..)
1261 | ty::CoroutineClosure(..)
1262 | ty::Dynamic(..)
1263 | ty::Foreign(_)
1264 | ty::Coroutine(..)
1265 | ty::CoroutineWitness(..)
1266 | ty::UnsafeBinder(_)
1267 | ty::Infer(_)
1268 | ty::Alias(..)
1269 | ty::Param(_)
1270 | ty::Placeholder(_) => false,
1271 }
1272 }
12731274/// Checks whether this type is an ADT that has unsafe fields.
1275pub fn has_unsafe_fields(self) -> bool {
1276if let ty::Adt(adt_def, ..) = self.kind() {
1277adt_def.all_fields().any(|x| x.safety.is_unsafe())
1278 } else {
1279false
1280}
1281 }
12821283/// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1284pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1285 !self.is_trivially_not_async_drop()
1286 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1287 }
12881289/// Fast path helper for testing if a type is `AsyncDrop`.
1290 ///
1291 /// Returning true means the type is known to be `!AsyncDrop`. Returning
1292 /// `false` means nothing -- could be `AsyncDrop`, might not be.
1293fn is_trivially_not_async_drop(self) -> bool {
1294match self.kind() {
1295 ty::Int(_)
1296 | ty::Uint(_)
1297 | ty::Float(_)
1298 | ty::Bool1299 | ty::Char1300 | ty::Str1301 | ty::Never1302 | ty::Ref(..)
1303 | ty::RawPtr(..)
1304 | ty::FnDef(..)
1305 | ty::Error(_)
1306 | ty::FnPtr(..) => true,
1307// FIXME(unsafe_binders):
1308 ty::UnsafeBinder(_) => ::core::panicking::panic("not implemented")unimplemented!(),
1309 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1310 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1311elem_ty.is_trivially_not_async_drop()
1312 }
1313 ty::Adt(..)
1314 | ty::Bound(..)
1315 | ty::Closure(..)
1316 | ty::CoroutineClosure(..)
1317 | ty::Dynamic(..)
1318 | ty::Foreign(_)
1319 | ty::Coroutine(..)
1320 | ty::CoroutineWitness(..)
1321 | ty::Infer(_)
1322 | ty::Alias(..)
1323 | ty::Param(_)
1324 | ty::Placeholder(_) => false,
1325 }
1326 }
13271328/// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1329 /// non-copy and *might* have a destructor attached; if it returns
1330 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1331 ///
1332 /// (Note that this implies that if `ty` has a destructor attached,
1333 /// then `needs_drop` will definitely return `true` for `ty`.)
1334 ///
1335 /// Note that this method is used to check eligible types in unions.
1336#[inline]
1337pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1338// Avoid querying in simple cases.
1339match needs_drop_components(tcx, self) {
1340Err(AlwaysRequiresDrop) => true,
1341Ok(components) => {
1342let query_ty = match *components {
1343 [] => return false,
1344// If we've got a single component, call the query with that
1345 // to increase the chance that we hit the query cache.
1346[component_ty] => component_ty,
1347_ => self,
1348 };
13491350// This doesn't depend on regions, so try to minimize distinct
1351 // query keys used. If normalization fails, we just use `query_ty`.
1352if 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());
1353let query_ty = tcx1354 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1355 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13561357tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1358 }
1359 }
1360 }
13611362/// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1363 /// non-copy and *might* have a async destructor attached; if it returns
1364 /// `false`, then `ty` definitely has no async destructor (i.e., no async
1365 /// drop glue).
1366 ///
1367 /// (Note that this implies that if `ty` has an async destructor attached,
1368 /// then `needs_async_drop` will definitely return `true` for `ty`.)
1369 ///
1370// FIXME(zetanumbers): Note that this method is used to check eligible types
1371 // in unions.
1372#[inline]
1373pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1374// Avoid querying in simple cases.
1375match needs_drop_components(tcx, self) {
1376Err(AlwaysRequiresDrop) => true,
1377Ok(components) => {
1378let query_ty = match *components {
1379 [] => return false,
1380// If we've got a single component, call the query with that
1381 // to increase the chance that we hit the query cache.
1382[component_ty] => component_ty,
1383_ => self,
1384 };
13851386// This doesn't depend on regions, so try to minimize distinct
1387 // query keys used.
1388 // If normalization fails, we just use `query_ty`.
1389if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1390let query_ty = tcx1391 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1392 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
13931394tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1395 }
1396 }
1397 }
13981399/// Checks if `ty` has a significant drop.
1400 ///
1401 /// Note that this method can return false even if `ty` has a destructor
1402 /// attached; even if that is the case then the adt has been marked with
1403 /// the attribute `rustc_insignificant_dtor`.
1404 ///
1405 /// Note that this method is used to check for change in drop order for
1406 /// 2229 drop reorder migration analysis.
1407#[inline]
1408pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1409// Avoid querying in simple cases.
1410match needs_drop_components(tcx, self) {
1411Err(AlwaysRequiresDrop) => true,
1412Ok(components) => {
1413let query_ty = match *components {
1414 [] => return false,
1415// If we've got a single component, call the query with that
1416 // to increase the chance that we hit the query cache.
1417[component_ty] => component_ty,
1418_ => self,
1419 };
14201421// FIXME
1422 // We should be canonicalizing, or else moving this to a method of inference
1423 // context, or *something* like that,
1424 // but for now just avoid passing inference variables
1425 // to queries that can't cope with them.
1426 // Instead, conservatively return "true" (may change drop order).
1427if query_ty.has_infer() {
1428return true;
1429 }
14301431// This doesn't depend on regions, so try to minimize distinct
1432 // query keys used.
1433 // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1434tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1435 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1436 .unwrap_or(true)
1437 }
1438 }
1439 }
14401441/// Returns `true` if equality for this type is both reflexive and structural.
1442 ///
1443 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1444 ///
1445 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1446 /// types, equality for the type as a whole is structural when it is the same as equality
1447 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1448 /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1449 ///
1450 /// This function is "shallow" because it may return `true` for a composite type whose fields
1451 /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1452 /// because equality for arrays is determined by the equality of each array element. If you
1453 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1454 /// down, you will need to use a type visitor.
1455#[inline]
1456pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1457match self.kind() {
1458// Look for an impl of `StructuralPartialEq`.
1459ty::Adt(..) => tcx.has_structural_eq_impl(self),
14601461// Primitive types that satisfy `Eq`.
1462ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
14631464// Composite types that satisfy `Eq` when all of their fields do.
1465 //
1466 // Because this function is "shallow", we return `true` for these composites regardless
1467 // of the type(s) contained within.
1468ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
14691470// Raw pointers use bitwise comparison.
1471ty::RawPtr(_, _) | ty::FnPtr(..) => true,
14721473// Floating point numbers are not `Eq`.
1474ty::Float(_) => false,
14751476// Conservatively return `false` for all others...
14771478 // Anonymous function types
1479ty::FnDef(..)
1480 | ty::Closure(..)
1481 | ty::CoroutineClosure(..)
1482 | ty::Dynamic(..)
1483 | ty::Coroutine(..) => false,
14841485// Generic or inferred types
1486 //
1487 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1488 // called for known, fully-monomorphized types.
1489ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1490false
1491}
14921493 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1494 }
1495 }
14961497/// Peel off all reference types in this type until there are none left.
1498 ///
1499 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1500 ///
1501 /// # Examples
1502 ///
1503 /// - `u8` -> `u8`
1504 /// - `&'a mut u8` -> `u8`
1505 /// - `&'a &'b u8` -> `u8`
1506 /// - `&'a *const &'b u8 -> *const &'b u8`
1507pub fn peel_refs(self) -> Ty<'tcx> {
1508let mut ty = self;
1509while let ty::Ref(_, inner_ty, _) = ty.kind() {
1510 ty = *inner_ty;
1511 }
1512ty1513 }
1514}
15151516/// Returns a list of types such that the given type needs drop if and only if
1517/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1518/// this type always needs drop.
1519//
1520// FIXME(zetanumbers): consider replacing this with only
1521// `needs_drop_components_with_async`
1522#[inline]
1523pub fn needs_drop_components<'tcx>(
1524 tcx: TyCtxt<'tcx>,
1525 ty: Ty<'tcx>,
1526) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1527needs_drop_components_with_async(tcx, ty, Asyncness::No)
1528}
15291530/// Returns a list of types such that the given type needs drop if and only if
1531/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1532/// this type always needs drop.
1533pub fn needs_drop_components_with_async<'tcx>(
1534 tcx: TyCtxt<'tcx>,
1535 ty: Ty<'tcx>,
1536 asyncness: Asyncness,
1537) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1538match *ty.kind() {
1539 ty::Infer(ty::FreshIntTy(_))
1540 | ty::Infer(ty::FreshFloatTy(_))
1541 | ty::Bool1542 | ty::Int(_)
1543 | ty::Uint(_)
1544 | ty::Float(_)
1545 | ty::Never1546 | ty::FnDef(..)
1547 | ty::FnPtr(..)
1548 | ty::Char1549 | ty::RawPtr(_, _)
1550 | ty::Ref(..)
1551 | ty::Str => Ok(SmallVec::new()),
15521553// Foreign types can never have destructors.
1554ty::Foreign(..) => Ok(SmallVec::new()),
15551556// FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1557ty::Dynamic(..) | ty::Error(_) => {
1558if asyncness.is_async() {
1559Ok(SmallVec::new())
1560 } else {
1561Err(AlwaysRequiresDrop)
1562 }
1563 }
15641565 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1566 ty::Array(elem_ty, size) => {
1567match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1568Ok(v) if v.is_empty() => Ok(v),
1569 res => match size.try_to_target_usize(tcx) {
1570// Arrays of size zero don't need drop, even if their element
1571 // type does.
1572Some(0) => Ok(SmallVec::new()),
1573Some(_) => res,
1574// We don't know which of the cases above we are in, so
1575 // return the whole type and let the caller decide what to
1576 // do.
1577None => 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]),
1578 },
1579 }
1580 }
1581// If any field needs drop, then the whole tuple does.
1582ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1583acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1584Ok(acc)
1585 }),
15861587// These require checking for `Copy` bounds or `Adt` destructors.
1588ty::Adt(..)
1589 | ty::Alias(..)
1590 | ty::Param(_)
1591 | ty::Bound(..)
1592 | ty::Placeholder(..)
1593 | ty::Infer(_)
1594 | ty::Closure(..)
1595 | ty::CoroutineClosure(..)
1596 | ty::Coroutine(..)
1597 | ty::CoroutineWitness(..)
1598 | 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]),
1599 }
1600}
16011602/// Does the equivalent of
1603/// ```ignore (illustrative)
1604/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1605/// folder.tcx().intern_*(&v)
1606/// ```
1607pub fn fold_list<'tcx, F, L, T>(
1608 list: L,
1609 folder: &mut F,
1610 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1611) -> L
1612where
1613F: TypeFolder<TyCtxt<'tcx>>,
1614 L: AsRef<[T]>,
1615 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1616{
1617let slice = list.as_ref();
1618let mut iter = slice.iter().copied();
1619// Look for the first element that changed
1620match iter.by_ref().enumerate().find_map(|(i, t)| {
1621let new_t = t.fold_with(folder);
1622if new_t != t { Some((i, new_t)) } else { None }
1623 }) {
1624Some((i, new_t)) => {
1625// An element changed, prepare to intern the resulting list
1626let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1627new_list.extend_from_slice(&slice[..i]);
1628new_list.push(new_t);
1629for t in iter {
1630 new_list.push(t.fold_with(folder))
1631 }
1632intern(folder.cx(), &new_list)
1633 }
1634None => list,
1635 }
1636}
16371638/// Does the equivalent of
1639/// ```ignore (illustrative)
1640/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1641/// folder.tcx().intern_*(&v)
1642/// ```
1643pub fn try_fold_list<'tcx, F, L, T>(
1644 list: L,
1645 folder: &mut F,
1646 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1647) -> Result<L, F::Error>
1648where
1649F: FallibleTypeFolder<TyCtxt<'tcx>>,
1650 L: AsRef<[T]>,
1651 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1652{
1653let slice = list.as_ref();
1654let mut iter = slice.iter().copied();
1655// Look for the first element that changed
1656match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1657Ok(new_t) if new_t == t => None,
1658 new_t => Some((i, new_t)),
1659 }) {
1660Some((i, Ok(new_t))) => {
1661// An element changed, prepare to intern the resulting list
1662let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1663new_list.extend_from_slice(&slice[..i]);
1664new_list.push(new_t);
1665for t in iter {
1666 new_list.push(t.try_fold_with(folder)?)
1667 }
1668Ok(intern(folder.cx(), &new_list))
1669 }
1670Some((_, Err(err))) => {
1671return Err(err);
1672 }
1673None => Ok(list),
1674 }
1675}
16761677#[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)]
1678pub struct AlwaysRequiresDrop;
16791680/// Reveals all opaque types in the given value, replacing them
1681/// with their underlying types.
1682pub fn reveal_opaque_types_in_bounds<'tcx>(
1683 tcx: TyCtxt<'tcx>,
1684 val: ty::Clauses<'tcx>,
1685) -> ty::Clauses<'tcx> {
1686if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1687let mut visitor = OpaqueTypeExpander {
1688 seen_opaque_tys: FxHashSet::default(),
1689 expanded_cache: FxHashMap::default(),
1690 primary_def_id: None,
1691 found_recursion: false,
1692 found_any_recursion: false,
1693 check_recursion: false,
1694tcx,
1695 };
1696val.fold_with(&mut visitor)
1697}
16981699/// Determines whether an item is directly annotated with `doc(hidden)`.
1700fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1701{
{
'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())1702}
17031704/// Determines whether an item is annotated with `doc(notable_trait)`.
1705pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1706{
{
'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())1707}
17081709/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1710///
1711/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1712/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1713/// cause an ICE that we otherwise may want to prevent.
1714pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1715if 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) {
1716let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1717 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1718 !has_body1719 }
1720_ => true,
1721 };
1722Some(ty::IntrinsicDef {
1723 name: tcx.item_name(def_id),
1724must_be_overridden,
1725 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),
1726 })
1727 } else {
1728None1729 }
1730}
17311732pub fn provide(providers: &mut Providers) {
1733*providers = Providers {
1734reveal_opaque_types_in_bounds,
1735is_doc_hidden,
1736is_doc_notable_trait,
1737intrinsic_raw,
1738 ..*providers1739 }
1740}