]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/util.rs
Rollup merge of #41429 - jonathandturner:update_rls_submod, r=alexcrichton
[rust.git] / src / librustc / ty / util.rs
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.
4 //
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.
10
11 //! misc. type-system utilities too small to deserve their own file
12
13 use hir::def_id::{DefId, LOCAL_CRATE};
14 use hir::map::DefPathData;
15 use infer::InferCtxt;
16 use ich::{StableHashingContext, NodeIdHashingMode};
17 use traits::{self, Reveal};
18 use ty::{self, Ty, TyCtxt, TypeAndMut, TypeFlags, TypeFoldable};
19 use ty::ParameterEnvironment;
20 use ty::fold::TypeVisitor;
21 use ty::layout::{Layout, LayoutError};
22 use ty::TypeVariants::*;
23 use util::common::ErrorReported;
24 use util::nodemap::FxHashMap;
25 use middle::lang_items;
26
27 use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
28 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
29                                            HashStable};
30 use std::cell::RefCell;
31 use std::cmp;
32 use std::hash::Hash;
33 use std::intrinsics;
34 use syntax::ast::{self, Name};
35 use syntax::attr::{self, SignedInt, UnsignedInt};
36 use syntax_pos::{Span, DUMMY_SP};
37
38 use hir;
39
40 type Disr = ConstInt;
41
42 pub trait IntTypeExt {
43     fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
44     fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
45                            -> Option<Disr>;
46     fn assert_ty_matches(&self, val: Disr);
47     fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr;
48 }
49
50
51 macro_rules! typed_literal {
52     ($tcx:expr, $ty:expr, $lit:expr) => {
53         match $ty {
54             SignedInt(ast::IntTy::I8)    => ConstInt::I8($lit),
55             SignedInt(ast::IntTy::I16)   => ConstInt::I16($lit),
56             SignedInt(ast::IntTy::I32)   => ConstInt::I32($lit),
57             SignedInt(ast::IntTy::I64)   => ConstInt::I64($lit),
58             SignedInt(ast::IntTy::I128)   => ConstInt::I128($lit),
59             SignedInt(ast::IntTy::Is) => match $tcx.sess.target.int_type {
60                 ast::IntTy::I16 => ConstInt::Isize(ConstIsize::Is16($lit)),
61                 ast::IntTy::I32 => ConstInt::Isize(ConstIsize::Is32($lit)),
62                 ast::IntTy::I64 => ConstInt::Isize(ConstIsize::Is64($lit)),
63                 _ => bug!(),
64             },
65             UnsignedInt(ast::UintTy::U8)  => ConstInt::U8($lit),
66             UnsignedInt(ast::UintTy::U16) => ConstInt::U16($lit),
67             UnsignedInt(ast::UintTy::U32) => ConstInt::U32($lit),
68             UnsignedInt(ast::UintTy::U64) => ConstInt::U64($lit),
69             UnsignedInt(ast::UintTy::U128) => ConstInt::U128($lit),
70             UnsignedInt(ast::UintTy::Us) => match $tcx.sess.target.uint_type {
71                 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16($lit)),
72                 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32($lit)),
73                 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64($lit)),
74                 _ => bug!(),
75             },
76         }
77     }
78 }
79
80 impl IntTypeExt for attr::IntType {
81     fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
82         match *self {
83             SignedInt(ast::IntTy::I8)      => tcx.types.i8,
84             SignedInt(ast::IntTy::I16)     => tcx.types.i16,
85             SignedInt(ast::IntTy::I32)     => tcx.types.i32,
86             SignedInt(ast::IntTy::I64)     => tcx.types.i64,
87             SignedInt(ast::IntTy::I128)     => tcx.types.i128,
88             SignedInt(ast::IntTy::Is)   => tcx.types.isize,
89             UnsignedInt(ast::UintTy::U8)    => tcx.types.u8,
90             UnsignedInt(ast::UintTy::U16)   => tcx.types.u16,
91             UnsignedInt(ast::UintTy::U32)   => tcx.types.u32,
92             UnsignedInt(ast::UintTy::U64)   => tcx.types.u64,
93             UnsignedInt(ast::UintTy::U128)   => tcx.types.u128,
94             UnsignedInt(ast::UintTy::Us) => tcx.types.usize,
95         }
96     }
97
98     fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr {
99         typed_literal!(tcx, *self, 0)
100     }
101
102     fn assert_ty_matches(&self, val: Disr) {
103         match (*self, val) {
104             (SignedInt(ast::IntTy::I8), ConstInt::I8(_)) => {},
105             (SignedInt(ast::IntTy::I16), ConstInt::I16(_)) => {},
106             (SignedInt(ast::IntTy::I32), ConstInt::I32(_)) => {},
107             (SignedInt(ast::IntTy::I64), ConstInt::I64(_)) => {},
108             (SignedInt(ast::IntTy::I128), ConstInt::I128(_)) => {},
109             (SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) => {},
110             (UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) => {},
111             (UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) => {},
112             (UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) => {},
113             (UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) => {},
114             (UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) => {},
115             (UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => {},
116             _ => bug!("disr type mismatch: {:?} vs {:?}", self, val),
117         }
118     }
119
120     fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
121                            -> Option<Disr> {
122         if let Some(val) = val {
123             self.assert_ty_matches(val);
124             (val + typed_literal!(tcx, *self, 1)).ok()
125         } else {
126             Some(self.initial_discriminant(tcx))
127         }
128     }
129 }
130
131
132 #[derive(Copy, Clone)]
133 pub enum CopyImplementationError<'tcx> {
134     InfrigingField(&'tcx ty::FieldDef),
135     NotAnAdt,
136     HasDestructor,
137 }
138
139 /// Describes whether a type is representable. For types that are not
140 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
141 /// distinguish between types that are recursive with themselves and types that
142 /// contain a different recursive type. These cases can therefore be treated
143 /// differently when reporting errors.
144 ///
145 /// The ordering of the cases is significant. They are sorted so that cmp::max
146 /// will keep the "more erroneous" of two values.
147 #[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
148 pub enum Representability {
149     Representable,
150     ContainsRecursive,
151     SelfRecursive,
152 }
153
154 impl<'tcx> ParameterEnvironment<'tcx> {
155     pub fn can_type_implement_copy<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
156                                        self_type: Ty<'tcx>, span: Span)
157                                        -> Result<(), CopyImplementationError> {
158         // FIXME: (@jroesch) float this code up
159         tcx.infer_ctxt(self.clone(), Reveal::UserFacing).enter(|infcx| {
160             let (adt, substs) = match self_type.sty {
161                 ty::TyAdt(adt, substs) => (adt, substs),
162                 _ => return Err(CopyImplementationError::NotAnAdt),
163             };
164
165             let field_implements_copy = |field: &ty::FieldDef| {
166                 let cause = traits::ObligationCause::dummy();
167                 match traits::fully_normalize(&infcx, cause, &field.ty(tcx, substs)) {
168                     Ok(ty) => !infcx.type_moves_by_default(ty, span),
169                     Err(..) => false,
170                 }
171             };
172
173             for variant in &adt.variants {
174                 for field in &variant.fields {
175                     if !field_implements_copy(field) {
176                         return Err(CopyImplementationError::InfrigingField(field));
177                     }
178                 }
179             }
180
181             if adt.has_dtor(tcx) {
182                 return Err(CopyImplementationError::HasDestructor);
183             }
184
185             Ok(())
186         })
187     }
188 }
189
190 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
191     /// Creates a hash of the type `Ty` which will be the same no matter what crate
192     /// context it's calculated within. This is used by the `type_id` intrinsic.
193     pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
194         let mut hasher = StableHasher::new();
195         let mut hcx = StableHashingContext::new(self);
196
197         hcx.while_hashing_spans(false, |hcx| {
198             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
199                 ty.hash_stable(hcx, &mut hasher);
200             });
201         });
202         hasher.finish()
203     }
204 }
205
206 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
207     pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
208         match ty.sty {
209             ty::TyAdt(def, substs) => {
210                 for field in def.all_fields() {
211                     let field_ty = field.ty(self, substs);
212                     if let TyError = field_ty.sty {
213                         return true;
214                     }
215                 }
216             }
217             _ => (),
218         }
219         false
220     }
221
222     /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
223     /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
224     pub fn positional_element_ty(self,
225                                  ty: Ty<'tcx>,
226                                  i: usize,
227                                  variant: Option<DefId>) -> Option<Ty<'tcx>> {
228         match (&ty.sty, variant) {
229             (&TyAdt(adt, substs), Some(vid)) => {
230                 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
231             }
232             (&TyAdt(adt, substs), None) => {
233                 // Don't use `struct_variant`, this may be a univariant enum.
234                 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
235             }
236             (&TyTuple(ref v, _), None) => v.get(i).cloned(),
237             _ => None,
238         }
239     }
240
241     /// Returns the type of element at field `n` in struct or struct-like type `t`.
242     /// For an enum `t`, `variant` must be some def id.
243     pub fn named_element_ty(self,
244                             ty: Ty<'tcx>,
245                             n: Name,
246                             variant: Option<DefId>) -> Option<Ty<'tcx>> {
247         match (&ty.sty, variant) {
248             (&TyAdt(adt, substs), Some(vid)) => {
249                 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
250             }
251             (&TyAdt(adt, substs), None) => {
252                 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
253             }
254             _ => return None
255         }
256     }
257
258     /// Returns the deeply last field of nested structures, or the same type,
259     /// if not a structure at all. Corresponds to the only possible unsized
260     /// field, and its type can be used to determine unsizing strategy.
261     pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
262         while let TyAdt(def, substs) = ty.sty {
263             if !def.is_struct() {
264                 break;
265             }
266             match def.struct_variant().fields.last() {
267                 Some(f) => ty = f.ty(self, substs),
268                 None => break,
269             }
270         }
271         ty
272     }
273
274     /// Same as applying struct_tail on `source` and `target`, but only
275     /// keeps going as long as the two types are instances of the same
276     /// structure definitions.
277     /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
278     /// whereas struct_tail produces `T`, and `Trait`, respectively.
279     pub fn struct_lockstep_tails(self,
280                                  source: Ty<'tcx>,
281                                  target: Ty<'tcx>)
282                                  -> (Ty<'tcx>, Ty<'tcx>) {
283         let (mut a, mut b) = (source, target);
284         while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
285             if a_def != b_def || !a_def.is_struct() {
286                 break;
287             }
288             match a_def.struct_variant().fields.last() {
289                 Some(f) => {
290                     a = f.ty(self, a_substs);
291                     b = f.ty(self, b_substs);
292                 }
293                 _ => break,
294             }
295         }
296         (a, b)
297     }
298
299     /// Given a set of predicates that apply to an object type, returns
300     /// the region bounds that the (erased) `Self` type must
301     /// outlive. Precisely *because* the `Self` type is erased, the
302     /// parameter `erased_self_ty` must be supplied to indicate what type
303     /// has been used to represent `Self` in the predicates
304     /// themselves. This should really be a unique type; `FreshTy(0)` is a
305     /// popular choice.
306     ///
307     /// NB: in some cases, particularly around higher-ranked bounds,
308     /// this function returns a kind of conservative approximation.
309     /// That is, all regions returned by this function are definitely
310     /// required, but there may be other region bounds that are not
311     /// returned, as well as requirements like `for<'a> T: 'a`.
312     ///
313     /// Requires that trait definitions have been processed so that we can
314     /// elaborate predicates and walk supertraits.
315     pub fn required_region_bounds(self,
316                                   erased_self_ty: Ty<'tcx>,
317                                   predicates: Vec<ty::Predicate<'tcx>>)
318                                   -> Vec<&'tcx ty::Region>    {
319         debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
320                erased_self_ty,
321                predicates);
322
323         assert!(!erased_self_ty.has_escaping_regions());
324
325         traits::elaborate_predicates(self, predicates)
326             .filter_map(|predicate| {
327                 match predicate {
328                     ty::Predicate::Projection(..) |
329                     ty::Predicate::Trait(..) |
330                     ty::Predicate::Equate(..) |
331                     ty::Predicate::Subtype(..) |
332                     ty::Predicate::WellFormed(..) |
333                     ty::Predicate::ObjectSafe(..) |
334                     ty::Predicate::ClosureKind(..) |
335                     ty::Predicate::RegionOutlives(..) => {
336                         None
337                     }
338                     ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
339                         // Search for a bound of the form `erased_self_ty
340                         // : 'a`, but be wary of something like `for<'a>
341                         // erased_self_ty : 'a` (we interpret a
342                         // higher-ranked bound like that as 'static,
343                         // though at present the code in `fulfill.rs`
344                         // considers such bounds to be unsatisfiable, so
345                         // it's kind of a moot point since you could never
346                         // construct such an object, but this seems
347                         // correct even if that code changes).
348                         if t == erased_self_ty && !r.has_escaping_regions() {
349                             Some(r)
350                         } else {
351                             None
352                         }
353                     }
354                 }
355             })
356             .collect()
357     }
358
359     /// Calculate the destructor of a given type.
360     pub fn calculate_dtor(
361         self,
362         adt_did: DefId,
363         validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
364     ) -> Option<ty::Destructor> {
365         let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
366             def_id
367         } else {
368             return None;
369         };
370
371         ty::queries::coherent_trait::get(self, DUMMY_SP, (LOCAL_CRATE, drop_trait));
372
373         let mut dtor_did = None;
374         let ty = self.item_type(adt_did);
375         self.lookup_trait_def(drop_trait).for_each_relevant_impl(self, ty, |impl_did| {
376             if let Some(item) = self.associated_items(impl_did).next() {
377                 if let Ok(()) = validate(self, impl_did) {
378                     dtor_did = Some(item.def_id);
379                 }
380             }
381         });
382
383         let dtor_did = match dtor_did {
384             Some(dtor) => dtor,
385             None => return None,
386         };
387
388         // RFC 1238: if the destructor method is tagged with the
389         // attribute `unsafe_destructor_blind_to_params`, then the
390         // compiler is being instructed to *assume* that the
391         // destructor will not access borrowed data,
392         // even if such data is otherwise reachable.
393         //
394         // Such access can be in plain sight (e.g. dereferencing
395         // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
396         // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
397         let is_dtorck = !self.has_attr(dtor_did, "unsafe_destructor_blind_to_params");
398         Some(ty::Destructor { did: dtor_did, is_dtorck: is_dtorck })
399     }
400
401     pub fn closure_base_def_id(&self, def_id: DefId) -> DefId {
402         let mut def_id = def_id;
403         while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
404             def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
405                 bug!("closure {:?} has no parent", def_id);
406             });
407         }
408         def_id
409     }
410
411     /// Given the def-id of some item that has no type parameters, make
412     /// a suitable "empty substs" for it.
413     pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
414         ty::Substs::for_item(self, item_def_id,
415                              |_, _| self.mk_region(ty::ReErased),
416                              |_, _| {
417             bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
418         })
419     }
420 }
421
422 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
423     tcx: TyCtxt<'a, 'gcx, 'tcx>,
424     state: StableHasher<W>,
425 }
426
427 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
428     where W: StableHasherResult
429 {
430     pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
431         TypeIdHasher { tcx: tcx, state: StableHasher::new() }
432     }
433
434     pub fn finish(self) -> W {
435         self.state.finish()
436     }
437
438     pub fn hash<T: Hash>(&mut self, x: T) {
439         x.hash(&mut self.state);
440     }
441
442     fn hash_discriminant_u8<T>(&mut self, x: &T) {
443         let v = unsafe {
444             intrinsics::discriminant_value(x)
445         };
446         let b = v as u8;
447         assert_eq!(v, b as u64);
448         self.hash(b)
449     }
450
451     fn def_id(&mut self, did: DefId) {
452         // Hash the DefPath corresponding to the DefId, which is independent
453         // of compiler internal state. We already have a stable hash value of
454         // all DefPaths available via tcx.def_path_hash(), so we just feed that
455         // into the hasher.
456         let hash = self.tcx.def_path_hash(did);
457         self.hash(hash);
458     }
459 }
460
461 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
462     where W: StableHasherResult
463 {
464     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
465         // Distinguish between the Ty variants uniformly.
466         self.hash_discriminant_u8(&ty.sty);
467
468         match ty.sty {
469             TyInt(i) => self.hash(i),
470             TyUint(u) => self.hash(u),
471             TyFloat(f) => self.hash(f),
472             TyArray(_, n) => self.hash(n),
473             TyRawPtr(m) |
474             TyRef(_, m) => self.hash(m.mutbl),
475             TyClosure(def_id, _) |
476             TyAnon(def_id, _) |
477             TyFnDef(def_id, ..) => self.def_id(def_id),
478             TyAdt(d, _) => self.def_id(d.did),
479             TyFnPtr(f) => {
480                 self.hash(f.unsafety());
481                 self.hash(f.abi());
482                 self.hash(f.variadic());
483                 self.hash(f.inputs().skip_binder().len());
484             }
485             TyDynamic(ref data, ..) => {
486                 if let Some(p) = data.principal() {
487                     self.def_id(p.def_id());
488                 }
489                 for d in data.auto_traits() {
490                     self.def_id(d);
491                 }
492             }
493             TyTuple(tys, defaulted) => {
494                 self.hash(tys.len());
495                 self.hash(defaulted);
496             }
497             TyParam(p) => {
498                 self.hash(p.idx);
499                 self.hash(p.name.as_str());
500             }
501             TyProjection(ref data) => {
502                 self.def_id(data.trait_ref.def_id);
503                 self.hash(data.item_name.as_str());
504             }
505             TyNever |
506             TyBool |
507             TyChar |
508             TyStr |
509             TySlice(_) => {}
510
511             TyError |
512             TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
513         }
514
515         ty.super_visit_with(self)
516     }
517
518     fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
519         self.hash_discriminant_u8(r);
520         match *r {
521             ty::ReErased |
522             ty::ReStatic |
523             ty::ReEmpty => {
524                 // No variant fields to hash for these ...
525             }
526             ty::ReLateBound(db, ty::BrAnon(i)) => {
527                 self.hash(db.depth);
528                 self.hash(i);
529             }
530             ty::ReEarlyBound(ty::EarlyBoundRegion { index, name }) => {
531                 self.hash(index);
532                 self.hash(name.as_str());
533             }
534             ty::ReLateBound(..) |
535             ty::ReFree(..) |
536             ty::ReScope(..) |
537             ty::ReVar(..) |
538             ty::ReSkolemized(..) => {
539                 bug!("TypeIdHasher: unexpected region {:?}", r)
540             }
541         }
542         false
543     }
544
545     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
546         // Anonymize late-bound regions so that, for example:
547         // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
548         // result in the same TypeId (the two types are equivalent).
549         self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
550     }
551 }
552
553 impl<'a, 'tcx> ty::TyS<'tcx> {
554     fn impls_bound(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
555                    param_env: &ParameterEnvironment<'tcx>,
556                    def_id: DefId,
557                    cache: &RefCell<FxHashMap<Ty<'tcx>, bool>>,
558                    span: Span) -> bool
559     {
560         if self.has_param_types() || self.has_self_ty() {
561             if let Some(result) = cache.borrow().get(self) {
562                 return *result;
563             }
564         }
565         let result =
566             tcx.infer_ctxt(param_env.clone(), Reveal::UserFacing)
567             .enter(|infcx| {
568                 traits::type_known_to_meet_bound(&infcx, self, def_id, span)
569             });
570         if self.has_param_types() || self.has_self_ty() {
571             cache.borrow_mut().insert(self, result);
572         }
573         return result;
574     }
575
576     // FIXME (@jroesch): I made this public to use it, not sure if should be private
577     pub fn moves_by_default(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
578                             param_env: &ParameterEnvironment<'tcx>,
579                             span: Span) -> bool {
580         if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
581             return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
582         }
583
584         assert!(!self.needs_infer());
585
586         // Fast-path for primitive types
587         let result = match self.sty {
588             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) | TyNever |
589             TyRawPtr(..) | TyFnDef(..) | TyFnPtr(_) | TyRef(_, TypeAndMut {
590                 mutbl: hir::MutImmutable, ..
591             }) => Some(false),
592
593             TyStr | TyRef(_, TypeAndMut {
594                 mutbl: hir::MutMutable, ..
595             }) => Some(true),
596
597             TyArray(..) | TySlice(..) | TyDynamic(..) | TyTuple(..) |
598             TyClosure(..) | TyAdt(..) | TyAnon(..) |
599             TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
600         }.unwrap_or_else(|| {
601             !self.impls_bound(tcx, param_env,
602                               tcx.require_lang_item(lang_items::CopyTraitLangItem),
603                               &param_env.is_copy_cache, span) });
604
605         if !self.has_param_types() && !self.has_self_ty() {
606             self.flags.set(self.flags.get() | if result {
607                 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
608             } else {
609                 TypeFlags::MOVENESS_CACHED
610             });
611         }
612
613         result
614     }
615
616     #[inline]
617     pub fn is_sized(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
618                     param_env: &ParameterEnvironment<'tcx>,
619                     span: Span) -> bool
620     {
621         if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
622             return self.flags.get().intersects(TypeFlags::IS_SIZED);
623         }
624
625         self.is_sized_uncached(tcx, param_env, span)
626     }
627
628     fn is_sized_uncached(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
629                          param_env: &ParameterEnvironment<'tcx>,
630                          span: Span) -> bool {
631         assert!(!self.needs_infer());
632
633         // Fast-path for primitive types
634         let result = match self.sty {
635             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
636             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
637             TyArray(..) | TyTuple(..) | TyClosure(..) | TyNever => Some(true),
638
639             TyStr | TyDynamic(..) | TySlice(_) => Some(false),
640
641             TyAdt(..) | TyProjection(..) | TyParam(..) |
642             TyInfer(..) | TyAnon(..) | TyError => None
643         }.unwrap_or_else(|| {
644             self.impls_bound(tcx, param_env, tcx.require_lang_item(lang_items::SizedTraitLangItem),
645                               &param_env.is_sized_cache, span) });
646
647         if !self.has_param_types() && !self.has_self_ty() {
648             self.flags.set(self.flags.get() | if result {
649                 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
650             } else {
651                 TypeFlags::SIZEDNESS_CACHED
652             });
653         }
654
655         result
656     }
657
658     #[inline]
659     pub fn layout<'lcx>(&'tcx self, infcx: &InferCtxt<'a, 'tcx, 'lcx>)
660                         -> Result<&'tcx Layout, LayoutError<'tcx>> {
661         let tcx = infcx.tcx.global_tcx();
662         let can_cache = !self.has_param_types() && !self.has_self_ty();
663         if can_cache {
664             if let Some(&cached) = tcx.layout_cache.borrow().get(&self) {
665                 return Ok(cached);
666             }
667         }
668
669         let rec_limit = tcx.sess.recursion_limit.get();
670         let depth = tcx.layout_depth.get();
671         if depth > rec_limit {
672             tcx.sess.fatal(
673                 &format!("overflow representing the type `{}`", self));
674         }
675
676         tcx.layout_depth.set(depth+1);
677         let layout = Layout::compute_uncached(self, infcx);
678         tcx.layout_depth.set(depth);
679         let layout = layout?;
680         if can_cache {
681             tcx.layout_cache.borrow_mut().insert(self, layout);
682         }
683         Ok(layout)
684     }
685
686
687     /// Check whether a type is representable. This means it cannot contain unboxed
688     /// structural recursion. This check is needed for structs and enums.
689     pub fn is_representable(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span)
690                             -> Representability {
691
692         // Iterate until something non-representable is found
693         fn find_nonrepresentable<'a, 'tcx, It>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
694                                                sp: Span,
695                                                seen: &mut Vec<Ty<'tcx>>,
696                                                iter: It)
697                                                -> Representability
698         where It: Iterator<Item=Ty<'tcx>> {
699             iter.fold(Representability::Representable,
700                       |r, ty| cmp::max(r, is_type_structurally_recursive(tcx, sp, seen, ty)))
701         }
702
703         fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
704                                                seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
705                                                -> Representability {
706             match ty.sty {
707                 TyTuple(ref ts, _) => {
708                     find_nonrepresentable(tcx, sp, seen, ts.iter().cloned())
709                 }
710                 // Fixed-length vectors.
711                 // FIXME(#11924) Behavior undecided for zero-length vectors.
712                 TyArray(ty, _) => {
713                     is_type_structurally_recursive(tcx, sp, seen, ty)
714                 }
715                 TyAdt(def, substs) => {
716                     find_nonrepresentable(tcx,
717                                           sp,
718                                           seen,
719                                           def.all_fields().map(|f| f.ty(tcx, substs)))
720                 }
721                 TyClosure(..) => {
722                     // this check is run on type definitions, so we don't expect
723                     // to see closure types
724                     bug!("requires check invoked on inapplicable type: {:?}", ty)
725                 }
726                 _ => Representability::Representable,
727             }
728         }
729
730         fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
731             match ty.sty {
732                 TyAdt(ty_def, _) => {
733                      ty_def == def
734                 }
735                 _ => false
736             }
737         }
738
739         fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
740             match (&a.sty, &b.sty) {
741                 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
742                     if did_a != did_b {
743                         return false;
744                     }
745
746                     substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
747                 }
748                 _ => a == b,
749             }
750         }
751
752         // Does the type `ty` directly (without indirection through a pointer)
753         // contain any types on stack `seen`?
754         fn is_type_structurally_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
755                                                     sp: Span,
756                                                     seen: &mut Vec<Ty<'tcx>>,
757                                                     ty: Ty<'tcx>) -> Representability {
758             debug!("is_type_structurally_recursive: {:?}", ty);
759
760             match ty.sty {
761                 TyAdt(def, _) => {
762                     {
763                         // Iterate through stack of previously seen types.
764                         let mut iter = seen.iter();
765
766                         // The first item in `seen` is the type we are actually curious about.
767                         // We want to return SelfRecursive if this type contains itself.
768                         // It is important that we DON'T take generic parameters into account
769                         // for this check, so that Bar<T> in this example counts as SelfRecursive:
770                         //
771                         // struct Foo;
772                         // struct Bar<T> { x: Bar<Foo> }
773
774                         if let Some(&seen_type) = iter.next() {
775                             if same_struct_or_enum(seen_type, def) {
776                                 debug!("SelfRecursive: {:?} contains {:?}",
777                                        seen_type,
778                                        ty);
779                                 return Representability::SelfRecursive;
780                             }
781                         }
782
783                         // We also need to know whether the first item contains other types
784                         // that are structurally recursive. If we don't catch this case, we
785                         // will recurse infinitely for some inputs.
786                         //
787                         // It is important that we DO take generic parameters into account
788                         // here, so that code like this is considered SelfRecursive, not
789                         // ContainsRecursive:
790                         //
791                         // struct Foo { Option<Option<Foo>> }
792
793                         for &seen_type in iter {
794                             if same_type(ty, seen_type) {
795                                 debug!("ContainsRecursive: {:?} contains {:?}",
796                                        seen_type,
797                                        ty);
798                                 return Representability::ContainsRecursive;
799                             }
800                         }
801                     }
802
803                     // For structs and enums, track all previously seen types by pushing them
804                     // onto the 'seen' stack.
805                     seen.push(ty);
806                     let out = are_inner_types_recursive(tcx, sp, seen, ty);
807                     seen.pop();
808                     out
809                 }
810                 _ => {
811                     // No need to push in other cases.
812                     are_inner_types_recursive(tcx, sp, seen, ty)
813                 }
814             }
815         }
816
817         debug!("is_type_representable: {:?}", self);
818
819         // To avoid a stack overflow when checking an enum variant or struct that
820         // contains a different, structurally recursive type, maintain a stack
821         // of seen types and check recursion for each of them (issues #3008, #3779).
822         let mut seen: Vec<Ty> = Vec::new();
823         let r = is_type_structurally_recursive(tcx, sp, &mut seen, self);
824         debug!("is_type_representable: {:?} is {:?}", self, r);
825         r
826     }
827 }