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,
28 use rustc_data_structures::fx::FxHashMap;
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> ty::ParamEnv<'tcx> {
152 /// Construct a trait environment suitable for contexts where
153 /// there are no where clauses in scope.
154 pub fn empty(reveal: Reveal) -> Self {
155 Self::new(ty::Slice::empty(), reveal)
158 /// Construct a trait environment with the given set of predicates.
159 pub fn new(caller_bounds: &'tcx ty::Slice<ty::Predicate<'tcx>>,
162 ty::ParamEnv { caller_bounds, reveal }
165 /// Returns a new parameter environment with the same clauses, but
166 /// which "reveals" the true results of projections in all cases
167 /// (even for associated types that are specializable). This is
168 /// the desired behavior during trans and certain other special
169 /// contexts; normally though we want to use `Reveal::UserFacing`,
170 /// which is the default.
171 pub fn reveal_all(self) -> Self {
172 ty::ParamEnv { reveal: Reveal::All, ..self }
175 pub fn can_type_implement_copy<'a>(self,
176 tcx: TyCtxt<'a, 'tcx, 'tcx>,
177 self_type: Ty<'tcx>, span: Span)
178 -> Result<(), CopyImplementationError<'tcx>> {
179 // FIXME: (@jroesch) float this code up
180 tcx.infer_ctxt().enter(|infcx| {
181 let (adt, substs) = match self_type.sty {
182 ty::TyAdt(adt, substs) => (adt, substs),
183 _ => return Err(CopyImplementationError::NotAnAdt),
186 let field_implements_copy = |field: &ty::FieldDef| {
187 let cause = traits::ObligationCause::dummy();
188 match traits::fully_normalize(&infcx, cause, self, &field.ty(tcx, substs)) {
189 Ok(ty) => !infcx.type_moves_by_default(self, ty, span),
194 for variant in &adt.variants {
195 for field in &variant.fields {
196 if !field_implements_copy(field) {
197 return Err(CopyImplementationError::InfrigingField(field));
202 if adt.has_dtor(tcx) {
203 return Err(CopyImplementationError::HasDestructor);
211 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
212 /// Creates a hash of the type `Ty` which will be the same no matter what crate
213 /// context it's calculated within. This is used by the `type_id` intrinsic.
214 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
215 let mut hasher = StableHasher::new();
216 let mut hcx = StableHashingContext::new(self);
218 // We want the type_id be independent of the types free regions, so we
219 // erase them. The erase_regions() call will also anonymize bound
220 // regions, which is desirable too.
221 let ty = self.erase_regions(&ty);
223 hcx.while_hashing_spans(false, |hcx| {
224 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
225 ty.hash_stable(hcx, &mut hasher);
232 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
233 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
235 ty::TyAdt(def, substs) => {
236 for field in def.all_fields() {
237 let field_ty = field.ty(self, substs);
238 if let TyError = field_ty.sty {
248 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
249 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
250 pub fn positional_element_ty(self,
253 variant: Option<DefId>) -> Option<Ty<'tcx>> {
254 match (&ty.sty, variant) {
255 (&TyAdt(adt, substs), Some(vid)) => {
256 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
258 (&TyAdt(adt, substs), None) => {
259 // Don't use `struct_variant`, this may be a univariant enum.
260 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
262 (&TyTuple(ref v, _), None) => v.get(i).cloned(),
267 /// Returns the type of element at field `n` in struct or struct-like type `t`.
268 /// For an enum `t`, `variant` must be some def id.
269 pub fn named_element_ty(self,
272 variant: Option<DefId>) -> Option<Ty<'tcx>> {
273 match (&ty.sty, variant) {
274 (&TyAdt(adt, substs), Some(vid)) => {
275 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
277 (&TyAdt(adt, substs), None) => {
278 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
284 /// Returns the deeply last field of nested structures, or the same type,
285 /// if not a structure at all. Corresponds to the only possible unsized
286 /// field, and its type can be used to determine unsizing strategy.
287 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
290 ty::TyAdt(def, substs) => {
291 if !def.is_struct() {
294 match def.struct_variant().fields.last() {
295 Some(f) => ty = f.ty(self, substs),
300 ty::TyTuple(tys, _) => {
301 if let Some((&last_ty, _)) = tys.split_last() {
316 /// Same as applying struct_tail on `source` and `target`, but only
317 /// keeps going as long as the two types are instances of the same
318 /// structure definitions.
319 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
320 /// whereas struct_tail produces `T`, and `Trait`, respectively.
321 pub fn struct_lockstep_tails(self,
324 -> (Ty<'tcx>, Ty<'tcx>) {
325 let (mut a, mut b) = (source, target);
327 match (&a.sty, &b.sty) {
328 (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs))
329 if a_def == b_def && a_def.is_struct() => {
330 if let Some(f) = a_def.struct_variant().fields.last() {
331 a = f.ty(self, a_substs);
332 b = f.ty(self, b_substs);
337 (&TyTuple(a_tys, _), &TyTuple(b_tys, _))
338 if a_tys.len() == b_tys.len() => {
339 if let Some(a_last) = a_tys.last() {
341 b = b_tys.last().unwrap();
352 /// Given a set of predicates that apply to an object type, returns
353 /// the region bounds that the (erased) `Self` type must
354 /// outlive. Precisely *because* the `Self` type is erased, the
355 /// parameter `erased_self_ty` must be supplied to indicate what type
356 /// has been used to represent `Self` in the predicates
357 /// themselves. This should really be a unique type; `FreshTy(0)` is a
360 /// NB: in some cases, particularly around higher-ranked bounds,
361 /// this function returns a kind of conservative approximation.
362 /// That is, all regions returned by this function are definitely
363 /// required, but there may be other region bounds that are not
364 /// returned, as well as requirements like `for<'a> T: 'a`.
366 /// Requires that trait definitions have been processed so that we can
367 /// elaborate predicates and walk supertraits.
369 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
370 /// what this code should accept.
371 pub fn required_region_bounds(self,
372 erased_self_ty: Ty<'tcx>,
373 predicates: Vec<ty::Predicate<'tcx>>)
374 -> Vec<ty::Region<'tcx>> {
375 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
379 assert!(!erased_self_ty.has_escaping_regions());
381 traits::elaborate_predicates(self, predicates)
382 .filter_map(|predicate| {
384 ty::Predicate::Projection(..) |
385 ty::Predicate::Trait(..) |
386 ty::Predicate::Equate(..) |
387 ty::Predicate::Subtype(..) |
388 ty::Predicate::WellFormed(..) |
389 ty::Predicate::ObjectSafe(..) |
390 ty::Predicate::ClosureKind(..) |
391 ty::Predicate::RegionOutlives(..) => {
394 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
395 // Search for a bound of the form `erased_self_ty
396 // : 'a`, but be wary of something like `for<'a>
397 // erased_self_ty : 'a` (we interpret a
398 // higher-ranked bound like that as 'static,
399 // though at present the code in `fulfill.rs`
400 // considers such bounds to be unsatisfiable, so
401 // it's kind of a moot point since you could never
402 // construct such an object, but this seems
403 // correct even if that code changes).
404 if t == erased_self_ty && !r.has_escaping_regions() {
415 /// Calculate the destructor of a given type.
416 pub fn calculate_dtor(
419 validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
420 ) -> Option<ty::Destructor> {
421 let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
427 self.coherent_trait((LOCAL_CRATE, drop_trait));
429 let mut dtor_did = None;
430 let ty = self.type_of(adt_did);
431 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
432 if let Some(item) = self.associated_items(impl_did).next() {
433 if let Ok(()) = validate(self, impl_did) {
434 dtor_did = Some(item.def_id);
439 let dtor_did = match dtor_did {
444 Some(ty::Destructor { did: dtor_did })
447 /// Return the set of types that are required to be alive in
448 /// order to run the destructor of `def` (see RFCs 769 and
451 /// Note that this returns only the constraints for the
452 /// destructor of `def` itself. For the destructors of the
453 /// contents, you need `adt_dtorck_constraint`.
454 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
455 -> Vec<ty::subst::Kind<'tcx>>
457 let dtor = match def.destructor(self) {
459 debug!("destructor_constraints({:?}) - no dtor", def.did);
462 Some(dtor) => dtor.did
465 // RFC 1238: if the destructor method is tagged with the
466 // attribute `unsafe_destructor_blind_to_params`, then the
467 // compiler is being instructed to *assume* that the
468 // destructor will not access borrowed data,
469 // even if such data is otherwise reachable.
471 // Such access can be in plain sight (e.g. dereferencing
472 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
473 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
474 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
475 debug!("destructor_constraint({:?}) - blind", def.did);
479 let impl_def_id = self.associated_item(dtor).container.id();
480 let impl_generics = self.generics_of(impl_def_id);
482 // We have a destructor - all the parameters that are not
483 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
486 // We need to return the list of parameters from the ADTs
487 // generics/substs that correspond to impure parameters on the
488 // impl's generics. This is a bit ugly, but conceptually simple:
490 // Suppose our ADT looks like the following
492 // struct S<X, Y, Z>(X, Y, Z);
496 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
498 // We want to return the parameters (X, Y). For that, we match
499 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
500 // <P1, P2, P0>, and then look up which of the impl substs refer to
501 // parameters marked as pure.
503 let impl_substs = match self.type_of(impl_def_id).sty {
504 ty::TyAdt(def_, substs) if def_ == def => substs,
508 let item_substs = match self.type_of(def.did).sty {
509 ty::TyAdt(def_, substs) if def_ == def => substs,
513 let result = item_substs.iter().zip(impl_substs.iter())
515 if let Some(&ty::RegionKind::ReEarlyBound(ref ebr)) = k.as_region() {
516 !impl_generics.region_param(ebr).pure_wrt_drop
517 } else if let Some(&ty::TyS {
518 sty: ty::TypeVariants::TyParam(ref pt), ..
520 !impl_generics.type_param(pt).pure_wrt_drop
522 // not a type or region param - this should be reported
526 }).map(|(&item_param, _)| item_param).collect();
527 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
531 /// Return a set of constraints that needs to be satisfied in
532 /// order for `ty` to be valid for destruction.
533 pub fn dtorck_constraint_for_ty(self,
538 -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
540 debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
541 span, for_ty, depth, ty);
543 if depth >= self.sess.recursion_limit.get() {
544 let mut err = struct_span_err!(
545 self.sess, span, E0320,
546 "overflow while adding drop-check rules for {}", for_ty);
547 err.note(&format!("overflowed on {}", ty));
549 return Err(ErrorReported);
552 let result = match ty.sty {
553 ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
554 ty::TyFloat(_) | ty::TyStr | ty::TyNever |
555 ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => {
556 // these types never have a destructor
557 Ok(ty::DtorckConstraint::empty())
560 ty::TyArray(ety, _) | ty::TySlice(ety) => {
561 // single-element containers, behave like their element
562 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
565 ty::TyTuple(tys, _) => {
566 tys.iter().map(|ty| {
567 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
571 ty::TyClosure(def_id, substs) => {
572 substs.upvar_tys(def_id, self).map(|ty| {
573 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
577 ty::TyGenerator(def_id, substs, interior) => {
578 substs.upvar_tys(def_id, self).chain(iter::once(interior.witness)).map(|ty| {
579 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
583 ty::TyAdt(def, substs) => {
584 let ty::DtorckConstraint {
585 dtorck_types, outlives
586 } = self.at(span).adt_dtorck_constraint(def.did);
587 Ok(ty::DtorckConstraint {
588 // FIXME: we can try to recursively `dtorck_constraint_on_ty`
589 // there, but that needs some way to handle cycles.
590 dtorck_types: dtorck_types.subst(self, substs),
591 outlives: outlives.subst(self, substs)
595 // Objects must be alive in order for their destructor
597 ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
598 outlives: vec![Kind::from(ty)],
599 dtorck_types: vec![],
602 // Types that can't be resolved. Pass them forward.
603 ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
604 Ok(ty::DtorckConstraint {
606 dtorck_types: vec![ty],
610 ty::TyInfer(..) | ty::TyError => {
611 self.sess.delay_span_bug(span, "unresolved type in dtorck");
616 debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
620 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
621 let mut def_id = def_id;
622 while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
623 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
624 bug!("closure {:?} has no parent", def_id);
630 /// Given the def-id of some item that has no type parameters, make
631 /// a suitable "empty substs" for it.
632 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
633 ty::Substs::for_item(self, item_def_id,
634 |_, _| self.types.re_erased,
636 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
640 pub fn const_usize(&self, val: u16) -> ConstInt {
641 match self.sess.target.uint_type {
642 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16(val as u16)),
643 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32(val as u32)),
644 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64(val as u64)),
650 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
651 tcx: TyCtxt<'a, 'gcx, 'tcx>,
652 state: StableHasher<W>,
655 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
656 where W: StableHasherResult
658 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
659 TypeIdHasher { tcx: tcx, state: StableHasher::new() }
662 pub fn finish(self) -> W {
666 pub fn hash<T: Hash>(&mut self, x: T) {
667 x.hash(&mut self.state);
670 fn hash_discriminant_u8<T>(&mut self, x: &T) {
672 intrinsics::discriminant_value(x)
675 assert_eq!(v, b as u64);
679 fn def_id(&mut self, did: DefId) {
680 // Hash the DefPath corresponding to the DefId, which is independent
681 // of compiler internal state. We already have a stable hash value of
682 // all DefPaths available via tcx.def_path_hash(), so we just feed that
684 let hash = self.tcx.def_path_hash(did);
689 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
690 where W: StableHasherResult
692 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
693 // Distinguish between the Ty variants uniformly.
694 self.hash_discriminant_u8(&ty.sty);
697 TyInt(i) => self.hash(i),
698 TyUint(u) => self.hash(u),
699 TyFloat(f) => self.hash(f),
700 TyArray(_, n) => self.hash(n),
702 TyRef(_, m) => self.hash(m.mutbl),
703 TyClosure(def_id, _) |
704 TyGenerator(def_id, _, _) |
706 TyFnDef(def_id, _) => self.def_id(def_id),
707 TyAdt(d, _) => self.def_id(d.did),
709 self.hash(f.unsafety());
711 self.hash(f.variadic());
712 self.hash(f.inputs().skip_binder().len());
714 TyDynamic(ref data, ..) => {
715 if let Some(p) = data.principal() {
716 self.def_id(p.def_id());
718 for d in data.auto_traits() {
722 TyTuple(tys, defaulted) => {
723 self.hash(tys.len());
724 self.hash(defaulted);
728 self.hash(p.name.as_str());
730 TyProjection(ref data) => {
731 self.def_id(data.item_def_id);
740 TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
743 ty.super_visit_with(self)
746 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
747 self.hash_discriminant_u8(r);
752 // No variant fields to hash for these ...
754 ty::ReLateBound(db, ty::BrAnon(i)) => {
758 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
761 ty::ReLateBound(..) |
765 ty::ReSkolemized(..) => {
766 bug!("TypeIdHasher: unexpected region {:?}", r)
772 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
773 // Anonymize late-bound regions so that, for example:
774 // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
775 // result in the same TypeId (the two types are equivalent).
776 self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
780 impl<'a, 'tcx> ty::TyS<'tcx> {
781 pub fn moves_by_default(&'tcx self,
782 tcx: TyCtxt<'a, 'tcx, 'tcx>,
783 param_env: ty::ParamEnv<'tcx>,
786 !tcx.at(span).is_copy_raw(param_env.and(self))
789 pub fn is_sized(&'tcx self,
790 tcx: TyCtxt<'a, 'tcx, 'tcx>,
791 param_env: ty::ParamEnv<'tcx>,
794 tcx.at(span).is_sized_raw(param_env.and(self))
797 pub fn is_freeze(&'tcx self,
798 tcx: TyCtxt<'a, 'tcx, 'tcx>,
799 param_env: ty::ParamEnv<'tcx>,
802 tcx.at(span).is_freeze_raw(param_env.and(self))
805 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
806 /// non-copy and *might* have a destructor attached; if it returns
807 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
809 /// (Note that this implies that if `ty` has a destructor attached,
810 /// then `needs_drop` will definitely return `true` for `ty`.)
812 pub fn needs_drop(&'tcx self,
813 tcx: TyCtxt<'a, 'tcx, 'tcx>,
814 param_env: ty::ParamEnv<'tcx>)
816 tcx.needs_drop_raw(param_env.and(self))
819 /// Computes the layout of a type. Note that this implicitly
820 /// executes in "reveal all" mode.
822 pub fn layout<'lcx>(&'tcx self,
823 tcx: TyCtxt<'a, 'tcx, 'tcx>,
824 param_env: ty::ParamEnv<'tcx>)
825 -> Result<&'tcx Layout, LayoutError<'tcx>> {
826 let ty = tcx.erase_regions(&self);
827 let layout = tcx.layout_raw(param_env.reveal_all().and(ty));
829 // NB: This recording is normally disabled; when enabled, it
830 // can however trigger recursive invocations of `layout()`.
831 // Therefore, we execute it *after* the main query has
832 // completed, to avoid problems around recursive structures
833 // and the like. (Admitedly, I wasn't able to reproduce a problem
834 // here, but it seems like the right thing to do. -nmatsakis)
835 if let Ok(l) = layout {
836 Layout::record_layout_for_printing(tcx, ty, param_env, l);
843 /// Check whether a type is representable. This means it cannot contain unboxed
844 /// structural recursion. This check is needed for structs and enums.
845 pub fn is_representable(&'tcx self,
846 tcx: TyCtxt<'a, 'tcx, 'tcx>,
848 -> Representability {
850 // Iterate until something non-representable is found
851 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
852 iter.fold(Representability::Representable, |r1, r2| {
854 (Representability::SelfRecursive(v1),
855 Representability::SelfRecursive(v2)) => {
856 Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
858 (r1, r2) => cmp::max(r1, r2)
863 fn are_inner_types_recursive<'a, 'tcx>(
864 tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
865 seen: &mut Vec<Ty<'tcx>>,
866 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
871 TyTuple(ref ts, _) => {
872 // Find non representable
873 fold_repr(ts.iter().map(|ty| {
874 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
877 // Fixed-length vectors.
878 // FIXME(#11924) Behavior undecided for zero-length vectors.
880 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
882 TyAdt(def, substs) => {
883 // Find non representable fields with their spans
884 fold_repr(def.all_fields().map(|field| {
885 let ty = field.ty(tcx, substs);
886 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
887 match is_type_structurally_recursive(tcx, span, seen,
888 representable_cache, ty)
890 Representability::SelfRecursive(_) => {
891 Representability::SelfRecursive(vec![span])
898 // this check is run on type definitions, so we don't expect
899 // to see closure types
900 bug!("requires check invoked on inapplicable type: {:?}", ty)
902 _ => Representability::Representable,
906 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
908 TyAdt(ty_def, _) => {
915 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
916 match (&a.sty, &b.sty) {
917 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
922 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
928 // Does the type `ty` directly (without indirection through a pointer)
929 // contain any types on stack `seen`?
930 fn is_type_structurally_recursive<'a, 'tcx>(
931 tcx: TyCtxt<'a, 'tcx, 'tcx>,
933 seen: &mut Vec<Ty<'tcx>>,
934 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
935 ty: Ty<'tcx>) -> Representability
937 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
938 if let Some(representability) = representable_cache.get(ty) {
939 debug!("is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
940 ty, sp, representability);
941 return representability.clone();
944 let representability = is_type_structurally_recursive_inner(
945 tcx, sp, seen, representable_cache, ty);
947 representable_cache.insert(ty, representability.clone());
951 fn is_type_structurally_recursive_inner<'a, 'tcx>(
952 tcx: TyCtxt<'a, 'tcx, 'tcx>,
954 seen: &mut Vec<Ty<'tcx>>,
955 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
956 ty: Ty<'tcx>) -> Representability
961 // Iterate through stack of previously seen types.
962 let mut iter = seen.iter();
964 // The first item in `seen` is the type we are actually curious about.
965 // We want to return SelfRecursive if this type contains itself.
966 // It is important that we DON'T take generic parameters into account
967 // for this check, so that Bar<T> in this example counts as SelfRecursive:
970 // struct Bar<T> { x: Bar<Foo> }
972 if let Some(&seen_type) = iter.next() {
973 if same_struct_or_enum(seen_type, def) {
974 debug!("SelfRecursive: {:?} contains {:?}",
977 return Representability::SelfRecursive(vec![sp]);
981 // We also need to know whether the first item contains other types
982 // that are structurally recursive. If we don't catch this case, we
983 // will recurse infinitely for some inputs.
985 // It is important that we DO take generic parameters into account
986 // here, so that code like this is considered SelfRecursive, not
987 // ContainsRecursive:
989 // struct Foo { Option<Option<Foo>> }
991 for &seen_type in iter {
992 if same_type(ty, seen_type) {
993 debug!("ContainsRecursive: {:?} contains {:?}",
996 return Representability::ContainsRecursive;
1001 // For structs and enums, track all previously seen types by pushing them
1002 // onto the 'seen' stack.
1004 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
1009 // No need to push in other cases.
1010 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
1015 debug!("is_type_representable: {:?}", self);
1017 // To avoid a stack overflow when checking an enum variant or struct that
1018 // contains a different, structurally recursive type, maintain a stack
1019 // of seen types and check recursion for each of them (issues #3008, #3779).
1020 let mut seen: Vec<Ty> = Vec::new();
1021 let mut representable_cache = FxHashMap();
1022 let r = is_type_structurally_recursive(
1023 tcx, sp, &mut seen, &mut representable_cache, self);
1024 debug!("is_type_representable: {:?} is {:?}", self, r);
1029 fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1030 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1033 let (param_env, ty) = query.into_parts();
1034 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
1036 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1043 fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1044 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1047 let (param_env, ty) = query.into_parts();
1048 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
1050 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1057 fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1058 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1061 let (param_env, ty) = query.into_parts();
1062 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
1064 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
1071 fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1072 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1075 let (param_env, ty) = query.into_parts();
1077 let needs_drop = |ty: Ty<'tcx>| -> bool {
1078 match ty::queries::needs_drop_raw::try_get(tcx, DUMMY_SP, param_env.and(ty)) {
1081 // Cycles should be reported as an error by `check_representable`.
1083 // Consider the type as not needing drop in the meanwhile to avoid
1090 assert!(!ty.needs_infer());
1093 // Fast-path for primitive types
1094 ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
1095 ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
1096 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
1097 ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
1099 // Issue #22536: We first query type_moves_by_default. It sees a
1100 // normalized version of the type, and therefore will definitely
1101 // know whether the type implements Copy (and thus needs no
1102 // cleanup/drop/zeroing) ...
1103 _ if !ty.moves_by_default(tcx, param_env, DUMMY_SP) => false,
1105 // ... (issue #22536 continued) but as an optimization, still use
1106 // prior logic of asking for the structural "may drop".
1108 // FIXME(#22815): Note that this is a conservative heuristic;
1109 // it may report that the type "may drop" when actual type does
1110 // not actually have a destructor associated with it. But since
1111 // the type absolutely did not have the `Copy` bound attached
1112 // (see above), it is sound to treat it as having a destructor.
1114 // User destructors are the only way to have concrete drop types.
1115 ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
1117 // Can refer to a type which may drop.
1118 // FIXME(eddyb) check this against a ParamEnv.
1119 ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
1120 ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
1122 // Structural recursion.
1123 ty::TyArray(ty, _) | ty::TySlice(ty) => needs_drop(ty),
1125 ty::TyClosure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
1127 ty::TyGenerator(..) => true,
1129 ty::TyTuple(ref tys, _) => tys.iter().cloned().any(needs_drop),
1131 // unions don't have destructors regardless of the child types
1132 ty::TyAdt(def, _) if def.is_union() => false,
1134 ty::TyAdt(def, substs) =>
1135 def.variants.iter().any(
1136 |variant| variant.fields.iter().any(
1137 |field| needs_drop(field.ty(tcx, substs)))),
1141 fn layout_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1142 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
1143 -> Result<&'tcx Layout, LayoutError<'tcx>>
1145 let (param_env, ty) = query.into_parts();
1147 let rec_limit = tcx.sess.recursion_limit.get();
1148 let depth = tcx.layout_depth.get();
1149 if depth > rec_limit {
1151 &format!("overflow representing the type `{}`", ty));
1154 tcx.layout_depth.set(depth+1);
1155 let layout = Layout::compute_uncached(tcx, param_env, ty);
1156 tcx.layout_depth.set(depth);
1161 pub fn provide(providers: &mut ty::maps::Providers) {
1162 *providers = ty::maps::Providers {