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;
15 use ich::NodeIdHashingMode;
16 use middle::const_val::ConstVal;
17 use traits::{self, Reveal};
18 use ty::{self, Ty, TyCtxt, TypeFoldable};
19 use ty::fold::TypeVisitor;
20 use ty::layout::{Layout, LayoutError};
21 use ty::subst::{Subst, Kind};
22 use ty::TypeVariants::*;
23 use util::common::ErrorReported;
24 use middle::lang_items;
26 use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
27 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
29 use rustc_data_structures::fx::FxHashMap;
34 use syntax::ast::{self, Name};
35 use syntax::attr::{self, SignedInt, UnsignedInt};
36 use syntax_pos::{Span, DUMMY_SP};
40 pub trait IntTypeExt {
41 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
42 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
44 fn assert_ty_matches(&self, val: Disr);
45 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr;
49 macro_rules! typed_literal {
50 ($tcx:expr, $ty:expr, $lit:expr) => {
52 SignedInt(ast::IntTy::I8) => ConstInt::I8($lit),
53 SignedInt(ast::IntTy::I16) => ConstInt::I16($lit),
54 SignedInt(ast::IntTy::I32) => ConstInt::I32($lit),
55 SignedInt(ast::IntTy::I64) => ConstInt::I64($lit),
56 SignedInt(ast::IntTy::I128) => ConstInt::I128($lit),
57 SignedInt(ast::IntTy::Is) => match $tcx.sess.target.isize_ty {
58 ast::IntTy::I16 => ConstInt::Isize(ConstIsize::Is16($lit)),
59 ast::IntTy::I32 => ConstInt::Isize(ConstIsize::Is32($lit)),
60 ast::IntTy::I64 => ConstInt::Isize(ConstIsize::Is64($lit)),
63 UnsignedInt(ast::UintTy::U8) => ConstInt::U8($lit),
64 UnsignedInt(ast::UintTy::U16) => ConstInt::U16($lit),
65 UnsignedInt(ast::UintTy::U32) => ConstInt::U32($lit),
66 UnsignedInt(ast::UintTy::U64) => ConstInt::U64($lit),
67 UnsignedInt(ast::UintTy::U128) => ConstInt::U128($lit),
68 UnsignedInt(ast::UintTy::Us) => match $tcx.sess.target.usize_ty {
69 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16($lit)),
70 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32($lit)),
71 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64($lit)),
78 impl IntTypeExt for attr::IntType {
79 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
81 SignedInt(ast::IntTy::I8) => tcx.types.i8,
82 SignedInt(ast::IntTy::I16) => tcx.types.i16,
83 SignedInt(ast::IntTy::I32) => tcx.types.i32,
84 SignedInt(ast::IntTy::I64) => tcx.types.i64,
85 SignedInt(ast::IntTy::I128) => tcx.types.i128,
86 SignedInt(ast::IntTy::Is) => tcx.types.isize,
87 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
88 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
89 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
90 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
91 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
92 UnsignedInt(ast::UintTy::Us) => tcx.types.usize,
96 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr {
97 typed_literal!(tcx, *self, 0)
100 fn assert_ty_matches(&self, val: Disr) {
102 (SignedInt(ast::IntTy::I8), ConstInt::I8(_)) => {},
103 (SignedInt(ast::IntTy::I16), ConstInt::I16(_)) => {},
104 (SignedInt(ast::IntTy::I32), ConstInt::I32(_)) => {},
105 (SignedInt(ast::IntTy::I64), ConstInt::I64(_)) => {},
106 (SignedInt(ast::IntTy::I128), ConstInt::I128(_)) => {},
107 (SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) => {},
108 (UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) => {},
109 (UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) => {},
110 (UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) => {},
111 (UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) => {},
112 (UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) => {},
113 (UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => {},
114 _ => bug!("disr type mismatch: {:?} vs {:?}", self, val),
118 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
120 if let Some(val) = val {
121 self.assert_ty_matches(val);
122 (val + typed_literal!(tcx, *self, 1)).ok()
124 Some(self.initial_discriminant(tcx))
130 #[derive(Copy, Clone)]
131 pub enum CopyImplementationError<'tcx> {
132 InfrigingField(&'tcx ty::FieldDef),
137 /// Describes whether a type is representable. For types that are not
138 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
139 /// distinguish between types that are recursive with themselves and types that
140 /// contain a different recursive type. These cases can therefore be treated
141 /// differently when reporting errors.
143 /// The ordering of the cases is significant. They are sorted so that cmp::max
144 /// will keep the "more erroneous" of two values.
145 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
146 pub enum Representability {
149 SelfRecursive(Vec<Span>),
152 impl<'tcx> ty::ParamEnv<'tcx> {
153 /// Construct a trait environment suitable for contexts where
154 /// there are no where clauses in scope.
155 pub fn empty(reveal: Reveal) -> Self {
156 Self::new(ty::Slice::empty(), reveal)
159 /// Construct a trait environment with the given set of predicates.
160 pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>,
163 ty::ParamEnv { caller_bounds, reveal }
166 /// Returns a new parameter environment with the same clauses, but
167 /// which "reveals" the true results of projections in all cases
168 /// (even for associated types that are specializable). This is
169 /// the desired behavior during trans and certain other special
170 /// contexts; normally though we want to use `Reveal::UserFacing`,
171 /// which is the default.
172 pub fn reveal_all(self) -> Self {
173 ty::ParamEnv { reveal: Reveal::All, ..self }
176 pub fn can_type_implement_copy<'a>(self,
177 tcx: TyCtxt<'a, 'tcx, 'tcx>,
178 self_type: Ty<'tcx>, span: Span)
179 -> Result<(), CopyImplementationError<'tcx>> {
180 // FIXME: (@jroesch) float this code up
181 tcx.infer_ctxt().enter(|infcx| {
182 let (adt, substs) = match self_type.sty {
183 ty::TyAdt(adt, substs) => (adt, substs),
184 _ => return Err(CopyImplementationError::NotAnAdt),
187 let field_implements_copy = |field: &ty::FieldDef| {
188 let cause = traits::ObligationCause::dummy();
189 match traits::fully_normalize(&infcx, cause, self, &field.ty(tcx, substs)) {
190 Ok(ty) => !infcx.type_moves_by_default(self, ty, span),
195 for variant in &adt.variants {
196 for field in &variant.fields {
197 if !field_implements_copy(field) {
198 return Err(CopyImplementationError::InfrigingField(field));
203 if adt.has_dtor(tcx) {
204 return Err(CopyImplementationError::HasDestructor);
212 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
213 /// Creates a hash of the type `Ty` which will be the same no matter what crate
214 /// context it's calculated within. This is used by the `type_id` intrinsic.
215 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
216 let mut hasher = StableHasher::new();
217 let mut hcx = self.create_stable_hashing_context();
219 // We want the type_id be independent of the types free regions, so we
220 // erase them. The erase_regions() call will also anonymize bound
221 // regions, which is desirable too.
222 let ty = self.erase_regions(&ty);
224 hcx.while_hashing_spans(false, |hcx| {
225 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
226 ty.hash_stable(hcx, &mut hasher);
233 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
234 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
236 ty::TyAdt(def, substs) => {
237 for field in def.all_fields() {
238 let field_ty = field.ty(self, substs);
239 if let TyError = field_ty.sty {
249 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
250 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
251 pub fn positional_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).fields.get(i).map(|f| f.ty(self, substs))
259 (&TyAdt(adt, substs), None) => {
260 // Don't use `struct_variant`, this may be a univariant enum.
261 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
263 (&TyTuple(ref v, _), None) => v.get(i).cloned(),
268 /// Returns the type of element at field `n` in struct or struct-like type `t`.
269 /// For an enum `t`, `variant` must be some def id.
270 pub fn named_element_ty(self,
273 variant: Option<DefId>) -> Option<Ty<'tcx>> {
274 match (&ty.sty, variant) {
275 (&TyAdt(adt, substs), Some(vid)) => {
276 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
278 (&TyAdt(adt, substs), None) => {
279 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
285 /// Returns the deeply last field of nested structures, or the same type,
286 /// if not a structure at all. Corresponds to the only possible unsized
287 /// field, and its type can be used to determine unsizing strategy.
288 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
291 ty::TyAdt(def, substs) => {
292 if !def.is_struct() {
295 match def.struct_variant().fields.last() {
296 Some(f) => ty = f.ty(self, substs),
301 ty::TyTuple(tys, _) => {
302 if let Some((&last_ty, _)) = tys.split_last() {
317 /// Same as applying struct_tail on `source` and `target`, but only
318 /// keeps going as long as the two types are instances of the same
319 /// structure definitions.
320 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
321 /// whereas struct_tail produces `T`, and `Trait`, respectively.
322 pub fn struct_lockstep_tails(self,
325 -> (Ty<'tcx>, Ty<'tcx>) {
326 let (mut a, mut b) = (source, target);
328 match (&a.sty, &b.sty) {
329 (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs))
330 if a_def == b_def && a_def.is_struct() => {
331 if let Some(f) = a_def.struct_variant().fields.last() {
332 a = f.ty(self, a_substs);
333 b = f.ty(self, b_substs);
338 (&TyTuple(a_tys, _), &TyTuple(b_tys, _))
339 if a_tys.len() == b_tys.len() => {
340 if let Some(a_last) = a_tys.last() {
342 b = b_tys.last().unwrap();
353 /// Given a set of predicates that apply to an object type, returns
354 /// the region bounds that the (erased) `Self` type must
355 /// outlive. Precisely *because* the `Self` type is erased, the
356 /// parameter `erased_self_ty` must be supplied to indicate what type
357 /// has been used to represent `Self` in the predicates
358 /// themselves. This should really be a unique type; `FreshTy(0)` is a
361 /// NB: in some cases, particularly around higher-ranked bounds,
362 /// this function returns a kind of conservative approximation.
363 /// That is, all regions returned by this function are definitely
364 /// required, but there may be other region bounds that are not
365 /// returned, as well as requirements like `for<'a> T: 'a`.
367 /// Requires that trait definitions have been processed so that we can
368 /// elaborate predicates and walk supertraits.
370 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
371 /// what this code should accept.
372 pub fn required_region_bounds(self,
373 erased_self_ty: Ty<'tcx>,
374 predicates: Vec<ty::Predicate<'tcx>>)
375 -> Vec<ty::Region<'tcx>> {
376 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
380 assert!(!erased_self_ty.has_escaping_regions());
382 traits::elaborate_predicates(self, predicates)
383 .filter_map(|predicate| {
385 ty::Predicate::Projection(..) |
386 ty::Predicate::Trait(..) |
387 ty::Predicate::Equate(..) |
388 ty::Predicate::Subtype(..) |
389 ty::Predicate::WellFormed(..) |
390 ty::Predicate::ObjectSafe(..) |
391 ty::Predicate::ClosureKind(..) |
392 ty::Predicate::RegionOutlives(..) |
393 ty::Predicate::ConstEvaluatable(..) => {
396 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
397 // Search for a bound of the form `erased_self_ty
398 // : 'a`, but be wary of something like `for<'a>
399 // erased_self_ty : 'a` (we interpret a
400 // higher-ranked bound like that as 'static,
401 // though at present the code in `fulfill.rs`
402 // considers such bounds to be unsatisfiable, so
403 // it's kind of a moot point since you could never
404 // construct such an object, but this seems
405 // correct even if that code changes).
406 if t == erased_self_ty && !r.has_escaping_regions() {
417 /// Calculate the destructor of a given type.
418 pub fn calculate_dtor(
421 validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
422 ) -> Option<ty::Destructor> {
423 let drop_trait = if let Some(def_id) = self.lang_items().drop_trait() {
429 self.coherent_trait((LOCAL_CRATE, drop_trait));
431 let mut dtor_did = None;
432 let ty = self.type_of(adt_did);
433 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
434 if let Some(item) = self.associated_items(impl_did).next() {
435 if let Ok(()) = validate(self, impl_did) {
436 dtor_did = Some(item.def_id);
441 let dtor_did = match dtor_did {
446 Some(ty::Destructor { did: dtor_did })
449 /// Return the set of types that are required to be alive in
450 /// order to run the destructor of `def` (see RFCs 769 and
453 /// Note that this returns only the constraints for the
454 /// destructor of `def` itself. For the destructors of the
455 /// contents, you need `adt_dtorck_constraint`.
456 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
457 -> Vec<ty::subst::Kind<'tcx>>
459 let dtor = match def.destructor(self) {
461 debug!("destructor_constraints({:?}) - no dtor", def.did);
464 Some(dtor) => dtor.did
467 // RFC 1238: if the destructor method is tagged with the
468 // attribute `unsafe_destructor_blind_to_params`, then the
469 // compiler is being instructed to *assume* that the
470 // destructor will not access borrowed data,
471 // even if such data is otherwise reachable.
473 // Such access can be in plain sight (e.g. dereferencing
474 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
475 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
476 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
477 debug!("destructor_constraint({:?}) - blind", def.did);
481 let impl_def_id = self.associated_item(dtor).container.id();
482 let impl_generics = self.generics_of(impl_def_id);
484 // We have a destructor - all the parameters that are not
485 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
488 // We need to return the list of parameters from the ADTs
489 // generics/substs that correspond to impure parameters on the
490 // impl's generics. This is a bit ugly, but conceptually simple:
492 // Suppose our ADT looks like the following
494 // struct S<X, Y, Z>(X, Y, Z);
498 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
500 // We want to return the parameters (X, Y). For that, we match
501 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
502 // <P1, P2, P0>, and then look up which of the impl substs refer to
503 // parameters marked as pure.
505 let impl_substs = match self.type_of(impl_def_id).sty {
506 ty::TyAdt(def_, substs) if def_ == def => substs,
510 let item_substs = match self.type_of(def.did).sty {
511 ty::TyAdt(def_, substs) if def_ == def => substs,
515 let result = item_substs.iter().zip(impl_substs.iter())
517 if let Some(&ty::RegionKind::ReEarlyBound(ref ebr)) = k.as_region() {
518 !impl_generics.region_param(ebr, self).pure_wrt_drop
519 } else if let Some(&ty::TyS {
520 sty: ty::TypeVariants::TyParam(ref pt), ..
522 !impl_generics.type_param(pt, self).pure_wrt_drop
524 // not a type or region param - this should be reported
528 }).map(|(&item_param, _)| item_param).collect();
529 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
533 /// Return a set of constraints that needs to be satisfied in
534 /// order for `ty` to be valid for destruction.
535 pub fn dtorck_constraint_for_ty(self,
540 -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
542 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
543 span, for_ty, depth, ty);
545 if depth >= self.sess.recursion_limit.get() {
546 let mut err = struct_span_err!(
547 self.sess, span, E0320,
548 "overflow while adding drop-check rules for {}", for_ty);
549 err.note(&format!("overflowed on {}", ty));
551 return Err(ErrorReported);
554 let result = match ty.sty {
555 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
556 ty::TyFloat(_) | ty::TyStr | ty::TyNever |
557 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => {
558 // these types never have a destructor
559 Ok(ty::DtorckConstraint::empty())
562 ty::TyArray(ety, _) | ty::TySlice(ety) => {
563 // single-element containers, behave like their element
564 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
567 ty::TyTuple(tys, _) => {
568 tys.iter().map(|ty| {
569 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
573 ty::TyClosure(def_id, substs) => {
574 substs.upvar_tys(def_id, self).map(|ty| {
575 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
579 ty::TyGenerator(def_id, substs, interior) => {
580 substs.upvar_tys(def_id, self).chain(iter::once(interior.witness)).map(|ty| {
581 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
585 ty::TyAdt(def, substs) => {
586 let ty::DtorckConstraint {
587 dtorck_types, outlives
588 } = self.at(span).adt_dtorck_constraint(def.did);
589 Ok(ty::DtorckConstraint {
590 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
591 // there, but that needs some way to handle cycles.
592 dtorck_types: dtorck_types.subst(self, substs),
593 outlives: outlives.subst(self, substs)
597 // Objects must be alive in order for their destructor
599 ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
600 outlives: vec![Kind::from(ty)],
601 dtorck_types: vec![],
604 // Types that can't be resolved. Pass them forward.
605 ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
606 Ok(ty::DtorckConstraint {
608 dtorck_types: vec![ty],
612 ty::TyInfer(..) | ty::TyError => {
613 self.sess.delay_span_bug(span, "unresolved type in dtorck");
618 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
622 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
623 let mut def_id = def_id;
624 while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
625 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
626 bug!("closure {:?} has no parent", def_id);
632 /// Given the def-id of some item that has no type parameters, make
633 /// a suitable "empty substs" for it.
634 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
635 ty::Substs::for_item(self, item_def_id,
636 |_, _| self.types.re_erased,
638 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
642 pub fn const_usize(&self, val: u16) -> ConstInt {
643 match self.sess.target.usize_ty {
644 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16(val as u16)),
645 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32(val as u32)),
646 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64(val as u64)),
652 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
653 tcx: TyCtxt<'a, 'gcx, 'tcx>,
654 state: StableHasher<W>,
657 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
658 where W: StableHasherResult
660 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
661 TypeIdHasher { tcx: tcx, state: StableHasher::new() }
664 pub fn finish(self) -> W {
668 pub fn hash<T: Hash>(&mut self, x: T) {
669 x.hash(&mut self.state);
672 fn hash_discriminant_u8<T>(&mut self, x: &T) {
674 intrinsics::discriminant_value(x)
677 assert_eq!(v, b as u64);
681 fn def_id(&mut self, did: DefId) {
682 // Hash the DefPath corresponding to the DefId, which is independent
683 // of compiler internal state. We already have a stable hash value of
684 // all DefPaths available via tcx.def_path_hash(), so we just feed that
686 let hash = self.tcx.def_path_hash(did);
691 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
692 where W: StableHasherResult
694 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
695 // Distinguish between the Ty variants uniformly.
696 self.hash_discriminant_u8(&ty.sty);
699 TyInt(i) => self.hash(i),
700 TyUint(u) => self.hash(u),
701 TyFloat(f) => self.hash(f),
703 self.hash_discriminant_u8(&n.val);
705 ConstVal::Integral(x) => self.hash(x.to_u64().unwrap()),
706 ConstVal::Unevaluated(def_id, _) => self.def_id(def_id),
707 _ => bug!("arrays should not have {:?} as length", n)
711 TyRef(_, m) => self.hash(m.mutbl),
712 TyClosure(def_id, _) |
713 TyGenerator(def_id, _, _) |
715 TyFnDef(def_id, _) => self.def_id(def_id),
716 TyAdt(d, _) => self.def_id(d.did),
718 self.hash(f.unsafety());
720 self.hash(f.variadic());
721 self.hash(f.inputs().skip_binder().len());
723 TyDynamic(ref data, ..) => {
724 if let Some(p) = data.principal() {
725 self.def_id(p.def_id());
727 for d in data.auto_traits() {
731 TyTuple(tys, defaulted) => {
732 self.hash(tys.len());
733 self.hash(defaulted);
737 self.hash(p.name.as_str());
739 TyProjection(ref data) => {
740 self.def_id(data.item_def_id);
749 TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
752 ty.super_visit_with(self)
755 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
756 self.hash_discriminant_u8(r);
761 // No variant fields to hash for these ...
763 ty::ReLateBound(db, ty::BrAnon(i)) => {
767 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
770 ty::ReLateBound(..) |
774 ty::ReSkolemized(..) => {
775 bug!("TypeIdHasher: unexpected region {:?}", r)
781 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
782 // Anonymize late-bound regions so that, for example:
783 // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
784 // result in the same TypeId (the two types are equivalent).
785 self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
789 impl<'a, 'tcx> ty::TyS<'tcx> {
790 pub fn moves_by_default(&'tcx self,
791 tcx: TyCtxt<'a, 'tcx, 'tcx>,
792 param_env: ty::ParamEnv<'tcx>,
795 !tcx.at(span).is_copy_raw(param_env.and(self))
798 pub fn is_sized(&'tcx self,
799 tcx: TyCtxt<'a, 'tcx, 'tcx>,
800 param_env: ty::ParamEnv<'tcx>,
803 tcx.at(span).is_sized_raw(param_env.and(self))
806 pub fn is_freeze(&'tcx self,
807 tcx: TyCtxt<'a, 'tcx, 'tcx>,
808 param_env: ty::ParamEnv<'tcx>,
811 tcx.at(span).is_freeze_raw(param_env.and(self))
814 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
815 /// non-copy and *might* have a destructor attached; if it returns
816 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
818 /// (Note that this implies that if `ty` has a destructor attached,
819 /// then `needs_drop` will definitely return `true` for `ty`.)
821 pub fn needs_drop(&'tcx self,
822 tcx: TyCtxt<'a, 'tcx, 'tcx>,
823 param_env: ty::ParamEnv<'tcx>)
825 tcx.needs_drop_raw(param_env.and(self))
828 /// Computes the layout of a type. Note that this implicitly
829 /// executes in "reveal all" mode.
831 pub fn layout<'lcx>(&'tcx self,
832 tcx: TyCtxt<'a, 'tcx, 'tcx>,
833 param_env: ty::ParamEnv<'tcx>)
834 -> Result<&'tcx Layout, LayoutError<'tcx>> {
835 let ty = tcx.erase_regions(&self);
836 let layout = tcx.layout_raw(param_env.reveal_all().and(ty));
838 // NB: This recording is normally disabled; when enabled, it
839 // can however trigger recursive invocations of `layout()`.
840 // Therefore, we execute it *after* the main query has
841 // completed, to avoid problems around recursive structures
842 // and the like. (Admitedly, I wasn't able to reproduce a problem
843 // here, but it seems like the right thing to do. -nmatsakis)
844 if let Ok(l) = layout {
845 Layout::record_layout_for_printing(tcx, ty, param_env, l);
852 /// Check whether a type is representable. This means it cannot contain unboxed
853 /// structural recursion. This check is needed for structs and enums.
854 pub fn is_representable(&'tcx self,
855 tcx: TyCtxt<'a, 'tcx, 'tcx>,
857 -> Representability {
859 // Iterate until something non-representable is found
860 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
861 iter.fold(Representability::Representable, |r1, r2| {
863 (Representability::SelfRecursive(v1),
864 Representability::SelfRecursive(v2)) => {
865 Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
867 (r1, r2) => cmp::max(r1, r2)
872 fn are_inner_types_recursive<'a, 'tcx>(
873 tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
874 seen: &mut Vec<Ty<'tcx>>,
875 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
880 TyTuple(ref ts, _) => {
881 // Find non representable
882 fold_repr(ts.iter().map(|ty| {
883 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
886 // Fixed-length vectors.
887 // FIXME(#11924) Behavior undecided for zero-length vectors.
889 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
891 TyAdt(def, substs) => {
892 // Find non representable fields with their spans
893 fold_repr(def.all_fields().map(|field| {
894 let ty = field.ty(tcx, substs);
895 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
896 match is_type_structurally_recursive(tcx, span, seen,
897 representable_cache, ty)
899 Representability::SelfRecursive(_) => {
900 Representability::SelfRecursive(vec![span])
907 // this check is run on type definitions, so we don't expect
908 // to see closure types
909 bug!("requires check invoked on inapplicable type: {:?}", ty)
911 _ => Representability::Representable,
915 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
917 TyAdt(ty_def, _) => {
924 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
925 match (&a.sty, &b.sty) {
926 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
931 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
937 // Does the type `ty` directly (without indirection through a pointer)
938 // contain any types on stack `seen`?
939 fn is_type_structurally_recursive<'a, 'tcx>(
940 tcx: TyCtxt<'a, 'tcx, 'tcx>,
942 seen: &mut Vec<Ty<'tcx>>,
943 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
944 ty: Ty<'tcx>) -> Representability
946 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
947 if let Some(representability) = representable_cache.get(ty) {
948 debug!("is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
949 ty, sp, representability);
950 return representability.clone();
953 let representability = is_type_structurally_recursive_inner(
954 tcx, sp, seen, representable_cache, ty);
956 representable_cache.insert(ty, representability.clone());
960 fn is_type_structurally_recursive_inner<'a, 'tcx>(
961 tcx: TyCtxt<'a, 'tcx, 'tcx>,
963 seen: &mut Vec<Ty<'tcx>>,
964 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
965 ty: Ty<'tcx>) -> Representability
970 // Iterate through stack of previously seen types.
971 let mut iter = seen.iter();
973 // The first item in `seen` is the type we are actually curious about.
974 // We want to return SelfRecursive if this type contains itself.
975 // It is important that we DON'T take generic parameters into account
976 // for this check, so that Bar<T> in this example counts as SelfRecursive:
979 // struct Bar<T> { x: Bar<Foo> }
981 if let Some(&seen_type) = iter.next() {
982 if same_struct_or_enum(seen_type, def) {
983 debug!("SelfRecursive: {:?} contains {:?}",
986 return Representability::SelfRecursive(vec![sp]);
990 // We also need to know whether the first item contains other types
991 // that are structurally recursive. If we don't catch this case, we
992 // will recurse infinitely for some inputs.
994 // It is important that we DO take generic parameters into account
995 // here, so that code like this is considered SelfRecursive, not
996 // ContainsRecursive:
998 // struct Foo { Option<Option<Foo>> }
1000 for &seen_type in iter {
1001 if same_type(ty, seen_type) {
1002 debug!("ContainsRecursive: {:?} contains {:?}",
1005 return Representability::ContainsRecursive;
1010 // For structs and enums, track all previously seen types by pushing them
1011 // onto the 'seen' stack.
1013 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
1018 // No need to push in other cases.
1019 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
1024 debug!("is_type_representable: {:?}", self);
1026 // To avoid a stack overflow when checking an enum variant or struct that
1027 // contains a different, structurally recursive type, maintain a stack
1028 // of seen types and check recursion for each of them (issues #3008, #3779).
1029 let mut seen: Vec<Ty> = Vec::new();
1030 let mut representable_cache = FxHashMap();
1031 let r = is_type_structurally_recursive(
1032 tcx, sp, &mut seen, &mut representable_cache, self);
1033 debug!("is_type_representable: {:?} is {:?}", self, r);
1038 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1039 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1042 let (param_env, ty) = query.into_parts();
1043 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
1045 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1052 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1053 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1056 let (param_env, ty) = query.into_parts();
1057 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
1059 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1066 fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1067 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1070 let (param_env, ty) = query.into_parts();
1071 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
1073 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1080 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1081 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1084 let (param_env, ty) = query.into_parts();
1086 let needs_drop = |ty: Ty<'tcx>| -> bool {
1087 match ty::queries::needs_drop_raw::try_get(tcx, DUMMY_SP, param_env.and(ty)) {
1090 // Cycles should be reported as an error by `check_representable`.
1092 // Consider the type as not needing drop in the meanwhile to
1093 // avoid further errors.
1095 // In case we forgot to emit a bug elsewhere, delay our
1096 // diagnostic to get emitted as a compiler bug.
1103 assert!(!ty.needs_infer());
1106 // Fast-path for primitive types
1107 ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
1108 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
1109 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1110 ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
1112 // Issue #22536: We first query type_moves_by_default. It sees a
1113 // normalized version of the type, and therefore will definitely
1114 // know whether the type implements Copy (and thus needs no
1115 // cleanup/drop/zeroing) ...
1116 _ if !ty.moves_by_default(tcx, param_env, DUMMY_SP) => false,
1118 // ... (issue #22536 continued) but as an optimization, still use
1119 // prior logic of asking for the structural "may drop".
1121 // FIXME(#22815): Note that this is a conservative heuristic;
1122 // it may report that the type "may drop" when actual type does
1123 // not actually have a destructor associated with it. But since
1124 // the type absolutely did not have the `Copy` bound attached
1125 // (see above), it is sound to treat it as having a destructor.
1127 // User destructors are the only way to have concrete drop types.
1128 ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
1130 // Can refer to a type which may drop.
1131 // FIXME(eddyb) check this against a ParamEnv.
1132 ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
1133 ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
1135 // Structural recursion.
1136 ty::TyArray(ty, _) | ty::TySlice(ty) => needs_drop(ty),
1138 ty::TyClosure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1140 // Pessimistically assume that all generators will require destructors
1141 // as we don't know if a destructor is a noop or not until after the MIR
1142 // state transformation pass
1143 ty::TyGenerator(..) => true,
1145 ty::TyTuple(ref tys, _) => tys.iter().cloned().any(needs_drop),
1147 // unions don't have destructors regardless of the child types
1148 ty::TyAdt(def, _) if def.is_union() => false,
1150 ty::TyAdt(def, substs) =>
1151 def.variants.iter().any(
1152 |variant| variant.fields.iter().any(
1153 |field| needs_drop(field.ty(tcx, substs)))),
1157 fn layout_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1158 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1159 -> Result<&'tcx Layout, LayoutError<'tcx>>
1161 let (param_env, ty) = query.into_parts();
1163 let rec_limit = tcx.sess.recursion_limit.get();
1164 let depth = tcx.layout_depth.get();
1165 if depth > rec_limit {
1167 &format!("overflow representing the type `{}`", ty));
1170 tcx.layout_depth.set(depth+1);
1171 let layout = Layout::compute_uncached(tcx, param_env, ty);
1172 tcx.layout_depth.set(depth);
1177 pub fn provide(providers: &mut ty::maps::Providers) {
1178 *providers = ty::maps::Providers {