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