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::fold::TypeFolder;
7 use crate::ty::layout::IntegerExt;
8 use crate::ty::query::TyCtxtAt;
9 use crate::ty::subst::{GenericArgKind, InternalSubsts, Subst, SubstsRef};
10 use crate::ty::TyKind::*;
11 use crate::ty::{self, DefIdTree, GenericParamDefKind, List, Ty, TyCtxt, TypeFoldable};
12 use rustc_apfloat::Float as _;
14 use rustc_attr::{self as attr, SignedInt, UnsignedInt};
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
17 use rustc_errors::ErrorReported;
19 use rustc_hir::def::DefKind;
20 use rustc_hir::def_id::DefId;
21 use rustc_macros::HashStable;
23 use rustc_target::abi::{Integer, Size, TargetDataLayout};
24 use smallvec::SmallVec;
27 #[derive(Copy, Clone, Debug)]
28 pub struct Discr<'tcx> {
29 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
34 impl<'tcx> fmt::Display for Discr<'tcx> {
35 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
36 match *self.ty.kind() {
38 let size = ty::tls::with(|tcx| Integer::from_attr(&tcx, SignedInt(ity)).size());
40 // sign extend the raw representation to be an i128
41 let x = sign_extend(x, size) as i128;
44 _ => write!(fmt, "{}", self.val),
49 fn signed_min(size: Size) -> i128 {
50 sign_extend(1_u128 << (size.bits() - 1), size) as i128
53 fn signed_max(size: Size) -> i128 {
54 i128::MAX >> (128 - size.bits())
57 fn unsigned_max(size: Size) -> u128 {
58 u128::MAX >> (128 - size.bits())
61 fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
62 let (int, signed) = match *ty.kind() {
63 Int(ity) => (Integer::from_attr(&tcx, SignedInt(ity)), true),
64 Uint(uty) => (Integer::from_attr(&tcx, UnsignedInt(uty)), false),
65 _ => bug!("non integer discriminant"),
70 impl<'tcx> Discr<'tcx> {
71 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
72 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
73 self.checked_add(tcx, 1).0
75 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
76 let (size, signed) = int_size_and_signed(tcx, self.ty);
77 let (val, oflo) = if signed {
78 let min = signed_min(size);
79 let max = signed_max(size);
80 let val = sign_extend(self.val, size) as i128;
81 assert!(n < (i128::MAX as u128));
83 let oflo = val > max - n;
84 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
85 // zero the upper bits
86 let val = val as u128;
87 let val = truncate(val, size);
90 let max = unsigned_max(size);
92 let oflo = val > max - n;
93 let val = if oflo { n - (max - val) - 1 } else { val + n };
96 (Self { val, ty: self.ty }, oflo)
100 pub trait IntTypeExt {
101 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
102 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
103 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
106 impl IntTypeExt for attr::IntType {
107 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
109 SignedInt(ast::IntTy::I8) => tcx.types.i8,
110 SignedInt(ast::IntTy::I16) => tcx.types.i16,
111 SignedInt(ast::IntTy::I32) => tcx.types.i32,
112 SignedInt(ast::IntTy::I64) => tcx.types.i64,
113 SignedInt(ast::IntTy::I128) => tcx.types.i128,
114 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
115 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
116 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
117 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
118 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
119 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
120 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
124 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
125 Discr { val: 0, ty: self.to_ty(tcx) }
128 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
129 if let Some(val) = val {
130 assert_eq!(self.to_ty(tcx), val.ty);
131 let (new, oflo) = val.checked_add(tcx, 1);
132 if oflo { None } else { Some(new) }
134 Some(self.initial_discriminant(tcx))
139 /// Describes whether a type is representable. For types that are not
140 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
141 /// distinguish between types that are recursive with themselves and types that
142 /// contain a different recursive type. These cases can therefore be treated
143 /// differently when reporting errors.
145 /// The ordering of the cases is significant. They are sorted so that cmp::max
146 /// will keep the "more erroneous" of two values.
147 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
148 pub enum Representability {
151 SelfRecursive(Vec<Span>),
154 impl<'tcx> TyCtxt<'tcx> {
155 /// Creates a hash of the type `Ty` which will be the same no matter what crate
156 /// context it's calculated within. This is used by the `type_id` intrinsic.
157 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
158 let mut hasher = StableHasher::new();
159 let mut hcx = self.create_stable_hashing_context();
161 // We want the type_id be independent of the types free regions, so we
162 // erase them. The erase_regions() call will also anonymize bound
163 // regions, which is desirable too.
164 let ty = self.erase_regions(&ty);
166 hcx.while_hashing_spans(false, |hcx| {
167 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
168 ty.hash_stable(hcx, &mut hasher);
174 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
175 if let ty::Adt(def, substs) = *ty.kind() {
176 for field in def.all_fields() {
177 let field_ty = field.ty(self, substs);
178 if let Error(_) = field_ty.kind() {
186 /// Attempts to returns the deeply last field of nested structures, but
187 /// does not apply any normalization in its search. Returns the same type
188 /// if input `ty` is not a structure at all.
189 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
191 tcx.struct_tail_with_normalize(ty, |ty| ty)
194 /// Returns the deeply last field of nested structures, or the same type if
195 /// not a structure at all. Corresponds to the only possible unsized field,
196 /// and its type can be used to determine unsizing strategy.
198 /// Should only be called if `ty` has no inference variables and does not
199 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
200 /// normalization attempt may cause compiler bugs.
201 pub fn struct_tail_erasing_lifetimes(
204 param_env: ty::ParamEnv<'tcx>,
207 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty))
210 /// Returns the deeply last field of nested structures, or the same type if
211 /// not a structure at all. Corresponds to the only possible unsized field,
212 /// and its type can be used to determine unsizing strategy.
214 /// This is parameterized over the normalization strategy (i.e. how to
215 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
216 /// function to indicate no normalization should take place.
218 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
220 pub fn struct_tail_with_normalize(
223 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
227 ty::Adt(def, substs) => {
228 if !def.is_struct() {
231 match def.non_enum_variant().fields.last() {
232 Some(f) => ty = f.ty(self, substs),
238 if let Some((&last_ty, _)) = tys.split_last() {
239 ty = last_ty.expect_ty();
245 ty::Projection(_) | ty::Opaque(..) => {
246 let normalized = normalize(ty);
247 if ty == normalized {
262 /// Same as applying `struct_tail` on `source` and `target`, but only
263 /// keeps going as long as the two types are instances of the same
264 /// structure definitions.
265 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
266 /// whereas struct_tail produces `T`, and `Trait`, respectively.
268 /// Should only be called if the types have no inference variables and do
269 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
270 /// normalization attempt may cause compiler bugs.
271 pub fn struct_lockstep_tails_erasing_lifetimes(
275 param_env: ty::ParamEnv<'tcx>,
276 ) -> (Ty<'tcx>, Ty<'tcx>) {
278 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
279 tcx.normalize_erasing_regions(param_env, ty)
283 /// Same as applying `struct_tail` on `source` and `target`, but only
284 /// keeps going as long as the two types are instances of the same
285 /// structure definitions.
286 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
287 /// whereas struct_tail produces `T`, and `Trait`, respectively.
289 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
291 pub fn struct_lockstep_tails_with_normalize(
295 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
296 ) -> (Ty<'tcx>, Ty<'tcx>) {
297 let (mut a, mut b) = (source, target);
299 match (&a.kind(), &b.kind()) {
300 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
301 if a_def == b_def && a_def.is_struct() =>
303 if let Some(f) = a_def.non_enum_variant().fields.last() {
304 a = f.ty(self, a_substs);
305 b = f.ty(self, b_substs);
310 (&Tuple(a_tys), &Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
311 if let Some(a_last) = a_tys.last() {
312 a = a_last.expect_ty();
313 b = b_tys.last().unwrap().expect_ty();
318 (ty::Projection(_) | ty::Opaque(..), _)
319 | (_, ty::Projection(_) | ty::Opaque(..)) => {
320 // If either side is a projection, attempt to
321 // progress via normalization. (Should be safe to
322 // apply to both sides as normalization is
324 let a_norm = normalize(a);
325 let b_norm = normalize(b);
326 if a == a_norm && b == b_norm {
340 /// Calculate the destructor of a given type.
341 pub fn calculate_dtor(
344 validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>,
345 ) -> Option<ty::Destructor> {
346 let drop_trait = self.lang_items().drop_trait()?;
347 self.ensure().coherent_trait(drop_trait);
349 let ty = self.type_of(adt_did);
350 let dtor_did = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
351 if let Some(item) = self.associated_items(impl_did).in_definition_order().next() {
352 if validate(self, impl_did).is_ok() {
353 return Some(item.def_id);
359 Some(ty::Destructor { did: dtor_did? })
362 /// Returns the set of types that are required to be alive in
363 /// order to run the destructor of `def` (see RFCs 769 and
366 /// Note that this returns only the constraints for the
367 /// destructor of `def` itself. For the destructors of the
368 /// contents, you need `adt_dtorck_constraint`.
369 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec<ty::subst::GenericArg<'tcx>> {
370 let dtor = match def.destructor(self) {
372 debug!("destructor_constraints({:?}) - no dtor", def.did);
375 Some(dtor) => dtor.did,
378 let impl_def_id = self.associated_item(dtor).container.id();
379 let impl_generics = self.generics_of(impl_def_id);
381 // We have a destructor - all the parameters that are not
382 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
385 // We need to return the list of parameters from the ADTs
386 // generics/substs that correspond to impure parameters on the
387 // impl's generics. This is a bit ugly, but conceptually simple:
389 // Suppose our ADT looks like the following
391 // struct S<X, Y, Z>(X, Y, Z);
395 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
397 // We want to return the parameters (X, Y). For that, we match
398 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
399 // <P1, P2, P0>, and then look up which of the impl substs refer to
400 // parameters marked as pure.
402 let impl_substs = match *self.type_of(impl_def_id).kind() {
403 ty::Adt(def_, substs) if def_ == def => substs,
407 let item_substs = match *self.type_of(def.did).kind() {
408 ty::Adt(def_, substs) if def_ == def => substs,
412 let result = item_substs
414 .zip(impl_substs.iter())
417 GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
418 !impl_generics.region_param(ebr, self).pure_wrt_drop
420 GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => {
421 !impl_generics.type_param(pt, self).pure_wrt_drop
423 GenericArgKind::Const(&ty::Const {
424 val: ty::ConstKind::Param(ref pc), ..
425 }) => !impl_generics.const_param(pc, self).pure_wrt_drop,
426 GenericArgKind::Lifetime(_)
427 | GenericArgKind::Type(_)
428 | GenericArgKind::Const(_) => {
429 // Not a type, const or region param: this should be reported
435 .map(|(item_param, _)| item_param)
437 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
441 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
442 /// that closures have a `DefId`, but the closure *expression* also
443 /// has a `HirId` that is located within the context where the
444 /// closure appears (and, sadly, a corresponding `NodeId`, since
445 /// those are not yet phased out). The parent of the closure's
446 /// `DefId` will also be the context where it appears.
447 pub fn is_closure(self, def_id: DefId) -> bool {
448 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
451 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
452 pub fn is_trait(self, def_id: DefId) -> bool {
453 self.def_kind(def_id) == DefKind::Trait
456 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
457 /// and `false` otherwise.
458 pub fn is_trait_alias(self, def_id: DefId) -> bool {
459 self.def_kind(def_id) == DefKind::TraitAlias
462 /// Returns `true` if this `DefId` refers to the implicit constructor for
463 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
464 pub fn is_constructor(self, def_id: DefId) -> bool {
465 matches!(self.def_kind(def_id), DefKind::Ctor(..))
468 /// Given the def-ID of a fn or closure, returns the def-ID of
469 /// the innermost fn item that the closure is contained within.
470 /// This is a significant `DefId` because, when we do
471 /// type-checking, we type-check this fn item and all of its
472 /// (transitive) closures together. Therefore, when we fetch the
473 /// `typeck` the closure, for example, we really wind up
474 /// fetching the `typeck` the enclosing fn item.
475 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
476 let mut def_id = def_id;
477 while self.is_closure(def_id) {
478 def_id = self.parent(def_id).unwrap_or_else(|| {
479 bug!("closure {:?} has no parent", def_id);
485 /// Given the `DefId` and substs a closure, creates the type of
486 /// `self` argument that the closure expects. For example, for a
487 /// `Fn` closure, this would return a reference type `&T` where
488 /// `T = closure_ty`.
490 /// Returns `None` if this closure's kind has not yet been inferred.
491 /// This should only be possible during type checking.
493 /// Note that the return value is a late-bound region and hence
494 /// wrapped in a binder.
495 pub fn closure_env_ty(
497 closure_def_id: DefId,
498 closure_substs: SubstsRef<'tcx>,
499 ) -> Option<ty::Binder<Ty<'tcx>>> {
500 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
501 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
502 let closure_kind_ty = closure_substs.as_closure().kind_ty();
503 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
504 let env_ty = match closure_kind {
505 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
506 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
507 ty::ClosureKind::FnOnce => closure_ty,
509 Some(ty::Binder::bind(env_ty))
512 /// Given the `DefId` of some item that has no type or const parameters, make
513 /// a suitable "empty substs" for it.
514 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> SubstsRef<'tcx> {
515 InternalSubsts::for_item(self, item_def_id, |param, _| match param.kind {
516 GenericParamDefKind::Lifetime => self.lifetimes.re_erased.into(),
517 GenericParamDefKind::Type { .. } => {
518 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
520 GenericParamDefKind::Const { .. } => {
521 bug!("empty_substs_for_def_id: {:?} has const parameters", item_def_id)
526 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
527 pub fn is_static(self, def_id: DefId) -> bool {
528 self.static_mutability(def_id).is_some()
531 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
532 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
533 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
536 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
537 pub fn is_mutable_static(self, def_id: DefId) -> bool {
538 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
541 /// Get the type of the pointer to the static that we use in MIR.
542 pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
543 // Make sure that any constants in the static's type are evaluated.
544 let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
546 if self.is_mutable_static(def_id) {
547 self.mk_mut_ptr(static_ty)
549 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
553 /// Expands the given impl trait type, stopping if the type is recursive.
554 pub fn try_expand_impl_trait_type(
557 substs: SubstsRef<'tcx>,
558 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
559 let mut visitor = OpaqueTypeExpander {
560 seen_opaque_tys: FxHashSet::default(),
561 expanded_cache: FxHashMap::default(),
562 primary_def_id: Some(def_id),
563 found_recursion: false,
564 check_recursion: true,
568 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
569 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
573 struct OpaqueTypeExpander<'tcx> {
574 // Contains the DefIds of the opaque types that are currently being
575 // expanded. When we expand an opaque type we insert the DefId of
576 // that type, and when we finish expanding that type we remove the
578 seen_opaque_tys: FxHashSet<DefId>,
579 // Cache of all expansions we've seen so far. This is a critical
580 // optimization for some large types produced by async fn trees.
581 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
582 primary_def_id: Option<DefId>,
583 found_recursion: bool,
584 /// Whether or not to check for recursive opaque types.
585 /// This is `true` when we're explicitly checking for opaque type
586 /// recursion, and 'false' otherwise to avoid unnecessary work.
587 check_recursion: bool,
591 impl<'tcx> OpaqueTypeExpander<'tcx> {
592 fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
593 if self.found_recursion {
596 let substs = substs.fold_with(self);
597 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
598 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
599 Some(expanded_ty) => expanded_ty,
601 let generic_ty = self.tcx.type_of(def_id);
602 let concrete_ty = generic_ty.subst(self.tcx, substs);
603 let expanded_ty = self.fold_ty(concrete_ty);
604 self.expanded_cache.insert((def_id, substs), expanded_ty);
608 if self.check_recursion {
609 self.seen_opaque_tys.remove(&def_id);
613 // If another opaque type that we contain is recursive, then it
614 // will report the error, so we don't have to.
615 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
621 impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
622 fn tcx(&self) -> TyCtxt<'tcx> {
626 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
627 if let ty::Opaque(def_id, substs) = t.kind {
628 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
629 } else if t.has_opaque_types() {
630 t.super_fold_with(self)
637 impl<'tcx> ty::TyS<'tcx> {
638 /// Returns the maximum value for the given numeric type (including `char`s)
639 /// or returns `None` if the type is not numeric.
640 pub fn numeric_max_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
641 let val = match self.kind() {
642 ty::Int(_) | ty::Uint(_) => {
643 let (size, signed) = int_size_and_signed(tcx, self);
644 let val = if signed { signed_max(size) as u128 } else { unsigned_max(size) };
647 ty::Char => Some(std::char::MAX as u128),
648 ty::Float(fty) => Some(match fty {
649 ast::FloatTy::F32 => ::rustc_apfloat::ieee::Single::INFINITY.to_bits(),
650 ast::FloatTy::F64 => ::rustc_apfloat::ieee::Double::INFINITY.to_bits(),
654 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
657 /// Returns the minimum value for the given numeric type (including `char`s)
658 /// or returns `None` if the type is not numeric.
659 pub fn numeric_min_val(&'tcx self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ty::Const<'tcx>> {
660 let val = match self.kind() {
661 ty::Int(_) | ty::Uint(_) => {
662 let (size, signed) = int_size_and_signed(tcx, self);
663 let val = if signed { truncate(signed_min(size) as u128, size) } else { 0 };
667 ty::Float(fty) => Some(match fty {
668 ast::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
669 ast::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
673 val.map(|v| ty::Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
676 /// Checks whether values of this type `T` are *moved* or *copied*
677 /// when referenced -- this amounts to a check for whether `T:
678 /// Copy`, but note that we **don't** consider lifetimes when
679 /// doing this check. This means that we may generate MIR which
680 /// does copies even when the type actually doesn't satisfy the
681 /// full requirements for the `Copy` trait (cc #29149) -- this
682 /// winds up being reported as an error during NLL borrow check.
683 pub fn is_copy_modulo_regions(
685 tcx_at: TyCtxtAt<'tcx>,
686 param_env: ty::ParamEnv<'tcx>,
688 tcx_at.is_copy_raw(param_env.and(self))
691 /// Checks whether values of this type `T` have a size known at
692 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
693 /// for the purposes of this check, so it can be an
694 /// over-approximation in generic contexts, where one can have
695 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
696 /// actually carry lifetime requirements.
697 pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
698 self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
701 /// Checks whether values of this type `T` implement the `Freeze`
702 /// trait -- frozen types are those that do not contain a
703 /// `UnsafeCell` anywhere. This is a language concept used to
704 /// distinguish "true immutability", which is relevant to
705 /// optimization as well as the rules around static values. Note
706 /// that the `Freeze` trait is not exposed to end users and is
707 /// effectively an implementation detail.
708 // FIXME: use `TyCtxtAt` instead of separate `Span`.
709 pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
710 self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
713 /// Fast path helper for testing if a type is `Freeze`.
715 /// Returning true means the type is known to be `Freeze`. Returning
716 /// `false` means nothing -- could be `Freeze`, might not be.
717 fn is_trivially_freeze(&self) -> bool {
730 | ty::FnPtr(_) => true,
731 ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_freeze),
732 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
739 | ty::GeneratorWitness(_)
744 | ty::Projection(_) => false,
748 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
749 /// non-copy and *might* have a destructor attached; if it returns
750 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
752 /// (Note that this implies that if `ty` has a destructor attached,
753 /// then `needs_drop` will definitely return `true` for `ty`.)
755 /// Note that this method is used to check eligible types in unions.
757 pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
758 // Avoid querying in simple cases.
759 match needs_drop_components(self, &tcx.data_layout) {
760 Err(AlwaysRequiresDrop) => true,
762 let query_ty = match *components {
764 // If we've got a single component, call the query with that
765 // to increase the chance that we hit the query cache.
766 [component_ty] => component_ty,
769 // This doesn't depend on regions, so try to minimize distinct
771 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
772 tcx.needs_drop_raw(param_env.and(erased))
777 /// Returns `true` if equality for this type is both reflexive and structural.
779 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
781 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
782 /// types, equality for the type as a whole is structural when it is the same as equality
783 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
784 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
787 /// This function is "shallow" because it may return `true` for a composite type whose fields
788 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
789 /// because equality for arrays is determined by the equality of each array element. If you
790 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
791 /// down, you will need to use a type visitor.
793 pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool {
795 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
796 Adt(..) => tcx.has_structural_eq_impls(self),
798 // Primitive types that satisfy `Eq`.
799 Bool | Char | Int(_) | Uint(_) | Str | Never => true,
801 // Composite types that satisfy `Eq` when all of their fields do.
803 // Because this function is "shallow", we return `true` for these composites regardless
804 // of the type(s) contained within.
805 Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
807 // Raw pointers use bitwise comparison.
808 RawPtr(_) | FnPtr(_) => true,
810 // Floating point numbers are not `Eq`.
813 // Conservatively return `false` for all others...
815 // Anonymous function types
816 FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
818 // Generic or inferred types
820 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
821 // called for known, fully-monomorphized types.
822 Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
824 Foreign(_) | GeneratorWitness(..) | Error(_) => false,
828 pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
829 match (&a.kind(), &b.kind()) {
830 (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
835 substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b))
841 /// Check whether a type is representable. This means it cannot contain unboxed
842 /// structural recursion. This check is needed for structs and enums.
843 pub fn is_representable(&'tcx self, tcx: TyCtxt<'tcx>, sp: Span) -> Representability {
844 // Iterate until something non-representable is found
845 fn fold_repr<It: Iterator<Item = Representability>>(iter: It) -> Representability {
846 iter.fold(Representability::Representable, |r1, r2| match (r1, r2) {
847 (Representability::SelfRecursive(v1), Representability::SelfRecursive(v2)) => {
848 Representability::SelfRecursive(v1.into_iter().chain(v2).collect())
850 (r1, r2) => cmp::max(r1, r2),
854 fn are_inner_types_recursive<'tcx>(
857 seen: &mut Vec<Ty<'tcx>>,
858 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
860 ) -> Representability {
863 // Find non representable
864 fold_repr(ty.tuple_fields().map(|ty| {
865 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
868 // Fixed-length vectors.
869 // FIXME(#11924) Behavior undecided for zero-length vectors.
871 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
873 Adt(def, substs) => {
874 // Find non representable fields with their spans
875 fold_repr(def.all_fields().map(|field| {
876 let ty = field.ty(tcx, substs);
877 let span = match field
880 .map(|id| tcx.hir().local_def_id_to_hir_id(id))
881 .and_then(|id| tcx.hir().find(id))
883 Some(hir::Node::Field(field)) => field.ty.span,
886 match is_type_structurally_recursive(
893 Representability::SelfRecursive(_) => {
894 Representability::SelfRecursive(vec![span])
901 // this check is run on type definitions, so we don't expect
902 // to see closure types
903 bug!("requires check invoked on inapplicable type: {:?}", ty)
905 _ => Representability::Representable,
909 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
911 Adt(ty_def, _) => ty_def == def,
916 // Does the type `ty` directly (without indirection through a pointer)
917 // contain any types on stack `seen`?
918 fn is_type_structurally_recursive<'tcx>(
921 seen: &mut Vec<Ty<'tcx>>,
922 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
924 ) -> Representability {
925 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
926 if let Some(representability) = representable_cache.get(ty) {
928 "is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
929 ty, sp, representability
931 return representability.clone();
934 let representability =
935 is_type_structurally_recursive_inner(tcx, sp, seen, representable_cache, ty);
937 representable_cache.insert(ty, representability.clone());
941 fn is_type_structurally_recursive_inner<'tcx>(
944 seen: &mut Vec<Ty<'tcx>>,
945 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
947 ) -> Representability {
951 // Iterate through stack of previously seen types.
952 let mut iter = seen.iter();
954 // The first item in `seen` is the type we are actually curious about.
955 // We want to return SelfRecursive if this type contains itself.
956 // It is important that we DON'T take generic parameters into account
957 // for this check, so that Bar<T> in this example counts as SelfRecursive:
960 // struct Bar<T> { x: Bar<Foo> }
962 if let Some(&seen_type) = iter.next() {
963 if same_struct_or_enum(seen_type, *def) {
964 debug!("SelfRecursive: {:?} contains {:?}", seen_type, ty);
965 return Representability::SelfRecursive(vec![sp]);
969 // We also need to know whether the first item contains other types
970 // that are structurally recursive. If we don't catch this case, we
971 // will recurse infinitely for some inputs.
973 // It is important that we DO take generic parameters into account
974 // here, so that code like this is considered SelfRecursive, not
975 // ContainsRecursive:
977 // struct Foo { Option<Option<Foo>> }
979 for &seen_type in iter {
980 if ty::TyS::same_type(ty, seen_type) {
981 debug!("ContainsRecursive: {:?} contains {:?}", seen_type, ty);
982 return Representability::ContainsRecursive;
987 // For structs and enums, track all previously seen types by pushing them
988 // onto the 'seen' stack.
990 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
995 // No need to push in other cases.
996 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
1001 debug!("is_type_representable: {:?}", self);
1003 // To avoid a stack overflow when checking an enum variant or struct that
1004 // contains a different, structurally recursive type, maintain a stack
1005 // of seen types and check recursion for each of them (issues #3008, #3779).
1006 let mut seen: Vec<Ty<'_>> = Vec::new();
1007 let mut representable_cache = FxHashMap::default();
1008 let r = is_type_structurally_recursive(tcx, sp, &mut seen, &mut representable_cache, self);
1009 debug!("is_type_representable: {:?} is {:?}", self, r);
1013 /// Peel off all reference types in this type until there are none left.
1015 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
1020 /// - `&'a mut u8` -> `u8`
1021 /// - `&'a &'b u8` -> `u8`
1022 /// - `&'a *const &'b u8 -> *const &'b u8`
1023 pub fn peel_refs(&'tcx self) -> Ty<'tcx> {
1025 while let Ref(_, inner_ty, _) = ty.kind() {
1032 pub enum ExplicitSelf<'tcx> {
1034 ByReference(ty::Region<'tcx>, hir::Mutability),
1035 ByRawPointer(hir::Mutability),
1040 impl<'tcx> ExplicitSelf<'tcx> {
1041 /// Categorizes an explicit self declaration like `self: SomeType`
1042 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1044 /// This is mainly used to require the arbitrary_self_types feature
1045 /// in the case of `Other`, to improve error messages in the common cases,
1046 /// and to make `Other` non-object-safe.
1051 /// impl<'a> Foo for &'a T {
1052 /// // Legal declarations:
1053 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1054 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1055 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1056 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1058 /// // Invalid cases will be caught by `check_method_receiver`:
1059 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1060 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1061 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1065 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
1067 P: Fn(Ty<'tcx>) -> bool,
1069 use self::ExplicitSelf::*;
1071 match *self_arg_ty.kind() {
1072 _ if is_self_ty(self_arg_ty) => ByValue,
1073 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
1074 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
1075 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1081 /// Returns a list of types such that the given type needs drop if and only if
1082 /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1083 /// this type always needs drop.
1084 pub fn needs_drop_components(
1086 target_layout: &TargetDataLayout,
1087 ) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1089 ty::Infer(ty::FreshIntTy(_))
1090 | ty::Infer(ty::FreshFloatTy(_))
1099 | ty::GeneratorWitness(..)
1102 | ty::Str => Ok(SmallVec::new()),
1104 // Foreign types can never have destructors.
1105 ty::Foreign(..) => Ok(SmallVec::new()),
1107 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
1109 ty::Slice(ty) => needs_drop_components(ty, target_layout),
1110 ty::Array(elem_ty, size) => {
1111 match needs_drop_components(elem_ty, target_layout) {
1112 Ok(v) if v.is_empty() => Ok(v),
1113 res => match size.val.try_to_bits(target_layout.pointer_size) {
1114 // Arrays of size zero don't need drop, even if their element
1116 Some(0) => Ok(SmallVec::new()),
1118 // We don't know which of the cases above we are in, so
1119 // return the whole type and let the caller decide what to
1121 None => Ok(smallvec![ty]),
1125 // If any field needs drop, then the whole tuple does.
1126 ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| {
1127 acc.extend(needs_drop_components(elem, target_layout)?);
1131 // These require checking for `Copy` bounds or `Adt` destructors.
1133 | ty::Projection(..)
1136 | ty::Placeholder(..)
1140 | ty::Generator(..) => Ok(smallvec![ty]),
1144 #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1145 pub struct AlwaysRequiresDrop;
1147 /// Normalizes all opaque types in the given value, replacing them
1148 /// with their underlying types.
1149 pub fn normalize_opaque_types(
1151 val: &'tcx List<ty::Predicate<'tcx>>,
1152 ) -> &'tcx List<ty::Predicate<'tcx>> {
1153 let mut visitor = OpaqueTypeExpander {
1154 seen_opaque_tys: FxHashSet::default(),
1155 expanded_cache: FxHashMap::default(),
1156 primary_def_id: None,
1157 found_recursion: false,
1158 check_recursion: false,
1161 val.fold_with(&mut visitor)
1164 pub fn provide(providers: &mut ty::query::Providers) {
1165 *providers = ty::query::Providers { normalize_opaque_types, ..*providers }