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_attr_ir::find_attr;
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_data_structures::stable_hash::{StableHash, StableHasher};
10use rustc_errors::ErrorGuaranteed;
11use rustc_hashes::Hash128;
12use rustc_hir as hir;
13use rustc_hir::def::{CtorOf, DefKind, Res};
14use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
15use rustc_index::bit_set::GrowableBitSet;
16use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
17use rustc_span::{bug, span_bug, sym};
18use rustc_structures::Limit;
19use rustc_type_ir::PredicateProxy;
20use rustc_type_ir::solve::SizedTraitKind;
21use smallvec::{SmallVec, smallvec};
22use tracing::{debug, instrument};
23
24use super::TypingEnv;
25use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
26use crate::mir;
27use crate::query::Providers;
28use crate::traits::ObligationCause;
29use crate::ty::consts::ConstExt;
30use crate::ty::layout::{FloatExt, IntegerExt};
31use crate::ty::{
32    self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
33    TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized,
34};
35
36#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Discr<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for Discr<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Discr<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u128>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Discr<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Discr", "val",
            &self.val, "ty", &&self.ty)
    }
}Debug)]
37pub struct Discr<'tcx> {
38    /// Bit representation of the discriminant (e.g., `-1i8` is `0xFF_u128`).
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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CheckRegions { }
#[automatically_derived]
impl ::core::clone::Clone for CheckRegions {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CheckRegions {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CheckRegions::No => "No",
                CheckRegions::OnlyParam => "OnlyParam",
                CheckRegions::FromFunction => "FromFunction",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CheckRegions { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CheckRegions {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CheckRegions { }Eq)]
45pub enum CheckRegions {
46    No,
47    /// Only permit parameter regions. This should be used
48    /// for everything apart from functions, which may use
49    /// `ReBound` to represent late-bound regions.
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]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for NotUniqueParam<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for NotUniqueParam<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<ty::GenericArg<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ty::GenericArg<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for NotUniqueParam<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::DuplicateParam(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "DuplicateParam", &__self_0),
            Self::NotParam(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NotParam", &__self_0),
        }
    }
}Debug)]
58pub enum NotUniqueParam<'tcx> {
59    DuplicateParam(ty::GenericArg<'tcx>),
60    NotParam(ty::GenericArg<'tcx>),
61}
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
108pub trait IntTypeExt {
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>)
    -> Ty<'tcx>;
    fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>)
    -> Discr<'tcx>;
    fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>)
    -> Option<Discr<'tcx>>;
}
impl IntTypeExt for IntegerType {
    fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
        match self {
            IntegerType::Pointer(true) => tcx.types.isize,
            IntegerType::Pointer(false) => tcx.types.usize,
            IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
        }
    }
    fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
        Discr { val: 0, ty: self.to_ty(tcx) }
    }
    fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>)
        -> Option<Discr<'tcx>> {
        if let Some(val) = val {
            {
                match (&self.to_ty(tcx), &val.ty) {
                    (left_val, right_val) => {
                        if !(*left_val == *right_val) {
                            let kind = ::core::panicking::AssertKind::Eq;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val, ::core::option::Option::None);
                        }
                    }
                }
            };
            let (new, oflo) = val.checked_add(tcx, 1);
            if oflo { None } else { Some(new) }
        } else { Some(self.initial_discriminant(tcx)) }
    }
}#[extension(pub trait IntTypeExt)]
109impl IntegerType {
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.stable_hash(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        self.assert_fully_normalized(typing_env, ty);
222        self.struct_tail_raw(
223            ty,
224            &ObligationCause::dummy(),
225            |ty| self.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            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected unsized tail: {0:?}", tail), Location::caller())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(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
261        // This is currently used to allow us to walk a ValTree
262        // in lockstep with the type in order to get the ValTree branch that
263        // corresponds to an unsized field.
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::diagnostics::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 = normalize(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                _ => {
307                    break;
308                }
309            }
310        }
311        ty
312    }
313
314    /// Same as applying `struct_tail` on `source` and `target`, but only
315    /// keeps going as long as the two types are instances of the same
316    /// structure definitions.
317    /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, dyn Trait)`,
318    /// whereas struct_tail produces `T`, and `Trait`, respectively.
319    ///
320    /// Should only be called if the types have no inference variables and do
321    /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
322    /// normalization attempt may cause compiler bugs.
323    pub fn struct_lockstep_tails_for_codegen(
324        self,
325        source: Ty<'tcx>,
326        target: Ty<'tcx>,
327        typing_env: ty::TypingEnv<'tcx>,
328    ) -> (Ty<'tcx>, Ty<'tcx>) {
329        self.assert_fully_normalized(typing_env, (source, target));
330        self.struct_lockstep_tails_raw(source, target, |ty| {
331            self.normalize_erasing_regions(typing_env, ty)
332        })
333    }
334
335    /// Same as applying `struct_tail` on `source` and `target`, but only
336    /// keeps going as long as the two types are instances of the same
337    /// structure definitions.
338    /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
339    /// whereas struct_tail produces `T`, and `Trait`, respectively.
340    ///
341    /// See also `struct_lockstep_tails_for_codegen`, which is suitable for use
342    /// during codegen.
343    pub fn struct_lockstep_tails_raw(
344        self,
345        source: Ty<'tcx>,
346        target: Ty<'tcx>,
347        normalize: impl Fn(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
348    ) -> (Ty<'tcx>, Ty<'tcx>) {
349        let (mut a, mut b) = (source, target);
350        loop {
351            match (a.kind(), b.kind()) {
352                (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
353                    if a_def == b_def && a_def.is_struct() =>
354                {
355                    if let Some(f) = a_def.non_enum_variant().tail_opt() {
356                        a = normalize(f.ty(self, a_args));
357                        b = normalize(f.ty(self, b_args));
358                    } else {
359                        break;
360                    }
361                }
362                (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
363                    if let Some(&a_last) = a_tys.last() {
364                        a = a_last;
365                        b = *b_tys.last().unwrap();
366                    } else {
367                        break;
368                    }
369                }
370
371                _ => break,
372            }
373        }
374        (a, b)
375    }
376
377    /// Calculate the destructor of a given type.
378    pub fn calculate_dtor(
379        self,
380        adt_did: LocalDefId,
381        validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
382    ) -> Option<ty::Destructor> {
383        let drop_trait = self.lang_items().drop_trait()?;
384        self.ensure_result().coherent_trait(drop_trait).ok()?;
385
386        let mut dtor_candidate = None;
387        // `Drop` impls can only be written in the same crate as the adt, and cannot be blanket impls
388        for &impl_did in self.local_trait_impls(drop_trait) {
389            let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
390            if adt_def.did() != adt_did.to_def_id() {
391                continue;
392            }
393
394            if validate(self, impl_did).is_err() {
395                // Already `ErrorGuaranteed`, no need to delay a span bug here.
396                continue;
397            }
398
399            let Some(&item_id) = self.associated_item_def_ids(impl_did).first() else {
400                self.dcx()
401                    .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
402                continue;
403            };
404
405            if self.def_kind(item_id) != DefKind::AssocFn {
406                self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
407                continue;
408            }
409
410            if let Some(old_item_id) = dtor_candidate {
411                self.dcx()
412                    .struct_span_err(self.def_span(item_id), "multiple drop impls found")
413                    .with_span_note(self.def_span(old_item_id), "other impl here")
414                    .delay_as_bug();
415            }
416
417            dtor_candidate = Some(item_id);
418        }
419
420        let did = dtor_candidate?;
421        Some(ty::Destructor { did })
422    }
423
424    /// Calculate the async destructor of a given type.
425    pub fn calculate_async_dtor(
426        self,
427        adt_did: LocalDefId,
428        validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
429    ) -> Option<ty::AsyncDestructor> {
430        let async_drop_trait = self.lang_items().async_drop_trait()?;
431        self.ensure_result().coherent_trait(async_drop_trait).ok()?;
432
433        let mut dtor_candidate = None;
434        // `AsyncDrop` impls can only be written in the same crate as the adt, and cannot be blanket impls
435        for &impl_did in self.local_trait_impls(async_drop_trait) {
436            let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
437            if adt_def.did() != adt_did.to_def_id() {
438                continue;
439            }
440
441            if validate(self, impl_did).is_err() {
442                // Already `ErrorGuaranteed`, no need to delay a span bug here.
443                continue;
444            }
445
446            if let Some(old_impl_did) = dtor_candidate {
447                self.dcx()
448                    .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
449                    .with_span_note(self.def_span(old_impl_did), "other impl here")
450                    .delay_as_bug();
451            }
452
453            dtor_candidate = Some(impl_did);
454        }
455
456        Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
457    }
458
459    /// Returns the set of types that are required to be alive in
460    /// order to run the destructor of `def` (see RFCs 769 and
461    /// 1238).
462    ///
463    /// Note that this returns only the constraints for the
464    /// destructor of `def` itself. For the destructors of the
465    /// contents, you need `adt_dtorck_constraint`.
466    pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
467        let dtor = match def.destructor(self) {
468            None => {
469                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs:469",
                        "rustc_middle::ty::util", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(469u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("destructor_constraints({0:?}) - no dtor",
                                                    def.did()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("destructor_constraints({:?}) - no dtor", def.did());
470                return ::alloc::vec::Vec::new()vec![];
471            }
472            Some(dtor) => dtor.did,
473        };
474
475        let impl_def_id = self.parent(dtor);
476        let impl_generics = self.generics_of(impl_def_id);
477
478        // We have a destructor - all the parameters that are not
479        // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
480        // must be live.
481
482        // We need to return the list of parameters from the ADTs
483        // generics/args that correspond to impure parameters on the
484        // impl's generics. This is a bit ugly, but conceptually simple:
485        //
486        // Suppose our ADT looks like the following
487        //
488        //     struct S<X, Y, Z>(X, Y, Z);
489        //
490        // and the impl is
491        //
492        //     impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
493        //
494        // We want to return the parameters (X, Y). For that, we match
495        // up the item-args <X, Y, Z> with the args on the impl ADT,
496        // <P1, P2, P0>, and then look up which of the impl args refer to
497        // parameters marked as pure.
498
499        let impl_args =
500            match *self.type_of(impl_def_id).instantiate_identity().skip_norm_wip().kind() {
501                ty::Adt(def_, args) if def_ == def => args,
502                _ => ::rustc_span::macros::bug_impl(Some(self.def_span(impl_def_id)),
    format_args!("expected ADT for self type of `Drop` impl"),
    Location::caller())span_bug!(
503                    self.def_span(impl_def_id),
504                    "expected ADT for self type of `Drop` impl"
505                ),
506            };
507
508        let item_args = ty::GenericArgs::identity_for_item(self, def.did());
509
510        let result = iter::zip(item_args, impl_args)
511            .filter(|&(_, arg)| {
512                match arg.kind() {
513                    GenericArgKind::Lifetime(region) => match region.kind() {
514                        ty::ReEarlyParam(ebr) => {
515                            !impl_generics.region_param(ebr, self).pure_wrt_drop
516                        }
517                        // Error: not a region param
518                        _ => false,
519                    },
520                    GenericArgKind::Type(ty) => match *ty.kind() {
521                        ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
522                        // Error: not a type param
523                        _ => false,
524                    },
525                    GenericArgKind::Const(ct) => match ct.kind() {
526                        ty::ConstKind::Param(pc) => {
527                            !impl_generics.const_param(pc, self).pure_wrt_drop
528                        }
529                        // Error: not a const param
530                        _ => false,
531                    },
532                }
533            })
534            .map(|(item_param, _)| item_param)
535            .collect();
536        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs:536",
                        "rustc_middle::ty::util", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(536u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("destructor_constraint({0:?}) = {1:?}",
                                                    def.did(), result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
537        result
538    }
539
540    /// Checks whether each generic argument is simply a unique generic parameter.
541    pub fn uses_unique_generic_params(
542        self,
543        args: &[ty::GenericArg<'tcx>],
544        ignore_regions: CheckRegions,
545    ) -> Result<(), NotUniqueParam<'tcx>> {
546        let mut seen = GrowableBitSet::default();
547        let mut seen_late = FxHashSet::default();
548        for arg in args {
549            match arg.kind() {
550                GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
551                    (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
552                        if !seen_late.insert((di, reg)) {
553                            return Err(NotUniqueParam::DuplicateParam(lt.into()));
554                        }
555                    }
556                    (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
557                        if !seen.insert(p.index) {
558                            return Err(NotUniqueParam::DuplicateParam(lt.into()));
559                        }
560                    }
561                    (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
562                        return Err(NotUniqueParam::NotParam(lt.into()));
563                    }
564                    (CheckRegions::No, _) => {}
565                },
566                GenericArgKind::Type(t) => match t.kind() {
567                    ty::Param(p) => {
568                        if !seen.insert(p.index) {
569                            return Err(NotUniqueParam::DuplicateParam(t.into()));
570                        }
571                    }
572                    _ => return Err(NotUniqueParam::NotParam(t.into())),
573                },
574                GenericArgKind::Const(c) => match c.kind() {
575                    ty::ConstKind::Param(p) => {
576                        if !seen.insert(p.index) {
577                            return Err(NotUniqueParam::DuplicateParam(c.into()));
578                        }
579                    }
580                    _ => return Err(NotUniqueParam::NotParam(c.into())),
581                },
582            }
583        }
584
585        Ok(())
586    }
587
588    /// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
589    /// (i.e. an async closure). These are all represented by `hir::Closure`, and all
590    /// have the same `DefKind`.
591    ///
592    /// Note that closures have a `DefId`, but the closure *expression* also has a
593    /// `HirId` that is located within the context where the closure appears. The
594    /// parent of the closure's `DefId` will also be the context where it appears.
595    pub fn is_closure_like(self, def_id: DefId) -> bool {
596        #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
    DefKind::Closure => true,
    _ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)
597    }
598
599    /// Returns `true` if `def_id` refers to a definition that does not have its own
600    /// type-checking context, i.e. closure, coroutine or inline const.
601    pub fn is_typeck_child(self, def_id: DefId) -> bool {
602        match self.def_kind(def_id) {
603            DefKind::AnonConst => {
604                self.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline
605            }
606            DefKind::Closure | DefKind::SyntheticCoroutineBody => true,
607            DefKind::Mod
608            | DefKind::Struct
609            | DefKind::Union
610            | DefKind::Enum
611            | DefKind::Variant
612            | DefKind::Trait
613            | DefKind::TyAlias
614            | DefKind::ForeignTy
615            | DefKind::TraitAlias
616            | DefKind::AssocTy
617            | DefKind::TyParam
618            | DefKind::Fn
619            | DefKind::Const
620            | DefKind::ConstParam
621            | DefKind::Static { .. }
622            | DefKind::Ctor(_, _)
623            | DefKind::AssocFn
624            | DefKind::AssocConst
625            | DefKind::Macro(_)
626            | DefKind::ExternCrate
627            | DefKind::Use
628            | DefKind::ForeignMod
629            | DefKind::OpaqueTy
630            | DefKind::Field
631            | DefKind::LifetimeParam
632            | DefKind::GlobalAsm
633            | DefKind::Impl { .. }
634            | DefKind::TestBinderConstraints => false,
635        }
636    }
637
638    /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
639    pub fn is_trait(self, def_id: DefId) -> bool {
640        self.def_kind(def_id) == DefKind::Trait
641    }
642
643    /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
644    /// and `false` otherwise.
645    pub fn is_trait_alias(self, def_id: DefId) -> bool {
646        self.def_kind(def_id) == DefKind::TraitAlias
647    }
648
649    /// Returns `true` if this `DefId` refers to the implicit constructor for
650    /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
651    pub fn is_constructor(self, def_id: DefId) -> bool {
652        #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
    DefKind::Ctor(..) => true,
    _ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))
653    }
654
655    /// Given the `DefId`, returns the `DefId` of the innermost item that
656    /// has its own type-checking context or "inference environment".
657    ///
658    /// For example, a closure has its own `DefId`, but it is type-checked
659    /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
660    /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
661    pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
662        let mut def_id = def_id;
663        while self.is_typeck_child(def_id) {
664            def_id = self.parent(def_id);
665        }
666        def_id
667    }
668
669    /// Given the `LocalDefId`, returns the `LocalDefId` of the innermost item that
670    /// has its own type-checking context or "inference environment".
671    ///
672    /// For example, a closure has its own `LocalDefId`, but it is type-checked
673    /// with the containing item. Therefore, when we fetch the `typeck` of the closure,
674    /// for example, we really wind up fetching the `typeck` of the enclosing fn item.
675    pub fn typeck_root_def_id_local(self, def_id: LocalDefId) -> LocalDefId {
676        let mut def_id = def_id;
677        while self.is_typeck_child(def_id.to_def_id()) {
678            def_id = self.local_parent(def_id);
679        }
680        def_id
681    }
682
683    /// Given the `DefId` and args a closure, creates the type of
684    /// `self` argument that the closure expects. For example, for a
685    /// `Fn` closure, this would return a reference type `&T` where
686    /// `T = closure_ty`.
687    ///
688    /// Returns `None` if this closure's kind has not yet been inferred.
689    /// This should only be possible during type checking.
690    ///
691    /// Note that the return value is a late-bound region and hence
692    /// wrapped in a binder.
693    pub fn closure_env_ty(
694        self,
695        closure_ty: Ty<'tcx>,
696        closure_kind: ty::ClosureKind,
697        env_region: ty::Region<'tcx>,
698    ) -> Ty<'tcx> {
699        match closure_kind {
700            ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
701            ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
702            ty::ClosureKind::FnOnce => closure_ty,
703        }
704    }
705
706    /// Returns `true` if the node pointed to by `def_id` is a `static` item.
707    #[inline]
708    pub fn is_static(self, def_id: DefId) -> bool {
709        #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
    DefKind::Static { .. } => true,
    _ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })
710    }
711
712    #[inline]
713    pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
714        if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
715            Some(mutability)
716        } else {
717            None
718        }
719    }
720
721    /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
722    pub fn is_thread_local_static(self, def_id: DefId) -> bool {
723        self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
724    }
725
726    /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
727    #[inline]
728    pub fn is_mutable_static(self, def_id: DefId) -> bool {
729        self.static_mutability(def_id) == Some(hir::Mutability::Mut)
730    }
731
732    /// Returns `true` if the item pointed to by `def_id` is a thread local which needs a
733    /// thread local shim generated.
734    #[inline]
735    pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
736        !self.sess.target.dll_tls_export
737            && self.is_thread_local_static(def_id)
738            && !self.is_foreign_item(def_id)
739    }
740
741    /// Returns the type a reference to the thread local takes in MIR.
742    pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
743        let static_ty = self.type_of(def_id).instantiate_identity().skip_norm_wip();
744        if self.is_mutable_static(def_id) {
745            Ty::new_mut_ptr(self, static_ty)
746        } else if self.is_foreign_item(def_id) {
747            Ty::new_imm_ptr(self, static_ty)
748        } else {
749            // FIXME: These things don't *really* have 'static lifetime.
750            Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
751        }
752    }
753
754    /// Get the type of the pointer to the static that we use in MIR.
755    pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
756        // Make sure that any constants in the static's type are evaluated.
757        let static_ty =
758            self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
759
760        // Make sure that accesses to unsafe statics end up using raw pointers.
761        // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
762        if self.is_mutable_static(def_id) {
763            Ty::new_mut_ptr(self, static_ty)
764        } else if self.is_foreign_item(def_id) {
765            Ty::new_imm_ptr(self, static_ty)
766        } else {
767            Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
768        }
769    }
770
771    /// Expands the given impl trait type, stopping if the type is recursive.
772    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("try_expand_impl_trait_type",
                                "rustc_middle::ty::util", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
                                ::tracing_core::__macro_support::Option::Some(772u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("args")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("args");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: Result<Ty<'tcx>, Ty<'tcx>> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let mut visitor =
                            OpaqueTypeExpander {
                                seen_opaque_tys: FxHashSet::default(),
                                expanded_cache: FxHashMap::default(),
                                primary_def_id: Some(def_id),
                                found_recursion: false,
                                found_any_recursion: false,
                                check_recursion: true,
                                tcx: self,
                            };
                        let expanded_type =
                            visitor.expand_opaque_ty(def_id, args).unwrap();
                        if visitor.found_recursion {
                            Err(expanded_type)
                        } else { Ok(expanded_type) }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs:772",
                        "rustc_middle::ty::util", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c1070d69382b8d2f2eb65119c738a77d9e324c9e/compiler/rustc_middle/src/ty/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(772u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(self), level = "debug", ret)]
773    pub fn try_expand_impl_trait_type(
774        self,
775        def_id: DefId,
776        args: GenericArgsRef<'tcx>,
777    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
778        let mut visitor = OpaqueTypeExpander {
779            seen_opaque_tys: FxHashSet::default(),
780            expanded_cache: FxHashMap::default(),
781            primary_def_id: Some(def_id),
782            found_recursion: false,
783            found_any_recursion: false,
784            check_recursion: true,
785            tcx: self,
786        };
787
788        let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
789        if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
790    }
791
792    /// Query and get an English description for the item's kind.
793    pub fn def_descr(self, def_id: DefId) -> &'static str {
794        self.def_kind_descr(self.def_kind(def_id), def_id)
795    }
796
797    /// Get an English description for the item's kind.
798    pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
799        match def_kind {
800            DefKind::AssocFn if self.associated_item(def_id).is_method() => "method",
801            DefKind::AssocTy if self.opt_rpitit_info(def_id).is_some() => "opaque type",
802            DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
803                match coroutine_kind {
804                    hir::CoroutineKind::Desugared(
805                        hir::CoroutineDesugaring::Async,
806                        hir::CoroutineSource::Fn,
807                    ) => "async fn",
808                    hir::CoroutineKind::Desugared(
809                        hir::CoroutineDesugaring::Async,
810                        hir::CoroutineSource::Block,
811                    ) => "async block",
812                    hir::CoroutineKind::Desugared(
813                        hir::CoroutineDesugaring::Async,
814                        hir::CoroutineSource::Closure,
815                    ) => "async closure",
816                    hir::CoroutineKind::Desugared(
817                        hir::CoroutineDesugaring::AsyncGen,
818                        hir::CoroutineSource::Fn,
819                    ) => "async gen fn",
820                    hir::CoroutineKind::Desugared(
821                        hir::CoroutineDesugaring::AsyncGen,
822                        hir::CoroutineSource::Block,
823                    ) => "async gen block",
824                    hir::CoroutineKind::Desugared(
825                        hir::CoroutineDesugaring::AsyncGen,
826                        hir::CoroutineSource::Closure,
827                    ) => "async gen closure",
828                    hir::CoroutineKind::Desugared(
829                        hir::CoroutineDesugaring::Gen,
830                        hir::CoroutineSource::Fn,
831                    ) => "gen fn",
832                    hir::CoroutineKind::Desugared(
833                        hir::CoroutineDesugaring::Gen,
834                        hir::CoroutineSource::Block,
835                    ) => "gen block",
836                    hir::CoroutineKind::Desugared(
837                        hir::CoroutineDesugaring::Gen,
838                        hir::CoroutineSource::Closure,
839                    ) => "gen closure",
840                    hir::CoroutineKind::Coroutine(_) => "coroutine",
841                }
842            }
843            _ => def_kind.descr(def_id),
844        }
845    }
846
847    /// Gets an English article for the [`TyCtxt::def_descr`].
848    pub fn def_descr_article(self, def_id: DefId) -> &'static str {
849        self.def_kind_descr_article(self.def_kind(def_id), def_id)
850    }
851
852    /// Gets an English article for the [`TyCtxt::def_kind_descr`].
853    pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
854        match def_kind {
855            DefKind::AssocFn if self.associated_item(def_id).is_method() => "a",
856            DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
857                match coroutine_kind {
858                    hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
859                    hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
860                    hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
861                    hir::CoroutineKind::Coroutine(_) => "a",
862                }
863            }
864            _ => def_kind.article(),
865        }
866    }
867
868    /// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
869    /// dependency, or a [direct] private dependency. This is used to decide whether the crate can
870    /// be shown in `impl` suggestions.
871    ///
872    /// [public]: TyCtxt::is_private_dep
873    /// [direct]: rustc_crate_store::ExternCrate::is_direct
874    pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
875        // `#![rustc_private]` overrides defaults to make private dependencies usable.
876        if self.features().enabled(sym::rustc_private) {
877            return true;
878        }
879
880        // | Private | Direct | Visible |                    |
881        // |---------|--------|---------|--------------------|
882        // | Yes     | Yes    | Yes     | !true || true   |
883        // | No      | Yes    | Yes     | !false || true  |
884        // | Yes     | No     | No      | !true || false  |
885        // | No      | No     | Yes     | !false || false |
886        !self.is_private_dep(key)
887            // If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
888            // Treat that kind of crate as "indirect", since it's an implementation detail of
889            // the language.
890            || self.extern_crate(key).is_some_and(|e| e.is_direct())
891    }
892
893    /// Expand any [free alias types][free] contained within the given `value`.
894    ///
895    /// This should be used over other normalization routines in situations where
896    /// it's important not to normalize other alias types and where the predicates
897    /// on the corresponding type alias shouldn't be taken into consideration.
898    ///
899    /// Whenever possible **prefer not to use this function**! Instead, use standard
900    /// normalization routines or if feasible don't normalize at all.
901    ///
902    /// This function comes in handy if you want to mimic the behavior of eager
903    /// type alias expansion in a localized manner.
904    ///
905    /// <div class="warning">
906    /// This delays a bug on overflow! Therefore you need to be certain that the
907    /// contained types get fully normalized at a later stage. Note that even on
908    /// overflow all well-behaved free alias types get expanded correctly, so the
909    /// result is still useful.
910    /// </div>
911    ///
912    /// [free]: ty::Free
913    pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
914        value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
915    }
916
917    /// Peel off all [free alias types] in this type until there are none left.
918    ///
919    /// This only expands free alias types in “head” / outermost positions. It can
920    /// be used over [expand_free_alias_tys] as an optimization in situations where
921    /// one only really cares about the *kind* of the final aliased type but not
922    /// the types the other constituent types alias.
923    ///
924    /// <div class="warning">
925    /// This delays a bug on overflow! Therefore you need to be certain that the
926    /// type gets fully normalized at a later stage.
927    /// </div>
928    ///
929    /// [free]: ty::Free
930    /// [expand_free_alias_tys]: Self::expand_free_alias_tys
931    pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
932        let ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) = ty.kind() else {
933            return ty;
934        };
935
936        let limit = self.recursion_limit();
937        let mut depth = 0;
938
939        while let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() {
940            if !limit.value_within_limit(depth) {
941                let guar = self.dcx().delayed_bug("overflow expanding free alias type");
942                return Ty::new_error(self, guar);
943            }
944
945            ty = self.type_of(def_id).instantiate(self, args).skip_normalization();
946            depth += 1;
947        }
948
949        ty
950    }
951
952    // Computes the variances for an alias (opaque or RPITIT) that represent
953    // its (un)captured regions.
954    pub fn opt_alias_variances(
955        self,
956        kind: impl Into<ty::AliasTermKind<'tcx>>,
957    ) -> Option<&'tcx [ty::Variance]> {
958        match kind.into() {
959            ty::AliasTermKind::ProjectionTy { def_id } => {
960                if self.is_impl_trait_in_trait(def_id) {
961                    Some(self.variances_of(def_id))
962                } else {
963                    None
964                }
965            }
966            ty::AliasTermKind::OpaqueTy { def_id } => Some(self.variances_of(def_id)),
967            ty::AliasTermKind::InherentTy { .. }
968            | ty::AliasTermKind::InherentConstSelf { .. }
969            | ty::AliasTermKind::InherentConstImpl { .. }
970            | ty::AliasTermKind::FreeTy { .. }
971            | ty::AliasTermKind::FreeConst { .. }
972            | ty::AliasTermKind::AnonConst { .. }
973            | ty::AliasTermKind::ProjectionConst { .. } => None,
974        }
975    }
976}
977
978struct OpaqueTypeExpander<'tcx> {
979    // Contains the DefIds of the opaque types that are currently being
980    // expanded. When we expand an opaque type we insert the DefId of
981    // that type, and when we finish expanding that type we remove the
982    // its DefId.
983    seen_opaque_tys: FxHashSet<DefId>,
984    // Cache of all expansions we've seen so far. This is a critical
985    // optimization for some large types produced by async fn trees.
986    expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
987    primary_def_id: Option<DefId>,
988    found_recursion: bool,
989    found_any_recursion: bool,
990    /// Whether or not to check for recursive opaque types.
991    /// This is `true` when we're explicitly checking for opaque type
992    /// recursion, and 'false' otherwise to avoid unnecessary work.
993    check_recursion: bool,
994    tcx: TyCtxt<'tcx>,
995}
996
997impl<'tcx> OpaqueTypeExpander<'tcx> {
998    fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
999        if self.found_any_recursion {
1000            return None;
1001        }
1002        let args = args.fold_with(self);
1003        if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
1004            let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
1005                Some(expanded_ty) => *expanded_ty,
1006                None => {
1007                    let generic_ty = self.tcx.type_of(def_id);
1008                    let concrete_ty = generic_ty.instantiate(self.tcx, args).skip_normalization();
1009                    let expanded_ty = self.fold_ty(concrete_ty);
1010                    self.expanded_cache.insert((def_id, args), expanded_ty);
1011                    expanded_ty
1012                }
1013            };
1014            if self.check_recursion {
1015                self.seen_opaque_tys.remove(&def_id);
1016            }
1017            Some(expanded_ty)
1018        } else {
1019            // If another opaque type that we contain is recursive, then it
1020            // will report the error, so we don't have to.
1021            self.found_any_recursion = true;
1022            self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1023            None
1024        }
1025    }
1026}
1027
1028impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1029    fn cx(&self) -> TyCtxt<'tcx> {
1030        self.tcx
1031    }
1032
1033    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1034        if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *t.kind() {
1035            self.expand_opaque_ty(def_id, args).unwrap_or(t)
1036        } else if t.has_opaque_types() {
1037            t.super_fold_with(self)
1038        } else {
1039            t
1040        }
1041    }
1042
1043    fn fold_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> P {
1044        // We use `map_projection` to execute the closure only if `p` is a projection clause,
1045        // to implement the logic described below (i.e. avoid folding the `term`).
1046        // In all other cases, fold recursively, as normal.
1047        p.map_projection(self.tcx, |bound_clause| {
1048            let projection_clause = bound_clause.skip_binder();
1049            bound_clause.rebind(ty::ProjectionClause {
1050                projection_term: projection_clause.projection_term.fold_with(self),
1051                // Don't fold the term on the RHS of the projection predicate.
1052                // This is because for default trait methods with RPITITs, we
1053                // install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`
1054                // predicate, which would trivially cause a cycle when we do
1055                // anything that requires `TypingEnv::with_post_analysis_normalized`.
1056                term: projection_clause.term,
1057            })
1058        })
1059        .unwrap_or_else(|| p.super_fold_with(self))
1060    }
1061}
1062
1063struct FreeAliasTypeExpander<'tcx> {
1064    tcx: TyCtxt<'tcx>,
1065    depth: usize,
1066}
1067
1068impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1069    fn cx(&self) -> TyCtxt<'tcx> {
1070        self.tcx
1071    }
1072
1073    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1074        if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1075            return ty;
1076        }
1077        let &ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) = ty.kind() else {
1078            return ty.super_fold_with(self);
1079        };
1080        if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1081            let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1082            return Ty::new_error(self.tcx, guar);
1083        }
1084
1085        self.depth += 1;
1086        let ty = self
1087            .tcx
1088            .type_of(def_id)
1089            .instantiate(self.tcx, args)
1090            .skip_normalization()
1091            .fold_with(self);
1092        self.depth -= 1;
1093        ty
1094    }
1095
1096    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1097        if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1098            return ct;
1099        }
1100        ct.super_fold_with(self)
1101    }
1102}
1103
1104impl<'tcx> Ty<'tcx> {
1105    /// Returns the `Size` for primitive types (bool, uint, int, char, float).
1106    pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1107        match *self.kind() {
1108            ty::Bool => Size::from_bytes(1),
1109            ty::Char => Size::from_bytes(4),
1110            ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1111            ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1112            ty::Float(fty) => Float::from_float_ty(fty).size(),
1113            _ => ::rustc_span::macros::bug_impl(None, format_args!("non primitive type"),
    Location::caller())bug!("non primitive type"),
1114        }
1115    }
1116
1117    pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1118        match *self.kind() {
1119            ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1120            ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1121            _ => ::rustc_span::macros::bug_impl(None, format_args!("non integer discriminant"),
    Location::caller())bug!("non integer discriminant"),
1122        }
1123    }
1124
1125    /// Returns the minimum and maximum values for the given numeric type (including `char`s) or
1126    /// returns `None` if the type is not numeric.
1127    pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1128        use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1129        Some(match self.kind() {
1130            ty::Int(_) | ty::Uint(_) => {
1131                let (size, signed) = self.int_size_and_signed(tcx);
1132                let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1133                let max =
1134                    if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1135                (min, max)
1136            }
1137            ty::Char => (0, std::char::MAX as u128),
1138            ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1139            ty::Float(ty::FloatTy::F32) => {
1140                ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1141            }
1142            ty::Float(ty::FloatTy::F64) => {
1143                ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1144            }
1145            ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1146            _ => return None,
1147        })
1148    }
1149
1150    /// Returns the maximum value for the given numeric type (including `char`s)
1151    /// or returns `None` if the type is not numeric.
1152    pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1153        let typing_env = TypingEnv::fully_monomorphized();
1154        self.numeric_min_and_max_as_bits(tcx)
1155            .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1156    }
1157
1158    /// Returns the minimum value for the given numeric type (including `char`s)
1159    /// or returns `None` if the type is not numeric.
1160    pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1161        let typing_env = TypingEnv::fully_monomorphized();
1162        self.numeric_min_and_max_as_bits(tcx)
1163            .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1164    }
1165
1166    /// Checks whether values of this type `T` have a size known at
1167    /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
1168    /// for the purposes of this check, so it can be an
1169    /// over-approximation in generic contexts, where one can have
1170    /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
1171    /// actually carry lifetime requirements.
1172    pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1173        self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1174            || tcx.is_sized_raw(typing_env.as_query_input(self))
1175    }
1176
1177    /// Checks whether values of this type `T` implement the `Freeze`
1178    /// trait -- frozen types are those that do not contain an
1179    /// `UnsafeCell` anywhere. This is a language concept used to
1180    /// distinguish "true immutability", which is relevant to
1181    /// optimization as well as the rules around static values. Note
1182    /// that the `Freeze` trait is not exposed to end users and is
1183    /// effectively an implementation detail.
1184    pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1185        self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1186    }
1187
1188    /// Fast path helper for testing if a type is `Freeze`.
1189    ///
1190    /// Returning true means the type is known to be `Freeze`. Returning
1191    /// `false` means nothing -- could be `Freeze`, might not be.
1192    pub fn is_trivially_freeze(self) -> bool {
1193        match self.kind() {
1194            ty::Int(_)
1195            | ty::Uint(_)
1196            | ty::Float(_)
1197            | ty::Bool
1198            | ty::Char
1199            | ty::Str
1200            | ty::Never
1201            | ty::Ref(..)
1202            | ty::RawPtr(_, _)
1203            | ty::FnDef(..)
1204            | ty::Error(_)
1205            | ty::FnPtr(..) => true,
1206            ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1207            ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1208            ty::Adt(..)
1209            | ty::Bound(..)
1210            | ty::Closure(..)
1211            | ty::CoroutineClosure(..)
1212            | ty::Dynamic(..)
1213            | ty::Foreign(_)
1214            | ty::Coroutine(..)
1215            | ty::CoroutineWitness(..)
1216            | ty::UnsafeBinder(_)
1217            | ty::Infer(_)
1218            | ty::Alias(..)
1219            | ty::Param(_)
1220            | ty::Placeholder(_) => false,
1221        }
1222    }
1223
1224    /// Checks whether values of this type `T` implement the `UnsafeUnpin` trait.
1225    pub fn is_unsafe_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1226        self.is_trivially_unpin() || tcx.is_unsafe_unpin_raw(typing_env.as_query_input(self))
1227    }
1228
1229    /// Checks whether values of this type `T` implement the `Unpin` trait.
1230    ///
1231    /// Note that this is a safe trait, so it cannot be very semantically meaningful.
1232    /// However, as a hack to mitigate <https://github.com/rust-lang/rust/issues/63818> until a
1233    /// proper solution is implemented, we do give special semantics to the `Unpin` trait.
1234    pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1235        self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1236    }
1237
1238    /// Fast path helper for testing if a type is `Unpin` *and* `UnsafeUnpin`.
1239    ///
1240    /// Returning true means the type is known to be `Unpin` and `UnsafeUnpin`. Returning
1241    /// `false` means nothing -- could be `Unpin`, might not be.
1242    fn is_trivially_unpin(self) -> bool {
1243        match self.kind() {
1244            ty::Int(_)
1245            | ty::Uint(_)
1246            | ty::Float(_)
1247            | ty::Bool
1248            | ty::Char
1249            | ty::Str
1250            | ty::Never
1251            | ty::Ref(..)
1252            | ty::RawPtr(_, _)
1253            | ty::FnDef(..)
1254            | ty::Error(_)
1255            | ty::FnPtr(..) => true,
1256            ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1257            ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1258            ty::Adt(..)
1259            | ty::Bound(..)
1260            | ty::Closure(..)
1261            | ty::CoroutineClosure(..)
1262            | ty::Dynamic(..)
1263            | ty::Foreign(_)
1264            | ty::Coroutine(..)
1265            | ty::CoroutineWitness(..)
1266            | ty::UnsafeBinder(_)
1267            | ty::Infer(_)
1268            | ty::Alias(..)
1269            | ty::Param(_)
1270            | ty::Placeholder(_) => false,
1271        }
1272    }
1273
1274    /// Checks whether this type is an ADT that has unsafe fields.
1275    pub fn has_unsafe_fields(self) -> bool {
1276        if let ty::Adt(adt_def, ..) = self.kind() {
1277            adt_def.all_fields().any(|x| x.safety.is_unsafe())
1278        } else {
1279            false
1280        }
1281    }
1282
1283    /// Checks whether values of this type `T` implement the `AsyncDrop` trait.
1284    pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1285        !self.is_trivially_not_async_drop()
1286            && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1287    }
1288
1289    /// Fast path helper for testing if a type is `AsyncDrop`.
1290    ///
1291    /// Returning true means the type is known to be `!AsyncDrop`. Returning
1292    /// `false` means nothing -- could be `AsyncDrop`, might not be.
1293    fn is_trivially_not_async_drop(self) -> bool {
1294        match self.kind() {
1295            ty::Int(_)
1296            | ty::Uint(_)
1297            | ty::Float(_)
1298            | ty::Bool
1299            | ty::Char
1300            | ty::Str
1301            | ty::Never
1302            | ty::Ref(..)
1303            | ty::RawPtr(..)
1304            | ty::FnDef(..)
1305            | ty::Error(_)
1306            | ty::FnPtr(..) => true,
1307            // FIXME(unsafe_binders):
1308            ty::UnsafeBinder(_) => ::core::panicking::panic("not implemented")unimplemented!(),
1309            ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1310            ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1311                elem_ty.is_trivially_not_async_drop()
1312            }
1313            ty::Adt(..)
1314            | ty::Bound(..)
1315            | ty::Closure(..)
1316            | ty::CoroutineClosure(..)
1317            | ty::Dynamic(..)
1318            | ty::Foreign(_)
1319            | ty::Coroutine(..)
1320            | ty::CoroutineWitness(..)
1321            | ty::Infer(_)
1322            | ty::Alias(..)
1323            | ty::Param(_)
1324            | ty::Placeholder(_) => false,
1325        }
1326    }
1327
1328    /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
1329    /// non-copy and *might* have a destructor attached; if it returns
1330    /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
1331    ///
1332    /// (Note that this implies that if `ty` has a destructor attached,
1333    /// then `needs_drop` will definitely return `true` for `ty`.)
1334    ///
1335    /// Note that this method is used to check eligible types in unions.
1336    #[inline]
1337    pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1338        // Avoid querying in simple cases.
1339        match needs_drop_components(tcx, self) {
1340            Err(AlwaysRequiresDrop) => true,
1341            Ok(components) => {
1342                let query_ty = match *components {
1343                    [] => return false,
1344                    // If we've got a single component, call the query with that
1345                    // to increase the chance that we hit the query cache.
1346                    [component_ty] => component_ty,
1347                    _ => self,
1348                };
1349
1350                // This doesn't depend on regions, so try to minimize distinct
1351                // query keys used. If normalization fails, we just use `query_ty`.
1352                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());
1353                let query_ty = tcx
1354                    .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1355                    .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
1356
1357                tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1358            }
1359        }
1360    }
1361
1362    /// If `ty.needs_async_drop(...)` returns `true`, then `ty` is definitely
1363    /// non-copy and *might* have a async destructor attached; if it returns
1364    /// `false`, then `ty` definitely has no async destructor (i.e., no async
1365    /// drop glue).
1366    ///
1367    /// (Note that this implies that if `ty` has an async destructor attached,
1368    /// then `needs_async_drop` will definitely return `true` for `ty`.)
1369    ///
1370    // FIXME(zetanumbers): Note that this method is used to check eligible types
1371    // in unions.
1372    #[inline]
1373    pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1374        // Avoid querying in simple cases.
1375        match needs_drop_components(tcx, self) {
1376            Err(AlwaysRequiresDrop) => true,
1377            Ok(components) => {
1378                let query_ty = match *components {
1379                    [] => return false,
1380                    // If we've got a single component, call the query with that
1381                    // to increase the chance that we hit the query cache.
1382                    [component_ty] => component_ty,
1383                    _ => self,
1384                };
1385
1386                // This doesn't depend on regions, so try to minimize distinct
1387                // query keys used.
1388                // If normalization fails, we just use `query_ty`.
1389                if true {
    if !!typing_env.has_infer() {
        ::core::panicking::panic("assertion failed: !typing_env.has_infer()")
    };
};debug_assert!(!typing_env.has_infer());
1390                let query_ty = tcx
1391                    .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1392                    .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
1393
1394                tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1395            }
1396        }
1397    }
1398
1399    /// Checks if `ty` has a significant drop.
1400    ///
1401    /// Note that this method can return false even if `ty` has a destructor
1402    /// attached; even if that is the case then the adt has been marked with
1403    /// the attribute `rustc_insignificant_dtor`.
1404    ///
1405    /// Note that this method is used to check for change in drop order for
1406    /// 2229 drop reorder migration analysis.
1407    #[inline]
1408    pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1409        // Avoid querying in simple cases.
1410        match needs_drop_components(tcx, self) {
1411            Err(AlwaysRequiresDrop) => true,
1412            Ok(components) => {
1413                let query_ty = match *components {
1414                    [] => return false,
1415                    // If we've got a single component, call the query with that
1416                    // to increase the chance that we hit the query cache.
1417                    [component_ty] => component_ty,
1418                    _ => self,
1419                };
1420
1421                // FIXME
1422                // We should be canonicalizing, or else moving this to a method of inference
1423                // context, or *something* like that,
1424                // but for now just avoid passing inference variables
1425                // to queries that can't cope with them.
1426                // Instead, conservatively return "true" (may change drop order).
1427                if query_ty.has_infer() {
1428                    return true;
1429                }
1430
1431                // This doesn't depend on regions, so try to minimize distinct
1432                // query keys used.
1433                // FIX: Use try_normalize to avoid crashing. If it fails, return true.
1434                tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(query_ty))
1435                    .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1436                    .unwrap_or(true)
1437            }
1438        }
1439    }
1440
1441    /// Returns `true` if equality for this type is both reflexive and structural.
1442    ///
1443    /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
1444    ///
1445    /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
1446    /// types, equality for the type as a whole is structural when it is the same as equality
1447    /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1448    /// equality is indicated by an implementation of `StructuralPartialEq` for that type.
1449    ///
1450    /// This function is "shallow" because it may return `true` for a composite type whose fields
1451    /// are not `StructuralPartialEq`. For example, `[T; 4]` has structural equality regardless of `T`
1452    /// because equality for arrays is determined by the equality of each array element. If you
1453    /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1454    /// down, you will need to use a type visitor.
1455    #[inline]
1456    pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1457        match self.kind() {
1458            // Look for an impl of `StructuralPartialEq`.
1459            ty::Adt(..) => tcx.has_structural_eq_impl(self),
1460
1461            // Primitive types that satisfy `Eq`.
1462            ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
1463
1464            // Composite types that satisfy `Eq` when all of their fields do.
1465            //
1466            // Because this function is "shallow", we return `true` for these composites regardless
1467            // of the type(s) contained within.
1468            ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
1469
1470            // Raw pointers use bitwise comparison.
1471            ty::RawPtr(_, _) | ty::FnPtr(..) => true,
1472
1473            // Floating point numbers are not `Eq`.
1474            ty::Float(_) => false,
1475
1476            // Conservatively return `false` for all others...
1477
1478            // Anonymous function types
1479            ty::FnDef(..)
1480            | ty::Closure(..)
1481            | ty::CoroutineClosure(..)
1482            | ty::Dynamic(..)
1483            | ty::Coroutine(..) => false,
1484
1485            // Generic or inferred types
1486            //
1487            // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1488            // called for known, fully-monomorphized types.
1489            ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1490                false
1491            }
1492
1493            ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1494        }
1495    }
1496
1497    /// Peel off all reference types in this type until there are none left.
1498    ///
1499    /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1500    ///
1501    /// # Examples
1502    ///
1503    /// - `u8` -> `u8`
1504    /// - `&'a mut u8` -> `u8`
1505    /// - `&'a &'b u8` -> `u8`
1506    /// - `&'a *const &'b u8 -> *const &'b u8`
1507    pub fn peel_refs(self) -> Ty<'tcx> {
1508        let mut ty = self;
1509        while let ty::Ref(_, inner_ty, _) = ty.kind() {
1510            ty = *inner_ty;
1511        }
1512        ty
1513    }
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.
1519//
1520// FIXME(zetanumbers): consider replacing this with only
1521// `needs_drop_components_with_async`
1522#[inline]
1523pub fn needs_drop_components<'tcx>(
1524    tcx: TyCtxt<'tcx>,
1525    ty: Ty<'tcx>,
1526) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1527    needs_drop_components_with_async(tcx, ty, Asyncness::No)
1528}
1529
1530/// Returns a list of types such that the given type needs drop if and only if
1531/// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1532/// this type always needs drop.
1533pub fn needs_drop_components_with_async<'tcx>(
1534    tcx: TyCtxt<'tcx>,
1535    ty: Ty<'tcx>,
1536    asyncness: Asyncness,
1537) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1538    match *ty.kind() {
1539        ty::Infer(ty::FreshIntTy(_))
1540        | ty::Infer(ty::FreshFloatTy(_))
1541        | ty::Bool
1542        | ty::Int(_)
1543        | ty::Uint(_)
1544        | ty::Float(_)
1545        | ty::Never
1546        | ty::FnDef(..)
1547        | ty::FnPtr(..)
1548        | ty::Char
1549        | ty::RawPtr(_, _)
1550        | ty::Ref(..)
1551        | ty::Str => Ok(SmallVec::new()),
1552
1553        // Foreign types can never have destructors.
1554        ty::Foreign(..) => Ok(SmallVec::new()),
1555
1556        // FIXME(zetanumbers): Temporary workaround for async drop of dynamic types
1557        ty::Dynamic(..) | ty::Error(_) => {
1558            if asyncness.is_async() {
1559                Ok(SmallVec::new())
1560            } else {
1561                Err(AlwaysRequiresDrop)
1562            }
1563        }
1564
1565        ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1566        ty::Array(elem_ty, size) => {
1567            match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1568                Ok(v) if v.is_empty() => Ok(v),
1569                res => match size.try_to_target_usize(tcx) {
1570                    // Arrays of size zero don't need drop, even if their element
1571                    // type does.
1572                    Some(0) => Ok(SmallVec::new()),
1573                    Some(_) => res,
1574                    // We don't know which of the cases above we are in, so
1575                    // return the whole type and let the caller decide what to
1576                    // do.
1577                    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]),
1578                },
1579            }
1580        }
1581        // If any field needs drop, then the whole tuple does.
1582        ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1583            acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1584            Ok(acc)
1585        }),
1586
1587        // These require checking for `Copy` bounds or `Adt` destructors.
1588        ty::Adt(..)
1589        | ty::Alias(..)
1590        | ty::Param(_)
1591        | ty::Bound(..)
1592        | ty::Placeholder(..)
1593        | ty::Infer(_)
1594        | ty::Closure(..)
1595        | ty::CoroutineClosure(..)
1596        | ty::Coroutine(..)
1597        | ty::CoroutineWitness(..)
1598        | ty::UnsafeBinder(_) => Ok({
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(ty);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [ty])))
    }
}smallvec![ty]),
1599    }
1600}
1601
1602/// Does the equivalent of
1603/// ```ignore (illustrative)
1604/// let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1605/// folder.tcx().intern_*(&v)
1606/// ```
1607pub fn fold_list<'tcx, F, L, T>(
1608    list: L,
1609    folder: &mut F,
1610    intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1611) -> L
1612where
1613    F: TypeFolder<TyCtxt<'tcx>>,
1614    L: AsRef<[T]>,
1615    T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1616{
1617    let slice = list.as_ref();
1618    let mut iter = slice.iter().copied();
1619    // Look for the first element that changed
1620    match iter.by_ref().enumerate().find_map(|(i, t)| {
1621        let new_t = t.fold_with(folder);
1622        if new_t != t { Some((i, new_t)) } else { None }
1623    }) {
1624        Some((i, new_t)) => {
1625            // An element changed, prepare to intern the resulting list
1626            let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1627            new_list.extend_from_slice(&slice[..i]);
1628            new_list.push(new_t);
1629            for t in iter {
1630                new_list.push(t.fold_with(folder))
1631            }
1632            intern(folder.cx(), &new_list)
1633        }
1634        None => list,
1635    }
1636}
1637
1638/// Does the equivalent of
1639/// ```ignore (illustrative)
1640/// let v = self.iter().map(|p| p.try_fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1641/// folder.tcx().intern_*(&v)
1642/// ```
1643pub fn try_fold_list<'tcx, F, L, T>(
1644    list: L,
1645    folder: &mut F,
1646    intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1647) -> Result<L, F::Error>
1648where
1649    F: FallibleTypeFolder<TyCtxt<'tcx>>,
1650    L: AsRef<[T]>,
1651    T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1652{
1653    let slice = list.as_ref();
1654    let mut iter = slice.iter().copied();
1655    // Look for the first element that changed
1656    match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1657        Ok(new_t) if new_t == t => None,
1658        new_t => Some((i, new_t)),
1659    }) {
1660        Some((i, Ok(new_t))) => {
1661            // An element changed, prepare to intern the resulting list
1662            let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1663            new_list.extend_from_slice(&slice[..i]);
1664            new_list.push(new_t);
1665            for t in iter {
1666                new_list.push(t.try_fold_with(folder)?)
1667            }
1668            Ok(intern(folder.cx(), &new_list))
1669        }
1670        Some((_, Err(err))) => {
1671            return Err(err);
1672        }
1673        None => Ok(list),
1674    }
1675}
1676
1677#[derive(#[automatically_derived]
impl ::core::marker::Copy for AlwaysRequiresDrop { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AlwaysRequiresDrop { }
#[automatically_derived]
impl ::core::clone::Clone for AlwaysRequiresDrop {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AlwaysRequiresDrop {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "AlwaysRequiresDrop")
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            AlwaysRequiresDrop {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self { AlwaysRequiresDrop => {} }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for AlwaysRequiresDrop {
            fn encode(&self, __encoder: &mut __E) {}
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for AlwaysRequiresDrop {
            fn decode(__decoder: &mut __D) -> Self { AlwaysRequiresDrop }
        }
    };TyDecodable)]
1678pub struct AlwaysRequiresDrop;
1679
1680/// Reveals all opaque types in the given value, replacing them
1681/// with their underlying types.
1682pub fn reveal_opaque_types_in_bounds<'tcx>(
1683    tcx: TyCtxt<'tcx>,
1684    val: ty::Clauses<'tcx>,
1685) -> ty::Clauses<'tcx> {
1686    if !!tcx.next_trait_solver_globally() {
    ::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1687    let mut visitor = OpaqueTypeExpander {
1688        seen_opaque_tys: FxHashSet::default(),
1689        expanded_cache: FxHashMap::default(),
1690        primary_def_id: None,
1691        found_recursion: false,
1692        found_any_recursion: false,
1693        check_recursion: false,
1694        tcx,
1695    };
1696    val.fold_with(&mut visitor)
1697}
1698
1699/// Determines whether an item is directly annotated with `doc(hidden)`.
1700fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1701    {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Doc(doc)) if
                            doc.hidden.is_some() => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, Doc(doc) if doc.hidden.is_some())
1702}
1703
1704/// Determines whether an item is annotated with `doc(notable_trait)`.
1705pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1706    {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Doc(doc)) if
                            doc.notable_trait.is_some() => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, Doc(doc) if doc.notable_trait.is_some())
1707}
1708
1709/// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute).
1710///
1711/// We double check the feature gate here because whether a function may be defined as an intrinsic causes
1712/// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may
1713/// cause an ICE that we otherwise may want to prevent.
1714pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1715    if tcx.features().intrinsics() && {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcIntrinsic) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcIntrinsic) {
1716        let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1717            hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1718                !has_body
1719            }
1720            _ => true,
1721        };
1722        Some(ty::IntrinsicDef {
1723            name: tcx.item_name(def_id),
1724            must_be_overridden,
1725            const_stable_indirect: {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcIntrinsicConstStableIndirect)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcIntrinsicConstStableIndirect),
1726        })
1727    } else {
1728        None
1729    }
1730}
1731
1732pub fn provide(providers: &mut Providers) {
1733    *providers = Providers {
1734        reveal_opaque_types_in_bounds,
1735        is_doc_hidden,
1736        is_doc_notable_trait,
1737        intrinsic_raw,
1738        ..*providers
1739    }
1740}