1 //! Miscellaneous type-system utilities that are too small to deserve their own modules.
3 use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
4 use crate::ty::layout::IntegerExt;
5 use crate::ty::query::TyCtxtAt;
6 use crate::ty::subst::{GenericArgKind, Subst, SubstsRef};
8 self, DefIdTree, FallibleTypeFolder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
11 use rustc_apfloat::Float as _;
13 use rustc_attr::{self as attr, SignedInt, UnsignedInt};
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
16 use rustc_errors::ErrorGuaranteed;
18 use rustc_hir::def::{CtorOf, DefKind, Res};
19 use rustc_hir::def_id::DefId;
20 use rustc_index::bit_set::GrowableBitSet;
21 use rustc_macros::HashStable;
22 use rustc_span::{sym, DUMMY_SP};
23 use rustc_target::abi::{Integer, Size, TargetDataLayout};
24 use rustc_target::spec::abi::Abi;
25 use smallvec::SmallVec;
28 #[derive(Copy, Clone, Debug)]
29 pub struct Discr<'tcx> {
30 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
35 /// Used as an input to [`TyCtxt::uses_unique_generic_params`].
36 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
37 pub enum IgnoreRegions {
42 #[derive(Copy, Clone, Debug)]
43 pub enum NotUniqueParam<'tcx> {
44 DuplicateParam(ty::GenericArg<'tcx>),
45 NotParam(ty::GenericArg<'tcx>),
48 impl<'tcx> fmt::Display for Discr<'tcx> {
49 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
50 match *self.ty.kind() {
52 let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
54 // sign extend the raw representation to be an i128
55 let x = size.sign_extend(x) as i128;
58 _ => write!(fmt, "{}", self.val),
63 fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
64 let (int, signed) = match *ty.kind() {
65 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity), true),
66 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false),
67 _ => bug!("non integer discriminant"),
72 impl<'tcx> Discr<'tcx> {
73 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
74 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
75 self.checked_add(tcx, 1).0
77 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
78 let (size, signed) = int_size_and_signed(tcx, self.ty);
79 let (val, oflo) = if signed {
80 let min = size.signed_int_min();
81 let max = size.signed_int_max();
82 let val = size.sign_extend(self.val) as i128;
83 assert!(n < (i128::MAX as u128));
85 let oflo = val > max - n;
86 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
87 // zero the upper bits
88 let val = val as u128;
89 let val = size.truncate(val);
92 let max = size.unsigned_int_max();
94 let oflo = val > max - n;
95 let val = if oflo { n - (max - val) - 1 } else { val + n };
98 (Self { val, ty: self.ty }, oflo)
102 pub trait IntTypeExt {
103 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
104 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
105 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
108 impl IntTypeExt for attr::IntType {
109 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
111 SignedInt(ast::IntTy::I8) => tcx.types.i8,
112 SignedInt(ast::IntTy::I16) => tcx.types.i16,
113 SignedInt(ast::IntTy::I32) => tcx.types.i32,
114 SignedInt(ast::IntTy::I64) => tcx.types.i64,
115 SignedInt(ast::IntTy::I128) => tcx.types.i128,
116 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
117 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
118 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
119 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
120 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
121 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
122 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
126 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
127 Discr { val: 0, ty: self.to_ty(tcx) }
130 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
131 if let Some(val) = val {
132 assert_eq!(self.to_ty(tcx), val.ty);
133 let (new, oflo) = val.checked_add(tcx, 1);
134 if oflo { None } else { Some(new) }
136 Some(self.initial_discriminant(tcx))
141 impl<'tcx> TyCtxt<'tcx> {
142 /// Creates a hash of the type `Ty` which will be the same no matter what crate
143 /// context it's calculated within. This is used by the `type_id` intrinsic.
144 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
145 // We want the type_id be independent of the types free regions, so we
146 // erase them. The erase_regions() call will also anonymize bound
147 // regions, which is desirable too.
148 let ty = self.erase_regions(ty);
150 self.with_stable_hashing_context(|mut hcx| {
151 let mut hasher = StableHasher::new();
152 hcx.while_hashing_spans(false, |hcx| ty.hash_stable(hcx, &mut hasher));
157 pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
159 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
160 Some(self.parent(self.parent(def_id)))
162 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
163 Some(self.parent(def_id))
165 // Other `DefKind`s don't have generics and would ICE when calling
175 | DefKind::TraitAlias
179 | DefKind::AssocConst
188 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
189 if let ty::Adt(def, substs) = *ty.kind() {
190 for field in def.all_fields() {
191 let field_ty = field.ty(self, substs);
192 if let ty::Error(_) = field_ty.kind() {
200 /// Attempts to returns the deeply last field of nested structures, but
201 /// does not apply any normalization in its search. Returns the same type
202 /// if input `ty` is not a structure at all.
203 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
205 tcx.struct_tail_with_normalize(ty, |ty| ty, || {})
208 /// Returns the deeply last field of nested structures, or the same type if
209 /// not a structure at all. Corresponds to the only possible unsized field,
210 /// and its type can be used to determine unsizing strategy.
212 /// Should only be called if `ty` has no inference variables and does not
213 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
214 /// normalization attempt may cause compiler bugs.
215 pub fn struct_tail_erasing_lifetimes(
218 param_env: ty::ParamEnv<'tcx>,
221 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty), || {})
224 /// Returns the deeply last field of nested structures, or the same type if
225 /// not a structure at all. Corresponds to the only possible unsized field,
226 /// and its type can be used to determine unsizing strategy.
228 /// This is parameterized over the normalization strategy (i.e. how to
229 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
230 /// function to indicate no normalization should take place.
232 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
234 pub fn struct_tail_with_normalize(
237 mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
238 // This is currently used to allow us to walk a ValTree
239 // in lockstep with the type in order to get the ValTree branch that
240 // corresponds to an unsized field.
241 mut f: impl FnMut() -> (),
243 let recursion_limit = self.recursion_limit();
244 for iteration in 0.. {
245 if !recursion_limit.value_within_limit(iteration) {
246 return self.ty_error_with_message(
248 &format!("reached the recursion limit finding the struct tail for {}", ty),
252 ty::Adt(def, substs) => {
253 if !def.is_struct() {
256 match def.non_enum_variant().fields.last() {
259 ty = field.ty(self, substs);
265 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
270 ty::Tuple(_) => break,
272 ty::Projection(_) | ty::Opaque(..) => {
273 let normalized = normalize(ty);
274 if ty == normalized {
289 /// Same as applying `struct_tail` on `source` and `target`, but only
290 /// keeps going as long as the two types are instances of the same
291 /// structure definitions.
292 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
293 /// whereas struct_tail produces `T`, and `Trait`, respectively.
295 /// Should only be called if the types have no inference variables and do
296 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
297 /// normalization attempt may cause compiler bugs.
298 pub fn struct_lockstep_tails_erasing_lifetimes(
302 param_env: ty::ParamEnv<'tcx>,
303 ) -> (Ty<'tcx>, Ty<'tcx>) {
305 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
306 tcx.normalize_erasing_regions(param_env, ty)
310 /// Same as applying `struct_tail` on `source` and `target`, but only
311 /// keeps going as long as the two types are instances of the same
312 /// structure definitions.
313 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
314 /// whereas struct_tail produces `T`, and `Trait`, respectively.
316 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
318 pub fn struct_lockstep_tails_with_normalize(
322 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
323 ) -> (Ty<'tcx>, Ty<'tcx>) {
324 let (mut a, mut b) = (source, target);
326 match (&a.kind(), &b.kind()) {
327 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs))
328 if a_def == b_def && a_def.is_struct() =>
330 if let Some(f) = a_def.non_enum_variant().fields.last() {
331 a = f.ty(self, a_substs);
332 b = f.ty(self, b_substs);
337 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
338 if let Some(&a_last) = a_tys.last() {
340 b = *b_tys.last().unwrap();
345 (ty::Projection(_) | ty::Opaque(..), _)
346 | (_, ty::Projection(_) | ty::Opaque(..)) => {
347 // If either side is a projection, attempt to
348 // progress via normalization. (Should be safe to
349 // apply to both sides as normalization is
351 let a_norm = normalize(a);
352 let b_norm = normalize(b);
353 if a == a_norm && b == b_norm {
367 /// Calculate the destructor of a given type.
368 pub fn calculate_dtor(
371 validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
372 ) -> Option<ty::Destructor> {
373 let drop_trait = self.lang_items().drop_trait()?;
374 self.ensure().coherent_trait(drop_trait);
376 let ty = self.type_of(adt_did);
377 let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
378 if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
379 if validate(self, impl_did).is_ok() {
380 return Some((*item_id, self.constness(impl_did)));
386 Some(ty::Destructor { did, constness })
389 /// Returns the set of types that are required to be alive in
390 /// order to run the destructor of `def` (see RFCs 769 and
393 /// Note that this returns only the constraints for the
394 /// destructor of `def` itself. For the destructors of the
395 /// contents, you need `adt_dtorck_constraint`.
396 pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::subst::GenericArg<'tcx>> {
397 let dtor = match def.destructor(self) {
399 debug!("destructor_constraints({:?}) - no dtor", def.did());
402 Some(dtor) => dtor.did,
405 let impl_def_id = self.parent(dtor);
406 let impl_generics = self.generics_of(impl_def_id);
408 // We have a destructor - all the parameters that are not
409 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
412 // We need to return the list of parameters from the ADTs
413 // generics/substs that correspond to impure parameters on the
414 // impl's generics. This is a bit ugly, but conceptually simple:
416 // Suppose our ADT looks like the following
418 // struct S<X, Y, Z>(X, Y, Z);
422 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
424 // We want to return the parameters (X, Y). For that, we match
425 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
426 // <P1, P2, P0>, and then look up which of the impl substs refer to
427 // parameters marked as pure.
429 let impl_substs = match *self.type_of(impl_def_id).kind() {
430 ty::Adt(def_, substs) if def_ == def => substs,
434 let item_substs = match *self.type_of(def.did()).kind() {
435 ty::Adt(def_, substs) if def_ == def => substs,
439 let result = iter::zip(item_substs, impl_substs)
442 GenericArgKind::Lifetime(region) => match region.kind() {
443 ty::ReEarlyBound(ref ebr) => {
444 !impl_generics.region_param(ebr, self).pure_wrt_drop
446 // Error: not a region param
449 GenericArgKind::Type(ty) => match ty.kind() {
450 ty::Param(ref pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
451 // Error: not a type param
454 GenericArgKind::Const(ct) => match ct.kind() {
455 ty::ConstKind::Param(ref pc) => {
456 !impl_generics.const_param(pc, self).pure_wrt_drop
458 // Error: not a const param
463 .map(|(item_param, _)| item_param)
465 debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
469 /// Checks whether each generic argument is simply a unique generic parameter.
470 pub fn uses_unique_generic_params(
472 substs: SubstsRef<'tcx>,
473 ignore_regions: IgnoreRegions,
474 ) -> Result<(), NotUniqueParam<'tcx>> {
475 let mut seen = GrowableBitSet::default();
478 GenericArgKind::Lifetime(lt) => {
479 if ignore_regions == IgnoreRegions::No {
480 let ty::ReEarlyBound(p) = lt.kind() else {
481 return Err(NotUniqueParam::NotParam(lt.into()))
483 if !seen.insert(p.index) {
484 return Err(NotUniqueParam::DuplicateParam(lt.into()));
488 GenericArgKind::Type(t) => match t.kind() {
490 if !seen.insert(p.index) {
491 return Err(NotUniqueParam::DuplicateParam(t.into()));
494 _ => return Err(NotUniqueParam::NotParam(t.into())),
496 GenericArgKind::Const(c) => match c.kind() {
497 ty::ConstKind::Param(p) => {
498 if !seen.insert(p.index) {
499 return Err(NotUniqueParam::DuplicateParam(c.into()));
502 _ => return Err(NotUniqueParam::NotParam(c.into())),
510 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
511 /// that closures have a `DefId`, but the closure *expression* also
512 /// has a `HirId` that is located within the context where the
513 /// closure appears (and, sadly, a corresponding `NodeId`, since
514 /// those are not yet phased out). The parent of the closure's
515 /// `DefId` will also be the context where it appears.
516 pub fn is_closure(self, def_id: DefId) -> bool {
517 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
520 /// Returns `true` if `def_id` refers to a definition that does not have its own
521 /// type-checking context, i.e. closure, generator or inline const.
522 pub fn is_typeck_child(self, def_id: DefId) -> bool {
524 self.def_kind(def_id),
525 DefKind::Closure | DefKind::Generator | DefKind::InlineConst
529 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
530 pub fn is_trait(self, def_id: DefId) -> bool {
531 self.def_kind(def_id) == DefKind::Trait
534 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
535 /// and `false` otherwise.
536 pub fn is_trait_alias(self, def_id: DefId) -> bool {
537 self.def_kind(def_id) == DefKind::TraitAlias
540 /// Returns `true` if this `DefId` refers to the implicit constructor for
541 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
542 pub fn is_constructor(self, def_id: DefId) -> bool {
543 matches!(self.def_kind(def_id), DefKind::Ctor(..))
546 /// Given the `DefId`, returns the `DefId` of the innermost item that
547 /// has its own type-checking context or "inference environment".
549 /// For example, a closure has its own `DefId`, but it is type-checked
550 /// with the containing item. Similarly, an inline const block has its
551 /// own `DefId` but it is type-checked together with the containing item.
553 /// Therefore, when we fetch the
554 /// `typeck` the closure, for example, we really wind up
555 /// fetching the `typeck` the enclosing fn item.
556 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
557 let mut def_id = def_id;
558 while self.is_typeck_child(def_id) {
559 def_id = self.parent(def_id);
564 /// Given the `DefId` and substs a closure, creates the type of
565 /// `self` argument that the closure expects. For example, for a
566 /// `Fn` closure, this would return a reference type `&T` where
567 /// `T = closure_ty`.
569 /// Returns `None` if this closure's kind has not yet been inferred.
570 /// This should only be possible during type checking.
572 /// Note that the return value is a late-bound region and hence
573 /// wrapped in a binder.
574 pub fn closure_env_ty(
576 closure_def_id: DefId,
577 closure_substs: SubstsRef<'tcx>,
578 env_region: ty::RegionKind<'tcx>,
579 ) -> Option<Ty<'tcx>> {
580 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
581 let closure_kind_ty = closure_substs.as_closure().kind_ty();
582 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
583 let env_ty = match closure_kind {
584 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
585 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
586 ty::ClosureKind::FnOnce => closure_ty,
591 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
593 pub fn is_static(self, def_id: DefId) -> bool {
594 matches!(self.def_kind(def_id), DefKind::Static(_))
598 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
599 if let DefKind::Static(mt) = self.def_kind(def_id) { Some(mt) } else { None }
602 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
603 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
604 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
607 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
609 pub fn is_mutable_static(self, def_id: DefId) -> bool {
610 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
613 /// Get the type of the pointer to the static that we use in MIR.
614 pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
615 // Make sure that any constants in the static's type are evaluated.
616 let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
618 // Make sure that accesses to unsafe statics end up using raw pointers.
619 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
620 if self.is_mutable_static(def_id) {
621 self.mk_mut_ptr(static_ty)
622 } else if self.is_foreign_item(def_id) {
623 self.mk_imm_ptr(static_ty)
625 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
629 /// Expands the given impl trait type, stopping if the type is recursive.
630 #[instrument(skip(self), level = "debug")]
631 pub fn try_expand_impl_trait_type(
634 substs: SubstsRef<'tcx>,
635 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
636 let mut visitor = OpaqueTypeExpander {
637 seen_opaque_tys: FxHashSet::default(),
638 expanded_cache: FxHashMap::default(),
639 primary_def_id: Some(def_id),
640 found_recursion: false,
641 found_any_recursion: false,
642 check_recursion: true,
646 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
647 trace!(?expanded_type);
648 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
651 pub fn bound_type_of(self, def_id: DefId) -> ty::EarlyBinder<Ty<'tcx>> {
652 ty::EarlyBinder(self.type_of(def_id))
655 pub fn bound_fn_sig(self, def_id: DefId) -> ty::EarlyBinder<ty::PolyFnSig<'tcx>> {
656 ty::EarlyBinder(self.fn_sig(def_id))
659 pub fn bound_impl_trait_ref(
662 ) -> Option<ty::EarlyBinder<ty::TraitRef<'tcx>>> {
663 self.impl_trait_ref(def_id).map(|i| ty::EarlyBinder(i))
666 pub fn bound_explicit_item_bounds(
669 ) -> ty::EarlyBinder<&'tcx [(ty::Predicate<'tcx>, rustc_span::Span)]> {
670 ty::EarlyBinder(self.explicit_item_bounds(def_id))
673 pub fn bound_item_bounds(
676 ) -> ty::EarlyBinder<&'tcx ty::List<ty::Predicate<'tcx>>> {
677 ty::EarlyBinder(self.item_bounds(def_id))
680 pub fn bound_const_param_default(self, def_id: DefId) -> ty::EarlyBinder<ty::Const<'tcx>> {
681 ty::EarlyBinder(self.const_param_default(def_id))
684 pub fn bound_predicates_of(
687 ) -> ty::EarlyBinder<ty::generics::GenericPredicates<'tcx>> {
688 ty::EarlyBinder(self.predicates_of(def_id))
691 pub fn bound_explicit_predicates_of(
694 ) -> ty::EarlyBinder<ty::generics::GenericPredicates<'tcx>> {
695 ty::EarlyBinder(self.explicit_predicates_of(def_id))
698 pub fn bound_impl_subject(self, def_id: DefId) -> ty::EarlyBinder<ty::ImplSubject<'tcx>> {
699 ty::EarlyBinder(self.impl_subject(def_id))
703 struct OpaqueTypeExpander<'tcx> {
704 // Contains the DefIds of the opaque types that are currently being
705 // expanded. When we expand an opaque type we insert the DefId of
706 // that type, and when we finish expanding that type we remove the
708 seen_opaque_tys: FxHashSet<DefId>,
709 // Cache of all expansions we've seen so far. This is a critical
710 // optimization for some large types produced by async fn trees.
711 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
712 primary_def_id: Option<DefId>,
713 found_recursion: bool,
714 found_any_recursion: bool,
715 /// Whether or not to check for recursive opaque types.
716 /// This is `true` when we're explicitly checking for opaque type
717 /// recursion, and 'false' otherwise to avoid unnecessary work.
718 check_recursion: bool,
722 impl<'tcx> OpaqueTypeExpander<'tcx> {
723 fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
724 if self.found_any_recursion {
727 let substs = substs.fold_with(self);
728 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
729 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
730 Some(expanded_ty) => *expanded_ty,
732 let generic_ty = self.tcx.bound_type_of(def_id);
733 let concrete_ty = generic_ty.subst(self.tcx, substs);
734 let expanded_ty = self.fold_ty(concrete_ty);
735 self.expanded_cache.insert((def_id, substs), expanded_ty);
739 if self.check_recursion {
740 self.seen_opaque_tys.remove(&def_id);
744 // If another opaque type that we contain is recursive, then it
745 // will report the error, so we don't have to.
746 self.found_any_recursion = true;
747 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
753 impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
754 fn tcx(&self) -> TyCtxt<'tcx> {
758 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
759 if let ty::Opaque(def_id, substs) = *t.kind() {
760 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
761 } else if t.has_opaque_types() {
762 t.super_fold_with(self)
769 impl<'tcx> Ty<'tcx> {
770 /// Returns the maximum value for the given numeric type (including `char`s)
771 /// or returns `None` if the type is not numeric.
772 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
773 let val = match self.kind() {
774 ty::Int(_) | ty::Uint(_) => {
775 let (size, signed) = int_size_and_signed(tcx, self);
777 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
780 ty::Char => Some(std::char::MAX as u128),
781 ty::Float(fty) => Some(match fty {
782 ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
783 ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
788 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
791 /// Returns the minimum value for the given numeric type (including `char`s)
792 /// or returns `None` if the type is not numeric.
793 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<ty::Const<'tcx>> {
794 let val = match self.kind() {
795 ty::Int(_) | ty::Uint(_) => {
796 let (size, signed) = int_size_and_signed(tcx, self);
797 let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
801 ty::Float(fty) => Some(match fty {
802 ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
803 ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
808 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
811 /// Checks whether values of this type `T` are *moved* or *copied*
812 /// when referenced -- this amounts to a check for whether `T:
813 /// Copy`, but note that we **don't** consider lifetimes when
814 /// doing this check. This means that we may generate MIR which
815 /// does copies even when the type actually doesn't satisfy the
816 /// full requirements for the `Copy` trait (cc #29149) -- this
817 /// winds up being reported as an error during NLL borrow check.
818 pub fn is_copy_modulo_regions(
820 tcx_at: TyCtxtAt<'tcx>,
821 param_env: ty::ParamEnv<'tcx>,
823 self.is_trivially_pure_clone_copy() || tcx_at.is_copy_raw(param_env.and(self))
826 /// Checks whether values of this type `T` have a size known at
827 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
828 /// for the purposes of this check, so it can be an
829 /// over-approximation in generic contexts, where one can have
830 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
831 /// actually carry lifetime requirements.
832 pub fn is_sized(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
833 self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
836 /// Checks whether values of this type `T` implement the `Freeze`
837 /// trait -- frozen types are those that do not contain an
838 /// `UnsafeCell` anywhere. This is a language concept used to
839 /// distinguish "true immutability", which is relevant to
840 /// optimization as well as the rules around static values. Note
841 /// that the `Freeze` trait is not exposed to end users and is
842 /// effectively an implementation detail.
843 pub fn is_freeze(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
844 self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
847 /// Fast path helper for testing if a type is `Freeze`.
849 /// Returning true means the type is known to be `Freeze`. Returning
850 /// `false` means nothing -- could be `Freeze`, might not be.
851 fn is_trivially_freeze(self) -> bool {
864 | ty::FnPtr(_) => true,
865 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
866 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
873 | ty::GeneratorWitness(_)
878 | ty::Projection(_) => false,
882 /// Checks whether values of this type `T` implement the `Unpin` trait.
883 pub fn is_unpin(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
884 self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self))
887 /// Fast path helper for testing if a type is `Unpin`.
889 /// Returning true means the type is known to be `Unpin`. Returning
890 /// `false` means nothing -- could be `Unpin`, might not be.
891 fn is_trivially_unpin(self) -> bool {
904 | ty::FnPtr(_) => true,
905 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
906 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(),
913 | ty::GeneratorWitness(_)
918 | ty::Projection(_) => false,
922 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
923 /// non-copy and *might* have a destructor attached; if it returns
924 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
926 /// (Note that this implies that if `ty` has a destructor attached,
927 /// then `needs_drop` will definitely return `true` for `ty`.)
929 /// Note that this method is used to check eligible types in unions.
931 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
932 // Avoid querying in simple cases.
933 match needs_drop_components(self, &tcx.data_layout) {
934 Err(AlwaysRequiresDrop) => true,
936 let query_ty = match *components {
938 // If we've got a single component, call the query with that
939 // to increase the chance that we hit the query cache.
940 [component_ty] => component_ty,
944 // This doesn't depend on regions, so try to minimize distinct
946 // If normalization fails, we just use `query_ty`.
948 tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty);
950 tcx.needs_drop_raw(param_env.and(query_ty))
955 /// Checks if `ty` has has a significant drop.
957 /// Note that this method can return false even if `ty` has a destructor
958 /// attached; even if that is the case then the adt has been marked with
959 /// the attribute `rustc_insignificant_dtor`.
961 /// Note that this method is used to check for change in drop order for
962 /// 2229 drop reorder migration analysis.
964 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
965 // Avoid querying in simple cases.
966 match needs_drop_components(self, &tcx.data_layout) {
967 Err(AlwaysRequiresDrop) => true,
969 let query_ty = match *components {
971 // If we've got a single component, call the query with that
972 // to increase the chance that we hit the query cache.
973 [component_ty] => component_ty,
977 // FIXME(#86868): We should be canonicalizing, or else moving this to a method of inference
978 // context, or *something* like that, but for now just avoid passing inference
979 // variables to queries that can't cope with them. Instead, conservatively
980 // return "true" (may change drop order).
981 if query_ty.needs_infer() {
985 // This doesn't depend on regions, so try to minimize distinct
987 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
988 tcx.has_significant_drop_raw(param_env.and(erased))
993 /// Returns `true` if equality for this type is both reflexive and structural.
995 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
997 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
998 /// types, equality for the type as a whole is structural when it is the same as equality
999 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
1000 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
1003 /// This function is "shallow" because it may return `true` for a composite type whose fields
1004 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
1005 /// because equality for arrays is determined by the equality of each array element. If you
1006 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
1007 /// down, you will need to use a type visitor.
1009 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1011 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
1012 ty::Adt(..) => tcx.has_structural_eq_impls(self),
1014 // Primitive types that satisfy `Eq`.
1015 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
1017 // Composite types that satisfy `Eq` when all of their fields do.
1019 // Because this function is "shallow", we return `true` for these composites regardless
1020 // of the type(s) contained within.
1021 ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
1023 // Raw pointers use bitwise comparison.
1024 ty::RawPtr(_) | ty::FnPtr(_) => true,
1026 // Floating point numbers are not `Eq`.
1027 ty::Float(_) => false,
1029 // Conservatively return `false` for all others...
1031 // Anonymous function types
1032 ty::FnDef(..) | ty::Closure(..) | ty::Dynamic(..) | ty::Generator(..) => false,
1034 // Generic or inferred types
1036 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
1037 // called for known, fully-monomorphized types.
1042 | ty::Placeholder(_)
1043 | ty::Infer(_) => false,
1045 ty::Foreign(_) | ty::GeneratorWitness(..) | ty::Error(_) => false,
1049 /// Peel off all reference types in this type until there are none left.
1051 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1056 /// - `&'a mut u8` -> `u8`
1057 /// - `&'a &'b u8` -> `u8`
1058 /// - `&'a *const &'b u8 -> *const &'b u8`
1059 pub fn peel_refs(self) -> Ty<'tcx> {
1061 while let ty::Ref(_, inner_ty, _) = ty.kind() {
1068 pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
1069 self.0.outer_exclusive_binder
1073 pub enum ExplicitSelf<'tcx> {
1075 ByReference(ty::Region<'tcx>, hir::Mutability),
1076 ByRawPointer(hir::Mutability),
1081 impl<'tcx> ExplicitSelf<'tcx> {
1082 /// Categorizes an explicit self declaration like `self: SomeType`
1083 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1085 /// This is mainly used to require the arbitrary_self_types feature
1086 /// in the case of `Other`, to improve error messages in the common cases,
1087 /// and to make `Other` non-object-safe.
1091 /// ```ignore (illustrative)
1092 /// impl<'a> Foo for &'a T {
1093 /// // Legal declarations:
1094 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1095 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1096 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1097 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1099 /// // Invalid cases will be caught by `check_method_receiver`:
1100 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1101 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1102 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1106 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
1108 P: Fn(Ty<'tcx>) -> bool,
1110 use self::ExplicitSelf::*;
1112 match *self_arg_ty.kind() {
1113 _ if is_self_ty(self_arg_ty) => ByValue,
1114 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
1115 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
1116 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1122 /// Returns a list of types such that the given type needs drop if and only if
1123 /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1124 /// this type always needs drop.
1125 pub fn needs_drop_components<'tcx>(
1127 target_layout: &TargetDataLayout,
1128 ) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1130 ty::Infer(ty::FreshIntTy(_))
1131 | ty::Infer(ty::FreshFloatTy(_))
1140 | ty::GeneratorWitness(..)
1143 | ty::Str => Ok(SmallVec::new()),
1145 // Foreign types can never have destructors.
1146 ty::Foreign(..) => Ok(SmallVec::new()),
1148 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
1150 ty::Slice(ty) => needs_drop_components(*ty, target_layout),
1151 ty::Array(elem_ty, size) => {
1152 match needs_drop_components(*elem_ty, target_layout) {
1153 Ok(v) if v.is_empty() => Ok(v),
1154 res => match size.kind().try_to_bits(target_layout.pointer_size) {
1155 // Arrays of size zero don't need drop, even if their element
1157 Some(0) => Ok(SmallVec::new()),
1159 // We don't know which of the cases above we are in, so
1160 // return the whole type and let the caller decide what to
1162 None => Ok(smallvec![ty]),
1166 // If any field needs drop, then the whole tuple does.
1167 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1168 acc.extend(needs_drop_components(elem, target_layout)?);
1172 // These require checking for `Copy` bounds or `Adt` destructors.
1174 | ty::Projection(..)
1177 | ty::Placeholder(..)
1181 | ty::Generator(..) => Ok(smallvec![ty]),
1185 pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool {
1192 | ty::Infer(ty::IntVar(_))
1193 | ty::Infer(ty::FloatVar(_))
1200 | ty::Foreign(_) => true,
1207 | ty::Placeholder(_)
1209 | ty::Infer(_) => false,
1211 // Not trivial because they have components, and instead of looking inside,
1212 // we'll just perform trait selection.
1213 ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false,
1215 ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty),
1217 ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty)),
1221 // Does the equivalent of
1223 // let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1224 // folder.tcx().intern_*(&v)
1226 pub fn fold_list<'tcx, F, T>(
1227 list: &'tcx ty::List<T>,
1229 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
1230 ) -> Result<&'tcx ty::List<T>, F::Error>
1232 F: FallibleTypeFolder<'tcx>,
1233 T: TypeFoldable<'tcx> + PartialEq + Copy,
1235 let mut iter = list.iter();
1236 // Look for the first element that changed
1237 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1238 Ok(new_t) if new_t == t => None,
1239 new_t => Some((i, new_t)),
1241 Some((i, Ok(new_t))) => {
1242 // An element changed, prepare to intern the resulting list
1243 let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1244 new_list.extend_from_slice(&list[..i]);
1245 new_list.push(new_t);
1247 new_list.push(t.try_fold_with(folder)?)
1249 Ok(intern(folder.tcx(), &new_list))
1251 Some((_, Err(err))) => {
1258 #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1259 pub struct AlwaysRequiresDrop;
1261 /// Normalizes all opaque types in the given value, replacing them
1262 /// with their underlying types.
1263 pub fn normalize_opaque_types<'tcx>(
1265 val: &'tcx ty::List<ty::Predicate<'tcx>>,
1266 ) -> &'tcx ty::List<ty::Predicate<'tcx>> {
1267 let mut visitor = OpaqueTypeExpander {
1268 seen_opaque_tys: FxHashSet::default(),
1269 expanded_cache: FxHashMap::default(),
1270 primary_def_id: None,
1271 found_recursion: false,
1272 found_any_recursion: false,
1273 check_recursion: false,
1276 val.fold_with(&mut visitor)
1279 /// Determines whether an item is annotated with `doc(hidden)`.
1280 pub fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1281 tcx.get_attrs(def_id, sym::doc)
1282 .filter_map(|attr| attr.meta_item_list())
1283 .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1286 /// Determines whether an item is an intrinsic by Abi.
1287 pub fn is_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1288 matches!(tcx.fn_sig(def_id).abi(), Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1291 pub fn provide(providers: &mut ty::query::Providers) {
1293 ty::query::Providers { normalize_opaque_types, is_doc_hidden, is_intrinsic, ..*providers }