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