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::{StableHashingContext, NodeIdHashingMode};
16 use traits::{self, Reveal};
17 use ty::{self, Ty, TyCtxt, TypeFoldable};
18 use ty::fold::TypeVisitor;
19 use ty::layout::{Layout, LayoutError};
20 use ty::subst::{Subst, Kind};
21 use ty::TypeVariants::*;
22 use util::common::ErrorReported;
23 use middle::lang_items;
25 use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
26 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
31 use syntax::ast::{self, Name};
32 use syntax::attr::{self, SignedInt, UnsignedInt};
33 use syntax_pos::{Span, DUMMY_SP};
37 pub trait IntTypeExt {
38 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
39 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
41 fn assert_ty_matches(&self, val: Disr);
42 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr;
46 macro_rules! typed_literal {
47 ($tcx:expr, $ty:expr, $lit:expr) => {
49 SignedInt(ast::IntTy::I8) => ConstInt::I8($lit),
50 SignedInt(ast::IntTy::I16) => ConstInt::I16($lit),
51 SignedInt(ast::IntTy::I32) => ConstInt::I32($lit),
52 SignedInt(ast::IntTy::I64) => ConstInt::I64($lit),
53 SignedInt(ast::IntTy::I128) => ConstInt::I128($lit),
54 SignedInt(ast::IntTy::Is) => match $tcx.sess.target.int_type {
55 ast::IntTy::I16 => ConstInt::Isize(ConstIsize::Is16($lit)),
56 ast::IntTy::I32 => ConstInt::Isize(ConstIsize::Is32($lit)),
57 ast::IntTy::I64 => ConstInt::Isize(ConstIsize::Is64($lit)),
60 UnsignedInt(ast::UintTy::U8) => ConstInt::U8($lit),
61 UnsignedInt(ast::UintTy::U16) => ConstInt::U16($lit),
62 UnsignedInt(ast::UintTy::U32) => ConstInt::U32($lit),
63 UnsignedInt(ast::UintTy::U64) => ConstInt::U64($lit),
64 UnsignedInt(ast::UintTy::U128) => ConstInt::U128($lit),
65 UnsignedInt(ast::UintTy::Us) => match $tcx.sess.target.uint_type {
66 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16($lit)),
67 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32($lit)),
68 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64($lit)),
75 impl IntTypeExt for attr::IntType {
76 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
78 SignedInt(ast::IntTy::I8) => tcx.types.i8,
79 SignedInt(ast::IntTy::I16) => tcx.types.i16,
80 SignedInt(ast::IntTy::I32) => tcx.types.i32,
81 SignedInt(ast::IntTy::I64) => tcx.types.i64,
82 SignedInt(ast::IntTy::I128) => tcx.types.i128,
83 SignedInt(ast::IntTy::Is) => tcx.types.isize,
84 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
85 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
86 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
87 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
88 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
89 UnsignedInt(ast::UintTy::Us) => tcx.types.usize,
93 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr {
94 typed_literal!(tcx, *self, 0)
97 fn assert_ty_matches(&self, val: Disr) {
99 (SignedInt(ast::IntTy::I8), ConstInt::I8(_)) => {},
100 (SignedInt(ast::IntTy::I16), ConstInt::I16(_)) => {},
101 (SignedInt(ast::IntTy::I32), ConstInt::I32(_)) => {},
102 (SignedInt(ast::IntTy::I64), ConstInt::I64(_)) => {},
103 (SignedInt(ast::IntTy::I128), ConstInt::I128(_)) => {},
104 (SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) => {},
105 (UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) => {},
106 (UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) => {},
107 (UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) => {},
108 (UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) => {},
109 (UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) => {},
110 (UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => {},
111 _ => bug!("disr type mismatch: {:?} vs {:?}", self, val),
115 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
117 if let Some(val) = val {
118 self.assert_ty_matches(val);
119 (val + typed_literal!(tcx, *self, 1)).ok()
121 Some(self.initial_discriminant(tcx))
127 #[derive(Copy, Clone)]
128 pub enum CopyImplementationError<'tcx> {
129 InfrigingField(&'tcx ty::FieldDef),
134 /// Describes whether a type is representable. For types that are not
135 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
136 /// distinguish between types that are recursive with themselves and types that
137 /// contain a different recursive type. These cases can therefore be treated
138 /// differently when reporting errors.
140 /// The ordering of the cases is significant. They are sorted so that cmp::max
141 /// will keep the "more erroneous" of two values.
142 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
143 pub enum Representability {
146 SelfRecursive(Vec<Span>),
149 impl<'tcx> ty::ParamEnv<'tcx> {
150 /// Construct a trait environment suitable for contexts where
151 /// there are no where clauses in scope.
152 pub fn empty(reveal: Reveal) -> Self {
153 Self::new(ty::Slice::empty(), reveal)
156 /// Construct a trait environment with the given set of predicates.
157 pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>,
160 ty::ParamEnv { caller_bounds, reveal }
163 /// Returns a new parameter environment with the same clauses, but
164 /// which "reveals" the true results of projections in all cases
165 /// (even for associated types that are specializable). This is
166 /// the desired behavior during trans and certain other special
167 /// contexts; normally though we want to use `Reveal::UserFacing`,
168 /// which is the default.
169 pub fn reveal_all(self) -> Self {
170 ty::ParamEnv { reveal: Reveal::All, ..self }
173 pub fn can_type_implement_copy<'a>(self,
174 tcx: TyCtxt<'a, 'tcx, 'tcx>,
175 self_type: Ty<'tcx>, span: Span)
176 -> Result<(), CopyImplementationError<'tcx>> {
177 // FIXME: (@jroesch) float this code up
178 tcx.infer_ctxt().enter(|infcx| {
179 let (adt, substs) = match self_type.sty {
180 ty::TyAdt(adt, substs) => (adt, substs),
181 _ => return Err(CopyImplementationError::NotAnAdt),
184 let field_implements_copy = |field: &ty::FieldDef| {
185 let cause = traits::ObligationCause::dummy();
186 match traits::fully_normalize(&infcx, cause, self, &field.ty(tcx, substs)) {
187 Ok(ty) => !infcx.type_moves_by_default(self, ty, span),
192 for variant in &adt.variants {
193 for field in &variant.fields {
194 if !field_implements_copy(field) {
195 return Err(CopyImplementationError::InfrigingField(field));
200 if adt.has_dtor(tcx) {
201 return Err(CopyImplementationError::HasDestructor);
209 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
210 /// Creates a hash of the type `Ty` which will be the same no matter what crate
211 /// context it's calculated within. This is used by the `type_id` intrinsic.
212 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
213 let mut hasher = StableHasher::new();
214 let mut hcx = StableHashingContext::new(self);
216 hcx.while_hashing_spans(false, |hcx| {
217 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
218 ty.hash_stable(hcx, &mut hasher);
225 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
226 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
228 ty::TyAdt(def, substs) => {
229 for field in def.all_fields() {
230 let field_ty = field.ty(self, substs);
231 if let TyError = field_ty.sty {
241 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
242 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
243 pub fn positional_element_ty(self,
246 variant: Option<DefId>) -> Option<Ty<'tcx>> {
247 match (&ty.sty, variant) {
248 (&TyAdt(adt, substs), Some(vid)) => {
249 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
251 (&TyAdt(adt, substs), None) => {
252 // Don't use `struct_variant`, this may be a univariant enum.
253 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
255 (&TyTuple(ref v, _), None) => v.get(i).cloned(),
260 /// Returns the type of element at field `n` in struct or struct-like type `t`.
261 /// For an enum `t`, `variant` must be some def id.
262 pub fn named_element_ty(self,
265 variant: Option<DefId>) -> Option<Ty<'tcx>> {
266 match (&ty.sty, variant) {
267 (&TyAdt(adt, substs), Some(vid)) => {
268 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
270 (&TyAdt(adt, substs), None) => {
271 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
277 /// Returns the deeply last field of nested structures, or the same type,
278 /// if not a structure at all. Corresponds to the only possible unsized
279 /// field, and its type can be used to determine unsizing strategy.
280 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
283 ty::TyAdt(def, substs) => {
284 if !def.is_struct() {
287 match def.struct_variant().fields.last() {
288 Some(f) => ty = f.ty(self, substs),
293 ty::TyTuple(tys, _) => {
294 if let Some((&last_ty, _)) = tys.split_last() {
309 /// Same as applying struct_tail on `source` and `target`, but only
310 /// keeps going as long as the two types are instances of the same
311 /// structure definitions.
312 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
313 /// whereas struct_tail produces `T`, and `Trait`, respectively.
314 pub fn struct_lockstep_tails(self,
317 -> (Ty<'tcx>, Ty<'tcx>) {
318 let (mut a, mut b) = (source, target);
319 while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
320 if a_def != b_def || !a_def.is_struct() {
323 match a_def.struct_variant().fields.last() {
325 a = f.ty(self, a_substs);
326 b = f.ty(self, b_substs);
334 /// Given a set of predicates that apply to an object type, returns
335 /// the region bounds that the (erased) `Self` type must
336 /// outlive. Precisely *because* the `Self` type is erased, the
337 /// parameter `erased_self_ty` must be supplied to indicate what type
338 /// has been used to represent `Self` in the predicates
339 /// themselves. This should really be a unique type; `FreshTy(0)` is a
342 /// NB: in some cases, particularly around higher-ranked bounds,
343 /// this function returns a kind of conservative approximation.
344 /// That is, all regions returned by this function are definitely
345 /// required, but there may be other region bounds that are not
346 /// returned, as well as requirements like `for<'a> T: 'a`.
348 /// Requires that trait definitions have been processed so that we can
349 /// elaborate predicates and walk supertraits.
351 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
352 /// what this code should accept.
353 pub fn required_region_bounds(self,
354 erased_self_ty: Ty<'tcx>,
355 predicates: Vec<ty::Predicate<'tcx>>)
356 -> Vec<ty::Region<'tcx>> {
357 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
361 assert!(!erased_self_ty.has_escaping_regions());
363 traits::elaborate_predicates(self, predicates)
364 .filter_map(|predicate| {
366 ty::Predicate::Projection(..) |
367 ty::Predicate::Trait(..) |
368 ty::Predicate::Equate(..) |
369 ty::Predicate::Subtype(..) |
370 ty::Predicate::WellFormed(..) |
371 ty::Predicate::ObjectSafe(..) |
372 ty::Predicate::ClosureKind(..) |
373 ty::Predicate::RegionOutlives(..) => {
376 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
377 // Search for a bound of the form `erased_self_ty
378 // : 'a`, but be wary of something like `for<'a>
379 // erased_self_ty : 'a` (we interpret a
380 // higher-ranked bound like that as 'static,
381 // though at present the code in `fulfill.rs`
382 // considers such bounds to be unsatisfiable, so
383 // it's kind of a moot point since you could never
384 // construct such an object, but this seems
385 // correct even if that code changes).
386 if t == erased_self_ty && !r.has_escaping_regions() {
397 /// Calculate the destructor of a given type.
398 pub fn calculate_dtor(
401 validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
402 ) -> Option<ty::Destructor> {
403 let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
409 self.coherent_trait((LOCAL_CRATE, drop_trait));
411 let mut dtor_did = None;
412 let ty = self.type_of(adt_did);
413 self.trait_def(drop_trait).for_each_relevant_impl(self, ty, |impl_did| {
414 if let Some(item) = self.associated_items(impl_did).next() {
415 if let Ok(()) = validate(self, impl_did) {
416 dtor_did = Some(item.def_id);
421 let dtor_did = match dtor_did {
426 Some(ty::Destructor { did: dtor_did })
429 /// Return the set of types that are required to be alive in
430 /// order to run the destructor of `def` (see RFCs 769 and
433 /// Note that this returns only the constraints for the
434 /// destructor of `def` itself. For the destructors of the
435 /// contents, you need `adt_dtorck_constraint`.
436 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
437 -> Vec<ty::subst::Kind<'tcx>>
439 let dtor = match def.destructor(self) {
441 debug!("destructor_constraints({:?}) - no dtor", def.did);
444 Some(dtor) => dtor.did
447 // RFC 1238: if the destructor method is tagged with the
448 // attribute `unsafe_destructor_blind_to_params`, then the
449 // compiler is being instructed to *assume* that the
450 // destructor will not access borrowed data,
451 // even if such data is otherwise reachable.
453 // Such access can be in plain sight (e.g. dereferencing
454 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
455 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
456 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
457 debug!("destructor_constraint({:?}) - blind", def.did);
461 let impl_def_id = self.associated_item(dtor).container.id();
462 let impl_generics = self.generics_of(impl_def_id);
464 // We have a destructor - all the parameters that are not
465 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
468 // We need to return the list of parameters from the ADTs
469 // generics/substs that correspond to impure parameters on the
470 // impl's generics. This is a bit ugly, but conceptually simple:
472 // Suppose our ADT looks like the following
474 // struct S<X, Y, Z>(X, Y, Z);
478 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
480 // We want to return the parameters (X, Y). For that, we match
481 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
482 // <P1, P2, P0>, and then look up which of the impl substs refer to
483 // parameters marked as pure.
485 let impl_substs = match self.type_of(impl_def_id).sty {
486 ty::TyAdt(def_, substs) if def_ == def => substs,
490 let item_substs = match self.type_of(def.did).sty {
491 ty::TyAdt(def_, substs) if def_ == def => substs,
495 let result = item_substs.iter().zip(impl_substs.iter())
497 if let Some(&ty::RegionKind::ReEarlyBound(ref ebr)) = k.as_region() {
498 !impl_generics.region_param(ebr).pure_wrt_drop
499 } else if let Some(&ty::TyS {
500 sty: ty::TypeVariants::TyParam(ref pt), ..
502 !impl_generics.type_param(pt).pure_wrt_drop
504 // not a type or region param - this should be reported
508 }).map(|(&item_param, _)| item_param).collect();
509 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
513 /// Return a set of constraints that needs to be satisfied in
514 /// order for `ty` to be valid for destruction.
515 pub fn dtorck_constraint_for_ty(self,
520 -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
522 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
523 span, for_ty, depth, ty);
525 if depth >= self.sess.recursion_limit.get() {
526 let mut err = struct_span_err!(
527 self.sess, span, E0320,
528 "overflow while adding drop-check rules for {}", for_ty);
529 err.note(&format!("overflowed on {}", ty));
531 return Err(ErrorReported);
534 let result = match ty.sty {
535 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
536 ty::TyFloat(_) | ty::TyStr | ty::TyNever |
537 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => {
538 // these types never have a destructor
539 Ok(ty::DtorckConstraint::empty())
542 ty::TyArray(ety, _) | ty::TySlice(ety) => {
543 // single-element containers, behave like their element
544 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
547 ty::TyTuple(tys, _) => {
548 tys.iter().map(|ty| {
549 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
553 ty::TyClosure(def_id, substs) => {
554 substs.upvar_tys(def_id, self).map(|ty| {
555 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
559 ty::TyAdt(def, substs) => {
560 let ty::DtorckConstraint {
561 dtorck_types, outlives
562 } = self.at(span).adt_dtorck_constraint(def.did);
563 Ok(ty::DtorckConstraint {
564 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
565 // there, but that needs some way to handle cycles.
566 dtorck_types: dtorck_types.subst(self, substs),
567 outlives: outlives.subst(self, substs)
571 // Objects must be alive in order for their destructor
573 ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
574 outlives: vec![Kind::from(ty)],
575 dtorck_types: vec![],
578 // Types that can't be resolved. Pass them forward.
579 ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
580 Ok(ty::DtorckConstraint {
582 dtorck_types: vec![ty],
586 ty::TyInfer(..) | ty::TyError => {
587 self.sess.delay_span_bug(span, "unresolved type in dtorck");
592 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
596 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
597 let mut def_id = def_id;
598 while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
599 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
600 bug!("closure {:?} has no parent", def_id);
606 /// Given the def-id of some item that has no type parameters, make
607 /// a suitable "empty substs" for it.
608 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
609 ty::Substs::for_item(self, item_def_id,
610 |_, _| self.types.re_erased,
612 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
616 pub fn const_usize(&self, val: u16) -> ConstInt {
617 match self.sess.target.uint_type {
618 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16(val as u16)),
619 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32(val as u32)),
620 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64(val as u64)),
626 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
627 tcx: TyCtxt<'a, 'gcx, 'tcx>,
628 state: StableHasher<W>,
631 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
632 where W: StableHasherResult
634 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
635 TypeIdHasher { tcx: tcx, state: StableHasher::new() }
638 pub fn finish(self) -> W {
642 pub fn hash<T: Hash>(&mut self, x: T) {
643 x.hash(&mut self.state);
646 fn hash_discriminant_u8<T>(&mut self, x: &T) {
648 intrinsics::discriminant_value(x)
651 assert_eq!(v, b as u64);
655 fn def_id(&mut self, did: DefId) {
656 // Hash the DefPath corresponding to the DefId, which is independent
657 // of compiler internal state. We already have a stable hash value of
658 // all DefPaths available via tcx.def_path_hash(), so we just feed that
660 let hash = self.tcx.def_path_hash(did);
665 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
666 where W: StableHasherResult
668 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
669 // Distinguish between the Ty variants uniformly.
670 self.hash_discriminant_u8(&ty.sty);
673 TyInt(i) => self.hash(i),
674 TyUint(u) => self.hash(u),
675 TyFloat(f) => self.hash(f),
676 TyArray(_, n) => self.hash(n),
678 TyRef(_, m) => self.hash(m.mutbl),
679 TyClosure(def_id, _) |
681 TyFnDef(def_id, ..) => self.def_id(def_id),
682 TyAdt(d, _) => self.def_id(d.did),
684 self.hash(f.unsafety());
686 self.hash(f.variadic());
687 self.hash(f.inputs().skip_binder().len());
689 TyDynamic(ref data, ..) => {
690 if let Some(p) = data.principal() {
691 self.def_id(p.def_id());
693 for d in data.auto_traits() {
697 TyTuple(tys, defaulted) => {
698 self.hash(tys.len());
699 self.hash(defaulted);
703 self.hash(p.name.as_str());
705 TyProjection(ref data) => {
706 self.def_id(data.item_def_id);
715 TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
718 ty.super_visit_with(self)
721 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
722 self.hash_discriminant_u8(r);
727 // No variant fields to hash for these ...
729 ty::ReLateBound(db, ty::BrAnon(i)) => {
733 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
736 ty::ReLateBound(..) |
740 ty::ReSkolemized(..) => {
741 bug!("TypeIdHasher: unexpected region {:?}", r)
747 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
748 // Anonymize late-bound regions so that, for example:
749 // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
750 // result in the same TypeId (the two types are equivalent).
751 self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
755 impl<'a, 'tcx> ty::TyS<'tcx> {
756 pub fn moves_by_default(&'tcx self,
757 tcx: TyCtxt<'a, 'tcx, 'tcx>,
758 param_env: ty::ParamEnv<'tcx>,
761 !tcx.at(span).is_copy_raw(param_env.and(self))
764 pub fn is_sized(&'tcx self,
765 tcx: TyCtxt<'a, 'tcx, 'tcx>,
766 param_env: ty::ParamEnv<'tcx>,
769 tcx.at(span).is_sized_raw(param_env.and(self))
772 pub fn is_freeze(&'tcx self,
773 tcx: TyCtxt<'a, 'tcx, 'tcx>,
774 param_env: ty::ParamEnv<'tcx>,
777 tcx.at(span).is_freeze_raw(param_env.and(self))
780 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
781 /// non-copy and *might* have a destructor attached; if it returns
782 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
784 /// (Note that this implies that if `ty` has a destructor attached,
785 /// then `needs_drop` will definitely return `true` for `ty`.)
787 pub fn needs_drop(&'tcx self,
788 tcx: TyCtxt<'a, 'tcx, 'tcx>,
789 param_env: ty::ParamEnv<'tcx>)
791 tcx.needs_drop_raw(param_env.and(self))
794 /// Computes the layout of a type. Note that this implicitly
795 /// executes in "reveal all" mode.
797 pub fn layout<'lcx>(&'tcx self,
798 tcx: TyCtxt<'a, 'tcx, 'tcx>,
799 param_env: ty::ParamEnv<'tcx>)
800 -> Result<&'tcx Layout, LayoutError<'tcx>> {
801 let ty = tcx.erase_regions(&self);
802 let layout = tcx.layout_raw(param_env.reveal_all().and(ty));
804 // NB: This recording is normally disabled; when enabled, it
805 // can however trigger recursive invocations of `layout()`.
806 // Therefore, we execute it *after* the main query has
807 // completed, to avoid problems around recursive structures
808 // and the like. (Admitedly, I wasn't able to reproduce a problem
809 // here, but it seems like the right thing to do. -nmatsakis)
810 if let Ok(l) = layout {
811 Layout::record_layout_for_printing(tcx, ty, param_env, l);
818 /// Check whether a type is representable. This means it cannot contain unboxed
819 /// structural recursion. This check is needed for structs and enums.
820 pub fn is_representable(&'tcx self,
821 tcx: TyCtxt<'a, 'tcx, 'tcx>,
823 -> Representability {
825 // Iterate until something non-representable is found
826 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
827 iter.fold(Representability::Representable, |r1, r2| {
829 (Representability::SelfRecursive(v1),
830 Representability::SelfRecursive(v2)) => {
831 Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
833 (r1, r2) => cmp::max(r1, r2)
838 fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
839 seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
840 -> Representability {
842 TyTuple(ref ts, _) => {
843 // Find non representable
844 fold_repr(ts.iter().map(|ty| {
845 is_type_structurally_recursive(tcx, sp, seen, ty)
848 // Fixed-length vectors.
849 // FIXME(#11924) Behavior undecided for zero-length vectors.
851 is_type_structurally_recursive(tcx, sp, seen, ty)
853 TyAdt(def, substs) => {
854 // Find non representable fields with their spans
855 fold_repr(def.all_fields().map(|field| {
856 let ty = field.ty(tcx, substs);
857 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
858 match is_type_structurally_recursive(tcx, span, seen, ty) {
859 Representability::SelfRecursive(_) => {
860 Representability::SelfRecursive(vec![span])
867 // this check is run on type definitions, so we don't expect
868 // to see closure types
869 bug!("requires check invoked on inapplicable type: {:?}", ty)
871 _ => Representability::Representable,
875 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
877 TyAdt(ty_def, _) => {
884 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
885 match (&a.sty, &b.sty) {
886 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
891 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
897 // Does the type `ty` directly (without indirection through a pointer)
898 // contain any types on stack `seen`?
899 fn is_type_structurally_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
901 seen: &mut Vec<Ty<'tcx>>,
902 ty: Ty<'tcx>) -> Representability {
903 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
908 // Iterate through stack of previously seen types.
909 let mut iter = seen.iter();
911 // The first item in `seen` is the type we are actually curious about.
912 // We want to return SelfRecursive if this type contains itself.
913 // It is important that we DON'T take generic parameters into account
914 // for this check, so that Bar<T> in this example counts as SelfRecursive:
917 // struct Bar<T> { x: Bar<Foo> }
919 if let Some(&seen_type) = iter.next() {
920 if same_struct_or_enum(seen_type, def) {
921 debug!("SelfRecursive: {:?} contains {:?}",
924 return Representability::SelfRecursive(vec![sp]);
928 // We also need to know whether the first item contains other types
929 // that are structurally recursive. If we don't catch this case, we
930 // will recurse infinitely for some inputs.
932 // It is important that we DO take generic parameters into account
933 // here, so that code like this is considered SelfRecursive, not
934 // ContainsRecursive:
936 // struct Foo { Option<Option<Foo>> }
938 for &seen_type in iter {
939 if same_type(ty, seen_type) {
940 debug!("ContainsRecursive: {:?} contains {:?}",
943 return Representability::ContainsRecursive;
948 // For structs and enums, track all previously seen types by pushing them
949 // onto the 'seen' stack.
951 let out = are_inner_types_recursive(tcx, sp, seen, ty);
956 // No need to push in other cases.
957 are_inner_types_recursive(tcx, sp, seen, ty)
962 debug!("is_type_representable: {:?}", self);
964 // To avoid a stack overflow when checking an enum variant or struct that
965 // contains a different, structurally recursive type, maintain a stack
966 // of seen types and check recursion for each of them (issues #3008, #3779).
967 let mut seen: Vec<Ty> = Vec::new();
968 let r = is_type_structurally_recursive(tcx, sp, &mut seen, self);
969 debug!("is_type_representable: {:?} is {:?}", self, r);
974 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
975 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
978 let (param_env, ty) = query.into_parts();
979 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
981 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
988 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
989 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
992 let (param_env, ty) = query.into_parts();
993 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
995 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1002 fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1003 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1006 let (param_env, ty) = query.into_parts();
1007 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
1009 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1016 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1017 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1020 let (param_env, ty) = query.into_parts();
1022 let needs_drop = |ty: Ty<'tcx>| -> bool {
1023 match ty::queries::needs_drop_raw::try_get(tcx, DUMMY_SP, param_env.and(ty)) {
1026 // Cycles should be reported as an error by `check_representable`.
1028 // Consider the type as not needing drop in the meanwhile to avoid
1035 assert!(!ty.needs_infer());
1038 // Fast-path for primitive types
1039 ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
1040 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
1041 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1042 ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
1044 // Issue #22536: We first query type_moves_by_default. It sees a
1045 // normalized version of the type, and therefore will definitely
1046 // know whether the type implements Copy (and thus needs no
1047 // cleanup/drop/zeroing) ...
1048 _ if !ty.moves_by_default(tcx, param_env, DUMMY_SP) => false,
1050 // ... (issue #22536 continued) but as an optimization, still use
1051 // prior logic of asking for the structural "may drop".
1053 // FIXME(#22815): Note that this is a conservative heuristic;
1054 // it may report that the type "may drop" when actual type does
1055 // not actually have a destructor associated with it. But since
1056 // the type absolutely did not have the `Copy` bound attached
1057 // (see above), it is sound to treat it as having a destructor.
1059 // User destructors are the only way to have concrete drop types.
1060 ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
1062 // Can refer to a type which may drop.
1063 // FIXME(eddyb) check this against a ParamEnv.
1064 ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
1065 ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
1067 // Structural recursion.
1068 ty::TyArray(ty, _) | ty::TySlice(ty) => needs_drop(ty),
1070 ty::TyClosure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1072 ty::TyTuple(ref tys, _) => tys.iter().cloned().any(needs_drop),
1074 // unions don't have destructors regardless of the child types
1075 ty::TyAdt(def, _) if def.is_union() => false,
1077 ty::TyAdt(def, substs) =>
1078 def.variants.iter().any(
1079 |variant| variant.fields.iter().any(
1080 |field| needs_drop(field.ty(tcx, substs)))),
1084 fn layout_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1085 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1086 -> Result<&'tcx Layout, LayoutError<'tcx>>
1088 let (param_env, ty) = query.into_parts();
1090 let rec_limit = tcx.sess.recursion_limit.get();
1091 let depth = tcx.layout_depth.get();
1092 if depth > rec_limit {
1094 &format!("overflow representing the type `{}`", ty));
1097 tcx.layout_depth.set(depth+1);
1098 let layout = Layout::compute_uncached(tcx, param_env, ty);
1099 tcx.layout_depth.set(depth);
1104 pub fn provide(providers: &mut ty::maps::Providers) {
1105 *providers = ty::maps::Providers {