rustc_middle/ty/
util.rs

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