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