rustc_middle/ty/
util.rs

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