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