1 //! Miscellaneous type-system utilities that are too small to deserve their own modules.
3 use crate::hir::def::Def;
4 use crate::hir::def_id::DefId;
5 use crate::hir::map::DefPathData;
6 use crate::hir::{self, Node};
7 use crate::mir::interpret::{sign_extend, truncate};
8 use crate::ich::NodeIdHashingMode;
9 use crate::traits::{self, ObligationCause};
10 use crate::ty::{self, Ty, TyCtxt, GenericParamDefKind, TypeFoldable};
11 use crate::ty::subst::{Subst, InternalSubsts, SubstsRef, UnpackedKind};
12 use crate::ty::query::TyCtxtAt;
13 use crate::ty::TyKind::*;
14 use crate::ty::layout::{Integer, IntegerExt};
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};
22 use syntax::attr::{self, SignedInt, UnsignedInt};
23 use syntax_pos::{Span, DUMMY_SP};
25 #[derive(Copy, Clone, Debug)]
26 pub struct Discr<'tcx> {
27 /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`).
32 impl<'tcx> fmt::Display for Discr<'tcx> {
33 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
36 let size = ty::tls::with(|tcx| {
37 Integer::from_attr(&tcx, SignedInt(ity)).size()
40 // sign extend the raw representation to be an i128
41 let x = sign_extend(x, size) as i128;
44 _ => write!(fmt, "{}", self.val),
49 impl<'tcx> Discr<'tcx> {
50 /// Adds `1` to the value and wraps around if the maximum for the type is reached.
51 pub fn wrap_incr<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
52 self.checked_add(tcx, 1).0
54 pub fn checked_add<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, n: u128) -> (Self, bool) {
55 let (int, signed) = match self.ty.sty {
56 Int(ity) => (Integer::from_attr(&tcx, SignedInt(ity)), true),
57 Uint(uty) => (Integer::from_attr(&tcx, UnsignedInt(uty)), false),
58 _ => bug!("non integer discriminant"),
61 let size = int.size();
62 let bit_size = int.size().bits();
63 let shift = 128 - bit_size;
66 sign_extend(u, size) as i128
68 let min = sext(1_u128 << (bit_size - 1));
69 let max = i128::max_value() >> shift;
70 let val = sext(self.val);
71 assert!(n < (i128::max_value() as u128));
73 let oflo = val > max - n;
75 min + (n - (max - val) - 1)
79 // zero the upper bits
80 let val = val as u128;
81 let val = truncate(val, size);
87 let max = u128::max_value() >> shift;
89 let oflo = val > max - n;
103 pub trait IntTypeExt {
104 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
105 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Discr<'tcx>>)
106 -> Option<Discr<'tcx>>;
107 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx>;
110 impl IntTypeExt for attr::IntType {
111 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
113 SignedInt(ast::IntTy::I8) => tcx.types.i8,
114 SignedInt(ast::IntTy::I16) => tcx.types.i16,
115 SignedInt(ast::IntTy::I32) => tcx.types.i32,
116 SignedInt(ast::IntTy::I64) => tcx.types.i64,
117 SignedInt(ast::IntTy::I128) => tcx.types.i128,
118 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
119 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
120 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
121 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
122 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
123 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
124 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
128 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx> {
135 fn disr_incr<'a, 'tcx>(
137 tcx: TyCtxt<'a, 'tcx, 'tcx>,
138 val: Option<Discr<'tcx>>,
139 ) -> Option<Discr<'tcx>> {
140 if let Some(val) = val {
141 assert_eq!(self.to_ty(tcx), val.ty);
142 let (new, oflo) = val.checked_add(tcx, 1);
149 Some(self.initial_discriminant(tcx))
156 pub enum CopyImplementationError<'tcx> {
157 InfrigingFields(Vec<&'tcx ty::FieldDef>),
162 /// Describes whether a type is representable. For types that are not
163 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
164 /// distinguish between types that are recursive with themselves and types that
165 /// contain a different recursive type. These cases can therefore be treated
166 /// differently when reporting errors.
168 /// The ordering of the cases is significant. They are sorted so that cmp::max
169 /// will keep the "more erroneous" of two values.
170 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
171 pub enum Representability {
174 SelfRecursive(Vec<Span>),
177 impl<'tcx> ty::ParamEnv<'tcx> {
178 pub fn can_type_implement_copy<'a>(self,
179 tcx: TyCtxt<'a, 'tcx, 'tcx>,
181 -> Result<(), CopyImplementationError<'tcx>> {
182 // FIXME: (@jroesch) float this code up
183 tcx.infer_ctxt().enter(|infcx| {
184 let (adt, substs) = match self_type.sty {
185 // These types used to have a builtin impl.
186 // Now libcore provides that impl.
187 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
188 ty::Char | ty::RawPtr(..) | ty::Never |
189 ty::Ref(_, _, hir::MutImmutable) => return Ok(()),
191 ty::Adt(adt, substs) => (adt, substs),
193 _ => return Err(CopyImplementationError::NotAnAdt),
196 let mut infringing = Vec::new();
197 for variant in &adt.variants {
198 for field in &variant.fields {
199 let ty = field.ty(tcx, substs);
200 if ty.references_error() {
203 let span = tcx.def_span(field.did);
204 let cause = ObligationCause { span, ..ObligationCause::dummy() };
205 let ctx = traits::FulfillmentContext::new();
206 match traits::fully_normalize(&infcx, ctx, cause, self, &ty) {
207 Ok(ty) => if !infcx.type_is_copy_modulo_regions(self, ty, span) {
208 infringing.push(field);
211 infcx.report_fulfillment_errors(&errors, None, false);
216 if !infringing.is_empty() {
217 return Err(CopyImplementationError::InfrigingFields(infringing));
219 if adt.has_dtor(tcx) {
220 return Err(CopyImplementationError::HasDestructor);
228 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
229 /// Creates a hash of the type `Ty` which will be the same no matter what crate
230 /// context it's calculated within. This is used by the `type_id` intrinsic.
231 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
232 let mut hasher = StableHasher::new();
233 let mut hcx = self.create_stable_hashing_context();
235 // We want the type_id be independent of the types free regions, so we
236 // erase them. The erase_regions() call will also anonymize bound
237 // regions, which is desirable too.
238 let ty = self.erase_regions(&ty);
240 hcx.while_hashing_spans(false, |hcx| {
241 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
242 ty.hash_stable(hcx, &mut hasher);
249 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
250 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
251 if let ty::Adt(def, substs) = ty.sty {
252 for field in def.all_fields() {
253 let field_ty = field.ty(self, substs);
254 if let Error = field_ty.sty {
262 /// Returns the deeply last field of nested structures, or the same type,
263 /// if not a structure at all. Corresponds to the only possible unsized
264 /// field, and its type can be used to determine unsizing strategy.
265 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
268 ty::Adt(def, substs) => {
269 if !def.is_struct() {
272 match def.non_enum_variant().fields.last() {
273 Some(f) => ty = f.ty(self, substs),
279 if let Some((&last_ty, _)) = tys.split_last() {
294 /// Same as applying struct_tail on `source` and `target`, but only
295 /// keeps going as long as the two types are instances of the same
296 /// structure definitions.
297 /// For `(Foo<Foo<T>>, Foo<dyn Trait>)`, the result will be `(Foo<T>, Trait)`,
298 /// whereas struct_tail produces `T`, and `Trait`, respectively.
299 pub fn struct_lockstep_tails(self,
302 -> (Ty<'tcx>, Ty<'tcx>) {
303 let (mut a, mut b) = (source, target);
305 match (&a.sty, &b.sty) {
306 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
307 if a_def == b_def && a_def.is_struct() => {
308 if let Some(f) = a_def.non_enum_variant().fields.last() {
309 a = f.ty(self, a_substs);
310 b = f.ty(self, b_substs);
315 (&Tuple(a_tys), &Tuple(b_tys))
316 if a_tys.len() == b_tys.len() => {
317 if let Some(a_last) = a_tys.last() {
319 b = b_tys.last().unwrap();
330 /// Given a set of predicates that apply to an object type, returns
331 /// the region bounds that the (erased) `Self` type must
332 /// outlive. Precisely *because* the `Self` type is erased, the
333 /// parameter `erased_self_ty` must be supplied to indicate what type
334 /// has been used to represent `Self` in the predicates
335 /// themselves. This should really be a unique type; `FreshTy(0)` is a
338 /// N.B., in some cases, particularly around higher-ranked bounds,
339 /// this function returns a kind of conservative approximation.
340 /// That is, all regions returned by this function are definitely
341 /// required, but there may be other region bounds that are not
342 /// returned, as well as requirements like `for<'a> T: 'a`.
344 /// Requires that trait definitions have been processed so that we can
345 /// elaborate predicates and walk supertraits.
347 // FIXME: callers may only have a `&[Predicate]`, not a `Vec`, so that's
348 // what this code should accept.
349 pub fn required_region_bounds(self,
350 erased_self_ty: Ty<'tcx>,
351 predicates: Vec<ty::Predicate<'tcx>>)
352 -> Vec<ty::Region<'tcx>> {
353 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
357 assert!(!erased_self_ty.has_escaping_bound_vars());
359 traits::elaborate_predicates(self, predicates)
360 .filter_map(|predicate| {
362 ty::Predicate::Projection(..) |
363 ty::Predicate::Trait(..) |
364 ty::Predicate::Subtype(..) |
365 ty::Predicate::WellFormed(..) |
366 ty::Predicate::ObjectSafe(..) |
367 ty::Predicate::ClosureKind(..) |
368 ty::Predicate::RegionOutlives(..) |
369 ty::Predicate::ConstEvaluatable(..) => {
372 ty::Predicate::TypeOutlives(predicate) => {
373 // Search for a bound of the form `erased_self_ty
374 // : 'a`, but be wary of something like `for<'a>
375 // erased_self_ty : 'a` (we interpret a
376 // higher-ranked bound like that as 'static,
377 // though at present the code in `fulfill.rs`
378 // considers such bounds to be unsatisfiable, so
379 // it's kind of a moot point since you could never
380 // construct such an object, but this seems
381 // correct even if that code changes).
382 let ty::OutlivesPredicate(ref t, ref r) = predicate.skip_binder();
383 if t == &erased_self_ty && !r.has_escaping_bound_vars() {
394 /// Calculate the destructor of a given type.
395 pub fn calculate_dtor(
398 validate: &mut dyn FnMut(Self, DefId) -> Result<(), ErrorReported>
399 ) -> Option<ty::Destructor> {
400 let drop_trait = if let Some(def_id) = self.lang_items().drop_trait() {
406 self.ensure().coherent_trait(drop_trait);
408 let mut dtor_did = None;
409 let ty = self.type_of(adt_did);
410 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
411 if let Some(item) = self.associated_items(impl_did).next() {
412 if validate(self, impl_did).is_ok() {
413 dtor_did = Some(item.def_id);
418 Some(ty::Destructor { did: dtor_did? })
421 /// Returns the set of types that are required to be alive in
422 /// order to run the destructor of `def` (see RFCs 769 and
425 /// Note that this returns only the constraints for the
426 /// destructor of `def` itself. For the destructors of the
427 /// contents, you need `adt_dtorck_constraint`.
428 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
429 -> Vec<ty::subst::Kind<'tcx>>
431 let dtor = match def.destructor(self) {
433 debug!("destructor_constraints({:?}) - no dtor", def.did);
436 Some(dtor) => dtor.did
439 // RFC 1238: if the destructor method is tagged with the
440 // attribute `unsafe_destructor_blind_to_params`, then the
441 // compiler is being instructed to *assume* that the
442 // destructor will not access borrowed data,
443 // even if such data is otherwise reachable.
445 // Such access can be in plain sight (e.g., dereferencing
446 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
447 // (e.g., calling `foo.0.clone()` of `Foo<T:Clone>`).
448 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
449 debug!("destructor_constraint({:?}) - blind", def.did);
453 let impl_def_id = self.associated_item(dtor).container.id();
454 let impl_generics = self.generics_of(impl_def_id);
456 // We have a destructor - all the parameters that are not
457 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
460 // We need to return the list of parameters from the ADTs
461 // generics/substs that correspond to impure parameters on the
462 // impl's generics. This is a bit ugly, but conceptually simple:
464 // Suppose our ADT looks like the following
466 // struct S<X, Y, Z>(X, Y, Z);
470 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
472 // We want to return the parameters (X, Y). For that, we match
473 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
474 // <P1, P2, P0>, and then look up which of the impl substs refer to
475 // parameters marked as pure.
477 let impl_substs = match self.type_of(impl_def_id).sty {
478 ty::Adt(def_, substs) if def_ == def => substs,
482 let item_substs = match self.type_of(def.did).sty {
483 ty::Adt(def_, substs) if def_ == def => substs,
487 let result = item_substs.iter().zip(impl_substs.iter())
490 UnpackedKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
491 !impl_generics.region_param(ebr, self).pure_wrt_drop
493 UnpackedKind::Type(&ty::TyS {
494 sty: ty::Param(ref pt), ..
496 !impl_generics.type_param(pt, self).pure_wrt_drop
498 UnpackedKind::Lifetime(_) | UnpackedKind::Type(_) => {
499 // not a type or region param - this should be reported
505 .map(|(&item_param, _)| item_param)
507 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
511 /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
512 /// that closures have a `DefId`, but the closure *expression* also
513 /// has a `HirId` that is located within the context where the
514 /// closure appears (and, sadly, a corresponding `NodeId`, since
515 /// those are not yet phased out). The parent of the closure's
516 /// `DefId` will also be the context where it appears.
517 pub fn is_closure(self, def_id: DefId) -> bool {
518 self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr
521 /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`).
522 pub fn is_trait(self, def_id: DefId) -> bool {
523 if let DefPathData::Trait(_) = self.def_key(def_id).disambiguated_data.data {
530 /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`),
531 /// and `false` otherwise.
532 pub fn is_trait_alias(self, def_id: DefId) -> bool {
533 if let DefPathData::TraitAlias(_) = self.def_key(def_id).disambiguated_data.data {
540 /// Returns `true` if this `DefId` refers to the implicit constructor for
541 /// a tuple struct like `struct Foo(u32)`, and `false` otherwise.
542 pub fn is_struct_constructor(self, def_id: DefId) -> bool {
543 self.def_key(def_id).disambiguated_data.data == DefPathData::StructCtor
546 /// Given the `DefId` of a fn or closure, returns the `DefId` of
547 /// the innermost fn item that the closure is contained within.
548 /// This is a significant `DefId` because, when we do
549 /// type-checking, we type-check this fn item and all of its
550 /// (transitive) closures together. Therefore, when we fetch the
551 /// `typeck_tables_of` the closure, for example, we really wind up
552 /// fetching the `typeck_tables_of` the enclosing fn item.
553 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
554 let mut def_id = def_id;
555 while self.is_closure(def_id) {
556 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
557 bug!("closure {:?} has no parent", def_id);
563 /// Given the `DefId` and substs a closure, creates the type of
564 /// `self` argument that the closure expects. For example, for a
565 /// `Fn` closure, this would return a reference type `&T` where
566 /// `T = closure_ty`.
568 /// Returns `None` if this closure's kind has not yet been inferred.
569 /// This should only be possible during type checking.
571 /// Note that the return value is a late-bound region and hence
572 /// wrapped in a binder.
573 pub fn closure_env_ty(self,
574 closure_def_id: DefId,
575 closure_substs: ty::ClosureSubsts<'tcx>)
576 -> Option<ty::Binder<Ty<'tcx>>>
578 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
579 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
580 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self);
581 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
582 let env_ty = match closure_kind {
583 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
584 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
585 ty::ClosureKind::FnOnce => closure_ty,
587 Some(ty::Binder::bind(env_ty))
590 /// Given the `DefId` of some item that has no type parameters, make
591 /// a suitable "empty substs" for it.
592 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> SubstsRef<'tcx> {
593 InternalSubsts::for_item(self, item_def_id, |param, _| {
595 GenericParamDefKind::Lifetime => self.types.re_erased.into(),
596 GenericParamDefKind::Type {..} => {
597 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
603 /// Returns `true` if the node pointed to by `def_id` is a static item, and its mutability.
604 pub fn is_static(&self, def_id: DefId) -> Option<hir::Mutability> {
605 if let Some(node) = self.hir().get_if_local(def_id) {
607 Node::Item(&hir::Item {
608 node: hir::ItemKind::Static(_, mutbl, _), ..
610 Node::ForeignItem(&hir::ForeignItem {
611 node: hir::ForeignItemKind::Static(_, is_mutbl), ..
614 hir::Mutability::MutMutable
616 hir::Mutability::MutImmutable
621 match self.describe_def(def_id) {
622 Some(Def::Static(_, is_mutbl)) =>
624 hir::Mutability::MutMutable
626 hir::Mutability::MutImmutable
633 /// Expands the given impl trait type, stopping if the type is recursive.
634 pub fn try_expand_impl_trait_type(
637 substs: SubstsRef<'tcx>,
638 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
639 use crate::ty::fold::TypeFolder;
641 struct OpaqueTypeExpander<'a, 'gcx, 'tcx> {
642 // Contains the DefIds of the opaque types that are currently being
643 // expanded. When we expand an opaque type we insert the DefId of
644 // that type, and when we finish expanding that type we remove the
646 seen_opaque_tys: FxHashSet<DefId>,
647 primary_def_id: DefId,
648 found_recursion: bool,
649 tcx: TyCtxt<'a, 'gcx, 'tcx>,
652 impl<'a, 'gcx, 'tcx> OpaqueTypeExpander<'a, 'gcx, 'tcx> {
656 substs: SubstsRef<'tcx>,
657 ) -> Option<Ty<'tcx>> {
658 if self.found_recursion {
660 } else if self.seen_opaque_tys.insert(def_id) {
661 let generic_ty = self.tcx.type_of(def_id);
662 let concrete_ty = generic_ty.subst(self.tcx, substs);
663 let expanded_ty = self.fold_ty(concrete_ty);
664 self.seen_opaque_tys.remove(&def_id);
667 // If another opaque type that we contain is recursive, then it
668 // will report the error, so we don't have to.
669 self.found_recursion = def_id == self.primary_def_id;
675 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for OpaqueTypeExpander<'a, 'gcx, 'tcx> {
676 fn tcx(&self) -> TyCtxt<'_, 'gcx, 'tcx> {
680 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
681 if let ty::Opaque(def_id, substs) = t.sty {
682 self.expand_opaque_ty(def_id, substs).unwrap_or(t)
684 t.super_fold_with(self)
689 let mut visitor = OpaqueTypeExpander {
690 seen_opaque_tys: FxHashSet::default(),
691 primary_def_id: def_id,
692 found_recursion: false,
695 let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap();
696 if visitor.found_recursion {
704 impl<'a, 'tcx> ty::TyS<'tcx> {
705 /// Checks whether values of this type `T` are *moved* or *copied*
706 /// when referenced -- this amounts to a check for whether `T:
707 /// Copy`, but note that we **don't** consider lifetimes when
708 /// doing this check. This means that we may generate MIR which
709 /// does copies even when the type actually doesn't satisfy the
710 /// full requirements for the `Copy` trait (cc #29149) -- this
711 /// winds up being reported as an error during NLL borrow check.
712 pub fn is_copy_modulo_regions(&'tcx self,
713 tcx: TyCtxt<'a, 'tcx, 'tcx>,
714 param_env: ty::ParamEnv<'tcx>,
717 tcx.at(span).is_copy_raw(param_env.and(self))
720 /// Checks whether values of this type `T` have a size known at
721 /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored
722 /// for the purposes of this check, so it can be an
723 /// over-approximation in generic contexts, where one can have
724 /// strange rules like `<T as Foo<'static>>::Bar: Sized` that
725 /// actually carry lifetime requirements.
726 pub fn is_sized(&'tcx self,
727 tcx_at: TyCtxtAt<'a, 'tcx, 'tcx>,
728 param_env: ty::ParamEnv<'tcx>)-> bool
730 tcx_at.is_sized_raw(param_env.and(self))
733 /// Checks whether values of this type `T` implement the `Freeze`
734 /// trait -- frozen types are those that do not contain a
735 /// `UnsafeCell` anywhere. This is a language concept used to
736 /// distinguish "true immutability", which is relevant to
737 /// optimization as well as the rules around static values. Note
738 /// that the `Freeze` trait is not exposed to end users and is
739 /// effectively an implementation detail.
740 pub fn is_freeze(&'tcx self,
741 tcx: TyCtxt<'a, 'tcx, 'tcx>,
742 param_env: ty::ParamEnv<'tcx>,
745 tcx.at(span).is_freeze_raw(param_env.and(self))
748 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
749 /// non-copy and *might* have a destructor attached; if it returns
750 /// `false`, then `ty` definitely has no destructor (i.e., no drop glue).
752 /// (Note that this implies that if `ty` has a destructor attached,
753 /// then `needs_drop` will definitely return `true` for `ty`.)
755 pub fn needs_drop(&'tcx self,
756 tcx: TyCtxt<'a, 'tcx, 'tcx>,
757 param_env: ty::ParamEnv<'tcx>)
759 tcx.needs_drop_raw(param_env.and(self)).0
762 pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
763 match (&a.sty, &b.sty) {
764 (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
769 substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b))
775 /// Check whether a type is representable. This means it cannot contain unboxed
776 /// structural recursion. This check is needed for structs and enums.
777 pub fn is_representable(&'tcx self,
778 tcx: TyCtxt<'a, 'tcx, 'tcx>,
782 // Iterate until something non-representable is found
783 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
784 iter.fold(Representability::Representable, |r1, r2| {
786 (Representability::SelfRecursive(v1),
787 Representability::SelfRecursive(v2)) => {
788 Representability::SelfRecursive(v1.into_iter().chain(v2).collect())
790 (r1, r2) => cmp::max(r1, r2)
795 fn are_inner_types_recursive<'a, 'tcx>(
796 tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
797 seen: &mut Vec<Ty<'tcx>>,
798 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
804 // Find non representable
805 fold_repr(ts.iter().map(|ty| {
806 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
809 // Fixed-length vectors.
810 // FIXME(#11924) Behavior undecided for zero-length vectors.
812 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
814 Adt(def, substs) => {
815 // Find non representable fields with their spans
816 fold_repr(def.all_fields().map(|field| {
817 let ty = field.ty(tcx, substs);
818 let span = tcx.hir().span_if_local(field.did).unwrap_or(sp);
819 match is_type_structurally_recursive(tcx, span, seen,
820 representable_cache, ty)
822 Representability::SelfRecursive(_) => {
823 Representability::SelfRecursive(vec![span])
830 // this check is run on type definitions, so we don't expect
831 // to see closure types
832 bug!("requires check invoked on inapplicable type: {:?}", ty)
834 _ => Representability::Representable,
838 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
847 // Does the type `ty` directly (without indirection through a pointer)
848 // contain any types on stack `seen`?
849 fn is_type_structurally_recursive<'a, 'tcx>(
850 tcx: TyCtxt<'a, 'tcx, 'tcx>,
852 seen: &mut Vec<Ty<'tcx>>,
853 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
854 ty: Ty<'tcx>) -> Representability
856 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
857 if let Some(representability) = representable_cache.get(ty) {
858 debug!("is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
859 ty, sp, representability);
860 return representability.clone();
863 let representability = is_type_structurally_recursive_inner(
864 tcx, sp, seen, representable_cache, ty);
866 representable_cache.insert(ty, representability.clone());
870 fn is_type_structurally_recursive_inner<'a, 'tcx>(
871 tcx: TyCtxt<'a, 'tcx, 'tcx>,
873 seen: &mut Vec<Ty<'tcx>>,
874 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
875 ty: Ty<'tcx>) -> Representability
880 // Iterate through stack of previously seen types.
881 let mut iter = seen.iter();
883 // The first item in `seen` is the type we are actually curious about.
884 // We want to return SelfRecursive if this type contains itself.
885 // It is important that we DON'T take generic parameters into account
886 // for this check, so that Bar<T> in this example counts as SelfRecursive:
889 // struct Bar<T> { x: Bar<Foo> }
891 if let Some(&seen_type) = iter.next() {
892 if same_struct_or_enum(seen_type, def) {
893 debug!("SelfRecursive: {:?} contains {:?}",
896 return Representability::SelfRecursive(vec![sp]);
900 // We also need to know whether the first item contains other types
901 // that are structurally recursive. If we don't catch this case, we
902 // will recurse infinitely for some inputs.
904 // It is important that we DO take generic parameters into account
905 // here, so that code like this is considered SelfRecursive, not
906 // ContainsRecursive:
908 // struct Foo { Option<Option<Foo>> }
910 for &seen_type in iter {
911 if ty::TyS::same_type(ty, seen_type) {
912 debug!("ContainsRecursive: {:?} contains {:?}",
915 return Representability::ContainsRecursive;
920 // For structs and enums, track all previously seen types by pushing them
921 // onto the 'seen' stack.
923 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
928 // No need to push in other cases.
929 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
934 debug!("is_type_representable: {:?}", self);
936 // To avoid a stack overflow when checking an enum variant or struct that
937 // contains a different, structurally recursive type, maintain a stack
938 // of seen types and check recursion for each of them (issues #3008, #3779).
939 let mut seen: Vec<Ty<'_>> = Vec::new();
940 let mut representable_cache = FxHashMap::default();
941 let r = is_type_structurally_recursive(
942 tcx, sp, &mut seen, &mut representable_cache, self);
943 debug!("is_type_representable: {:?} is {:?}", self, r);
948 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
949 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
952 let (param_env, ty) = query.into_parts();
953 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
955 .enter(|infcx| traits::type_known_to_meet_bound_modulo_regions(
964 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
965 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
968 let (param_env, ty) = query.into_parts();
969 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
971 .enter(|infcx| traits::type_known_to_meet_bound_modulo_regions(
980 fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
981 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
984 let (param_env, ty) = query.into_parts();
985 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
987 .enter(|infcx| traits::type_known_to_meet_bound_modulo_regions(
997 pub struct NeedsDrop(pub bool);
999 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1000 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1003 let (param_env, ty) = query.into_parts();
1005 let needs_drop = |ty: Ty<'tcx>| -> bool {
1006 tcx.needs_drop_raw(param_env.and(ty)).0
1009 assert!(!ty.needs_infer());
1011 NeedsDrop(match ty.sty {
1012 // Fast-path for primitive types
1013 ty::Infer(ty::FreshIntTy(_)) | ty::Infer(ty::FreshFloatTy(_)) |
1014 ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never |
1015 ty::FnDef(..) | ty::FnPtr(_) | ty::Char | ty::GeneratorWitness(..) |
1016 ty::RawPtr(_) | ty::Ref(..) | ty::Str => false,
1018 // Foreign types can never have destructors
1019 ty::Foreign(..) => false,
1021 // `ManuallyDrop` doesn't have a destructor regardless of field types.
1022 ty::Adt(def, _) if Some(def.did) == tcx.lang_items().manually_drop() => false,
1024 // Issue #22536: We first query `is_copy_modulo_regions`. It sees a
1025 // normalized version of the type, and therefore will definitely
1026 // know whether the type implements Copy (and thus needs no
1027 // cleanup/drop/zeroing) ...
1028 _ if ty.is_copy_modulo_regions(tcx, param_env, DUMMY_SP) => false,
1030 // ... (issue #22536 continued) but as an optimization, still use
1031 // prior logic of asking for the structural "may drop".
1033 // FIXME(#22815): Note that this is a conservative heuristic;
1034 // it may report that the type "may drop" when actual type does
1035 // not actually have a destructor associated with it. But since
1036 // the type absolutely did not have the `Copy` bound attached
1037 // (see above), it is sound to treat it as having a destructor.
1039 // User destructors are the only way to have concrete drop types.
1040 ty::Adt(def, _) if def.has_dtor(tcx) => true,
1042 // Can refer to a type which may drop.
1043 // FIXME(eddyb) check this against a ParamEnv.
1044 ty::Dynamic(..) | ty::Projection(..) | ty::Param(_) | ty::Bound(..) |
1045 ty::Placeholder(..) | ty::Opaque(..) | ty::Infer(_) | ty::Error => true,
1047 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
1049 // Structural recursion.
1050 ty::Array(ty, _) | ty::Slice(ty) => needs_drop(ty),
1052 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1054 // Pessimistically assume that all generators will require destructors
1055 // as we don't know if a destructor is a noop or not until after the MIR
1056 // state transformation pass
1057 ty::Generator(..) => true,
1059 ty::Tuple(ref tys) => tys.iter().cloned().any(needs_drop),
1061 // unions don't have destructors because of the child types,
1062 // only if they manually implement `Drop` (handled above).
1063 ty::Adt(def, _) if def.is_union() => false,
1065 ty::Adt(def, substs) =>
1066 def.variants.iter().any(
1067 |variant| variant.fields.iter().any(
1068 |field| needs_drop(field.ty(tcx, substs)))),
1072 pub enum ExplicitSelf<'tcx> {
1074 ByReference(ty::Region<'tcx>, hir::Mutability),
1075 ByRawPointer(hir::Mutability),
1080 impl<'tcx> ExplicitSelf<'tcx> {
1081 /// Categorizes an explicit self declaration like `self: SomeType`
1082 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
1084 /// This is mainly used to require the arbitrary_self_types feature
1085 /// in the case of `Other`, to improve error messages in the common cases,
1086 /// and to make `Other` non-object-safe.
1091 /// impl<'a> Foo for &'a T {
1092 /// // Legal declarations:
1093 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1094 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1095 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1096 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1098 /// // Invalid cases will be caught by `check_method_receiver`:
1099 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1100 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1101 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1105 pub fn determine<P>(
1106 self_arg_ty: Ty<'tcx>,
1108 ) -> ExplicitSelf<'tcx>
1110 P: Fn(Ty<'tcx>) -> bool
1112 use self::ExplicitSelf::*;
1114 match self_arg_ty.sty {
1115 _ if is_self_ty(self_arg_ty) => ByValue,
1116 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => {
1117 ByReference(region, mutbl)
1119 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => {
1122 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => {
1130 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1131 *providers = ty::query::Providers {