1 //! Miscellaneous type-system utilities that are too small to deserve their own modules.
4 use crate::hir::def_id::DefId;
5 use crate::hir::map::DefPathData;
6 use crate::mir::interpret::{sign_extend, truncate};
7 use crate::ich::NodeIdHashingMode;
8 use crate::traits::{self, ObligationCause};
9 use crate::ty::{self, DefIdTree, Ty, TyCtxt, GenericParamDefKind, TypeFoldable};
10 use crate::ty::subst::{Subst, InternalSubsts, SubstsRef, UnpackedKind};
11 use crate::ty::query::TyCtxtAt;
12 use crate::ty::TyKind::*;
13 use crate::ty::layout::{Integer, IntegerExt};
14 use crate::mir::interpret::ConstValue;
15 use crate::util::common::ErrorReported;
16 use crate::middle::lang_items;
18 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use rustc_macros::HashStable;
23 use syntax::attr::{self, SignedInt, UnsignedInt};
24 use syntax_pos::{Span, DUMMY_SP};
26 #[derive(Copy, Clone, Debug)]
27 pub struct Discr<'tcx> {
28 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
33 impl<'tcx> fmt::Display for Discr<'tcx> {
34 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
37 let size = ty::tls::with(|tcx| {
38 Integer::from_attr(&tcx, SignedInt(ity)).size()
41 // sign extend the raw representation to be an i128
42 let x = sign_extend(x, size) as i128;
45 _ => write!(fmt, "{}", self.val),
50 impl<'tcx> Discr<'tcx> {
51 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
52 pub fn wrap_incr<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
53 self.checked_add(tcx, 1).0
55 pub fn checked_add<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, n: u128) -> (Self, bool) {
56 let (int, signed) = match self.ty.sty {
57 Int(ity) => (Integer::from_attr(&tcx, SignedInt(ity)), true),
58 Uint(uty) => (Integer::from_attr(&tcx, UnsignedInt(uty)), false),
59 _ => bug!("non integer discriminant"),
62 let size = int.size();
63 let bit_size = int.size().bits();
64 let shift = 128 - bit_size;
67 sign_extend(u, size) as i128
69 let min = sext(1_u128 << (bit_size - 1));
70 let max = i128::max_value() >> shift;
71 let val = sext(self.val);
72 assert!(n < (i128::max_value() as u128));
74 let oflo = val > max - n;
76 min + (n - (max - val) - 1)
80 // zero the upper bits
81 let val = val as u128;
82 let val = truncate(val, size);
88 let max = u128::max_value() >> shift;
90 let oflo = val > max - n;
104 pub trait IntTypeExt {
105 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
106 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Discr<'tcx>>)
107 -> Option<Discr<'tcx>>;
108 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx>;
111 impl IntTypeExt for attr::IntType {
112 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
114 SignedInt(ast::IntTy::I8) => tcx.types.i8,
115 SignedInt(ast::IntTy::I16) => tcx.types.i16,
116 SignedInt(ast::IntTy::I32) => tcx.types.i32,
117 SignedInt(ast::IntTy::I64) => tcx.types.i64,
118 SignedInt(ast::IntTy::I128) => tcx.types.i128,
119 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
120 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
121 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
122 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
123 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
124 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
125 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
129 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx> {
136 fn disr_incr<'a, 'tcx>(
138 tcx: TyCtxt<'a, 'tcx, 'tcx>,
139 val: Option<Discr<'tcx>>,
140 ) -> Option<Discr<'tcx>> {
141 if let Some(val) = val {
142 assert_eq!(self.to_ty(tcx), val.ty);
143 let (new, oflo) = val.checked_add(tcx, 1);
150 Some(self.initial_discriminant(tcx))
157 pub enum CopyImplementationError<'tcx> {
158 InfrigingFields(Vec<&'tcx ty::FieldDef>),
163 /// Describes whether a type is representable. For types that are not
164 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
165 /// distinguish between types that are recursive with themselves and types that
166 /// contain a different recursive type. These cases can therefore be treated
167 /// differently when reporting errors.
169 /// The ordering of the cases is significant. They are sorted so that cmp::max
170 /// will keep the "more erroneous" of two values.
171 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
172 pub enum Representability {
175 SelfRecursive(Vec<Span>),
178 impl<'tcx> ty::ParamEnv<'tcx> {
179 pub fn can_type_implement_copy<'a>(self,
180 tcx: TyCtxt<'a, 'tcx, 'tcx>,
182 -> Result<(), CopyImplementationError<'tcx>> {
183 // FIXME: (@jroesch) float this code up
184 tcx.infer_ctxt().enter(|infcx| {
185 let (adt, substs) = match self_type.sty {
186 // These types used to have a builtin impl.
187 // Now libcore provides that impl.
188 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
189 ty::Char | ty::RawPtr(..) | ty::Never |
190 ty::Ref(_, _, hir::MutImmutable) => return Ok(()),
192 ty::Adt(adt, substs) => (adt, substs),
194 _ => return Err(CopyImplementationError::NotAnAdt),
197 let mut infringing = Vec::new();
198 for variant in &adt.variants {
199 for field in &variant.fields {
200 let ty = field.ty(tcx, substs);
201 if ty.references_error() {
204 let span = tcx.def_span(field.did);
205 let cause = ObligationCause { span, ..ObligationCause::dummy() };
206 let ctx = traits::FulfillmentContext::new();
207 match traits::fully_normalize(&infcx, ctx, cause, self, &ty) {
208 Ok(ty) => if !infcx.type_is_copy_modulo_regions(self, ty, span) {
209 infringing.push(field);
212 infcx.report_fulfillment_errors(&errors, None, false);
217 if !infringing.is_empty() {
218 return Err(CopyImplementationError::InfrigingFields(infringing));
220 if adt.has_dtor(tcx) {
221 return Err(CopyImplementationError::HasDestructor);
229 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
230 /// Creates a hash of the type `Ty` which will be the same no matter what crate
231 /// context it's calculated within. This is used by the `type_id` intrinsic.
232 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
233 let mut hasher = StableHasher::new();
234 let mut hcx = self.create_stable_hashing_context();
236 // We want the type_id be independent of the types free regions, so we
237 // erase them. The erase_regions() call will also anonymize bound
238 // regions, which is desirable too.
239 let ty = self.erase_regions(&ty);
241 hcx.while_hashing_spans(false, |hcx| {
242 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
243 ty.hash_stable(hcx, &mut hasher);
250 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
251 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
252 if let ty::Adt(def, substs) = ty.sty {
253 for field in def.all_fields() {
254 let field_ty = field.ty(self, substs);
255 if let Error = field_ty.sty {
263 /// Returns the deeply last field of nested structures, or the same type,
264 /// if not a structure at all. Corresponds to the only possible unsized
265 /// field, and its type can be used to determine unsizing strategy.
266 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
269 ty::Adt(def, substs) => {
270 if !def.is_struct() {
273 match def.non_enum_variant().fields.last() {
274 Some(f) => ty = f.ty(self, substs),
280 if let Some((&last_ty, _)) = tys.split_last() {
295 /// Same as applying struct_tail on `source` and `target`, but only
296 /// keeps going as long as the two types are instances of the same
297 /// structure definitions.
298 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
299 /// whereas struct_tail produces `T`, and `Trait`, respectively.
300 pub fn struct_lockstep_tails(self,
303 -> (Ty<'tcx>, Ty<'tcx>) {
304 let (mut a, mut b) = (source, target);
306 match (&a.sty, &b.sty) {
307 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
308 if a_def == b_def && a_def.is_struct() => {
309 if let Some(f) = a_def.non_enum_variant().fields.last() {
310 a = f.ty(self, a_substs);
311 b = f.ty(self, b_substs);
316 (&Tuple(a_tys), &Tuple(b_tys))
317 if a_tys.len() == b_tys.len() => {
318 if let Some(a_last) = a_tys.last() {
320 b = b_tys.last().unwrap();
331 /// Given a set of predicates that apply to an object type, returns
332 /// the region bounds that the (erased) `Self` type must
333 /// outlive. Precisely *because* the `Self` type is erased, the
334 /// parameter `erased_self_ty` must be supplied to indicate what type
335 /// has been used to represent `Self` in the predicates
336 /// themselves. This should really be a unique type; `FreshTy(0)` is a
339 /// N.B., in some cases, particularly around higher-ranked bounds,
340 /// this function returns a kind of conservative approximation.
341 /// That is, all regions returned by this function are definitely
342 /// required, but there may be other region bounds that are not
343 /// returned, as well as requirements like `for<'a> T: 'a`.
345 /// Requires that trait definitions have been processed so that we can
346 /// elaborate predicates and walk supertraits.
348 // FIXME: callers may only have a `&[Predicate]`, not a `Vec`, so that's
349 // what this code should accept.
350 pub fn required_region_bounds(self,
351 erased_self_ty: Ty<'tcx>,
352 predicates: Vec<ty::Predicate<'tcx>>)
353 -> Vec<ty::Region<'tcx>> {
354 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
358 assert!(!erased_self_ty.has_escaping_bound_vars());
360 traits::elaborate_predicates(self, predicates)
361 .filter_map(|predicate| {
363 ty::Predicate::Projection(..) |
364 ty::Predicate::Trait(..) |
365 ty::Predicate::Subtype(..) |
366 ty::Predicate::WellFormed(..) |
367 ty::Predicate::ObjectSafe(..) |
368 ty::Predicate::ClosureKind(..) |
369 ty::Predicate::RegionOutlives(..) |
370 ty::Predicate::ConstEvaluatable(..) => {
373 ty::Predicate::TypeOutlives(predicate) => {
374 // Search for a bound of the form `erased_self_ty
375 // : 'a`, but be wary of something like `for<'a>
376 // erased_self_ty : 'a` (we interpret a
377 // higher-ranked bound like that as 'static,
378 // though at present the code in `fulfill.rs`
379 // considers such bounds to be unsatisfiable, so
380 // it's kind of a moot point since you could never
381 // construct such an object, but this seems
382 // correct even if that code changes).
383 let ty::OutlivesPredicate(ref t, ref r) = predicate.skip_binder();
384 if t == &erased_self_ty && !r.has_escaping_bound_vars() {
395 /// Calculate the destructor of a given type.
396 pub fn calculate_dtor(
399 validate: &mut dyn FnMut(Self, DefId) -> Result<(), ErrorReported>
400 ) -> Option<ty::Destructor> {
401 let drop_trait = if let Some(def_id) = self.lang_items().drop_trait() {
407 self.ensure().coherent_trait(drop_trait);
409 let mut dtor_did = None;
410 let ty = self.type_of(adt_did);
411 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
412 if let Some(item) = self.associated_items(impl_did).next() {
413 if validate(self, impl_did).is_ok() {
414 dtor_did = Some(item.def_id);
419 Some(ty::Destructor { did: dtor_did? })
422 /// Returns the set of types that are required to be alive in
423 /// order to run the destructor of `def` (see RFCs 769 and
426 /// Note that this returns only the constraints for the
427 /// destructor of `def` itself. For the destructors of the
428 /// contents, you need `adt_dtorck_constraint`.
429 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
430 -> Vec<ty::subst::Kind<'tcx>>
432 let dtor = match def.destructor(self) {
434 debug!("destructor_constraints({:?}) - no dtor", def.did);
437 Some(dtor) => dtor.did
440 // RFC 1238: if the destructor method is tagged with the
441 // attribute `unsafe_destructor_blind_to_params`, then the
442 // compiler is being instructed to *assume* that the
443 // destructor will not access borrowed data,
444 // even if such data is otherwise reachable.
446 // Such access can be in plain sight (e.g., dereferencing
447 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
448 // (e.g., calling `foo.0.clone()` of `Foo<T:Clone>`).
449 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
450 debug!("destructor_constraint({:?}) - blind", def.did);
454 let impl_def_id = self.associated_item(dtor).container.id();
455 let impl_generics = self.generics_of(impl_def_id);
457 // We have a destructor - all the parameters that are not
458 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
461 // We need to return the list of parameters from the ADTs
462 // generics/substs that correspond to impure parameters on the
463 // impl's generics. This is a bit ugly, but conceptually simple:
465 // Suppose our ADT looks like the following
467 // struct S<X, Y, Z>(X, Y, Z);
471 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
473 // We want to return the parameters (X, Y). For that, we match
474 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
475 // <P1, P2, P0>, and then look up which of the impl substs refer to
476 // parameters marked as pure.
478 let impl_substs = match self.type_of(impl_def_id).sty {
479 ty::Adt(def_, substs) if def_ == def => substs,
483 let item_substs = match self.type_of(def.did).sty {
484 ty::Adt(def_, substs) if def_ == def => substs,
488 let result = item_substs.iter().zip(impl_substs.iter())
491 UnpackedKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
492 !impl_generics.region_param(ebr, self).pure_wrt_drop
494 UnpackedKind::Type(&ty::TyS {
495 sty: ty::Param(ref pt), ..
497 !impl_generics.type_param(pt, self).pure_wrt_drop
499 UnpackedKind::Const(&ty::Const {
500 val: ConstValue::Param(ref pc),
503 !impl_generics.const_param(pc, self).pure_wrt_drop
505 UnpackedKind::Lifetime(_) |
506 UnpackedKind::Type(_) |
507 UnpackedKind::Const(_) => {
508 // Not a type, const or region param: this should be reported
514 .map(|(&item_param, _)| item_param)
516 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
520 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
521 /// that closures have a `DefId`, but the closure *expression* also
522 /// has a `HirId` that is located within the context where the
523 /// closure appears (and, sadly, a corresponding `NodeId`, since
524 /// those are not yet phased out). The parent of the closure's
525 /// `DefId` will also be the context where it appears.
526 pub fn is_closure(self, def_id: DefId) -> bool {
527 self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr
530 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
531 pub fn is_trait(self, def_id: DefId) -> bool {
532 if let DefPathData::Trait(_) = self.def_key(def_id).disambiguated_data.data {
539 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
540 /// and `false` otherwise.
541 pub fn is_trait_alias(self, def_id: DefId) -> bool {
542 if let DefPathData::TraitAlias(_) = self.def_key(def_id).disambiguated_data.data {
549 /// Returns `true` if this `DefId` refers to the implicit constructor for
550 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
551 pub fn is_constructor(self, def_id: DefId) -> bool {
552 self.def_key(def_id).disambiguated_data.data == DefPathData::Ctor
555 /// Given the `DefId` of a fn or closure, returns the `DefId` of
556 /// the innermost fn item that the closure is contained within.
557 /// This is a significant `DefId` because, when we do
558 /// type-checking, we type-check this fn item and all of its
559 /// (transitive) closures together. Therefore, when we fetch the
560 /// `typeck_tables_of` the closure, for example, we really wind up
561 /// fetching the `typeck_tables_of` the enclosing fn item.
562 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
563 let mut def_id = def_id;
564 while self.is_closure(def_id) {
565 def_id = self.parent(def_id).unwrap_or_else(|| {
566 bug!("closure {:?} has no parent", def_id);
572 /// Given the `DefId` and substs a closure, creates the type of
573 /// `self` argument that the closure expects. For example, for a
574 /// `Fn` closure, this would return a reference type `&T` where
575 /// `T = closure_ty`.
577 /// Returns `None` if this closure's kind has not yet been inferred.
578 /// This should only be possible during type checking.
580 /// Note that the return value is a late-bound region and hence
581 /// wrapped in a binder.
582 pub fn closure_env_ty(self,
583 closure_def_id: DefId,
584 closure_substs: ty::ClosureSubsts<'tcx>)
585 -> Option<ty::Binder<Ty<'tcx>>>
587 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
588 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
589 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self);
590 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
591 let env_ty = match closure_kind {
592 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
593 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
594 ty::ClosureKind::FnOnce => closure_ty,
596 Some(ty::Binder::bind(env_ty))
599 /// Given the `DefId` of some item that has no type or const parameters, make
600 /// a suitable "empty substs" for it.
601 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> SubstsRef<'tcx> {
602 InternalSubsts::for_item(self, item_def_id, |param, _| {
604 GenericParamDefKind::Lifetime => self.types.re_erased.into(),
605 GenericParamDefKind::Type { .. } => {
606 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
608 GenericParamDefKind::Const { .. } => {
609 bug!("empty_substs_for_def_id: {:?} has const parameters", item_def_id)
615 /// Returns `true` if the node pointed to by `def_id` is a `static` item.
616 pub fn is_static(&self, def_id: DefId) -> bool {
617 self.static_mutability(def_id).is_some()
620 /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item.
621 pub fn is_mutable_static(&self, def_id: DefId) -> bool {
622 self.static_mutability(def_id) == Some(hir::MutMutable)
625 /// Expands the given impl trait type, stopping if the type is recursive.
626 pub fn try_expand_impl_trait_type(
629 substs: SubstsRef<'tcx>,
630 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
631 use crate::ty::fold::TypeFolder;
633 struct OpaqueTypeExpander<'a, 'gcx, 'tcx> {
634 // Contains the DefIds of the opaque types that are currently being
635 // expanded. When we expand an opaque type we insert the DefId of
636 // that type, and when we finish expanding that type we remove the
638 seen_opaque_tys: FxHashSet<DefId>,
639 primary_def_id: DefId,
640 found_recursion: bool,
641 tcx: TyCtxt<'a, 'gcx, 'tcx>,
644 impl<'a, 'gcx, 'tcx> OpaqueTypeExpander<'a, 'gcx, 'tcx> {
648 substs: SubstsRef<'tcx>,
649 ) -> Option<Ty<'tcx>> {
650 if self.found_recursion {
652 } else if self.seen_opaque_tys.insert(def_id) {
653 let generic_ty = self.tcx.type_of(def_id);
654 let concrete_ty = generic_ty.subst(self.tcx, substs);
655 let expanded_ty = self.fold_ty(concrete_ty);
656 self.seen_opaque_tys.remove(&def_id);
659 // If another opaque type that we contain is recursive, then it
660 // will report the error, so we don't have to.
661 self.found_recursion = def_id == self.primary_def_id;
667 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for OpaqueTypeExpander<'a, 'gcx, 'tcx> {
668 fn tcx(&self) -> TyCtxt<'_, 'gcx, 'tcx> {
672 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
673 if let ty::Opaque(def_id, substs) = t.sty {
674 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
676 t.super_fold_with(self)
681 let mut visitor = OpaqueTypeExpander {
682 seen_opaque_tys: FxHashSet::default(),
683 primary_def_id: def_id,
684 found_recursion: false,
687 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
688 if visitor.found_recursion {
696 impl<'a, 'tcx> ty::TyS<'tcx> {
697 /// Checks whether values of this type `T` are *moved* or *copied*
698 /// when referenced -- this amounts to a check for whether `T:
699 /// Copy`, but note that we **don't** consider lifetimes when
700 /// doing this check. This means that we may generate MIR which
701 /// does copies even when the type actually doesn't satisfy the
702 /// full requirements for the `Copy` trait (cc #29149) -- this
703 /// winds up being reported as an error during NLL borrow check.
704 pub fn is_copy_modulo_regions(&'tcx self,
705 tcx: TyCtxt<'a, 'tcx, 'tcx>,
706 param_env: ty::ParamEnv<'tcx>,
709 tcx.at(span).is_copy_raw(param_env.and(self))
712 /// Checks whether values of this type `T` have a size known at
713 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
714 /// for the purposes of this check, so it can be an
715 /// over-approximation in generic contexts, where one can have
716 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
717 /// actually carry lifetime requirements.
718 pub fn is_sized(&'tcx self,
719 tcx_at: TyCtxtAt<'a, 'tcx, 'tcx>,
720 param_env: ty::ParamEnv<'tcx>)-> bool
722 tcx_at.is_sized_raw(param_env.and(self))
725 /// Checks whether values of this type `T` implement the `Freeze`
726 /// trait -- frozen types are those that do not contain a
727 /// `UnsafeCell` anywhere. This is a language concept used to
728 /// distinguish "true immutability", which is relevant to
729 /// optimization as well as the rules around static values. Note
730 /// that the `Freeze` trait is not exposed to end users and is
731 /// effectively an implementation detail.
732 pub fn is_freeze(&'tcx self,
733 tcx: TyCtxt<'a, 'tcx, 'tcx>,
734 param_env: ty::ParamEnv<'tcx>,
737 tcx.at(span).is_freeze_raw(param_env.and(self))
740 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
741 /// non-copy and *might* have a destructor attached; if it returns
742 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
744 /// (Note that this implies that if `ty` has a destructor attached,
745 /// then `needs_drop` will definitely return `true` for `ty`.)
747 pub fn needs_drop(&'tcx self,
748 tcx: TyCtxt<'a, 'tcx, 'tcx>,
749 param_env: ty::ParamEnv<'tcx>)
751 tcx.needs_drop_raw(param_env.and(self)).0
754 pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
755 match (&a.sty, &b.sty) {
756 (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
761 substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b))
767 /// Check whether a type is representable. This means it cannot contain unboxed
768 /// structural recursion. This check is needed for structs and enums.
769 pub fn is_representable(&'tcx self,
770 tcx: TyCtxt<'a, 'tcx, 'tcx>,
774 // Iterate until something non-representable is found
775 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
776 iter.fold(Representability::Representable, |r1, r2| {
778 (Representability::SelfRecursive(v1),
779 Representability::SelfRecursive(v2)) => {
780 Representability::SelfRecursive(v1.into_iter().chain(v2).collect())
782 (r1, r2) => cmp::max(r1, r2)
787 fn are_inner_types_recursive<'a, 'tcx>(
788 tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
789 seen: &mut Vec<Ty<'tcx>>,
790 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
796 // Find non representable
797 fold_repr(ts.iter().map(|ty| {
798 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
801 // Fixed-length vectors.
802 // FIXME(#11924) Behavior undecided for zero-length vectors.
804 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
806 Adt(def, substs) => {
807 // Find non representable fields with their spans
808 fold_repr(def.all_fields().map(|field| {
809 let ty = field.ty(tcx, substs);
810 let span = tcx.hir().span_if_local(field.did).unwrap_or(sp);
811 match is_type_structurally_recursive(tcx, span, seen,
812 representable_cache, ty)
814 Representability::SelfRecursive(_) => {
815 Representability::SelfRecursive(vec![span])
822 // this check is run on type definitions, so we don't expect
823 // to see closure types
824 bug!("requires check invoked on inapplicable type: {:?}", ty)
826 _ => Representability::Representable,
830 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
839 // Does the type `ty` directly (without indirection through a pointer)
840 // contain any types on stack `seen`?
841 fn is_type_structurally_recursive<'a, 'tcx>(
842 tcx: TyCtxt<'a, 'tcx, 'tcx>,
844 seen: &mut Vec<Ty<'tcx>>,
845 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
846 ty: Ty<'tcx>) -> Representability
848 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
849 if let Some(representability) = representable_cache.get(ty) {
850 debug!("is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
851 ty, sp, representability);
852 return representability.clone();
855 let representability = is_type_structurally_recursive_inner(
856 tcx, sp, seen, representable_cache, ty);
858 representable_cache.insert(ty, representability.clone());
862 fn is_type_structurally_recursive_inner<'a, 'tcx>(
863 tcx: TyCtxt<'a, 'tcx, 'tcx>,
865 seen: &mut Vec<Ty<'tcx>>,
866 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
867 ty: Ty<'tcx>) -> Representability
872 // Iterate through stack of previously seen types.
873 let mut iter = seen.iter();
875 // The first item in `seen` is the type we are actually curious about.
876 // We want to return SelfRecursive if this type contains itself.
877 // It is important that we DON'T take generic parameters into account
878 // for this check, so that Bar<T> in this example counts as SelfRecursive:
881 // struct Bar<T> { x: Bar<Foo> }
883 if let Some(&seen_type) = iter.next() {
884 if same_struct_or_enum(seen_type, def) {
885 debug!("SelfRecursive: {:?} contains {:?}",
888 return Representability::SelfRecursive(vec![sp]);
892 // We also need to know whether the first item contains other types
893 // that are structurally recursive. If we don't catch this case, we
894 // will recurse infinitely for some inputs.
896 // It is important that we DO take generic parameters into account
897 // here, so that code like this is considered SelfRecursive, not
898 // ContainsRecursive:
900 // struct Foo { Option<Option<Foo>> }
902 for &seen_type in iter {
903 if ty::TyS::same_type(ty, seen_type) {
904 debug!("ContainsRecursive: {:?} contains {:?}",
907 return Representability::ContainsRecursive;
912 // For structs and enums, track all previously seen types by pushing them
913 // onto the 'seen' stack.
915 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
920 // No need to push in other cases.
921 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
926 debug!("is_type_representable: {:?}", self);
928 // To avoid a stack overflow when checking an enum variant or struct that
929 // contains a different, structurally recursive type, maintain a stack
930 // of seen types and check recursion for each of them (issues #3008, #3779).
931 let mut seen: Vec<Ty<'_>> = Vec::new();
932 let mut representable_cache = FxHashMap::default();
933 let r = is_type_structurally_recursive(
934 tcx, sp, &mut seen, &mut representable_cache, self);
935 debug!("is_type_representable: {:?} is {:?}", self, r);
940 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
941 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
944 let (param_env, ty) = query.into_parts();
945 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
947 .enter(|infcx| traits::type_known_to_meet_bound_modulo_regions(
956 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
957 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
960 let (param_env, ty) = query.into_parts();
961 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
963 .enter(|infcx| traits::type_known_to_meet_bound_modulo_regions(
972 fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
973 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
976 let (param_env, ty) = query.into_parts();
977 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
979 .enter(|infcx| traits::type_known_to_meet_bound_modulo_regions(
988 #[derive(Clone, HashStable)]
989 pub struct NeedsDrop(pub bool);
991 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
992 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
995 let (param_env, ty) = query.into_parts();
997 let needs_drop = |ty: Ty<'tcx>| -> bool {
998 tcx.needs_drop_raw(param_env.and(ty)).0
1001 assert!(!ty.needs_infer());
1003 NeedsDrop(match ty.sty {
1004 // Fast-path for primitive types
1005 ty::Infer(ty::FreshIntTy(_)) | ty::Infer(ty::FreshFloatTy(_)) |
1006 ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never |
1007 ty::FnDef(..) | ty::FnPtr(_) | ty::Char | ty::GeneratorWitness(..) |
1008 ty::RawPtr(_) | ty::Ref(..) | ty::Str => false,
1010 // Foreign types can never have destructors
1011 ty::Foreign(..) => false,
1013 // `ManuallyDrop` doesn't have a destructor regardless of field types.
1014 ty::Adt(def, _) if Some(def.did) == tcx.lang_items().manually_drop() => false,
1016 // Issue #22536: We first query `is_copy_modulo_regions`. It sees a
1017 // normalized version of the type, and therefore will definitely
1018 // know whether the type implements Copy (and thus needs no
1019 // cleanup/drop/zeroing) ...
1020 _ if ty.is_copy_modulo_regions(tcx, param_env, DUMMY_SP) => false,
1022 // ... (issue #22536 continued) but as an optimization, still use
1023 // prior logic of asking for the structural "may drop".
1025 // FIXME(#22815): Note that this is a conservative heuristic;
1026 // it may report that the type "may drop" when actual type does
1027 // not actually have a destructor associated with it. But since
1028 // the type absolutely did not have the `Copy` bound attached
1029 // (see above), it is sound to treat it as having a destructor.
1031 // User destructors are the only way to have concrete drop types.
1032 ty::Adt(def, _) if def.has_dtor(tcx) => true,
1034 // Can refer to a type which may drop.
1035 // FIXME(eddyb) check this against a ParamEnv.
1036 ty::Dynamic(..) | ty::Projection(..) | ty::Param(_) | ty::Bound(..) |
1037 ty::Placeholder(..) | ty::Opaque(..) | ty::Infer(_) | ty::Error => true,
1039 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
1041 // Structural recursion.
1042 ty::Array(ty, _) | ty::Slice(ty) => needs_drop(ty),
1044 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1046 // Pessimistically assume that all generators will require destructors
1047 // as we don't know if a destructor is a noop or not until after the MIR
1048 // state transformation pass
1049 ty::Generator(..) => true,
1051 ty::Tuple(ref tys) => tys.iter().cloned().any(needs_drop),
1053 // unions don't have destructors because of the child types,
1054 // only if they manually implement `Drop` (handled above).
1055 ty::Adt(def, _) if def.is_union() => false,
1057 ty::Adt(def, substs) =>
1058 def.variants.iter().any(
1059 |variant| variant.fields.iter().any(
1060 |field| needs_drop(field.ty(tcx, substs)))),
1064 pub enum ExplicitSelf<'tcx> {
1066 ByReference(ty::Region<'tcx>, hir::Mutability),
1067 ByRawPointer(hir::Mutability),
1072 impl<'tcx> ExplicitSelf<'tcx> {
1073 /// Categorizes an explicit self declaration like `self: SomeType`
1074 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1076 /// This is mainly used to require the arbitrary_self_types feature
1077 /// in the case of `Other`, to improve error messages in the common cases,
1078 /// and to make `Other` non-object-safe.
1083 /// impl<'a> Foo for &'a T {
1084 /// // Legal declarations:
1085 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1086 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1087 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1088 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1090 /// // Invalid cases will be caught by `check_method_receiver`:
1091 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1092 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1093 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1097 pub fn determine<P>(
1098 self_arg_ty: Ty<'tcx>,
1100 ) -> ExplicitSelf<'tcx>
1102 P: Fn(Ty<'tcx>) -> bool
1104 use self::ExplicitSelf::*;
1106 match self_arg_ty.sty {
1107 _ if is_self_ty(self_arg_ty) => ByValue,
1108 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => {
1109 ByReference(region, mutbl)
1111 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => {
1114 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => {
1122 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1123 *providers = ty::query::Providers {