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