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_span::{sym, DUMMY_SP};
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 {
35 match *self.ty.kind() {
37 let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
39 // sign extend the raw representation to be an i128
40 let x = size.sign_extend(x) as i128;
43 _ => write!(fmt, "{}", self.val),
48 fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) {
49 let (int, signed) = match *ty.kind() {
50 Int(ity) => (Integer::from_int_ty(&tcx, ity), true),
51 Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false),
52 _ => bug!("non integer discriminant"),
57 impl<'tcx> Discr<'tcx> {
58 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
59 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
60 self.checked_add(tcx, 1).0
62 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
63 let (size, signed) = int_size_and_signed(tcx, self.ty);
64 let (val, oflo) = if signed {
65 let min = size.signed_int_min();
66 let max = size.signed_int_max();
67 let val = size.sign_extend(self.val) as i128;
68 assert!(n < (i128::MAX as u128));
70 let oflo = val > max - n;
71 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
72 // zero the upper bits
73 let val = val as u128;
74 let val = size.truncate(val);
77 let max = size.unsigned_int_max();
79 let oflo = val > max - n;
80 let val = if oflo { n - (max - val) - 1 } else { val + n };
83 (Self { val, ty: self.ty }, oflo)
87 pub trait IntTypeExt {
88 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>;
89 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>>;
90 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>;
93 impl IntTypeExt for attr::IntType {
94 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
96 SignedInt(ast::IntTy::I8) => tcx.types.i8,
97 SignedInt(ast::IntTy::I16) => tcx.types.i16,
98 SignedInt(ast::IntTy::I32) => tcx.types.i32,
99 SignedInt(ast::IntTy::I64) => tcx.types.i64,
100 SignedInt(ast::IntTy::I128) => tcx.types.i128,
101 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
102 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
103 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
104 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
105 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
106 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
107 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
111 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
112 Discr { val: 0, ty: self.to_ty(tcx) }
115 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
116 if let Some(val) = val {
117 assert_eq!(self.to_ty(tcx), val.ty);
118 let (new, oflo) = val.checked_add(tcx, 1);
119 if oflo { None } else { Some(new) }
121 Some(self.initial_discriminant(tcx))
126 impl<'tcx> TyCtxt<'tcx> {
127 /// Creates a hash of the type `Ty` which will be the same no matter what crate
128 /// context it's calculated within. This is used by the `type_id` intrinsic.
129 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
130 let mut hasher = StableHasher::new();
131 let mut hcx = self.create_stable_hashing_context();
133 // We want the type_id be independent of the types free regions, so we
134 // erase them. The erase_regions() call will also anonymize bound
135 // regions, which is desirable too.
136 let ty = self.erase_regions(ty);
138 hcx.while_hashing_spans(false, |hcx| ty.hash_stable(hcx, &mut hasher));
142 pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
144 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
145 Some(self.parent(def_id).and_then(|def_id| self.parent(def_id)).unwrap())
147 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
148 Some(self.parent(def_id).unwrap())
150 // Other `DefKind`s don't have generics and would ICE when calling
160 | DefKind::TraitAlias
164 | DefKind::AssocConst
173 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
174 if let ty::Adt(def, substs) = *ty.kind() {
175 for field in def.all_fields() {
176 let field_ty = field.ty(self, substs);
177 if let Error(_) = field_ty.kind() {
185 /// Attempts to returns the deeply last field of nested structures, but
186 /// does not apply any normalization in its search. Returns the same type
187 /// if input `ty` is not a structure at all.
188 pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> {
190 tcx.struct_tail_with_normalize(ty, |ty| ty)
193 /// Returns the deeply last field of nested structures, or the same type if
194 /// not a structure at all. Corresponds to the only possible unsized field,
195 /// and its type can be used to determine unsizing strategy.
197 /// Should only be called if `ty` has no inference variables and does not
198 /// need its lifetimes preserved (e.g. as part of codegen); otherwise
199 /// normalization attempt may cause compiler bugs.
200 pub fn struct_tail_erasing_lifetimes(
203 param_env: ty::ParamEnv<'tcx>,
206 tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty))
209 /// Returns the deeply last field of nested structures, or the same type if
210 /// not a structure at all. Corresponds to the only possible unsized field,
211 /// and its type can be used to determine unsizing strategy.
213 /// This is parameterized over the normalization strategy (i.e. how to
214 /// handle `<T as Trait>::Assoc` and `impl Trait`); pass the identity
215 /// function to indicate no normalization should take place.
217 /// See also `struct_tail_erasing_lifetimes`, which is suitable for use
219 pub fn struct_tail_with_normalize(
222 mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
224 let recursion_limit = self.recursion_limit();
225 for iteration in 0.. {
226 if !recursion_limit.value_within_limit(iteration) {
227 return self.ty_error_with_message(
229 &format!("reached the recursion limit finding the struct tail for {}", ty),
233 ty::Adt(def, substs) => {
234 if !def.is_struct() {
237 match def.non_enum_variant().fields.last() {
238 Some(f) => ty = f.ty(self, substs),
243 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
247 ty::Tuple(_) => break,
249 ty::Projection(_) | ty::Opaque(..) => {
250 let normalized = normalize(ty);
251 if ty == normalized {
266 /// Same as applying `struct_tail` on `source` and `target`, but only
267 /// keeps going as long as the two types are instances of the same
268 /// structure definitions.
269 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
270 /// whereas struct_tail produces `T`, and `Trait`, respectively.
272 /// Should only be called if the types have no inference variables and do
273 /// not need their lifetimes preserved (e.g., as part of codegen); otherwise,
274 /// normalization attempt may cause compiler bugs.
275 pub fn struct_lockstep_tails_erasing_lifetimes(
279 param_env: ty::ParamEnv<'tcx>,
280 ) -> (Ty<'tcx>, Ty<'tcx>) {
282 tcx.struct_lockstep_tails_with_normalize(source, target, |ty| {
283 tcx.normalize_erasing_regions(param_env, ty)
287 /// Same as applying `struct_tail` on `source` and `target`, but only
288 /// keeps going as long as the two types are instances of the same
289 /// structure definitions.
290 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
291 /// whereas struct_tail produces `T`, and `Trait`, respectively.
293 /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use
295 pub fn struct_lockstep_tails_with_normalize(
299 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
300 ) -> (Ty<'tcx>, Ty<'tcx>) {
301 let (mut a, mut b) = (source, target);
303 match (&a.kind(), &b.kind()) {
304 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
305 if a_def == b_def && a_def.is_struct() =>
307 if let Some(f) = a_def.non_enum_variant().fields.last() {
308 a = f.ty(self, a_substs);
309 b = f.ty(self, b_substs);
314 (&Tuple(a_tys), &Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
315 if let Some(&a_last) = a_tys.last() {
317 b = *b_tys.last().unwrap();
322 (ty::Projection(_) | ty::Opaque(..), _)
323 | (_, ty::Projection(_) | ty::Opaque(..)) => {
324 // If either side is a projection, attempt to
325 // progress via normalization. (Should be safe to
326 // apply to both sides as normalization is
328 let a_norm = normalize(a);
329 let b_norm = normalize(b);
330 if a == a_norm && b == b_norm {
344 /// Calculate the destructor of a given type.
345 pub fn calculate_dtor(
348 validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
349 ) -> Option<ty::Destructor> {
350 let drop_trait = self.lang_items().drop_trait()?;
351 self.ensure().coherent_trait(drop_trait);
353 let ty = self.type_of(adt_did);
354 let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| {
355 if let Some(item_id) = self.associated_item_def_ids(impl_did).first() {
356 if validate(self, impl_did).is_ok() {
357 return Some((*item_id, self.impl_constness(impl_did)));
363 Some(ty::Destructor { did, constness })
366 /// Returns the set of types that are required to be alive in
367 /// order to run the destructor of `def` (see RFCs 769 and
370 /// Note that this returns only the constraints for the
371 /// destructor of `def` itself. For the destructors of the
372 /// contents, you need `adt_dtorck_constraint`.
373 pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::subst::GenericArg<'tcx>> {
374 let dtor = match def.destructor(self) {
376 debug!("destructor_constraints({:?}) - no dtor", def.did());
379 Some(dtor) => dtor.did,
382 let impl_def_id = self.associated_item(dtor).container.id();
383 let impl_generics = self.generics_of(impl_def_id);
385 // We have a destructor - all the parameters that are not
386 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
389 // We need to return the list of parameters from the ADTs
390 // generics/substs that correspond to impure parameters on the
391 // impl's generics. This is a bit ugly, but conceptually simple:
393 // Suppose our ADT looks like the following
395 // struct S<X, Y, Z>(X, Y, Z);
399 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
401 // We want to return the parameters (X, Y). For that, we match
402 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
403 // <P1, P2, P0>, and then look up which of the impl substs refer to
404 // parameters marked as pure.
406 let impl_substs = match *self.type_of(impl_def_id).kind() {
407 ty::Adt(def_, substs) if def_ == def => substs,
411 let item_substs = match *self.type_of(def.did()).kind() {
412 ty::Adt(def_, substs) if def_ == def => substs,
416 let result = iter::zip(item_substs, impl_substs)
419 GenericArgKind::Lifetime(region) => match region.kind() {
420 ReEarlyBound(ref ebr) => {
421 !impl_generics.region_param(ebr, self).pure_wrt_drop
423 // Error: not a region param
426 GenericArgKind::Type(ty) => match ty.kind() {
427 ty::Param(ref pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
428 // Error: not a type param
431 GenericArgKind::Const(ct) => match ct.val() {
432 ty::ConstKind::Param(ref pc) => {
433 !impl_generics.const_param(pc, self).pure_wrt_drop
435 // Error: not a const param
440 .map(|(item_param, _)| item_param)
442 debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
446 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
447 /// that closures have a `DefId`, but the closure *expression* also
448 /// has a `HirId` that is located within the context where the
449 /// closure appears (and, sadly, a corresponding `NodeId`, since
450 /// those are not yet phased out). The parent of the closure's
451 /// `DefId` will also be the context where it appears.
452 pub fn is_closure(self, def_id: DefId) -> bool {
453 matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator)
456 /// Returns `true` if `def_id` refers to a definition that does not have its own
457 /// type-checking context, i.e. closure, generator or inline const.
458 pub fn is_typeck_child(self, def_id: DefId) -> bool {
460 self.def_kind(def_id),
461 DefKind::Closure | DefKind::Generator | DefKind::InlineConst
465 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
466 pub fn is_trait(self, def_id: DefId) -> bool {
467 self.def_kind(def_id) == DefKind::Trait
470 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
471 /// and `false` otherwise.
472 pub fn is_trait_alias(self, def_id: DefId) -> bool {
473 self.def_kind(def_id) == DefKind::TraitAlias
476 /// Returns `true` if this `DefId` refers to the implicit constructor for
477 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
478 pub fn is_constructor(self, def_id: DefId) -> bool {
479 matches!(self.def_kind(def_id), DefKind::Ctor(..))
482 /// Given the `DefId`, returns the `DefId` of the innermost item that
483 /// has its own type-checking context or "inference environment".
485 /// For example, a closure has its own `DefId`, but it is type-checked
486 /// with the containing item. Similarly, an inline const block has its
487 /// own `DefId` but it is type-checked together with the containing item.
489 /// Therefore, when we fetch the
490 /// `typeck` the closure, for example, we really wind up
491 /// fetching the `typeck` the enclosing fn item.
492 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
493 let mut def_id = def_id;
494 while self.is_typeck_child(def_id) {
495 def_id = self.parent(def_id).unwrap_or_else(|| {
496 bug!("closure {:?} has no parent", def_id);
502 /// Given the `DefId` and substs a closure, creates the type of
503 /// `self` argument that the closure expects. For example, for a
504 /// `Fn` closure, this would return a reference type `&T` where
505 /// `T = closure_ty`.
507 /// Returns `None` if this closure's kind has not yet been inferred.
508 /// This should only be possible during type checking.
510 /// Note that the return value is a late-bound region and hence
511 /// wrapped in a binder.
512 pub fn closure_env_ty(
514 closure_def_id: DefId,
515 closure_substs: SubstsRef<'tcx>,
516 env_region: ty::RegionKind,
517 ) -> Option<Ty<'tcx>> {
518 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
519 let closure_kind_ty = closure_substs.as_closure().kind_ty();
520 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
521 let env_ty = match closure_kind {
522 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
523 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
524 ty::ClosureKind::FnOnce => closure_ty,
529 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
531 pub fn is_static(self, def_id: DefId) -> bool {
532 matches!(self.def_kind(def_id), DefKind::Static(_))
536 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
537 if let DefKind::Static(mt) = self.def_kind(def_id) { Some(mt) } else { None }
540 /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute.
541 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
542 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
545 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
547 pub fn is_mutable_static(self, def_id: DefId) -> bool {
548 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
551 /// Get the type of the pointer to the static that we use in MIR.
552 pub fn static_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
553 // Make sure that any constants in the static's type are evaluated.
554 let static_ty = self.normalize_erasing_regions(ty::ParamEnv::empty(), self.type_of(def_id));
556 // Make sure that accesses to unsafe statics end up using raw pointers.
557 // For thread-locals, this needs to be kept in sync with `Rvalue::ty`.
558 if self.is_mutable_static(def_id) {
559 self.mk_mut_ptr(static_ty)
560 } else if self.is_foreign_item(def_id) {
561 self.mk_imm_ptr(static_ty)
563 self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
567 /// Expands the given impl trait type, stopping if the type is recursive.
568 #[instrument(skip(self), level = "debug")]
569 pub fn try_expand_impl_trait_type(
572 substs: SubstsRef<'tcx>,
573 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
574 let mut visitor = OpaqueTypeExpander {
575 seen_opaque_tys: FxHashSet::default(),
576 expanded_cache: FxHashMap::default(),
577 primary_def_id: Some(def_id),
578 found_recursion: false,
579 found_any_recursion: false,
580 check_recursion: true,
584 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
585 trace!(?expanded_type);
586 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
590 struct OpaqueTypeExpander<'tcx> {
591 // Contains the DefIds of the opaque types that are currently being
592 // expanded. When we expand an opaque type we insert the DefId of
593 // that type, and when we finish expanding that type we remove the
595 seen_opaque_tys: FxHashSet<DefId>,
596 // Cache of all expansions we've seen so far. This is a critical
597 // optimization for some large types produced by async fn trees.
598 expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>,
599 primary_def_id: Option<DefId>,
600 found_recursion: bool,
601 found_any_recursion: bool,
602 /// Whether or not to check for recursive opaque types.
603 /// This is `true` when we're explicitly checking for opaque type
604 /// recursion, and 'false' otherwise to avoid unnecessary work.
605 check_recursion: bool,
609 impl<'tcx> OpaqueTypeExpander<'tcx> {
610 fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> {
611 if self.found_any_recursion {
614 let substs = substs.fold_with(self);
615 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
616 let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) {
617 Some(expanded_ty) => *expanded_ty,
619 let generic_ty = self.tcx.type_of(def_id);
620 let concrete_ty = generic_ty.subst(self.tcx, substs);
621 let expanded_ty = self.fold_ty(concrete_ty);
622 self.expanded_cache.insert((def_id, substs), expanded_ty);
626 if self.check_recursion {
627 self.seen_opaque_tys.remove(&def_id);
631 // If another opaque type that we contain is recursive, then it
632 // will report the error, so we don't have to.
633 self.found_any_recursion = true;
634 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
640 impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> {
641 fn tcx(&self) -> TyCtxt<'tcx> {
645 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
646 if let ty::Opaque(def_id, substs) = *t.kind() {
647 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
648 } else if t.has_opaque_types() {
649 t.super_fold_with(self)
656 impl<'tcx> Ty<'tcx> {
657 /// Returns the maximum value for the given numeric type (including `char`s)
658 /// or returns `None` if the type is not numeric.
659 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<Const<'tcx>> {
660 let val = match self.kind() {
661 ty::Int(_) | ty::Uint(_) => {
662 let (size, signed) = int_size_and_signed(tcx, self);
664 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
667 ty::Char => Some(std::char::MAX as u128),
668 ty::Float(fty) => Some(match fty {
669 ty::FloatTy::F32 => rustc_apfloat::ieee::Single::INFINITY.to_bits(),
670 ty::FloatTy::F64 => rustc_apfloat::ieee::Double::INFINITY.to_bits(),
674 val.map(|v| Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
677 /// Returns the minimum value for the given numeric type (including `char`s)
678 /// or returns `None` if the type is not numeric.
679 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<Const<'tcx>> {
680 let val = match self.kind() {
681 ty::Int(_) | ty::Uint(_) => {
682 let (size, signed) = int_size_and_signed(tcx, self);
683 let val = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
687 ty::Float(fty) => Some(match fty {
688 ty::FloatTy::F32 => (-::rustc_apfloat::ieee::Single::INFINITY).to_bits(),
689 ty::FloatTy::F64 => (-::rustc_apfloat::ieee::Double::INFINITY).to_bits(),
693 val.map(|v| Const::from_bits(tcx, v, ty::ParamEnv::empty().and(self)))
696 /// Checks whether values of this type `T` are *moved* or *copied*
697 /// when referenced -- this amounts to a check for whether `T:
698 /// Copy`, but note that we **don't** consider lifetimes when
699 /// doing this check. This means that we may generate MIR which
700 /// does copies even when the type actually doesn't satisfy the
701 /// full requirements for the `Copy` trait (cc #29149) -- this
702 /// winds up being reported as an error during NLL borrow check.
703 pub fn is_copy_modulo_regions(
705 tcx_at: TyCtxtAt<'tcx>,
706 param_env: ty::ParamEnv<'tcx>,
708 self.is_trivially_pure_clone_copy() || tcx_at.is_copy_raw(param_env.and(self))
711 /// Checks whether values of this type `T` have a size known at
712 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
713 /// for the purposes of this check, so it can be an
714 /// over-approximation in generic contexts, where one can have
715 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
716 /// actually carry lifetime requirements.
717 pub fn is_sized(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
718 self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self))
721 /// Checks whether values of this type `T` implement the `Freeze`
722 /// trait -- frozen types are those that do not contain an
723 /// `UnsafeCell` anywhere. This is a language concept used to
724 /// distinguish "true immutability", which is relevant to
725 /// optimization as well as the rules around static values. Note
726 /// that the `Freeze` trait is not exposed to end users and is
727 /// effectively an implementation detail.
728 pub fn is_freeze(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
729 self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
732 /// Fast path helper for testing if a type is `Freeze`.
734 /// Returning true means the type is known to be `Freeze`. Returning
735 /// `false` means nothing -- could be `Freeze`, might not be.
736 fn is_trivially_freeze(self) -> bool {
749 | ty::FnPtr(_) => true,
750 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
751 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_freeze(),
758 | ty::GeneratorWitness(_)
763 | ty::Projection(_) => false,
767 /// Checks whether values of this type `T` implement the `Unpin` trait.
768 pub fn is_unpin(self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
769 self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self))
772 /// Fast path helper for testing if a type is `Unpin`.
774 /// Returning true means the type is known to be `Unpin`. Returning
775 /// `false` means nothing -- could be `Unpin`, might not be.
776 fn is_trivially_unpin(self) -> bool {
789 | ty::FnPtr(_) => true,
790 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
791 ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(),
798 | ty::GeneratorWitness(_)
803 | ty::Projection(_) => false,
807 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
808 /// non-copy and *might* have a destructor attached; if it returns
809 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
811 /// (Note that this implies that if `ty` has a destructor attached,
812 /// then `needs_drop` will definitely return `true` for `ty`.)
814 /// Note that this method is used to check eligible types in unions.
816 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
817 // Avoid querying in simple cases.
818 match needs_drop_components(self, &tcx.data_layout) {
819 Err(AlwaysRequiresDrop) => true,
821 let query_ty = match *components {
823 // If we've got a single component, call the query with that
824 // to increase the chance that we hit the query cache.
825 [component_ty] => component_ty,
829 // This doesn't depend on regions, so try to minimize distinct
831 // If normalization fails, we just use `query_ty`.
833 tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty);
835 tcx.needs_drop_raw(param_env.and(query_ty))
840 /// Checks if `ty` has has a significant drop.
842 /// Note that this method can return false even if `ty` has a destructor
843 /// attached; even if that is the case then the adt has been marked with
844 /// the attribute `rustc_insignificant_dtor`.
846 /// Note that this method is used to check for change in drop order for
847 /// 2229 drop reorder migration analysis.
849 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
850 // Avoid querying in simple cases.
851 match needs_drop_components(self, &tcx.data_layout) {
852 Err(AlwaysRequiresDrop) => true,
854 let query_ty = match *components {
856 // If we've got a single component, call the query with that
857 // to increase the chance that we hit the query cache.
858 [component_ty] => component_ty,
862 // FIXME(#86868): We should be canonicalizing, or else moving this to a method of inference
863 // context, or *something* like that, but for now just avoid passing inference
864 // variables to queries that can't cope with them. Instead, conservatively
865 // return "true" (may change drop order).
866 if query_ty.needs_infer() {
870 // This doesn't depend on regions, so try to minimize distinct
872 let erased = tcx.normalize_erasing_regions(param_env, query_ty);
873 tcx.has_significant_drop_raw(param_env.and(erased))
878 /// Returns `true` if equality for this type is both reflexive and structural.
880 /// Reflexive equality for a type is indicated by an `Eq` impl for that type.
882 /// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
883 /// types, equality for the type as a whole is structural when it is the same as equality
884 /// between all components (fields, array elements, etc.) of that type. For ADTs, structural
885 /// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
888 /// This function is "shallow" because it may return `true` for a composite type whose fields
889 /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
890 /// because equality for arrays is determined by the equality of each array element. If you
891 /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
892 /// down, you will need to use a type visitor.
894 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
896 // Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
897 Adt(..) => tcx.has_structural_eq_impls(self),
899 // Primitive types that satisfy `Eq`.
900 Bool | Char | Int(_) | Uint(_) | Str | Never => true,
902 // Composite types that satisfy `Eq` when all of their fields do.
904 // Because this function is "shallow", we return `true` for these composites regardless
905 // of the type(s) contained within.
906 Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
908 // Raw pointers use bitwise comparison.
909 RawPtr(_) | FnPtr(_) => true,
911 // Floating point numbers are not `Eq`.
914 // Conservatively return `false` for all others...
916 // Anonymous function types
917 FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
919 // Generic or inferred types
921 // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
922 // called for known, fully-monomorphized types.
923 Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
925 Foreign(_) | GeneratorWitness(..) | Error(_) => false,
929 /// Peel off all reference types in this type until there are none left.
931 /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`.
936 /// - `&'a mut u8` -> `u8`
937 /// - `&'a &'b u8` -> `u8`
938 /// - `&'a *const &'b u8 -> *const &'b u8`
939 pub fn peel_refs(self) -> Ty<'tcx> {
941 while let Ref(_, inner_ty, _) = ty.kind() {
947 pub fn outer_exclusive_binder(self) -> DebruijnIndex {
948 self.0.outer_exclusive_binder
952 pub enum ExplicitSelf<'tcx> {
954 ByReference(ty::Region<'tcx>, hir::Mutability),
955 ByRawPointer(hir::Mutability),
960 impl<'tcx> ExplicitSelf<'tcx> {
961 /// Categorizes an explicit self declaration like `self: SomeType`
962 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
964 /// This is mainly used to require the arbitrary_self_types feature
965 /// in the case of `Other`, to improve error messages in the common cases,
966 /// and to make `Other` non-object-safe.
971 /// impl<'a> Foo for &'a T {
972 /// // Legal declarations:
973 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
974 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
975 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
976 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
978 /// // Invalid cases will be caught by `check_method_receiver`:
979 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
980 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
981 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
985 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
987 P: Fn(Ty<'tcx>) -> bool,
989 use self::ExplicitSelf::*;
991 match *self_arg_ty.kind() {
992 _ if is_self_ty(self_arg_ty) => ByValue,
993 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
994 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => ByRawPointer(mutbl),
995 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => ByBox,
1001 /// Returns a list of types such that the given type needs drop if and only if
1002 /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if
1003 /// this type always needs drop.
1004 pub fn needs_drop_components<'tcx>(
1006 target_layout: &TargetDataLayout,
1007 ) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1009 ty::Infer(ty::FreshIntTy(_))
1010 | ty::Infer(ty::FreshFloatTy(_))
1019 | ty::GeneratorWitness(..)
1022 | ty::Str => Ok(SmallVec::new()),
1024 // Foreign types can never have destructors.
1025 ty::Foreign(..) => Ok(SmallVec::new()),
1027 ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop),
1029 ty::Slice(ty) => needs_drop_components(*ty, target_layout),
1030 ty::Array(elem_ty, size) => {
1031 match needs_drop_components(*elem_ty, target_layout) {
1032 Ok(v) if v.is_empty() => Ok(v),
1033 res => match size.val().try_to_bits(target_layout.pointer_size) {
1034 // Arrays of size zero don't need drop, even if their element
1036 Some(0) => Ok(SmallVec::new()),
1038 // We don't know which of the cases above we are in, so
1039 // return the whole type and let the caller decide what to
1041 None => Ok(smallvec![ty]),
1045 // If any field needs drop, then the whole tuple does.
1046 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1047 acc.extend(needs_drop_components(elem, target_layout)?);
1051 // These require checking for `Copy` bounds or `Adt` destructors.
1053 | ty::Projection(..)
1056 | ty::Placeholder(..)
1060 | ty::Generator(..) => Ok(smallvec![ty]),
1064 pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool {
1071 | ty::Infer(ty::IntVar(_))
1072 | ty::Infer(ty::FloatVar(_))
1079 | ty::Foreign(_) => true,
1086 | ty::Placeholder(_)
1088 | ty::Infer(_) => false,
1090 // Not trivial because they have components, and instead of looking inside,
1091 // we'll just perform trait selection.
1092 ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false,
1094 ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty),
1096 ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty)),
1100 // Does the equivalent of
1102 // let v = self.iter().map(|p| p.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
1103 // folder.tcx().intern_*(&v)
1105 pub fn fold_list<'tcx, F, T>(
1106 list: &'tcx ty::List<T>,
1108 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List<T>,
1109 ) -> Result<&'tcx ty::List<T>, F::Error>
1111 F: FallibleTypeFolder<'tcx>,
1112 T: TypeFoldable<'tcx> + PartialEq + Copy,
1114 let mut iter = list.iter();
1115 // Look for the first element that changed
1116 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1117 Ok(new_t) if new_t == t => None,
1118 new_t => Some((i, new_t)),
1120 Some((i, Ok(new_t))) => {
1121 // An element changed, prepare to intern the resulting list
1122 let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len());
1123 new_list.extend_from_slice(&list[..i]);
1124 new_list.push(new_t);
1126 new_list.push(t.try_fold_with(folder)?)
1128 Ok(intern(folder.tcx(), &new_list))
1130 Some((_, Err(err))) => {
1137 #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1138 pub struct AlwaysRequiresDrop;
1140 /// Normalizes all opaque types in the given value, replacing them
1141 /// with their underlying types.
1142 pub fn normalize_opaque_types<'tcx>(
1144 val: &'tcx List<ty::Predicate<'tcx>>,
1145 ) -> &'tcx List<ty::Predicate<'tcx>> {
1146 let mut visitor = OpaqueTypeExpander {
1147 seen_opaque_tys: FxHashSet::default(),
1148 expanded_cache: FxHashMap::default(),
1149 primary_def_id: None,
1150 found_recursion: false,
1151 found_any_recursion: false,
1152 check_recursion: false,
1155 val.fold_with(&mut visitor)
1158 /// Determines whether an item is annotated with `doc(hidden)`.
1159 pub fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1160 tcx.get_attrs(def_id)
1162 .filter_map(|attr| if attr.has_name(sym::doc) { attr.meta_item_list() } else { None })
1163 .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1166 pub fn provide(providers: &mut ty::query::Providers) {
1167 *providers = ty::query::Providers { normalize_opaque_types, is_doc_hidden, ..*providers }