Skip to main content

rustc_middle/ty/
util.rs

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