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, TypeFoldable};
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 middle::lang_items;
27 use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
28 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
33 use syntax::ast::{self, Name};
34 use syntax::attr::{self, SignedInt, UnsignedInt};
35 use syntax_pos::{Span, DUMMY_SP};
39 pub trait IntTypeExt {
40 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
41 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
43 fn assert_ty_matches(&self, val: Disr);
44 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr;
48 macro_rules! typed_literal {
49 ($tcx:expr, $ty:expr, $lit:expr) => {
51 SignedInt(ast::IntTy::I8) => ConstInt::I8($lit),
52 SignedInt(ast::IntTy::I16) => ConstInt::I16($lit),
53 SignedInt(ast::IntTy::I32) => ConstInt::I32($lit),
54 SignedInt(ast::IntTy::I64) => ConstInt::I64($lit),
55 SignedInt(ast::IntTy::I128) => ConstInt::I128($lit),
56 SignedInt(ast::IntTy::Is) => match $tcx.sess.target.int_type {
57 ast::IntTy::I16 => ConstInt::Isize(ConstIsize::Is16($lit)),
58 ast::IntTy::I32 => ConstInt::Isize(ConstIsize::Is32($lit)),
59 ast::IntTy::I64 => ConstInt::Isize(ConstIsize::Is64($lit)),
62 UnsignedInt(ast::UintTy::U8) => ConstInt::U8($lit),
63 UnsignedInt(ast::UintTy::U16) => ConstInt::U16($lit),
64 UnsignedInt(ast::UintTy::U32) => ConstInt::U32($lit),
65 UnsignedInt(ast::UintTy::U64) => ConstInt::U64($lit),
66 UnsignedInt(ast::UintTy::U128) => ConstInt::U128($lit),
67 UnsignedInt(ast::UintTy::Us) => match $tcx.sess.target.uint_type {
68 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16($lit)),
69 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32($lit)),
70 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64($lit)),
77 impl IntTypeExt for attr::IntType {
78 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
80 SignedInt(ast::IntTy::I8) => tcx.types.i8,
81 SignedInt(ast::IntTy::I16) => tcx.types.i16,
82 SignedInt(ast::IntTy::I32) => tcx.types.i32,
83 SignedInt(ast::IntTy::I64) => tcx.types.i64,
84 SignedInt(ast::IntTy::I128) => tcx.types.i128,
85 SignedInt(ast::IntTy::Is) => tcx.types.isize,
86 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
87 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
88 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
89 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
90 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
91 UnsignedInt(ast::UintTy::Us) => tcx.types.usize,
95 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr {
96 typed_literal!(tcx, *self, 0)
99 fn assert_ty_matches(&self, val: Disr) {
101 (SignedInt(ast::IntTy::I8), ConstInt::I8(_)) => {},
102 (SignedInt(ast::IntTy::I16), ConstInt::I16(_)) => {},
103 (SignedInt(ast::IntTy::I32), ConstInt::I32(_)) => {},
104 (SignedInt(ast::IntTy::I64), ConstInt::I64(_)) => {},
105 (SignedInt(ast::IntTy::I128), ConstInt::I128(_)) => {},
106 (SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) => {},
107 (UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) => {},
108 (UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) => {},
109 (UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) => {},
110 (UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) => {},
111 (UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) => {},
112 (UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => {},
113 _ => bug!("disr type mismatch: {:?} vs {:?}", self, val),
117 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
119 if let Some(val) = val {
120 self.assert_ty_matches(val);
121 (val + typed_literal!(tcx, *self, 1)).ok()
123 Some(self.initial_discriminant(tcx))
129 #[derive(Copy, Clone)]
130 pub enum CopyImplementationError<'tcx> {
131 InfrigingField(&'tcx ty::FieldDef),
136 /// Describes whether a type is representable. For types that are not
137 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
138 /// distinguish between types that are recursive with themselves and types that
139 /// contain a different recursive type. These cases can therefore be treated
140 /// differently when reporting errors.
142 /// The ordering of the cases is significant. They are sorted so that cmp::max
143 /// will keep the "more erroneous" of two values.
144 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
145 pub enum Representability {
148 SelfRecursive(Vec<Span>),
151 impl<'tcx> ParamEnv<'tcx> {
152 /// Construct a trait environment suitable for contexts where
153 /// there are no where clauses in scope.
154 pub fn empty() -> Self {
155 Self::new(ty::Slice::empty())
158 /// Construct a trait environment with the given set of predicates.
159 pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>) -> Self {
160 ty::ParamEnv { caller_bounds }
163 pub fn can_type_implement_copy<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
164 self_type: Ty<'tcx>, span: Span)
165 -> Result<(), CopyImplementationError> {
166 // FIXME: (@jroesch) float this code up
167 tcx.infer_ctxt(self.clone(), Reveal::UserFacing).enter(|infcx| {
168 let (adt, substs) = match self_type.sty {
169 ty::TyAdt(adt, substs) => (adt, substs),
170 _ => return Err(CopyImplementationError::NotAnAdt),
173 let field_implements_copy = |field: &ty::FieldDef| {
174 let cause = traits::ObligationCause::dummy();
175 match traits::fully_normalize(&infcx, cause, &field.ty(tcx, substs)) {
176 Ok(ty) => !infcx.type_moves_by_default(ty, span),
181 for variant in &adt.variants {
182 for field in &variant.fields {
183 if !field_implements_copy(field) {
184 return Err(CopyImplementationError::InfrigingField(field));
189 if adt.has_dtor(tcx) {
190 return Err(CopyImplementationError::HasDestructor);
198 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
199 /// Creates a hash of the type `Ty` which will be the same no matter what crate
200 /// context it's calculated within. This is used by the `type_id` intrinsic.
201 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
202 let mut hasher = StableHasher::new();
203 let mut hcx = StableHashingContext::new(self);
205 hcx.while_hashing_spans(false, |hcx| {
206 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
207 ty.hash_stable(hcx, &mut hasher);
214 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
215 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
217 ty::TyAdt(def, substs) => {
218 for field in def.all_fields() {
219 let field_ty = field.ty(self, substs);
220 if let TyError = field_ty.sty {
230 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
231 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
232 pub fn positional_element_ty(self,
235 variant: Option<DefId>) -> Option<Ty<'tcx>> {
236 match (&ty.sty, variant) {
237 (&TyAdt(adt, substs), Some(vid)) => {
238 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
240 (&TyAdt(adt, substs), None) => {
241 // Don't use `struct_variant`, this may be a univariant enum.
242 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
244 (&TyTuple(ref v, _), None) => v.get(i).cloned(),
249 /// Returns the type of element at field `n` in struct or struct-like type `t`.
250 /// For an enum `t`, `variant` must be some def id.
251 pub fn named_element_ty(self,
254 variant: Option<DefId>) -> Option<Ty<'tcx>> {
255 match (&ty.sty, variant) {
256 (&TyAdt(adt, substs), Some(vid)) => {
257 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
259 (&TyAdt(adt, substs), None) => {
260 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
266 /// Returns the deeply last field of nested structures, or the same type,
267 /// if not a structure at all. Corresponds to the only possible unsized
268 /// field, and its type can be used to determine unsizing strategy.
269 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
270 while let TyAdt(def, substs) = ty.sty {
271 if !def.is_struct() {
274 match def.struct_variant().fields.last() {
275 Some(f) => ty = f.ty(self, substs),
282 /// Same as applying struct_tail on `source` and `target`, but only
283 /// keeps going as long as the two types are instances of the same
284 /// structure definitions.
285 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
286 /// whereas struct_tail produces `T`, and `Trait`, respectively.
287 pub fn struct_lockstep_tails(self,
290 -> (Ty<'tcx>, Ty<'tcx>) {
291 let (mut a, mut b) = (source, target);
292 while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
293 if a_def != b_def || !a_def.is_struct() {
296 match a_def.struct_variant().fields.last() {
298 a = f.ty(self, a_substs);
299 b = f.ty(self, b_substs);
307 /// Given a set of predicates that apply to an object type, returns
308 /// the region bounds that the (erased) `Self` type must
309 /// outlive. Precisely *because* the `Self` type is erased, the
310 /// parameter `erased_self_ty` must be supplied to indicate what type
311 /// has been used to represent `Self` in the predicates
312 /// themselves. This should really be a unique type; `FreshTy(0)` is a
315 /// NB: in some cases, particularly around higher-ranked bounds,
316 /// this function returns a kind of conservative approximation.
317 /// That is, all regions returned by this function are definitely
318 /// required, but there may be other region bounds that are not
319 /// returned, as well as requirements like `for<'a> T: 'a`.
321 /// Requires that trait definitions have been processed so that we can
322 /// elaborate predicates and walk supertraits.
324 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
325 /// what this code should accept.
326 pub fn required_region_bounds(self,
327 erased_self_ty: Ty<'tcx>,
328 predicates: Vec<ty::Predicate<'tcx>>)
329 -> Vec<ty::Region<'tcx>> {
330 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
334 assert!(!erased_self_ty.has_escaping_regions());
336 traits::elaborate_predicates(self, predicates)
337 .filter_map(|predicate| {
339 ty::Predicate::Projection(..) |
340 ty::Predicate::Trait(..) |
341 ty::Predicate::Equate(..) |
342 ty::Predicate::Subtype(..) |
343 ty::Predicate::WellFormed(..) |
344 ty::Predicate::ObjectSafe(..) |
345 ty::Predicate::ClosureKind(..) |
346 ty::Predicate::RegionOutlives(..) => {
349 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
350 // Search for a bound of the form `erased_self_ty
351 // : 'a`, but be wary of something like `for<'a>
352 // erased_self_ty : 'a` (we interpret a
353 // higher-ranked bound like that as 'static,
354 // though at present the code in `fulfill.rs`
355 // considers such bounds to be unsatisfiable, so
356 // it's kind of a moot point since you could never
357 // construct such an object, but this seems
358 // correct even if that code changes).
359 if t == erased_self_ty && !r.has_escaping_regions() {
370 /// Calculate the destructor of a given type.
371 pub fn calculate_dtor(
374 validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
375 ) -> Option<ty::Destructor> {
376 let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
382 self.coherent_trait((LOCAL_CRATE, drop_trait));
384 let mut dtor_did = None;
385 let ty = self.type_of(adt_did);
386 self.trait_def(drop_trait).for_each_relevant_impl(self, ty, |impl_did| {
387 if let Some(item) = self.associated_items(impl_did).next() {
388 if let Ok(()) = validate(self, impl_did) {
389 dtor_did = Some(item.def_id);
394 let dtor_did = match dtor_did {
399 Some(ty::Destructor { did: dtor_did })
402 /// Return the set of types that are required to be alive in
403 /// order to run the destructor of `def` (see RFCs 769 and
406 /// Note that this returns only the constraints for the
407 /// destructor of `def` itself. For the destructors of the
408 /// contents, you need `adt_dtorck_constraint`.
409 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
410 -> Vec<ty::subst::Kind<'tcx>>
412 let dtor = match def.destructor(self) {
414 debug!("destructor_constraints({:?}) - no dtor", def.did);
417 Some(dtor) => dtor.did
420 // RFC 1238: if the destructor method is tagged with the
421 // attribute `unsafe_destructor_blind_to_params`, then the
422 // compiler is being instructed to *assume* that the
423 // destructor will not access borrowed data,
424 // even if such data is otherwise reachable.
426 // Such access can be in plain sight (e.g. dereferencing
427 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
428 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
429 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
430 debug!("destructor_constraint({:?}) - blind", def.did);
434 let impl_def_id = self.associated_item(dtor).container.id();
435 let impl_generics = self.generics_of(impl_def_id);
437 // We have a destructor - all the parameters that are not
438 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
441 // We need to return the list of parameters from the ADTs
442 // generics/substs that correspond to impure parameters on the
443 // impl's generics. This is a bit ugly, but conceptually simple:
445 // Suppose our ADT looks like the following
447 // struct S<X, Y, Z>(X, Y, Z);
451 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
453 // We want to return the parameters (X, Y). For that, we match
454 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
455 // <P1, P2, P0>, and then look up which of the impl substs refer to
456 // parameters marked as pure.
458 let impl_substs = match self.type_of(impl_def_id).sty {
459 ty::TyAdt(def_, substs) if def_ == def => substs,
463 let item_substs = match self.type_of(def.did).sty {
464 ty::TyAdt(def_, substs) if def_ == def => substs,
468 let result = item_substs.iter().zip(impl_substs.iter())
470 if let Some(&ty::RegionKind::ReEarlyBound(ref ebr)) = k.as_region() {
471 !impl_generics.region_param(ebr).pure_wrt_drop
472 } else if let Some(&ty::TyS {
473 sty: ty::TypeVariants::TyParam(ref pt), ..
475 !impl_generics.type_param(pt).pure_wrt_drop
477 // not a type or region param - this should be reported
481 }).map(|(&item_param, _)| item_param).collect();
482 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
486 /// Return a set of constraints that needs to be satisfied in
487 /// order for `ty` to be valid for destruction.
488 pub fn dtorck_constraint_for_ty(self,
493 -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
495 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
496 span, for_ty, depth, ty);
498 if depth >= self.sess.recursion_limit.get() {
499 let mut err = struct_span_err!(
500 self.sess, span, E0320,
501 "overflow while adding drop-check rules for {}", for_ty);
502 err.note(&format!("overflowed on {}", ty));
504 return Err(ErrorReported);
507 let result = match ty.sty {
508 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
509 ty::TyFloat(_) | ty::TyStr | ty::TyNever |
510 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => {
511 // these types never have a destructor
512 Ok(ty::DtorckConstraint::empty())
515 ty::TyArray(ety, _) | ty::TySlice(ety) => {
516 // single-element containers, behave like their element
517 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
520 ty::TyTuple(tys, _) => {
521 tys.iter().map(|ty| {
522 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
526 ty::TyClosure(def_id, substs) => {
527 substs.upvar_tys(def_id, self).map(|ty| {
528 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
532 ty::TyAdt(def, substs) => {
533 let ty::DtorckConstraint {
534 dtorck_types, outlives
535 } = self.at(span).adt_dtorck_constraint(def.did);
536 Ok(ty::DtorckConstraint {
537 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
538 // there, but that needs some way to handle cycles.
539 dtorck_types: dtorck_types.subst(self, substs),
540 outlives: outlives.subst(self, substs)
544 // Objects must be alive in order for their destructor
546 ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
547 outlives: vec![Kind::from(ty)],
548 dtorck_types: vec![],
551 // Types that can't be resolved. Pass them forward.
552 ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
553 Ok(ty::DtorckConstraint {
555 dtorck_types: vec![ty],
559 ty::TyInfer(..) | ty::TyError => {
560 self.sess.delay_span_bug(span, "unresolved type in dtorck");
565 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
569 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
570 let mut def_id = def_id;
571 while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
572 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
573 bug!("closure {:?} has no parent", def_id);
579 /// Given the def-id of some item that has no type parameters, make
580 /// a suitable "empty substs" for it.
581 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
582 ty::Substs::for_item(self, item_def_id,
583 |_, _| self.types.re_erased,
585 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
590 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
591 tcx: TyCtxt<'a, 'gcx, 'tcx>,
592 state: StableHasher<W>,
595 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
596 where W: StableHasherResult
598 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
599 TypeIdHasher { tcx: tcx, state: StableHasher::new() }
602 pub fn finish(self) -> W {
606 pub fn hash<T: Hash>(&mut self, x: T) {
607 x.hash(&mut self.state);
610 fn hash_discriminant_u8<T>(&mut self, x: &T) {
612 intrinsics::discriminant_value(x)
615 assert_eq!(v, b as u64);
619 fn def_id(&mut self, did: DefId) {
620 // Hash the DefPath corresponding to the DefId, which is independent
621 // of compiler internal state. We already have a stable hash value of
622 // all DefPaths available via tcx.def_path_hash(), so we just feed that
624 let hash = self.tcx.def_path_hash(did);
629 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
630 where W: StableHasherResult
632 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
633 // Distinguish between the Ty variants uniformly.
634 self.hash_discriminant_u8(&ty.sty);
637 TyInt(i) => self.hash(i),
638 TyUint(u) => self.hash(u),
639 TyFloat(f) => self.hash(f),
640 TyArray(_, n) => self.hash(n),
642 TyRef(_, m) => self.hash(m.mutbl),
643 TyClosure(def_id, _) |
645 TyFnDef(def_id, ..) => self.def_id(def_id),
646 TyAdt(d, _) => self.def_id(d.did),
648 self.hash(f.unsafety());
650 self.hash(f.variadic());
651 self.hash(f.inputs().skip_binder().len());
653 TyDynamic(ref data, ..) => {
654 if let Some(p) = data.principal() {
655 self.def_id(p.def_id());
657 for d in data.auto_traits() {
661 TyTuple(tys, defaulted) => {
662 self.hash(tys.len());
663 self.hash(defaulted);
667 self.hash(p.name.as_str());
669 TyProjection(ref data) => {
670 self.def_id(data.trait_ref.def_id);
671 self.hash(data.item_name.as_str());
680 TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
683 ty.super_visit_with(self)
686 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
687 self.hash_discriminant_u8(r);
692 // No variant fields to hash for these ...
694 ty::ReLateBound(db, ty::BrAnon(i)) => {
698 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
701 ty::ReLateBound(..) |
705 ty::ReSkolemized(..) => {
706 bug!("TypeIdHasher: unexpected region {:?}", r)
712 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
713 // Anonymize late-bound regions so that, for example:
714 // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
715 // result in the same TypeId (the two types are equivalent).
716 self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
720 impl<'a, 'tcx> ty::TyS<'tcx> {
721 pub fn moves_by_default(&'tcx self,
722 tcx: TyCtxt<'a, 'tcx, 'tcx>,
723 param_env: ParamEnv<'tcx>,
726 !tcx.at(span).is_copy_raw(param_env.and(self))
729 pub fn is_sized(&'tcx self,
730 tcx: TyCtxt<'a, 'tcx, 'tcx>,
731 param_env: ParamEnv<'tcx>,
734 tcx.at(span).is_sized_raw(param_env.and(self))
737 pub fn is_freeze(&'tcx self,
738 tcx: TyCtxt<'a, 'tcx, 'tcx>,
739 param_env: ParamEnv<'tcx>,
742 tcx.at(span).is_freeze_raw(param_env.and(self))
745 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
746 /// non-copy and *might* have a destructor attached; if it returns
747 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
749 /// (Note that this implies that if `ty` has a destructor attached,
750 /// then `needs_drop` will definitely return `true` for `ty`.)
752 pub fn needs_drop(&'tcx self,
753 tcx: TyCtxt<'a, 'tcx, 'tcx>,
754 param_env: ty::ParamEnv<'tcx>)
756 tcx.needs_drop_raw(param_env.and(self))
760 pub fn layout<'lcx>(&'tcx self, infcx: &InferCtxt<'a, 'tcx, 'lcx>)
761 -> Result<&'tcx Layout, LayoutError<'tcx>> {
762 let tcx = infcx.tcx.global_tcx();
763 let can_cache = !self.has_param_types() && !self.has_self_ty();
765 if let Some(&cached) = tcx.layout_cache.borrow().get(&self) {
770 let rec_limit = tcx.sess.recursion_limit.get();
771 let depth = tcx.layout_depth.get();
772 if depth > rec_limit {
774 &format!("overflow representing the type `{}`", self));
777 tcx.layout_depth.set(depth+1);
778 let layout = Layout::compute_uncached(self, infcx);
779 tcx.layout_depth.set(depth);
780 let layout = layout?;
782 tcx.layout_cache.borrow_mut().insert(self, layout);
788 /// Check whether a type is representable. This means it cannot contain unboxed
789 /// structural recursion. This check is needed for structs and enums.
790 pub fn is_representable(&'tcx self,
791 tcx: TyCtxt<'a, 'tcx, 'tcx>,
793 -> Representability {
795 // Iterate until something non-representable is found
796 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
797 iter.fold(Representability::Representable, |r1, r2| {
799 (Representability::SelfRecursive(v1),
800 Representability::SelfRecursive(v2)) => {
801 Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
803 (r1, r2) => cmp::max(r1, r2)
808 fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
809 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
810 -> Representability {
812 TyTuple(ref ts, _) => {
813 // Find non representable
814 fold_repr(ts.iter().map(|ty| {
815 is_type_structurally_recursive(tcx, sp, seen, ty)
818 // Fixed-length vectors.
819 // FIXME(#11924) Behavior undecided for zero-length vectors.
821 is_type_structurally_recursive(tcx, sp, seen, ty)
823 TyAdt(def, substs) => {
824 // Find non representable fields with their spans
825 fold_repr(def.all_fields().map(|field| {
826 let ty = field.ty(tcx, substs);
827 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
828 match is_type_structurally_recursive(tcx, span, seen, ty) {
829 Representability::SelfRecursive(_) => {
830 Representability::SelfRecursive(vec![span])
837 // this check is run on type definitions, so we don't expect
838 // to see closure types
839 bug!("requires check invoked on inapplicable type: {:?}", ty)
841 _ => Representability::Representable,
845 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
847 TyAdt(ty_def, _) => {
854 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
855 match (&a.sty, &b.sty) {
856 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
861 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
867 // Does the type `ty` directly (without indirection through a pointer)
868 // contain any types on stack `seen`?
869 fn is_type_structurally_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
871 seen: &mut Vec<Ty<'tcx>>,
872 ty: Ty<'tcx>) -> Representability {
873 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
878 // Iterate through stack of previously seen types.
879 let mut iter = seen.iter();
881 // The first item in `seen` is the type we are actually curious about.
882 // We want to return SelfRecursive if this type contains itself.
883 // It is important that we DON'T take generic parameters into account
884 // for this check, so that Bar<T> in this example counts as SelfRecursive:
887 // struct Bar<T> { x: Bar<Foo> }
889 if let Some(&seen_type) = iter.next() {
890 if same_struct_or_enum(seen_type, def) {
891 debug!("SelfRecursive: {:?} contains {:?}",
894 return Representability::SelfRecursive(vec![sp]);
898 // We also need to know whether the first item contains other types
899 // that are structurally recursive. If we don't catch this case, we
900 // will recurse infinitely for some inputs.
902 // It is important that we DO take generic parameters into account
903 // here, so that code like this is considered SelfRecursive, not
904 // ContainsRecursive:
906 // struct Foo { Option<Option<Foo>> }
908 for &seen_type in iter {
909 if same_type(ty, seen_type) {
910 debug!("ContainsRecursive: {:?} contains {:?}",
913 return Representability::ContainsRecursive;
918 // For structs and enums, track all previously seen types by pushing them
919 // onto the 'seen' stack.
921 let out = are_inner_types_recursive(tcx, sp, seen, ty);
926 // No need to push in other cases.
927 are_inner_types_recursive(tcx, sp, seen, ty)
932 debug!("is_type_representable: {:?}", self);
934 // To avoid a stack overflow when checking an enum variant or struct that
935 // contains a different, structurally recursive type, maintain a stack
936 // of seen types and check recursion for each of them (issues #3008, #3779).
937 let mut seen: Vec<Ty> = Vec::new();
938 let r = is_type_structurally_recursive(tcx, sp, &mut seen, self);
939 debug!("is_type_representable: {:?} is {:?}", self, r);
944 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
945 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
948 let (param_env, ty) = query.into_parts();
949 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
950 tcx.infer_ctxt(param_env, Reveal::UserFacing)
951 .enter(|infcx| traits::type_known_to_meet_bound(&infcx, ty, trait_def_id, DUMMY_SP))
954 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
955 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
958 let (param_env, ty) = query.into_parts();
959 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
960 tcx.infer_ctxt(param_env, Reveal::UserFacing)
961 .enter(|infcx| traits::type_known_to_meet_bound(&infcx, ty, trait_def_id, DUMMY_SP))
964 fn is_freeze_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::FreezeTraitLangItem);
970 tcx.infer_ctxt(param_env, Reveal::UserFacing)
971 .enter(|infcx| traits::type_known_to_meet_bound(&infcx, ty, trait_def_id, DUMMY_SP))
974 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
975 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
978 let (param_env, ty) = query.into_parts();
980 let needs_drop = |ty: Ty<'tcx>| -> bool {
981 match ty::queries::needs_drop_raw::try_get(tcx, DUMMY_SP, param_env.and(ty)) {
984 // Cycles should be reported as an error by `check_representable`.
986 // Consider the type as not needing drop in the meanwhile to avoid
993 assert!(!ty.needs_infer());
996 // Fast-path for primitive types
997 ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
998 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
999 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1000 ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
1002 // Issue #22536: We first query type_moves_by_default. It sees a
1003 // normalized version of the type, and therefore will definitely
1004 // know whether the type implements Copy (and thus needs no
1005 // cleanup/drop/zeroing) ...
1006 _ if !ty.moves_by_default(tcx, param_env, DUMMY_SP) => false,
1008 // ... (issue #22536 continued) but as an optimization, still use
1009 // prior logic of asking for the structural "may drop".
1011 // FIXME(#22815): Note that this is a conservative heuristic;
1012 // it may report that the type "may drop" when actual type does
1013 // not actually have a destructor associated with it. But since
1014 // the type absolutely did not have the `Copy` bound attached
1015 // (see above), it is sound to treat it as having a destructor.
1017 // User destructors are the only way to have concrete drop types.
1018 ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
1020 // Can refer to a type which may drop.
1021 // FIXME(eddyb) check this against a ParamEnv.
1022 ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
1023 ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
1025 // Structural recursion.
1026 ty::TyArray(ty, _) | ty::TySlice(ty) => needs_drop(ty),
1028 ty::TyClosure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1030 ty::TyTuple(ref tys, _) => tys.iter().cloned().any(needs_drop),
1032 // unions don't have destructors regardless of the child types
1033 ty::TyAdt(def, _) if def.is_union() => false,
1035 ty::TyAdt(def, substs) =>
1036 def.variants.iter().any(
1037 |variant| variant.fields.iter().any(
1038 |field| needs_drop(field.ty(tcx, substs)))),
1043 pub fn provide(providers: &mut ty::maps::Providers) {
1044 *providers = ty::maps::Providers {