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