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