1 //! Miscellaneous type-system utilities that are too small to deserve their own modules.
3 use crate::ich::NodeIdHashingMode;
4 use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5 use crate::mir::interpret::{sign_extend, truncate};
6 use crate::ty::layout::IntegerExt;
7 use crate::ty::query::TyCtxtAt;
8 use crate::ty::subst::{GenericArgKind, InternalSubsts, Subst, SubstsRef};
9 use crate::ty::TyKind::*;
10 use crate::ty::{self, DefIdTree, GenericParamDefKind, Ty, TyCtxt, TypeFoldable};
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::ErrorReported;
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_macros::HashStable;
22 use rustc_target::abi::{Integer, Size, TargetDataLayout};
23 use smallvec::SmallVec;
26 #[derive(Copy, Clone, Debug)]
27 pub struct Discr<'tcx> {
28 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
33 impl<'tcx> fmt::Display for Discr<'tcx> {
34 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
37 let size = ty::tls::with(|tcx| Integer::from_attr(&tcx, SignedInt(ity)).size());
39 // sign extend the raw representation to be an i128
40 let x = sign_extend(x, size) as i128;
43 _ => write!(fmt, "{}", self.val),
48 fn signed_min(size: Size) -> i128 {
49 sign_extend(1_u128 << (size.bits() - 1), size) as i128
52 fn signed_max(size: Size) -> i128 {
53 i128::MAX >> (128 - size.bits())
56 fn unsigned_max(size: Size) -> u128 {
57 u128::MAX >> (128 - size.bits())
60 fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
61 let (int, signed) = match ty.kind {
62 Int(ity) => (Integer::from_attr(&tcx, SignedInt(ity)), true),
63 Uint(uty) => (Integer::from_attr(&tcx, UnsignedInt(uty)), false),
64 _ => bug!("non integer discriminant"),
69 impl<'tcx> Discr<'tcx> {
70 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
71 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
72 self.checked_add(tcx, 1).0
74 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
75 let (size, signed) = int_size_and_signed(tcx, self.ty);
76 let (val, oflo) = if signed {
77 let min = signed_min(size);
78 let max = signed_max(size);
79 let val = sign_extend(self.val, size) as i128;
80 assert!(n < (i128::MAX as u128));
82 let oflo = val > max - n;
83 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
84 // zero the upper bits
85 let val = val as u128;
86 let val = truncate(val, size);
89 let max = unsigned_max(size);
91 let oflo = val > max - n;
92 let val = if oflo { n - (max - val) - 1 } else { val + n };
95 (Self { val, ty: self.ty }, oflo)
99 pub trait IntTypeExt {
100 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
101 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
102 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
105 impl IntTypeExt for attr::IntType {
106 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
108 SignedInt(ast::IntTy::I8) => tcx.types.i8,
109 SignedInt(ast::IntTy::I16) => tcx.types.i16,
110 SignedInt(ast::IntTy::I32) => tcx.types.i32,
111 SignedInt(ast::IntTy::I64) => tcx.types.i64,
112 SignedInt(ast::IntTy::I128) => tcx.types.i128,
113 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
114 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
115 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
116 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
117 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
118 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
119 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
123 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
124 Discr { val: 0, ty: self.to_ty(tcx) }
127 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
128 if let Some(val) = val {
129 assert_eq!(self.to_ty(tcx), val.ty);
130 let (new, oflo) = val.checked_add(tcx, 1);
131 if oflo { None } else { Some(new) }
133 Some(self.initial_discriminant(tcx))
138 /// Describes whether a type is representable. For types that are not
139 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
140 /// distinguish between types that are recursive with themselves and types that
141 /// contain a different recursive type. These cases can therefore be treated
142 /// differently when reporting errors.
144 /// The ordering of the cases is significant. They are sorted so that cmp::max
145 /// will keep the "more erroneous" of two values.
146 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
147 pub enum Representability {
150 SelfRecursive(Vec<Span>),
153 impl<'tcx> TyCtxt<'tcx> {
154 /// Creates a hash of the type `Ty` which will be the same no matter what crate
155 /// context it's calculated within. This is used by the `type_id` intrinsic.
156 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
157 let mut hasher = StableHasher::new();
158 let mut hcx = self.create_stable_hashing_context();
160 // We want the type_id be independent of the types free regions, so we
161 // erase them. The erase_regions() call will also anonymize bound
162 // regions, which is desirable too.
163 let ty = self.erase_regions(&ty);
165 hcx.while_hashing_spans(false, |hcx| {
166 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
167 ty.hash_stable(hcx, &mut hasher);
174 impl<'tcx> TyCtxt<'tcx> {
175 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
176 if let ty::Adt(def, substs) = ty.kind {
177 for field in def.all_fields() {
178 let field_ty = field.ty(self, substs);
179 if let Error(_) = field_ty.kind {
187 /// Attempts to returns the deeply last field of nested structures, but
188 /// does not apply any normalization in its search. Returns the same type
189 /// if input `ty` is not a structure at all.
190 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
192 tcx.struct_tail_with_normalize(ty, |ty| ty)
195 /// Returns the deeply last field of nested structures, or the same type if
196 /// not a structure at all. Corresponds to the only possible unsized field,
197 /// and its type can be used to determine unsizing strategy.
199 /// Should only be called if `ty` has no inference variables and does not
200 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
201 /// normalization attempt may cause compiler bugs.
202 pub fn struct_tail_erasing_lifetimes(
205 param_env: ty::ParamEnv<'tcx>,
208 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty))
211 /// Returns the deeply last field of nested structures, or the same type if
212 /// not a structure at all. Corresponds to the only possible unsized field,
213 /// and its type can be used to determine unsizing strategy.
215 /// This is parameterized over the normalization strategy (i.e. how to
216 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
217 /// function to indicate no normalization should take place.
219 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
221 pub fn struct_tail_with_normalize(
224 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
228 ty::Adt(def, substs) => {
229 if !def.is_struct() {
232 match def.non_enum_variant().fields.last() {
233 Some(f) => ty = f.ty(self, substs),
239 if let Some((&last_ty, _)) = tys.split_last() {
240 ty = last_ty.expect_ty();
246 ty::Projection(_) | ty::Opaque(..) => {
247 let normalized = normalize(ty);
248 if ty == normalized {
263 /// Same as applying `struct_tail` on `source` and `target`, but only
264 /// keeps going as long as the two types are instances of the same
265 /// structure definitions.
266 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
267 /// whereas struct_tail produces `T`, and `Trait`, respectively.
269 /// Should only be called if the types have no inference variables and do
270 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
271 /// normalization attempt may cause compiler bugs.
272 pub fn struct_lockstep_tails_erasing_lifetimes(
276 param_env: ty::ParamEnv<'tcx>,
277 ) -> (Ty<'tcx>, Ty<'tcx>) {
279 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
280 tcx.normalize_erasing_regions(param_env, ty)
284 /// Same as applying `struct_tail` on `source` and `target`, but only
285 /// keeps going as long as the two types are instances of the same
286 /// structure definitions.
287 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
288 /// whereas struct_tail produces `T`, and `Trait`, respectively.
290 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
292 pub fn struct_lockstep_tails_with_normalize(
296 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
297 ) -> (Ty<'tcx>, Ty<'tcx>) {
298 let (mut a, mut b) = (source, target);
300 match (&a.kind, &b.kind) {
301 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
302 if a_def == b_def && a_def.is_struct() =>
304 if let Some(f) = a_def.non_enum_variant().fields.last() {
305 a = f.ty(self, a_substs);
306 b = f.ty(self, b_substs);
311 (&Tuple(a_tys), &Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
312 if let Some(a_last) = a_tys.last() {
313 a = a_last.expect_ty();
314 b = b_tys.last().unwrap().expect_ty();
319 (ty::Projection(_) | ty::Opaque(..), _)
320 | (_, ty::Projection(_) | ty::Opaque(..)) => {
321 // If either side is a projection, attempt to
322 // progress via normalization. (Should be safe to
323 // apply to both sides as normalization is
325 let a_norm = normalize(a);
326 let b_norm = normalize(b);
327 if a == a_norm && b == b_norm {
341 /// Calculate the destructor of a given type.
342 pub fn calculate_dtor(
345 validate: &mut dyn FnMut(Self, DefId) -> Result<(), ErrorReported>,
346 ) -> Option<ty::Destructor> {
347 let drop_trait = self.lang_items().drop_trait()?;
348 self.ensure().coherent_trait(drop_trait);
350 let mut dtor_did = None;
351 let ty = self.type_of(adt_did);
352 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
353 if let Some(item) = self.associated_items(impl_did).in_definition_order().next() {
354 if validate(self, impl_did).is_ok() {
355 dtor_did = Some(item.def_id);
360 Some(ty::Destructor { did: dtor_did? })
363 /// Returns the set of types that are required to be alive in
364 /// order to run the destructor of `def` (see RFCs 769 and
367 /// Note that this returns only the constraints for the
368 /// destructor of `def` itself. For the destructors of the
369 /// contents, you need `adt_dtorck_constraint`.
370 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec<ty::subst::GenericArg<'tcx>> {
371 let dtor = match def.destructor(self) {
373 debug!("destructor_constraints({:?}) - no dtor", def.did);
376 Some(dtor) => dtor.did,
379 let impl_def_id = self.associated_item(dtor).container.id();
380 let impl_generics = self.generics_of(impl_def_id);
382 // We have a destructor - all the parameters that are not
383 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
386 // We need to return the list of parameters from the ADTs
387 // generics/substs that correspond to impure parameters on the
388 // impl's generics. This is a bit ugly, but conceptually simple:
390 // Suppose our ADT looks like the following
392 // struct S<X, Y, Z>(X, Y, Z);
396 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
398 // We want to return the parameters (X, Y). For that, we match
399 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
400 // <P1, P2, P0>, and then look up which of the impl substs refer to
401 // parameters marked as pure.
403 let impl_substs = match self.type_of(impl_def_id).kind {
404 ty::Adt(def_, substs) if def_ == def => substs,
408 let item_substs = match self.type_of(def.did).kind {
409 ty::Adt(def_, substs) if def_ == def => substs,
413 let result = item_substs
415 .zip(impl_substs.iter())
418 GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
419 !impl_generics.region_param(ebr, self).pure_wrt_drop
421 GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => {
422 !impl_generics.type_param(pt, self).pure_wrt_drop
424 GenericArgKind::Const(&ty::Const {
425 val: ty::ConstKind::Param(ref pc), ..
426 }) => !impl_generics.const_param(pc, self).pure_wrt_drop,
427 GenericArgKind::Lifetime(_)
428 | GenericArgKind::Type(_)
429 | GenericArgKind::Const(_) => {
430 // Not a type, const or region param: this should be reported
436 .map(|(item_param, _)| item_param)
438 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
442 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
443 /// that closures have a `DefId`, but the closure *expression* also
444 /// has a `HirId` that is located within the context where the
445 /// closure appears (and, sadly, a corresponding `NodeId`, since
446 /// those are not yet phased out). The parent of the closure's
447 /// `DefId` will also be the context where it appears.
448 pub fn is_closure(self, def_id: DefId) -> bool {
449 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
452 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
453 pub fn is_trait(self, def_id: DefId) -> bool {
454 self.def_kind(def_id) == DefKind::Trait
457 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
458 /// and `false` otherwise.
459 pub fn is_trait_alias(self, def_id: DefId) -> bool {
460 self.def_kind(def_id) == DefKind::TraitAlias
463 /// Returns `true` if this `DefId` refers to the implicit constructor for
464 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
465 pub fn is_constructor(self, def_id: DefId) -> bool {
466 matches!(self.def_kind(def_id), DefKind::Ctor(..))
469 /// Given the def-ID of a fn or closure, returns the def-ID of
470 /// the innermost fn item that the closure is contained within.
471 /// This is a significant `DefId` because, when we do
472 /// type-checking, we type-check this fn item and all of its
473 /// (transitive) closures together. Therefore, when we fetch the
474 /// `typeck_tables_of` the closure, for example, we really wind up
475 /// fetching the `typeck_tables_of` the enclosing fn item.
476 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
477 let mut def_id = def_id;
478 while self.is_closure(def_id) {
479 def_id = self.parent(def_id).unwrap_or_else(|| {
480 bug!("closure {:?} has no parent", def_id);
486 /// Given the `DefId` and substs a closure, creates the type of
487 /// `self` argument that the closure expects. For example, for a
488 /// `Fn` closure, this would return a reference type `&T` where
489 /// `T = closure_ty`.
491 /// Returns `None` if this closure's kind has not yet been inferred.
492 /// This should only be possible during type checking.
494 /// Note that the return value is a late-bound region and hence
495 /// wrapped in a binder.
496 pub fn closure_env_ty(
498 closure_def_id: DefId,
499 closure_substs: SubstsRef<'tcx>,
500 ) -> Option<ty::Binder<Ty<'tcx>>> {
501 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
502 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
503 let closure_kind_ty = closure_substs.as_closure().kind_ty();
504 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
505 let env_ty = match closure_kind {
506 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
507 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
508 ty::ClosureKind::FnOnce => closure_ty,
510 Some(ty::Binder::bind(env_ty))
513 /// Given the `DefId` of some item that has no type or const parameters, make
514 /// a suitable "empty substs" for it.
515 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> SubstsRef<'tcx> {
516 InternalSubsts::for_item(self, item_def_id, |param, _| match param.kind {
517 GenericParamDefKind::Lifetime => self.lifetimes.re_erased.into(),
518 GenericParamDefKind::Type { .. } => {
519 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
521 GenericParamDefKind::Const { .. } => {
522 bug!("empty_substs_for_def_id: {:?} has const parameters", item_def_id)
527 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
528 pub fn is_static(&self, def_id: DefId) -> bool {
529 self.static_mutability(def_id).is_some()
532 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
533 pub fn is_thread_local_static(&self, def_id: DefId) -> bool {
534 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
537 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
538 pub fn is_mutable_static(&self, def_id: DefId) -> bool {
539 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
542 /// Get the type of the pointer to the static that we use in MIR.
543 pub fn static_ptr_ty(&self, def_id: DefId) -> Ty<'tcx> {
544 // Make sure that any constants in the static's type are evaluated.
545 let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
547 if self.is_mutable_static(def_id) {
548 self.mk_mut_ptr(static_ty)
550 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
554 /// Expands the given impl trait type, stopping if the type is recursive.
555 pub fn try_expand_impl_trait_type(
558 substs: SubstsRef<'tcx>,
559 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
560 use crate::ty::fold::TypeFolder;
562 struct OpaqueTypeExpander<'tcx> {
563 // Contains the DefIds of the opaque types that are currently being
564 // expanded. When we expand an opaque type we insert the DefId of
565 // that type, and when we finish expanding that type we remove the
567 seen_opaque_tys: FxHashSet<DefId>,
568 // Cache of all expansions we've seen so far. This is a critical
569 // optimization for some large types produced by async fn trees.
570 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
571 primary_def_id: DefId,
572 found_recursion: bool,
576 impl<'tcx> OpaqueTypeExpander<'tcx> {
580 substs: SubstsRef<'tcx>,
581 ) -> Option<Ty<'tcx>> {
582 if self.found_recursion {
585 let substs = substs.fold_with(self);
586 if self.seen_opaque_tys.insert(def_id) {
587 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
588 Some(expanded_ty) => expanded_ty,
590 let generic_ty = self.tcx.type_of(def_id);
591 let concrete_ty = generic_ty.subst(self.tcx, substs);
592 let expanded_ty = self.fold_ty(concrete_ty);
593 self.expanded_cache.insert((def_id, substs), expanded_ty);
597 self.seen_opaque_tys.remove(&def_id);
600 // If another opaque type that we contain is recursive, then it
601 // will report the error, so we don't have to.
602 self.found_recursion = def_id == self.primary_def_id;
608 impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
609 fn tcx(&self) -> TyCtxt<'tcx> {
613 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
614 if let ty::Opaque(def_id, substs) = t.kind {
615 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
616 } else if t.has_opaque_types() {
617 t.super_fold_with(self)
624 let mut visitor = OpaqueTypeExpander {
625 seen_opaque_tys: FxHashSet::default(),
626 expanded_cache: FxHashMap::default(),
627 primary_def_id: def_id,
628 found_recursion: false,
631 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
632 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
636 impl<'tcx> ty::TyS<'tcx> {
637 /// Returns the maximum value for the given numeric type (including `char`s)
638 /// or returns `None` if the type is not numeric.
639 pub fn numeric_max_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
640 let val = match self.kind {
641 ty::Int(_) | ty::Uint(_) => {
642 let (size, signed) = int_size_and_signed(tcx, self);
643 let val = if signed { signed_max(size) as u128 } else { unsigned_max(size) };
646 ty::Char => Some(std::char::MAX as u128),
647 ty::Float(fty) => Some(match fty {
648 ast::FloatTy::F32 => ::rustc_apfloat::ieee::Single::INFINITY.to_bits(),
649 ast::FloatTy::F64 => ::rustc_apfloat::ieee::Double::INFINITY.to_bits(),
653 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
656 /// Returns the minimum value for the given numeric type (including `char`s)
657 /// or returns `None` if the type is not numeric.
658 pub fn numeric_min_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
659 let val = match self.kind {
660 ty::Int(_) | ty::Uint(_) => {
661 let (size, signed) = int_size_and_signed(tcx, self);
662 let val = if signed { truncate(signed_min(size) as u128, size) } else { 0 };
666 ty::Float(fty) => Some(match fty {
667 ast::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
668 ast::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
672 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
675 /// Checks whether values of this type `T` are *moved* or *copied*
676 /// when referenced -- this amounts to a check for whether `T:
677 /// Copy`, but note that we **don't** consider lifetimes when
678 /// doing this check. This means that we may generate MIR which
679 /// does copies even when the type actually doesn't satisfy the
680 /// full requirements for the `Copy` trait (cc #29149) -- this
681 /// winds up being reported as an error during NLL borrow check.
682 pub fn is_copy_modulo_regions(
684 tcx_at: TyCtxtAt<'tcx>,
685 param_env: ty::ParamEnv<'tcx>,
687 tcx_at.is_copy_raw(param_env.and(self))
690 /// Checks whether values of this type `T` have a size known at
691 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
692 /// for the purposes of this check, so it can be an
693 /// over-approximation in generic contexts, where one can have
694 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
695 /// actually carry lifetime requirements.
696 pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
697 self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
700 /// Checks whether values of this type `T` implement the `Freeze`
701 /// trait -- frozen types are those that do not contain a
702 /// `UnsafeCell` anywhere. This is a language concept used to
703 /// distinguish "true immutability", which is relevant to
704 /// optimization as well as the rules around static values. Note
705 /// that the `Freeze` trait is not exposed to end users and is
706 /// effectively an implementation detail.
707 // FIXME: use `TyCtxtAt` instead of separate `Span`.
708 pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
709 self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
712 /// Fast path helper for testing if a type is `Freeze`.
714 /// Returning true means the type is known to be `Freeze`. Returning
715 /// `false` means nothing -- could be `Freeze`, might not be.
716 fn is_trivially_freeze(&self) -> bool {
729 | ty::FnPtr(_) => true,
730 ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_freeze),
731 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
738 | ty::GeneratorWitness(_)
743 | ty::Projection(_) => false,
747 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
748 /// non-copy and *might* have a destructor attached; if it returns
749 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
751 /// (Note that this implies that if `ty` has a destructor attached,
752 /// then `needs_drop` will definitely return `true` for `ty`.)
754 /// Note that this method is used to check eligible types in unions.
756 pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
757 // Avoid querying in simple cases.
758 match needs_drop_components(self, &tcx.data_layout) {
759 Err(AlwaysRequiresDrop) => true,
761 let query_ty = match *components {
763 // If we've got a single component, call the query with that
764 // to increase the chance that we hit the query cache.
765 [component_ty] => component_ty,
768 // This doesn't depend on regions, so try to minimize distinct
770 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
771 tcx.needs_drop_raw(param_env.and(erased))
776 /// Returns `true` if equality for this type is both reflexive and structural.
778 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
780 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
781 /// types, equality for the type as a whole is structural when it is the same as equality
782 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
783 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
786 /// This function is "shallow" because it may return `true` for a composite type whose fields
787 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
788 /// because equality for arrays is determined by the equality of each array element. If you
789 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
790 /// down, you will need to use a type visitor.
792 pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool {
794 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
795 Adt(..) => tcx.has_structural_eq_impls(self),
797 // Primitive types that satisfy `Eq`.
798 Bool | Char | Int(_) | Uint(_) | Str | Never => true,
800 // Composite types that satisfy `Eq` when all of their fields do.
802 // Because this function is "shallow", we return `true` for these composites regardless
803 // of the type(s) contained within.
804 Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
806 // Raw pointers use bitwise comparison.
807 RawPtr(_) | FnPtr(_) => true,
809 // Floating point numbers are not `Eq`.
812 // Conservatively return `false` for all others...
814 // Anonymous function types
815 FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
817 // Generic or inferred types
819 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
820 // called for known, fully-monomorphized types.
821 Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
823 Foreign(_) | GeneratorWitness(..) | Error(_) => false,
827 pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
828 match (&a.kind, &b.kind) {
829 (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
834 substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b))
840 /// Check whether a type is representable. This means it cannot contain unboxed
841 /// structural recursion. This check is needed for structs and enums.
842 pub fn is_representable(&'tcx self, tcx: TyCtxt<'tcx>, sp: Span) -> Representability {
843 // Iterate until something non-representable is found
844 fn fold_repr<It: Iterator<Item = Representability>>(iter: It) -> Representability {
845 iter.fold(Representability::Representable, |r1, r2| match (r1, r2) {
846 (Representability::SelfRecursive(v1), Representability::SelfRecursive(v2)) => {
847 Representability::SelfRecursive(v1.into_iter().chain(v2).collect())
849 (r1, r2) => cmp::max(r1, r2),
853 fn are_inner_types_recursive<'tcx>(
856 seen: &mut Vec<Ty<'tcx>>,
857 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
859 ) -> Representability {
862 // Find non representable
863 fold_repr(ty.tuple_fields().map(|ty| {
864 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
867 // Fixed-length vectors.
868 // FIXME(#11924) Behavior undecided for zero-length vectors.
870 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
872 Adt(def, substs) => {
873 // Find non representable fields with their spans
874 fold_repr(def.all_fields().map(|field| {
875 let ty = field.ty(tcx, substs);
876 let span = match field
879 .map(|id| tcx.hir().as_local_hir_id(id))
880 .and_then(|id| tcx.hir().find(id))
882 Some(hir::Node::Field(field)) => field.ty.span,
885 match is_type_structurally_recursive(
892 Representability::SelfRecursive(_) => {
893 Representability::SelfRecursive(vec![span])
900 // this check is run on type definitions, so we don't expect
901 // to see closure types
902 bug!("requires check invoked on inapplicable type: {:?}", ty)
904 _ => Representability::Representable,
908 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
910 Adt(ty_def, _) => ty_def == def,
915 // Does the type `ty` directly (without indirection through a pointer)
916 // contain any types on stack `seen`?
917 fn is_type_structurally_recursive<'tcx>(
920 seen: &mut Vec<Ty<'tcx>>,
921 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
923 ) -> Representability {
924 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
925 if let Some(representability) = representable_cache.get(ty) {
927 "is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
928 ty, sp, representability
930 return representability.clone();
933 let representability =
934 is_type_structurally_recursive_inner(tcx, sp, seen, representable_cache, ty);
936 representable_cache.insert(ty, representability.clone());
940 fn is_type_structurally_recursive_inner<'tcx>(
943 seen: &mut Vec<Ty<'tcx>>,
944 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
946 ) -> Representability {
950 // Iterate through stack of previously seen types.
951 let mut iter = seen.iter();
953 // The first item in `seen` is the type we are actually curious about.
954 // We want to return SelfRecursive if this type contains itself.
955 // It is important that we DON'T take generic parameters into account
956 // for this check, so that Bar<T> in this example counts as SelfRecursive:
959 // struct Bar<T> { x: Bar<Foo> }
961 if let Some(&seen_type) = iter.next() {
962 if same_struct_or_enum(seen_type, def) {
963 debug!("SelfRecursive: {:?} contains {:?}", seen_type, ty);
964 return Representability::SelfRecursive(vec![sp]);
968 // We also need to know whether the first item contains other types
969 // that are structurally recursive. If we don't catch this case, we
970 // will recurse infinitely for some inputs.
972 // It is important that we DO take generic parameters into account
973 // here, so that code like this is considered SelfRecursive, not
974 // ContainsRecursive:
976 // struct Foo { Option<Option<Foo>> }
978 for &seen_type in iter {
979 if ty::TyS::same_type(ty, seen_type) {
980 debug!("ContainsRecursive: {:?} contains {:?}", seen_type, ty);
981 return Representability::ContainsRecursive;
986 // For structs and enums, track all previously seen types by pushing them
987 // onto the 'seen' stack.
989 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
994 // No need to push in other cases.
995 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
1000 debug!("is_type_representable: {:?}", self);
1002 // To avoid a stack overflow when checking an enum variant or struct that
1003 // contains a different, structurally recursive type, maintain a stack
1004 // of seen types and check recursion for each of them (issues #3008, #3779).
1005 let mut seen: Vec<Ty<'_>> = Vec::new();
1006 let mut representable_cache = FxHashMap::default();
1007 let r = is_type_structurally_recursive(tcx, sp, &mut seen, &mut representable_cache, self);
1008 debug!("is_type_representable: {:?} is {:?}", self, r);
1012 /// Peel off all reference types in this type until there are none left.
1014 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1019 /// - `&'a mut u8` -> `u8`
1020 /// - `&'a &'b u8` -> `u8`
1021 /// - `&'a *const &'b u8 -> *const &'b u8`
1022 pub fn peel_refs(&'tcx self) -> Ty<'tcx> {
1024 while let Ref(_, inner_ty, _) = ty.kind {
1031 pub enum ExplicitSelf<'tcx> {
1033 ByReference(ty::Region<'tcx>, hir::Mutability),
1034 ByRawPointer(hir::Mutability),
1039 impl<'tcx> ExplicitSelf<'tcx> {
1040 /// Categorizes an explicit self declaration like `self: SomeType`
1041 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1043 /// This is mainly used to require the arbitrary_self_types feature
1044 /// in the case of `Other`, to improve error messages in the common cases,
1045 /// and to make `Other` non-object-safe.
1050 /// impl<'a> Foo for &'a T {
1051 /// // Legal declarations:
1052 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1053 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1054 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1055 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1057 /// // Invalid cases will be caught by `check_method_receiver`:
1058 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1059 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1060 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1064 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
1066 P: Fn(Ty<'tcx>) -> bool,
1068 use self::ExplicitSelf::*;
1070 match self_arg_ty.kind {
1071 _ if is_self_ty(self_arg_ty) => ByValue,
1072 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
1073 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
1074 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1080 /// Returns a list of types such that the given type needs drop if and only if
1081 /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1082 /// this type always needs drop.
1083 pub fn needs_drop_components(
1085 target_layout: &TargetDataLayout,
1086 ) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1088 ty::Infer(ty::FreshIntTy(_))
1089 | ty::Infer(ty::FreshFloatTy(_))
1098 | ty::GeneratorWitness(..)
1101 | ty::Str => Ok(SmallVec::new()),
1103 // Foreign types can never have destructors.
1104 ty::Foreign(..) => Ok(SmallVec::new()),
1106 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
1108 ty::Slice(ty) => needs_drop_components(ty, target_layout),
1109 ty::Array(elem_ty, size) => {
1110 match needs_drop_components(elem_ty, target_layout) {
1111 Ok(v) if v.is_empty() => Ok(v),
1112 res => match size.val.try_to_bits(target_layout.pointer_size) {
1113 // Arrays of size zero don't need drop, even if their element
1115 Some(0) => Ok(SmallVec::new()),
1117 // We don't know which of the cases above we are in, so
1118 // return the whole type and let the caller decide what to
1120 None => Ok(smallvec![ty]),
1124 // If any field needs drop, then the whole tuple does.
1125 ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| {
1126 acc.extend(needs_drop_components(elem, target_layout)?);
1130 // These require checking for `Copy` bounds or `Adt` destructors.
1132 | ty::Projection(..)
1135 | ty::Placeholder(..)
1139 | ty::Generator(..) => Ok(smallvec![ty]),
1143 #[derive(Copy, Clone, Debug, HashStable, RustcEncodable, RustcDecodable)]
1144 pub struct AlwaysRequiresDrop;