1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! misc. type-system utilities too small to deserve their own file
13 use hir::def_id::{DefId, LOCAL_CRATE};
14 use hir::map::DefPathData;
16 use ich::{StableHashingContext, NodeIdHashingMode};
17 use traits::{self, Reveal};
18 use ty::{self, Ty, TyCtxt, TypeAndMut, TypeFlags, TypeFoldable};
19 use ty::ParameterEnvironment;
20 use ty::fold::TypeVisitor;
21 use ty::layout::{Layout, LayoutError};
22 use ty::subst::{Subst, Kind};
23 use ty::TypeVariants::*;
24 use util::common::ErrorReported;
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use middle::lang_items;
28 use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
29 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
31 use std::cell::RefCell;
35 use syntax::ast::{self, Name};
36 use syntax::attr::{self, SignedInt, UnsignedInt};
37 use syntax_pos::{Span, DUMMY_SP};
43 pub trait IntTypeExt {
44 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
45 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
47 fn assert_ty_matches(&self, val: Disr);
48 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr;
52 macro_rules! typed_literal {
53 ($tcx:expr, $ty:expr, $lit:expr) => {
55 SignedInt(ast::IntTy::I8) => ConstInt::I8($lit),
56 SignedInt(ast::IntTy::I16) => ConstInt::I16($lit),
57 SignedInt(ast::IntTy::I32) => ConstInt::I32($lit),
58 SignedInt(ast::IntTy::I64) => ConstInt::I64($lit),
59 SignedInt(ast::IntTy::I128) => ConstInt::I128($lit),
60 SignedInt(ast::IntTy::Is) => match $tcx.sess.target.int_type {
61 ast::IntTy::I16 => ConstInt::Isize(ConstIsize::Is16($lit)),
62 ast::IntTy::I32 => ConstInt::Isize(ConstIsize::Is32($lit)),
63 ast::IntTy::I64 => ConstInt::Isize(ConstIsize::Is64($lit)),
66 UnsignedInt(ast::UintTy::U8) => ConstInt::U8($lit),
67 UnsignedInt(ast::UintTy::U16) => ConstInt::U16($lit),
68 UnsignedInt(ast::UintTy::U32) => ConstInt::U32($lit),
69 UnsignedInt(ast::UintTy::U64) => ConstInt::U64($lit),
70 UnsignedInt(ast::UintTy::U128) => ConstInt::U128($lit),
71 UnsignedInt(ast::UintTy::Us) => match $tcx.sess.target.uint_type {
72 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16($lit)),
73 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32($lit)),
74 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64($lit)),
81 impl IntTypeExt for attr::IntType {
82 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
84 SignedInt(ast::IntTy::I8) => tcx.types.i8,
85 SignedInt(ast::IntTy::I16) => tcx.types.i16,
86 SignedInt(ast::IntTy::I32) => tcx.types.i32,
87 SignedInt(ast::IntTy::I64) => tcx.types.i64,
88 SignedInt(ast::IntTy::I128) => tcx.types.i128,
89 SignedInt(ast::IntTy::Is) => tcx.types.isize,
90 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
91 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
92 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
93 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
94 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
95 UnsignedInt(ast::UintTy::Us) => tcx.types.usize,
99 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr {
100 typed_literal!(tcx, *self, 0)
103 fn assert_ty_matches(&self, val: Disr) {
105 (SignedInt(ast::IntTy::I8), ConstInt::I8(_)) => {},
106 (SignedInt(ast::IntTy::I16), ConstInt::I16(_)) => {},
107 (SignedInt(ast::IntTy::I32), ConstInt::I32(_)) => {},
108 (SignedInt(ast::IntTy::I64), ConstInt::I64(_)) => {},
109 (SignedInt(ast::IntTy::I128), ConstInt::I128(_)) => {},
110 (SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) => {},
111 (UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) => {},
112 (UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) => {},
113 (UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) => {},
114 (UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) => {},
115 (UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) => {},
116 (UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => {},
117 _ => bug!("disr type mismatch: {:?} vs {:?}", self, val),
121 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
123 if let Some(val) = val {
124 self.assert_ty_matches(val);
125 (val + typed_literal!(tcx, *self, 1)).ok()
127 Some(self.initial_discriminant(tcx))
133 #[derive(Copy, Clone)]
134 pub enum CopyImplementationError<'tcx> {
135 InfrigingField(&'tcx ty::FieldDef),
140 /// Describes whether a type is representable. For types that are not
141 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
142 /// distinguish between types that are recursive with themselves and types that
143 /// contain a different recursive type. These cases can therefore be treated
144 /// differently when reporting errors.
146 /// The ordering of the cases is significant. They are sorted so that cmp::max
147 /// will keep the "more erroneous" of two values.
148 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
149 pub enum Representability {
152 SelfRecursive(Vec<Span>),
155 impl<'tcx> ParameterEnvironment<'tcx> {
156 pub fn can_type_implement_copy<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
157 self_type: Ty<'tcx>, span: Span)
158 -> Result<(), CopyImplementationError> {
159 // FIXME: (@jroesch) float this code up
160 tcx.infer_ctxt(self.clone(), Reveal::UserFacing).enter(|infcx| {
161 let (adt, substs) = match self_type.sty {
162 ty::TyAdt(adt, substs) => (adt, substs),
163 _ => return Err(CopyImplementationError::NotAnAdt),
166 let field_implements_copy = |field: &ty::FieldDef| {
167 let cause = traits::ObligationCause::dummy();
168 match traits::fully_normalize(&infcx, cause, &field.ty(tcx, substs)) {
169 Ok(ty) => !infcx.type_moves_by_default(ty, span),
174 for variant in &adt.variants {
175 for field in &variant.fields {
176 if !field_implements_copy(field) {
177 return Err(CopyImplementationError::InfrigingField(field));
182 if adt.has_dtor(tcx) {
183 return Err(CopyImplementationError::HasDestructor);
191 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
192 /// Creates a hash of the type `Ty` which will be the same no matter what crate
193 /// context it's calculated within. This is used by the `type_id` intrinsic.
194 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
195 let mut hasher = StableHasher::new();
196 let mut hcx = StableHashingContext::new(self);
198 hcx.while_hashing_spans(false, |hcx| {
199 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
200 ty.hash_stable(hcx, &mut hasher);
207 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
208 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
210 ty::TyAdt(def, substs) => {
211 for field in def.all_fields() {
212 let field_ty = field.ty(self, substs);
213 if let TyError = field_ty.sty {
223 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
224 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
225 pub fn positional_element_ty(self,
228 variant: Option<DefId>) -> Option<Ty<'tcx>> {
229 match (&ty.sty, variant) {
230 (&TyAdt(adt, substs), Some(vid)) => {
231 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
233 (&TyAdt(adt, substs), None) => {
234 // Don't use `struct_variant`, this may be a univariant enum.
235 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
237 (&TyTuple(ref v, _), None) => v.get(i).cloned(),
242 /// Returns the type of element at field `n` in struct or struct-like type `t`.
243 /// For an enum `t`, `variant` must be some def id.
244 pub fn named_element_ty(self,
247 variant: Option<DefId>) -> Option<Ty<'tcx>> {
248 match (&ty.sty, variant) {
249 (&TyAdt(adt, substs), Some(vid)) => {
250 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
252 (&TyAdt(adt, substs), None) => {
253 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
259 /// Returns the deeply last field of nested structures, or the same type,
260 /// if not a structure at all. Corresponds to the only possible unsized
261 /// field, and its type can be used to determine unsizing strategy.
262 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
263 while let TyAdt(def, substs) = ty.sty {
264 if !def.is_struct() {
267 match def.struct_variant().fields.last() {
268 Some(f) => ty = f.ty(self, substs),
275 /// Same as applying struct_tail on `source` and `target`, but only
276 /// keeps going as long as the two types are instances of the same
277 /// structure definitions.
278 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
279 /// whereas struct_tail produces `T`, and `Trait`, respectively.
280 pub fn struct_lockstep_tails(self,
283 -> (Ty<'tcx>, Ty<'tcx>) {
284 let (mut a, mut b) = (source, target);
285 while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
286 if a_def != b_def || !a_def.is_struct() {
289 match a_def.struct_variant().fields.last() {
291 a = f.ty(self, a_substs);
292 b = f.ty(self, b_substs);
300 /// Given a set of predicates that apply to an object type, returns
301 /// the region bounds that the (erased) `Self` type must
302 /// outlive. Precisely *because* the `Self` type is erased, the
303 /// parameter `erased_self_ty` must be supplied to indicate what type
304 /// has been used to represent `Self` in the predicates
305 /// themselves. This should really be a unique type; `FreshTy(0)` is a
308 /// NB: in some cases, particularly around higher-ranked bounds,
309 /// this function returns a kind of conservative approximation.
310 /// That is, all regions returned by this function are definitely
311 /// required, but there may be other region bounds that are not
312 /// returned, as well as requirements like `for<'a> T: 'a`.
314 /// Requires that trait definitions have been processed so that we can
315 /// elaborate predicates and walk supertraits.
317 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
318 /// what this code should accept.
319 pub fn required_region_bounds(self,
320 erased_self_ty: Ty<'tcx>,
321 predicates: Vec<ty::Predicate<'tcx>>)
322 -> Vec<ty::Region<'tcx>> {
323 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
327 assert!(!erased_self_ty.has_escaping_regions());
329 traits::elaborate_predicates(self, predicates)
330 .filter_map(|predicate| {
332 ty::Predicate::Projection(..) |
333 ty::Predicate::Trait(..) |
334 ty::Predicate::Equate(..) |
335 ty::Predicate::Subtype(..) |
336 ty::Predicate::WellFormed(..) |
337 ty::Predicate::ObjectSafe(..) |
338 ty::Predicate::ClosureKind(..) |
339 ty::Predicate::RegionOutlives(..) => {
342 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
343 // Search for a bound of the form `erased_self_ty
344 // : 'a`, but be wary of something like `for<'a>
345 // erased_self_ty : 'a` (we interpret a
346 // higher-ranked bound like that as 'static,
347 // though at present the code in `fulfill.rs`
348 // considers such bounds to be unsatisfiable, so
349 // it's kind of a moot point since you could never
350 // construct such an object, but this seems
351 // correct even if that code changes).
352 if t == erased_self_ty && !r.has_escaping_regions() {
363 /// Calculate the destructor of a given type.
364 pub fn calculate_dtor(
367 validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
368 ) -> Option<ty::Destructor> {
369 let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
375 self.coherent_trait((LOCAL_CRATE, drop_trait));
377 let mut dtor_did = None;
378 let ty = self.type_of(adt_did);
379 self.trait_def(drop_trait).for_each_relevant_impl(self, ty, |impl_did| {
380 if let Some(item) = self.associated_items(impl_did).next() {
381 if let Ok(()) = validate(self, impl_did) {
382 dtor_did = Some(item.def_id);
387 let dtor_did = match dtor_did {
392 Some(ty::Destructor { did: dtor_did })
395 /// Return the set of types that are required to be alive in
396 /// order to run the destructor of `def` (see RFCs 769 and
399 /// Note that this returns only the constraints for the
400 /// destructor of `def` itself. For the destructors of the
401 /// contents, you need `adt_dtorck_constraint`.
402 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
403 -> Vec<ty::subst::Kind<'tcx>>
405 let dtor = match def.destructor(self) {
407 debug!("destructor_constraints({:?}) - no dtor", def.did);
410 Some(dtor) => dtor.did
413 // RFC 1238: if the destructor method is tagged with the
414 // attribute `unsafe_destructor_blind_to_params`, then the
415 // compiler is being instructed to *assume* that the
416 // destructor will not access borrowed data,
417 // even if such data is otherwise reachable.
419 // Such access can be in plain sight (e.g. dereferencing
420 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
421 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
422 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
423 debug!("destructor_constraint({:?}) - blind", def.did);
427 let impl_def_id = self.associated_item(dtor).container.id();
428 let impl_generics = self.generics_of(impl_def_id);
430 // We have a destructor - all the parameters that are not
431 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
434 // We need to return the list of parameters from the ADTs
435 // generics/substs that correspond to impure parameters on the
436 // impl's generics. This is a bit ugly, but conceptually simple:
438 // Suppose our ADT looks like the following
440 // struct S<X, Y, Z>(X, Y, Z);
444 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
446 // We want to return the parameters (X, Y). For that, we match
447 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
448 // <P1, P2, P0>, and then look up which of the impl substs refer to
449 // parameters marked as pure.
451 let impl_substs = match self.type_of(impl_def_id).sty {
452 ty::TyAdt(def_, substs) if def_ == def => substs,
456 let item_substs = match self.type_of(def.did).sty {
457 ty::TyAdt(def_, substs) if def_ == def => substs,
461 let result = item_substs.iter().zip(impl_substs.iter())
463 if let Some(&ty::RegionKind::ReEarlyBound(ref ebr)) = k.as_region() {
464 !impl_generics.region_param(ebr).pure_wrt_drop
465 } else if let Some(&ty::TyS {
466 sty: ty::TypeVariants::TyParam(ref pt), ..
468 !impl_generics.type_param(pt).pure_wrt_drop
470 // not a type or region param - this should be reported
474 }).map(|(&item_param, _)| item_param).collect();
475 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
479 /// Return a set of constraints that needs to be satisfied in
480 /// order for `ty` to be valid for destruction.
481 pub fn dtorck_constraint_for_ty(self,
486 -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
488 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
489 span, for_ty, depth, ty);
491 if depth >= self.sess.recursion_limit.get() {
492 let mut err = struct_span_err!(
493 self.sess, span, E0320,
494 "overflow while adding drop-check rules for {}", for_ty);
495 err.note(&format!("overflowed on {}", ty));
497 return Err(ErrorReported);
500 let result = match ty.sty {
501 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
502 ty::TyFloat(_) | ty::TyStr | ty::TyNever |
503 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => {
504 // these types never have a destructor
505 Ok(ty::DtorckConstraint::empty())
508 ty::TyArray(ety, _) | ty::TySlice(ety) => {
509 // single-element containers, behave like their element
510 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
513 ty::TyTuple(tys, _) => {
514 tys.iter().map(|ty| {
515 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
519 ty::TyClosure(def_id, substs) => {
520 substs.upvar_tys(def_id, self).map(|ty| {
521 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
525 ty::TyAdt(def, substs) => {
526 let ty::DtorckConstraint {
527 dtorck_types, outlives
528 } = self.at(span).adt_dtorck_constraint(def.did);
529 Ok(ty::DtorckConstraint {
530 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
531 // there, but that needs some way to handle cycles.
532 dtorck_types: dtorck_types.subst(self, substs),
533 outlives: outlives.subst(self, substs)
537 // Objects must be alive in order for their destructor
539 ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
540 outlives: vec![Kind::from(ty)],
541 dtorck_types: vec![],
544 // Types that can't be resolved. Pass them forward.
545 ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
546 Ok(ty::DtorckConstraint {
548 dtorck_types: vec![ty],
552 ty::TyInfer(..) | ty::TyError => {
553 self.sess.delay_span_bug(span, "unresolved type in dtorck");
558 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
562 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
563 let mut def_id = def_id;
564 while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
565 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
566 bug!("closure {:?} has no parent", def_id);
572 /// Given the def-id of some item that has no type parameters, make
573 /// a suitable "empty substs" for it.
574 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
575 ty::Substs::for_item(self, item_def_id,
576 |_, _| self.types.re_erased,
578 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
583 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
584 tcx: TyCtxt<'a, 'gcx, 'tcx>,
585 state: StableHasher<W>,
588 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
589 where W: StableHasherResult
591 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
592 TypeIdHasher { tcx: tcx, state: StableHasher::new() }
595 pub fn finish(self) -> W {
599 pub fn hash<T: Hash>(&mut self, x: T) {
600 x.hash(&mut self.state);
603 fn hash_discriminant_u8<T>(&mut self, x: &T) {
605 intrinsics::discriminant_value(x)
608 assert_eq!(v, b as u64);
612 fn def_id(&mut self, did: DefId) {
613 // Hash the DefPath corresponding to the DefId, which is independent
614 // of compiler internal state. We already have a stable hash value of
615 // all DefPaths available via tcx.def_path_hash(), so we just feed that
617 let hash = self.tcx.def_path_hash(did);
622 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
623 where W: StableHasherResult
625 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
626 // Distinguish between the Ty variants uniformly.
627 self.hash_discriminant_u8(&ty.sty);
630 TyInt(i) => self.hash(i),
631 TyUint(u) => self.hash(u),
632 TyFloat(f) => self.hash(f),
633 TyArray(_, n) => self.hash(n),
635 TyRef(_, m) => self.hash(m.mutbl),
636 TyClosure(def_id, _) |
638 TyFnDef(def_id, ..) => self.def_id(def_id),
639 TyAdt(d, _) => self.def_id(d.did),
641 self.hash(f.unsafety());
643 self.hash(f.variadic());
644 self.hash(f.inputs().skip_binder().len());
646 TyDynamic(ref data, ..) => {
647 if let Some(p) = data.principal() {
648 self.def_id(p.def_id());
650 for d in data.auto_traits() {
654 TyTuple(tys, defaulted) => {
655 self.hash(tys.len());
656 self.hash(defaulted);
660 self.hash(p.name.as_str());
662 TyProjection(ref data) => {
663 self.def_id(data.trait_ref.def_id);
664 self.hash(data.item_name.as_str());
673 TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
676 ty.super_visit_with(self)
679 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
680 self.hash_discriminant_u8(r);
685 // No variant fields to hash for these ...
687 ty::ReLateBound(db, ty::BrAnon(i)) => {
691 ty::ReEarlyBound(ty::EarlyBoundRegion { index, name }) => {
693 self.hash(name.as_str());
695 ty::ReLateBound(..) |
699 ty::ReSkolemized(..) => {
700 bug!("TypeIdHasher: unexpected region {:?}", r)
706 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
707 // Anonymize late-bound regions so that, for example:
708 // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
709 // result in the same TypeId (the two types are equivalent).
710 self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
714 impl<'a, 'tcx> ty::TyS<'tcx> {
715 fn impls_bound(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
716 param_env: &ParameterEnvironment<'tcx>,
718 cache: &RefCell<FxHashMap<Ty<'tcx>, bool>>,
721 if self.has_param_types() || self.has_self_ty() {
722 if let Some(result) = cache.borrow().get(self) {
727 tcx.infer_ctxt(param_env.clone(), Reveal::UserFacing)
729 traits::type_known_to_meet_bound(&infcx, self, def_id, span)
731 if self.has_param_types() || self.has_self_ty() {
732 cache.borrow_mut().insert(self, result);
737 // FIXME (@jroesch): I made this public to use it, not sure if should be private
738 pub fn moves_by_default(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
739 param_env: &ParameterEnvironment<'tcx>,
740 span: Span) -> bool {
741 if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
742 return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
745 assert!(!self.needs_infer());
747 // Fast-path for primitive types
748 let result = match self.sty {
749 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) | TyNever |
750 TyRawPtr(..) | TyFnDef(..) | TyFnPtr(_) | TyRef(_, TypeAndMut {
751 mutbl: hir::MutImmutable, ..
754 TyStr | TyRef(_, TypeAndMut {
755 mutbl: hir::MutMutable, ..
758 TyArray(..) | TySlice(..) | TyDynamic(..) | TyTuple(..) |
759 TyClosure(..) | TyAdt(..) | TyAnon(..) |
760 TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
761 }.unwrap_or_else(|| {
762 !self.impls_bound(tcx, param_env,
763 tcx.require_lang_item(lang_items::CopyTraitLangItem),
764 ¶m_env.is_copy_cache, span) });
766 if !self.has_param_types() && !self.has_self_ty() {
767 self.flags.set(self.flags.get() | if result {
768 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
770 TypeFlags::MOVENESS_CACHED
778 pub fn is_sized(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
779 param_env: &ParameterEnvironment<'tcx>,
782 if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
783 return self.flags.get().intersects(TypeFlags::IS_SIZED);
786 self.is_sized_uncached(tcx, param_env, span)
789 fn is_sized_uncached(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
790 param_env: &ParameterEnvironment<'tcx>,
791 span: Span) -> bool {
792 assert!(!self.needs_infer());
794 // Fast-path for primitive types
795 let result = match self.sty {
796 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
797 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
798 TyArray(..) | TyTuple(..) | TyClosure(..) | TyNever => Some(true),
800 TyStr | TyDynamic(..) | TySlice(_) => Some(false),
802 TyAdt(..) | TyProjection(..) | TyParam(..) |
803 TyInfer(..) | TyAnon(..) | TyError => None
804 }.unwrap_or_else(|| {
805 self.impls_bound(tcx, param_env, tcx.require_lang_item(lang_items::SizedTraitLangItem),
806 ¶m_env.is_sized_cache, span) });
808 if !self.has_param_types() && !self.has_self_ty() {
809 self.flags.set(self.flags.get() | if result {
810 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
812 TypeFlags::SIZEDNESS_CACHED
819 /// Returns `true` if and only if there are no `UnsafeCell`s
820 /// nested within the type (ignoring `PhantomData` or pointers).
822 pub fn is_freeze(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
823 param_env: &ParameterEnvironment<'tcx>,
826 if self.flags.get().intersects(TypeFlags::FREEZENESS_CACHED) {
827 return self.flags.get().intersects(TypeFlags::IS_FREEZE);
830 self.is_freeze_uncached(tcx, param_env, span)
833 fn is_freeze_uncached(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
834 param_env: &ParameterEnvironment<'tcx>,
835 span: Span) -> bool {
836 assert!(!self.needs_infer());
838 // Fast-path for primitive types
839 let result = match self.sty {
840 TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
841 TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
842 TyStr | TyNever => Some(true),
844 TyArray(..) | TySlice(_) |
845 TyTuple(..) | TyClosure(..) | TyAdt(..) |
846 TyDynamic(..) | TyProjection(..) | TyParam(..) |
847 TyInfer(..) | TyAnon(..) | TyError => None
848 }.unwrap_or_else(|| {
849 self.impls_bound(tcx, param_env, tcx.require_lang_item(lang_items::FreezeTraitLangItem),
850 ¶m_env.is_freeze_cache, span) });
852 if !self.has_param_types() && !self.has_self_ty() {
853 self.flags.set(self.flags.get() | if result {
854 TypeFlags::FREEZENESS_CACHED | TypeFlags::IS_FREEZE
856 TypeFlags::FREEZENESS_CACHED
863 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
864 /// non-copy and *might* have a destructor attached; if it returns
865 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
867 /// (Note that this implies that if `ty` has a destructor attached,
868 /// then `needs_drop` will definitely return `true` for `ty`.)
870 pub fn needs_drop(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
871 param_env: &ty::ParameterEnvironment<'tcx>) -> bool {
872 if self.flags.get().intersects(TypeFlags::NEEDS_DROP_CACHED) {
873 return self.flags.get().intersects(TypeFlags::NEEDS_DROP);
876 self.needs_drop_uncached(tcx, param_env, &mut FxHashSet())
879 fn needs_drop_inner(&'tcx self,
880 tcx: TyCtxt<'a, 'tcx, 'tcx>,
881 param_env: &ty::ParameterEnvironment<'tcx>,
882 stack: &mut FxHashSet<Ty<'tcx>>)
884 if self.flags.get().intersects(TypeFlags::NEEDS_DROP_CACHED) {
885 return self.flags.get().intersects(TypeFlags::NEEDS_DROP);
888 // This should be reported as an error by `check_representable`.
890 // Consider the type as not needing drop in the meanwhile to avoid
892 if let Some(_) = stack.replace(self) {
896 let needs_drop = self.needs_drop_uncached(tcx, param_env, stack);
898 // "Pop" the cycle detection "stack".
904 fn needs_drop_uncached(&'tcx self,
905 tcx: TyCtxt<'a, 'tcx, 'tcx>,
906 param_env: &ty::ParameterEnvironment<'tcx>,
907 stack: &mut FxHashSet<Ty<'tcx>>)
909 assert!(!self.needs_infer());
911 let result = match self.sty {
912 // Fast-path for primitive types
913 ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
914 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
915 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
916 ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
918 // Issue #22536: We first query type_moves_by_default. It sees a
919 // normalized version of the type, and therefore will definitely
920 // know whether the type implements Copy (and thus needs no
921 // cleanup/drop/zeroing) ...
922 _ if !self.moves_by_default(tcx, param_env, DUMMY_SP) => false,
924 // ... (issue #22536 continued) but as an optimization, still use
925 // prior logic of asking for the structural "may drop".
927 // FIXME(#22815): Note that this is a conservative heuristic;
928 // it may report that the type "may drop" when actual type does
929 // not actually have a destructor associated with it. But since
930 // the type absolutely did not have the `Copy` bound attached
931 // (see above), it is sound to treat it as having a destructor.
933 // User destructors are the only way to have concrete drop types.
934 ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
936 // Can refer to a type which may drop.
937 // FIXME(eddyb) check this against a ParameterEnvironment.
938 ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
939 ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
941 // Structural recursion.
942 ty::TyArray(ty, _) | ty::TySlice(ty) => {
943 ty.needs_drop_inner(tcx, param_env, stack)
946 ty::TyClosure(def_id, ref substs) => {
947 substs.upvar_tys(def_id, tcx)
948 .any(|ty| ty.needs_drop_inner(tcx, param_env, stack))
951 ty::TyTuple(ref tys, _) => {
952 tys.iter().any(|ty| ty.needs_drop_inner(tcx, param_env, stack))
955 // unions don't have destructors regardless of the child types
956 ty::TyAdt(def, _) if def.is_union() => false,
958 ty::TyAdt(def, substs) => {
959 def.variants.iter().any(|v| {
960 v.fields.iter().any(|f| {
961 f.ty(tcx, substs).needs_drop_inner(tcx, param_env, stack)
967 if !self.has_param_types() && !self.has_self_ty() {
968 self.flags.set(self.flags.get() | if result {
969 TypeFlags::NEEDS_DROP_CACHED | TypeFlags::NEEDS_DROP
971 TypeFlags::NEEDS_DROP_CACHED
979 pub fn layout<'lcx>(&'tcx self, infcx: &InferCtxt<'a, 'tcx, 'lcx>)
980 -> Result<&'tcx Layout, LayoutError<'tcx>> {
981 let tcx = infcx.tcx.global_tcx();
982 let can_cache = !self.has_param_types() && !self.has_self_ty();
984 if let Some(&cached) = tcx.layout_cache.borrow().get(&self) {
989 let rec_limit = tcx.sess.recursion_limit.get();
990 let depth = tcx.layout_depth.get();
991 if depth > rec_limit {
993 &format!("overflow representing the type `{}`", self));
996 tcx.layout_depth.set(depth+1);
997 let layout = Layout::compute_uncached(self, infcx);
998 tcx.layout_depth.set(depth);
999 let layout = layout?;
1001 tcx.layout_cache.borrow_mut().insert(self, layout);
1007 /// Check whether a type is representable. This means it cannot contain unboxed
1008 /// structural recursion. This check is needed for structs and enums.
1009 pub fn is_representable(&'tcx self,
1010 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1012 -> Representability {
1014 // Iterate until something non-representable is found
1015 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
1016 iter.fold(Representability::Representable, |r1, r2| {
1018 (Representability::SelfRecursive(v1),
1019 Representability::SelfRecursive(v2)) => {
1020 Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
1022 (r1, r2) => cmp::max(r1, r2)
1027 fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
1028 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
1029 -> Representability {
1031 TyTuple(ref ts, _) => {
1032 // Find non representable
1033 fold_repr(ts.iter().map(|ty| {
1034 is_type_structurally_recursive(tcx, sp, seen, ty)
1037 // Fixed-length vectors.
1038 // FIXME(#11924) Behavior undecided for zero-length vectors.
1040 is_type_structurally_recursive(tcx, sp, seen, ty)
1042 TyAdt(def, substs) => {
1043 // Find non representable fields with their spans
1044 fold_repr(def.all_fields().map(|field| {
1045 let ty = field.ty(tcx, substs);
1046 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
1047 match is_type_structurally_recursive(tcx, span, seen, ty) {
1048 Representability::SelfRecursive(_) => {
1049 Representability::SelfRecursive(vec![span])
1056 // this check is run on type definitions, so we don't expect
1057 // to see closure types
1058 bug!("requires check invoked on inapplicable type: {:?}", ty)
1060 _ => Representability::Representable,
1064 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
1066 TyAdt(ty_def, _) => {
1073 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1074 match (&a.sty, &b.sty) {
1075 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
1080 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
1086 // Does the type `ty` directly (without indirection through a pointer)
1087 // contain any types on stack `seen`?
1088 fn is_type_structurally_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1090 seen: &mut Vec<Ty<'tcx>>,
1091 ty: Ty<'tcx>) -> Representability {
1092 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
1097 // Iterate through stack of previously seen types.
1098 let mut iter = seen.iter();
1100 // The first item in `seen` is the type we are actually curious about.
1101 // We want to return SelfRecursive if this type contains itself.
1102 // It is important that we DON'T take generic parameters into account
1103 // for this check, so that Bar<T> in this example counts as SelfRecursive:
1106 // struct Bar<T> { x: Bar<Foo> }
1108 if let Some(&seen_type) = iter.next() {
1109 if same_struct_or_enum(seen_type, def) {
1110 debug!("SelfRecursive: {:?} contains {:?}",
1113 return Representability::SelfRecursive(vec![sp]);
1117 // We also need to know whether the first item contains other types
1118 // that are structurally recursive. If we don't catch this case, we
1119 // will recurse infinitely for some inputs.
1121 // It is important that we DO take generic parameters into account
1122 // here, so that code like this is considered SelfRecursive, not
1123 // ContainsRecursive:
1125 // struct Foo { Option<Option<Foo>> }
1127 for &seen_type in iter {
1128 if same_type(ty, seen_type) {
1129 debug!("ContainsRecursive: {:?} contains {:?}",
1132 return Representability::ContainsRecursive;
1137 // For structs and enums, track all previously seen types by pushing them
1138 // onto the 'seen' stack.
1140 let out = are_inner_types_recursive(tcx, sp, seen, ty);
1145 // No need to push in other cases.
1146 are_inner_types_recursive(tcx, sp, seen, ty)
1151 debug!("is_type_representable: {:?}", self);
1153 // To avoid a stack overflow when checking an enum variant or struct that
1154 // contains a different, structurally recursive type, maintain a stack
1155 // of seen types and check recursion for each of them (issues #3008, #3779).
1156 let mut seen: Vec<Ty> = Vec::new();
1157 let r = is_type_structurally_recursive(tcx, sp, &mut seen, self);
1158 debug!("is_type_representable: {:?} is {:?}", self, r);