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::fold::{FallibleTypeFolder, TypeFolder};
5 use crate::ty::layout::IntegerExt;
6 use crate::ty::query::TyCtxtAt;
7 use crate::ty::subst::{GenericArgKind, Subst, SubstsRef};
9 self, Const, DebruijnIndex, DefIdTree, List, ReEarlyBound, Ty, TyCtxt, TyKind::*, 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::ErrorGuaranteed;
18 use rustc_hir::def::{CtorOf, DefKind, Res};
19 use rustc_hir::def_id::DefId;
20 use rustc_macros::HashStable;
21 use rustc_query_system::ich::NodeIdHashingMode;
22 use rustc_span::{sym, DUMMY_SP};
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_int_ty(&tcx, ity).size());
40 // sign extend the raw representation to be an i128
41 let x = size.sign_extend(x) as i128;
44 _ => write!(fmt, "{}", self.val),
49 fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
50 let (int, signed) = match *ty.kind() {
51 Int(ity) => (Integer::from_int_ty(&tcx, ity), true),
52 Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false),
53 _ => bug!("non integer discriminant"),
58 impl<'tcx> Discr<'tcx> {
59 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
60 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
61 self.checked_add(tcx, 1).0
63 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
64 let (size, signed) = int_size_and_signed(tcx, self.ty);
65 let (val, oflo) = if signed {
66 let min = size.signed_int_min();
67 let max = size.signed_int_max();
68 let val = size.sign_extend(self.val) as i128;
69 assert!(n < (i128::MAX as u128));
71 let oflo = val > max - n;
72 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
73 // zero the upper bits
74 let val = val as u128;
75 let val = size.truncate(val);
78 let max = size.unsigned_int_max();
80 let oflo = val > max - n;
81 let val = if oflo { n - (max - val) - 1 } else { val + n };
84 (Self { val, ty: self.ty }, oflo)
88 pub trait IntTypeExt {
89 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
90 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
91 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
94 impl IntTypeExt for attr::IntType {
95 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
97 SignedInt(ast::IntTy::I8) => tcx.types.i8,
98 SignedInt(ast::IntTy::I16) => tcx.types.i16,
99 SignedInt(ast::IntTy::I32) => tcx.types.i32,
100 SignedInt(ast::IntTy::I64) => tcx.types.i64,
101 SignedInt(ast::IntTy::I128) => tcx.types.i128,
102 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
103 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
104 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
105 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
106 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
107 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
108 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
112 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
113 Discr { val: 0, ty: self.to_ty(tcx) }
116 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
117 if let Some(val) = val {
118 assert_eq!(self.to_ty(tcx), val.ty);
119 let (new, oflo) = val.checked_add(tcx, 1);
120 if oflo { None } else { Some(new) }
122 Some(self.initial_discriminant(tcx))
127 impl<'tcx> TyCtxt<'tcx> {
128 /// Creates a hash of the type `Ty` which will be the same no matter what crate
129 /// context it's calculated within. This is used by the `type_id` intrinsic.
130 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
131 let mut hasher = StableHasher::new();
132 let mut hcx = self.create_stable_hashing_context();
134 // We want the type_id be independent of the types free regions, so we
135 // erase them. The erase_regions() call will also anonymize bound
136 // regions, which is desirable too.
137 let ty = self.erase_regions(ty);
139 hcx.while_hashing_spans(false, |hcx| {
140 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
141 ty.hash_stable(hcx, &mut hasher);
147 pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
149 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
150 Some(self.parent(def_id).and_then(|def_id| self.parent(def_id)).unwrap())
152 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
153 Some(self.parent(def_id).unwrap())
155 // Other `DefKind`s don't have generics and would ICE when calling
165 | DefKind::TraitAlias
169 | DefKind::AssocConst
178 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
179 if let ty::Adt(def, substs) = *ty.kind() {
180 for field in def.all_fields() {
181 let field_ty = field.ty(self, substs);
182 if let Error(_) = field_ty.kind() {
190 /// Attempts to returns the deeply last field of nested structures, but
191 /// does not apply any normalization in its search. Returns the same type
192 /// if input `ty` is not a structure at all.
193 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
195 tcx.struct_tail_with_normalize(ty, |ty| ty)
198 /// Returns the deeply last field of nested structures, or the same type if
199 /// not a structure at all. Corresponds to the only possible unsized field,
200 /// and its type can be used to determine unsizing strategy.
202 /// Should only be called if `ty` has no inference variables and does not
203 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
204 /// normalization attempt may cause compiler bugs.
205 pub fn struct_tail_erasing_lifetimes(
208 param_env: ty::ParamEnv<'tcx>,
211 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty))
214 /// Returns the deeply last field of nested structures, or the same type if
215 /// not a structure at all. Corresponds to the only possible unsized field,
216 /// and its type can be used to determine unsizing strategy.
218 /// This is parameterized over the normalization strategy (i.e. how to
219 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
220 /// function to indicate no normalization should take place.
222 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
224 pub fn struct_tail_with_normalize(
227 mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
229 let recursion_limit = self.recursion_limit();
230 for iteration in 0.. {
231 if !recursion_limit.value_within_limit(iteration) {
232 return self.ty_error_with_message(
234 &format!("reached the recursion limit finding the struct tail for {}", ty),
238 ty::Adt(def, substs) => {
239 if !def.is_struct() {
242 match def.non_enum_variant().fields.last() {
243 Some(f) => ty = f.ty(self, substs),
248 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
252 ty::Tuple(_) => break,
254 ty::Projection(_) | ty::Opaque(..) => {
255 let normalized = normalize(ty);
256 if ty == normalized {
271 /// Same as applying `struct_tail` on `source` and `target`, but only
272 /// keeps going as long as the two types are instances of the same
273 /// structure definitions.
274 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
275 /// whereas struct_tail produces `T`, and `Trait`, respectively.
277 /// Should only be called if the types have no inference variables and do
278 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
279 /// normalization attempt may cause compiler bugs.
280 pub fn struct_lockstep_tails_erasing_lifetimes(
284 param_env: ty::ParamEnv<'tcx>,
285 ) -> (Ty<'tcx>, Ty<'tcx>) {
287 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
288 tcx.normalize_erasing_regions(param_env, ty)
292 /// Same as applying `struct_tail` on `source` and `target`, but only
293 /// keeps going as long as the two types are instances of the same
294 /// structure definitions.
295 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
296 /// whereas struct_tail produces `T`, and `Trait`, respectively.
298 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
300 pub fn struct_lockstep_tails_with_normalize(
304 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
305 ) -> (Ty<'tcx>, Ty<'tcx>) {
306 let (mut a, mut b) = (source, target);
308 match (&a.kind(), &b.kind()) {
309 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
310 if a_def == b_def && a_def.is_struct() =>
312 if let Some(f) = a_def.non_enum_variant().fields.last() {
313 a = f.ty(self, a_substs);
314 b = f.ty(self, b_substs);
319 (&Tuple(a_tys), &Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
320 if let Some(&a_last) = a_tys.last() {
322 b = *b_tys.last().unwrap();
327 (ty::Projection(_) | ty::Opaque(..), _)
328 | (_, ty::Projection(_) | ty::Opaque(..)) => {
329 // If either side is a projection, attempt to
330 // progress via normalization. (Should be safe to
331 // apply to both sides as normalization is
333 let a_norm = normalize(a);
334 let b_norm = normalize(b);
335 if a == a_norm && b == b_norm {
349 /// Calculate the destructor of a given type.
350 pub fn calculate_dtor(
353 validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
354 ) -> Option<ty::Destructor> {
355 let drop_trait = self.lang_items().drop_trait()?;
356 self.ensure().coherent_trait(drop_trait);
358 let ty = self.type_of(adt_did);
359 let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
360 if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
361 if validate(self, impl_did).is_ok() {
362 return Some((*item_id, self.impl_constness(impl_did)));
368 Some(ty::Destructor { did, constness })
371 /// Returns the set of types that are required to be alive in
372 /// order to run the destructor of `def` (see RFCs 769 and
375 /// Note that this returns only the constraints for the
376 /// destructor of `def` itself. For the destructors of the
377 /// contents, you need `adt_dtorck_constraint`.
378 pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::subst::GenericArg<'tcx>> {
379 let dtor = match def.destructor(self) {
381 debug!("destructor_constraints({:?}) - no dtor", def.did());
384 Some(dtor) => dtor.did,
387 let impl_def_id = self.associated_item(dtor).container.id();
388 let impl_generics = self.generics_of(impl_def_id);
390 // We have a destructor - all the parameters that are not
391 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
394 // We need to return the list of parameters from the ADTs
395 // generics/substs that correspond to impure parameters on the
396 // impl's generics. This is a bit ugly, but conceptually simple:
398 // Suppose our ADT looks like the following
400 // struct S<X, Y, Z>(X, Y, Z);
404 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
406 // We want to return the parameters (X, Y). For that, we match
407 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
408 // <P1, P2, P0>, and then look up which of the impl substs refer to
409 // parameters marked as pure.
411 let impl_substs = match *self.type_of(impl_def_id).kind() {
412 ty::Adt(def_, substs) if def_ == def => substs,
416 let item_substs = match *self.type_of(def.did()).kind() {
417 ty::Adt(def_, substs) if def_ == def => substs,
421 let result = iter::zip(item_substs, impl_substs)
424 GenericArgKind::Lifetime(region) => match region.kind() {
425 ReEarlyBound(ref ebr) => {
426 !impl_generics.region_param(ebr, self).pure_wrt_drop
428 // Error: not a region param
431 GenericArgKind::Type(ty) => match ty.kind() {
432 ty::Param(ref pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
433 // Error: not a type param
436 GenericArgKind::Const(ct) => match ct.val() {
437 ty::ConstKind::Param(ref pc) => {
438 !impl_generics.const_param(pc, self).pure_wrt_drop
440 // Error: not a const param
445 .map(|(item_param, _)| item_param)
447 debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
451 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
452 /// that closures have a `DefId`, but the closure *expression* also
453 /// has a `HirId` that is located within the context where the
454 /// closure appears (and, sadly, a corresponding `NodeId`, since
455 /// those are not yet phased out). The parent of the closure's
456 /// `DefId` will also be the context where it appears.
457 pub fn is_closure(self, def_id: DefId) -> bool {
458 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
461 /// Returns `true` if `def_id` refers to a definition that does not have its own
462 /// type-checking context, i.e. closure, generator or inline const.
463 pub fn is_typeck_child(self, def_id: DefId) -> bool {
465 self.def_kind(def_id),
466 DefKind::Closure | DefKind::Generator | DefKind::InlineConst
470 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
471 pub fn is_trait(self, def_id: DefId) -> bool {
472 self.def_kind(def_id) == DefKind::Trait
475 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
476 /// and `false` otherwise.
477 pub fn is_trait_alias(self, def_id: DefId) -> bool {
478 self.def_kind(def_id) == DefKind::TraitAlias
481 /// Returns `true` if this `DefId` refers to the implicit constructor for
482 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
483 pub fn is_constructor(self, def_id: DefId) -> bool {
484 matches!(self.def_kind(def_id), DefKind::Ctor(..))
487 /// Given the `DefId`, returns the `DefId` of the innermost item that
488 /// has its own type-checking context or "inference environment".
490 /// For example, a closure has its own `DefId`, but it is type-checked
491 /// with the containing item. Similarly, an inline const block has its
492 /// own `DefId` but it is type-checked together with the containing item.
494 /// Therefore, when we fetch the
495 /// `typeck` the closure, for example, we really wind up
496 /// fetching the `typeck` the enclosing fn item.
497 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
498 let mut def_id = def_id;
499 while self.is_typeck_child(def_id) {
500 def_id = self.parent(def_id).unwrap_or_else(|| {
501 bug!("closure {:?} has no parent", def_id);
507 /// Given the `DefId` and substs a closure, creates the type of
508 /// `self` argument that the closure expects. For example, for a
509 /// `Fn` closure, this would return a reference type `&T` where
510 /// `T = closure_ty`.
512 /// Returns `None` if this closure's kind has not yet been inferred.
513 /// This should only be possible during type checking.
515 /// Note that the return value is a late-bound region and hence
516 /// wrapped in a binder.
517 pub fn closure_env_ty(
519 closure_def_id: DefId,
520 closure_substs: SubstsRef<'tcx>,
521 env_region: ty::RegionKind,
522 ) -> Option<Ty<'tcx>> {
523 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
524 let closure_kind_ty = closure_substs.as_closure().kind_ty();
525 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
526 let env_ty = match closure_kind {
527 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
528 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
529 ty::ClosureKind::FnOnce => closure_ty,
534 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
536 pub fn is_static(self, def_id: DefId) -> bool {
537 matches!(self.def_kind(def_id), DefKind::Static(_))
541 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
542 if let DefKind::Static(mt) = self.def_kind(def_id) { Some(mt) } else { None }
545 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
546 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
547 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
550 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
552 pub fn is_mutable_static(self, def_id: DefId) -> bool {
553 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
556 /// Get the type of the pointer to the static that we use in MIR.
557 pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
558 // Make sure that any constants in the static's type are evaluated.
559 let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
561 // Make sure that accesses to unsafe statics end up using raw pointers.
562 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
563 if self.is_mutable_static(def_id) {
564 self.mk_mut_ptr(static_ty)
565 } else if self.is_foreign_item(def_id) {
566 self.mk_imm_ptr(static_ty)
568 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
572 /// Expands the given impl trait type, stopping if the type is recursive.
573 #[instrument(skip(self), level = "debug")]
574 pub fn try_expand_impl_trait_type(
577 substs: SubstsRef<'tcx>,
578 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
579 let mut visitor = OpaqueTypeExpander {
580 seen_opaque_tys: FxHashSet::default(),
581 expanded_cache: FxHashMap::default(),
582 primary_def_id: Some(def_id),
583 found_recursion: false,
584 found_any_recursion: false,
585 check_recursion: true,
589 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
590 trace!(?expanded_type);
591 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
595 struct OpaqueTypeExpander<'tcx> {
596 // Contains the DefIds of the opaque types that are currently being
597 // expanded. When we expand an opaque type we insert the DefId of
598 // that type, and when we finish expanding that type we remove the
600 seen_opaque_tys: FxHashSet<DefId>,
601 // Cache of all expansions we've seen so far. This is a critical
602 // optimization for some large types produced by async fn trees.
603 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
604 primary_def_id: Option<DefId>,
605 found_recursion: bool,
606 found_any_recursion: bool,
607 /// Whether or not to check for recursive opaque types.
608 /// This is `true` when we're explicitly checking for opaque type
609 /// recursion, and 'false' otherwise to avoid unnecessary work.
610 check_recursion: bool,
614 impl<'tcx> OpaqueTypeExpander<'tcx> {
615 fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
616 if self.found_any_recursion {
619 let substs = substs.fold_with(self);
620 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
621 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
622 Some(expanded_ty) => *expanded_ty,
624 let generic_ty = self.tcx.type_of(def_id);
625 let concrete_ty = generic_ty.subst(self.tcx, substs);
626 let expanded_ty = self.fold_ty(concrete_ty);
627 self.expanded_cache.insert((def_id, substs), expanded_ty);
631 if self.check_recursion {
632 self.seen_opaque_tys.remove(&def_id);
636 // If another opaque type that we contain is recursive, then it
637 // will report the error, so we don't have to.
638 self.found_any_recursion = true;
639 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
645 impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
646 fn tcx(&self) -> TyCtxt<'tcx> {
650 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
651 if let ty::Opaque(def_id, substs) = *t.kind() {
652 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
653 } else if t.has_opaque_types() {
654 t.super_fold_with(self)
661 impl<'tcx> Ty<'tcx> {
662 /// Returns the maximum value for the given numeric type (including `char`s)
663 /// or returns `None` if the type is not numeric.
664 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<Const<'tcx>> {
665 let val = match self.kind() {
666 ty::Int(_) | ty::Uint(_) => {
667 let (size, signed) = int_size_and_signed(tcx, self);
669 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
672 ty::Char => Some(std::char::MAX as u128),
673 ty::Float(fty) => Some(match fty {
674 ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
675 ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
679 val.map(|v| Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
682 /// Returns the minimum value for the given numeric type (including `char`s)
683 /// or returns `None` if the type is not numeric.
684 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<Const<'tcx>> {
685 let val = match self.kind() {
686 ty::Int(_) | ty::Uint(_) => {
687 let (size, signed) = int_size_and_signed(tcx, self);
688 let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
692 ty::Float(fty) => Some(match fty {
693 ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
694 ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
698 val.map(|v| Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
701 /// Checks whether values of this type `T` are *moved* or *copied*
702 /// when referenced -- this amounts to a check for whether `T:
703 /// Copy`, but note that we **don't** consider lifetimes when
704 /// doing this check. This means that we may generate MIR which
705 /// does copies even when the type actually doesn't satisfy the
706 /// full requirements for the `Copy` trait (cc #29149) -- this
707 /// winds up being reported as an error during NLL borrow check.
708 pub fn is_copy_modulo_regions(
710 tcx_at: TyCtxtAt<'tcx>,
711 param_env: ty::ParamEnv<'tcx>,
713 self.is_trivially_pure_clone_copy() || tcx_at.is_copy_raw(param_env.and(self))
716 /// Checks whether values of this type `T` have a size known at
717 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
718 /// for the purposes of this check, so it can be an
719 /// over-approximation in generic contexts, where one can have
720 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
721 /// actually carry lifetime requirements.
722 pub fn is_sized(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
723 self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
726 /// Checks whether values of this type `T` implement the `Freeze`
727 /// trait -- frozen types are those that do not contain an
728 /// `UnsafeCell` anywhere. This is a language concept used to
729 /// distinguish "true immutability", which is relevant to
730 /// optimization as well as the rules around static values. Note
731 /// that the `Freeze` trait is not exposed to end users and is
732 /// effectively an implementation detail.
733 pub fn is_freeze(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
734 self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
737 /// Fast path helper for testing if a type is `Freeze`.
739 /// Returning true means the type is known to be `Freeze`. Returning
740 /// `false` means nothing -- could be `Freeze`, might not be.
741 fn is_trivially_freeze(self) -> bool {
754 | ty::FnPtr(_) => true,
755 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
756 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
763 | ty::GeneratorWitness(_)
768 | ty::Projection(_) => false,
772 /// Checks whether values of this type `T` implement the `Unpin` trait.
773 pub fn is_unpin(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
774 self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self))
777 /// Fast path helper for testing if a type is `Unpin`.
779 /// Returning true means the type is known to be `Unpin`. Returning
780 /// `false` means nothing -- could be `Unpin`, might not be.
781 fn is_trivially_unpin(self) -> bool {
794 | ty::FnPtr(_) => true,
795 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
796 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(),
803 | ty::GeneratorWitness(_)
808 | ty::Projection(_) => false,
812 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
813 /// non-copy and *might* have a destructor attached; if it returns
814 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
816 /// (Note that this implies that if `ty` has a destructor attached,
817 /// then `needs_drop` will definitely return `true` for `ty`.)
819 /// Note that this method is used to check eligible types in unions.
821 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
822 // Avoid querying in simple cases.
823 match needs_drop_components(self, &tcx.data_layout) {
824 Err(AlwaysRequiresDrop) => true,
826 let query_ty = match *components {
828 // If we've got a single component, call the query with that
829 // to increase the chance that we hit the query cache.
830 [component_ty] => component_ty,
834 // This doesn't depend on regions, so try to minimize distinct
836 // If normalization fails, we just use `query_ty`.
838 tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty);
840 tcx.needs_drop_raw(param_env.and(query_ty))
845 /// Checks if `ty` has has a significant drop.
847 /// Note that this method can return false even if `ty` has a destructor
848 /// attached; even if that is the case then the adt has been marked with
849 /// the attribute `rustc_insignificant_dtor`.
851 /// Note that this method is used to check for change in drop order for
852 /// 2229 drop reorder migration analysis.
854 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
855 // Avoid querying in simple cases.
856 match needs_drop_components(self, &tcx.data_layout) {
857 Err(AlwaysRequiresDrop) => true,
859 let query_ty = match *components {
861 // If we've got a single component, call the query with that
862 // to increase the chance that we hit the query cache.
863 [component_ty] => component_ty,
867 // FIXME(#86868): We should be canonicalizing, or else moving this to a method of inference
868 // context, or *something* like that, but for now just avoid passing inference
869 // variables to queries that can't cope with them. Instead, conservatively
870 // return "true" (may change drop order).
871 if query_ty.needs_infer() {
875 // This doesn't depend on regions, so try to minimize distinct
877 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
878 tcx.has_significant_drop_raw(param_env.and(erased))
883 /// Returns `true` if equality for this type is both reflexive and structural.
885 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
887 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
888 /// types, equality for the type as a whole is structural when it is the same as equality
889 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
890 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
893 /// This function is "shallow" because it may return `true` for a composite type whose fields
894 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
895 /// because equality for arrays is determined by the equality of each array element. If you
896 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
897 /// down, you will need to use a type visitor.
899 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
901 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
902 Adt(..) => tcx.has_structural_eq_impls(self),
904 // Primitive types that satisfy `Eq`.
905 Bool | Char | Int(_) | Uint(_) | Str | Never => true,
907 // Composite types that satisfy `Eq` when all of their fields do.
909 // Because this function is "shallow", we return `true` for these composites regardless
910 // of the type(s) contained within.
911 Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
913 // Raw pointers use bitwise comparison.
914 RawPtr(_) | FnPtr(_) => true,
916 // Floating point numbers are not `Eq`.
919 // Conservatively return `false` for all others...
921 // Anonymous function types
922 FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
924 // Generic or inferred types
926 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
927 // called for known, fully-monomorphized types.
928 Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
930 Foreign(_) | GeneratorWitness(..) | Error(_) => false,
934 /// Peel off all reference types in this type until there are none left.
936 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
941 /// - `&'a mut u8` -> `u8`
942 /// - `&'a &'b u8` -> `u8`
943 /// - `&'a *const &'b u8 -> *const &'b u8`
944 pub fn peel_refs(self) -> Ty<'tcx> {
946 while let Ref(_, inner_ty, _) = ty.kind() {
952 pub fn outer_exclusive_binder(self) -> DebruijnIndex {
953 self.0.outer_exclusive_binder
957 pub enum ExplicitSelf<'tcx> {
959 ByReference(ty::Region<'tcx>, hir::Mutability),
960 ByRawPointer(hir::Mutability),
965 impl<'tcx> ExplicitSelf<'tcx> {
966 /// Categorizes an explicit self declaration like `self: SomeType`
967 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
969 /// This is mainly used to require the arbitrary_self_types feature
970 /// in the case of `Other`, to improve error messages in the common cases,
971 /// and to make `Other` non-object-safe.
976 /// impl<'a> Foo for &'a T {
977 /// // Legal declarations:
978 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
979 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
980 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
981 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
983 /// // Invalid cases will be caught by `check_method_receiver`:
984 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
985 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
986 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
990 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
992 P: Fn(Ty<'tcx>) -> bool,
994 use self::ExplicitSelf::*;
996 match *self_arg_ty.kind() {
997 _ if is_self_ty(self_arg_ty) => ByValue,
998 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
999 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
1000 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1006 /// Returns a list of types such that the given type needs drop if and only if
1007 /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1008 /// this type always needs drop.
1009 pub fn needs_drop_components<'tcx>(
1011 target_layout: &TargetDataLayout,
1012 ) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1014 ty::Infer(ty::FreshIntTy(_))
1015 | ty::Infer(ty::FreshFloatTy(_))
1024 | ty::GeneratorWitness(..)
1027 | ty::Str => Ok(SmallVec::new()),
1029 // Foreign types can never have destructors.
1030 ty::Foreign(..) => Ok(SmallVec::new()),
1032 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
1034 ty::Slice(ty) => needs_drop_components(*ty, target_layout),
1035 ty::Array(elem_ty, size) => {
1036 match needs_drop_components(*elem_ty, target_layout) {
1037 Ok(v) if v.is_empty() => Ok(v),
1038 res => match size.val().try_to_bits(target_layout.pointer_size) {
1039 // Arrays of size zero don't need drop, even if their element
1041 Some(0) => Ok(SmallVec::new()),
1043 // We don't know which of the cases above we are in, so
1044 // return the whole type and let the caller decide what to
1046 None => Ok(smallvec![ty]),
1050 // If any field needs drop, then the whole tuple does.
1051 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1052 acc.extend(needs_drop_components(elem, target_layout)?);
1056 // These require checking for `Copy` bounds or `Adt` destructors.
1058 | ty::Projection(..)
1061 | ty::Placeholder(..)
1065 | ty::Generator(..) => Ok(smallvec![ty]),
1069 pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool {
1076 | ty::Infer(ty::IntVar(_))
1077 | ty::Infer(ty::FloatVar(_))
1084 | ty::Foreign(_) => true,
1091 | ty::Placeholder(_)
1093 | ty::Infer(_) => false,
1095 // Not trivial because they have components, and instead of looking inside,
1096 // we'll just perform trait selection.
1097 ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false,
1099 ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty),
1101 ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty)),
1105 // Does the equivalent of
1107 // let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1108 // folder.tcx().intern_*(&v)
1110 pub fn fold_list<'tcx, F, T>(
1111 list: &'tcx ty::List<T>,
1113 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
1114 ) -> Result<&'tcx ty::List<T>, F::Error>
1116 F: FallibleTypeFolder<'tcx>,
1117 T: TypeFoldable<'tcx> + PartialEq + Copy,
1119 let mut iter = list.iter();
1120 // Look for the first element that changed
1121 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1122 Ok(new_t) if new_t == t => None,
1123 new_t => Some((i, new_t)),
1125 Some((i, Ok(new_t))) => {
1126 // An element changed, prepare to intern the resulting list
1127 let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1128 new_list.extend_from_slice(&list[..i]);
1129 new_list.push(new_t);
1131 new_list.push(t.try_fold_with(folder)?)
1133 Ok(intern(folder.tcx(), &new_list))
1135 Some((_, Err(err))) => {
1142 #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1143 pub struct AlwaysRequiresDrop;
1145 /// Normalizes all opaque types in the given value, replacing them
1146 /// with their underlying types.
1147 pub fn normalize_opaque_types<'tcx>(
1149 val: &'tcx List<ty::Predicate<'tcx>>,
1150 ) -> &'tcx List<ty::Predicate<'tcx>> {
1151 let mut visitor = OpaqueTypeExpander {
1152 seen_opaque_tys: FxHashSet::default(),
1153 expanded_cache: FxHashMap::default(),
1154 primary_def_id: None,
1155 found_recursion: false,
1156 found_any_recursion: false,
1157 check_recursion: false,
1160 val.fold_with(&mut visitor)
1163 /// Determines whether an item is annotated with `doc(hidden)`.
1164 pub fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1165 tcx.get_attrs(def_id)
1167 .filter_map(|attr| if attr.has_name(sym::doc) { attr.meta_item_list() } else { None })
1168 .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1171 pub fn provide(providers: &mut ty::query::Providers) {
1172 *providers = ty::query::Providers { normalize_opaque_types, is_doc_hidden, ..*providers }