]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/util.rs
Rollup merge of #41056 - michaelwoerister:central-defpath-hashes, r=nikomatsakis
[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 hir::map as hir_map;
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
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, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
191     pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
192         match ty.sty {
193             ty::TyAdt(def, substs) => {
194                 for field in def.all_fields() {
195                     let field_ty = field.ty(self, substs);
196                     if let TyError = field_ty.sty {
197                         return true;
198                     }
199                 }
200             }
201             _ => (),
202         }
203         false
204     }
205
206     /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
207     /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
208     pub fn positional_element_ty(self,
209                                  ty: Ty<'tcx>,
210                                  i: usize,
211                                  variant: Option<DefId>) -> Option<Ty<'tcx>> {
212         match (&ty.sty, variant) {
213             (&TyAdt(adt, substs), Some(vid)) => {
214                 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
215             }
216             (&TyAdt(adt, substs), None) => {
217                 // Don't use `struct_variant`, this may be a univariant enum.
218                 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
219             }
220             (&TyTuple(ref v, _), None) => v.get(i).cloned(),
221             _ => None,
222         }
223     }
224
225     /// Returns the type of element at field `n` in struct or struct-like type `t`.
226     /// For an enum `t`, `variant` must be some def id.
227     pub fn named_element_ty(self,
228                             ty: Ty<'tcx>,
229                             n: Name,
230                             variant: Option<DefId>) -> Option<Ty<'tcx>> {
231         match (&ty.sty, variant) {
232             (&TyAdt(adt, substs), Some(vid)) => {
233                 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
234             }
235             (&TyAdt(adt, substs), None) => {
236                 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
237             }
238             _ => return None
239         }
240     }
241
242     /// Returns the deeply last field of nested structures, or the same type,
243     /// if not a structure at all. Corresponds to the only possible unsized
244     /// field, and its type can be used to determine unsizing strategy.
245     pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
246         while let TyAdt(def, substs) = ty.sty {
247             if !def.is_struct() {
248                 break;
249             }
250             match def.struct_variant().fields.last() {
251                 Some(f) => ty = f.ty(self, substs),
252                 None => break,
253             }
254         }
255         ty
256     }
257
258     /// Same as applying struct_tail on `source` and `target`, but only
259     /// keeps going as long as the two types are instances of the same
260     /// structure definitions.
261     /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
262     /// whereas struct_tail produces `T`, and `Trait`, respectively.
263     pub fn struct_lockstep_tails(self,
264                                  source: Ty<'tcx>,
265                                  target: Ty<'tcx>)
266                                  -> (Ty<'tcx>, Ty<'tcx>) {
267         let (mut a, mut b) = (source, target);
268         while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
269             if a_def != b_def || !a_def.is_struct() {
270                 break;
271             }
272             match a_def.struct_variant().fields.last() {
273                 Some(f) => {
274                     a = f.ty(self, a_substs);
275                     b = f.ty(self, b_substs);
276                 }
277                 _ => break,
278             }
279         }
280         (a, b)
281     }
282
283     /// Given a set of predicates that apply to an object type, returns
284     /// the region bounds that the (erased) `Self` type must
285     /// outlive. Precisely *because* the `Self` type is erased, the
286     /// parameter `erased_self_ty` must be supplied to indicate what type
287     /// has been used to represent `Self` in the predicates
288     /// themselves. This should really be a unique type; `FreshTy(0)` is a
289     /// popular choice.
290     ///
291     /// NB: in some cases, particularly around higher-ranked bounds,
292     /// this function returns a kind of conservative approximation.
293     /// That is, all regions returned by this function are definitely
294     /// required, but there may be other region bounds that are not
295     /// returned, as well as requirements like `for<'a> T: 'a`.
296     ///
297     /// Requires that trait definitions have been processed so that we can
298     /// elaborate predicates and walk supertraits.
299     pub fn required_region_bounds(self,
300                                   erased_self_ty: Ty<'tcx>,
301                                   predicates: Vec<ty::Predicate<'tcx>>)
302                                   -> Vec<&'tcx ty::Region>    {
303         debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
304                erased_self_ty,
305                predicates);
306
307         assert!(!erased_self_ty.has_escaping_regions());
308
309         traits::elaborate_predicates(self, predicates)
310             .filter_map(|predicate| {
311                 match predicate {
312                     ty::Predicate::Projection(..) |
313                     ty::Predicate::Trait(..) |
314                     ty::Predicate::Equate(..) |
315                     ty::Predicate::WellFormed(..) |
316                     ty::Predicate::ObjectSafe(..) |
317                     ty::Predicate::ClosureKind(..) |
318                     ty::Predicate::RegionOutlives(..) => {
319                         None
320                     }
321                     ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
322                         // Search for a bound of the form `erased_self_ty
323                         // : 'a`, but be wary of something like `for<'a>
324                         // erased_self_ty : 'a` (we interpret a
325                         // higher-ranked bound like that as 'static,
326                         // though at present the code in `fulfill.rs`
327                         // considers such bounds to be unsatisfiable, so
328                         // it's kind of a moot point since you could never
329                         // construct such an object, but this seems
330                         // correct even if that code changes).
331                         if t == erased_self_ty && !r.has_escaping_regions() {
332                             Some(r)
333                         } else {
334                             None
335                         }
336                     }
337                 }
338             })
339             .collect()
340     }
341
342     /// Creates a hash of the type `Ty` which will be the same no matter what crate
343     /// context it's calculated within. This is used by the `type_id` intrinsic.
344     pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
345         let mut hasher = TypeIdHasher::new(self);
346         hasher.visit_ty(ty);
347         hasher.finish()
348     }
349
350     /// Calculate the destructor of a given type.
351     pub fn calculate_dtor(
352         self,
353         adt_did: DefId,
354         validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
355     ) -> Option<ty::Destructor> {
356         let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
357             def_id
358         } else {
359             return None;
360         };
361
362         ty::queries::coherent_trait::get(self, DUMMY_SP, (LOCAL_CRATE, drop_trait));
363
364         let mut dtor_did = None;
365         let ty = self.item_type(adt_did);
366         self.lookup_trait_def(drop_trait).for_each_relevant_impl(self, ty, |impl_did| {
367             if let Some(item) = self.associated_items(impl_did).next() {
368                 if let Ok(()) = validate(self, impl_did) {
369                     dtor_did = Some(item.def_id);
370                 }
371             }
372         });
373
374         let dtor_did = match dtor_did {
375             Some(dtor) => dtor,
376             None => return None,
377         };
378
379         // RFC 1238: if the destructor method is tagged with the
380         // attribute `unsafe_destructor_blind_to_params`, then the
381         // compiler is being instructed to *assume* that the
382         // destructor will not access borrowed data,
383         // even if such data is otherwise reachable.
384         //
385         // Such access can be in plain sight (e.g. dereferencing
386         // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
387         // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
388         let is_dtorck = !self.has_attr(dtor_did, "unsafe_destructor_blind_to_params");
389         Some(ty::Destructor { did: dtor_did, is_dtorck: is_dtorck })
390     }
391
392     pub fn closure_base_def_id(&self, def_id: DefId) -> DefId {
393         let mut def_id = def_id;
394         while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
395             def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
396                 bug!("closure {:?} has no parent", def_id);
397             });
398         }
399         def_id
400     }
401
402     /// Given the def-id of some item that has no type parameters, make
403     /// a suitable "empty substs" for it.
404     pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
405         ty::Substs::for_item(self, item_def_id,
406                              |_, _| self.mk_region(ty::ReErased),
407                              |_, _| {
408             bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
409         })
410     }
411 }
412
413 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
414     tcx: TyCtxt<'a, 'gcx, 'tcx>,
415     state: StableHasher<W>,
416 }
417
418 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
419     where W: StableHasherResult
420 {
421     pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
422         TypeIdHasher { tcx: tcx, state: StableHasher::new() }
423     }
424
425     pub fn finish(self) -> W {
426         self.state.finish()
427     }
428
429     pub fn hash<T: Hash>(&mut self, x: T) {
430         x.hash(&mut self.state);
431     }
432
433     fn hash_discriminant_u8<T>(&mut self, x: &T) {
434         let v = unsafe {
435             intrinsics::discriminant_value(x)
436         };
437         let b = v as u8;
438         assert_eq!(v, b as u64);
439         self.hash(b)
440     }
441
442     fn def_id(&mut self, did: DefId) {
443         // Hash the DefPath corresponding to the DefId, which is independent
444         // of compiler internal state. We already have a stable hash value of
445         // all DefPaths available via tcx.def_path_hash(), so we just feed that
446         // into the hasher.
447         let hash = self.tcx.def_path_hash(did);
448         self.hash(hash);
449     }
450 }
451
452 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
453     where W: StableHasherResult
454 {
455     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
456         // Distinguish between the Ty variants uniformly.
457         self.hash_discriminant_u8(&ty.sty);
458
459         match ty.sty {
460             TyInt(i) => self.hash(i),
461             TyUint(u) => self.hash(u),
462             TyFloat(f) => self.hash(f),
463             TyArray(_, n) => self.hash(n),
464             TyRawPtr(m) |
465             TyRef(_, m) => self.hash(m.mutbl),
466             TyClosure(def_id, _) |
467             TyAnon(def_id, _) |
468             TyFnDef(def_id, ..) => self.def_id(def_id),
469             TyAdt(d, _) => self.def_id(d.did),
470             TyFnPtr(f) => {
471                 self.hash(f.unsafety());
472                 self.hash(f.abi());
473                 self.hash(f.variadic());
474                 self.hash(f.inputs().skip_binder().len());
475             }
476             TyDynamic(ref data, ..) => {
477                 if let Some(p) = data.principal() {
478                     self.def_id(p.def_id());
479                 }
480                 for d in data.auto_traits() {
481                     self.def_id(d);
482                 }
483             }
484             TyTuple(tys, defaulted) => {
485                 self.hash(tys.len());
486                 self.hash(defaulted);
487             }
488             TyParam(p) => {
489                 self.hash(p.idx);
490                 self.hash(p.name.as_str());
491             }
492             TyProjection(ref data) => {
493                 self.def_id(data.trait_ref.def_id);
494                 self.hash(data.item_name.as_str());
495             }
496             TyNever |
497             TyBool |
498             TyChar |
499             TyStr |
500             TySlice(_) => {}
501
502             TyError |
503             TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
504         }
505
506         ty.super_visit_with(self)
507     }
508
509     fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
510         self.hash_discriminant_u8(r);
511         match *r {
512             ty::ReErased |
513             ty::ReStatic |
514             ty::ReEmpty => {
515                 // No variant fields to hash for these ...
516             }
517             ty::ReLateBound(db, ty::BrAnon(i)) => {
518                 self.hash(db.depth);
519                 self.hash(i);
520             }
521             ty::ReEarlyBound(ty::EarlyBoundRegion { index, name }) => {
522                 self.hash(index);
523                 self.hash(name.as_str());
524             }
525             ty::ReLateBound(..) |
526             ty::ReFree(..) |
527             ty::ReScope(..) |
528             ty::ReVar(..) |
529             ty::ReSkolemized(..) => {
530                 bug!("TypeIdHasher: unexpected region {:?}", r)
531             }
532         }
533         false
534     }
535
536     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
537         // Anonymize late-bound regions so that, for example:
538         // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
539         // result in the same TypeId (the two types are equivalent).
540         self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
541     }
542 }
543
544 impl<'a, 'tcx> ty::TyS<'tcx> {
545     fn impls_bound(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
546                    param_env: &ParameterEnvironment<'tcx>,
547                    def_id: DefId,
548                    cache: &RefCell<FxHashMap<Ty<'tcx>, bool>>,
549                    span: Span) -> bool
550     {
551         if self.has_param_types() || self.has_self_ty() {
552             if let Some(result) = cache.borrow().get(self) {
553                 return *result;
554             }
555         }
556         let result =
557             tcx.infer_ctxt(param_env.clone(), Reveal::UserFacing)
558             .enter(|infcx| {
559                 traits::type_known_to_meet_bound(&infcx, self, def_id, span)
560             });
561         if self.has_param_types() || self.has_self_ty() {
562             cache.borrow_mut().insert(self, result);
563         }
564         return result;
565     }
566
567     // FIXME (@jroesch): I made this public to use it, not sure if should be private
568     pub fn moves_by_default(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
569                             param_env: &ParameterEnvironment<'tcx>,
570                             span: Span) -> bool {
571         if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
572             return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
573         }
574
575         assert!(!self.needs_infer());
576
577         // Fast-path for primitive types
578         let result = match self.sty {
579             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) | TyNever |
580             TyRawPtr(..) | TyFnDef(..) | TyFnPtr(_) | TyRef(_, TypeAndMut {
581                 mutbl: hir::MutImmutable, ..
582             }) => Some(false),
583
584             TyStr | TyRef(_, TypeAndMut {
585                 mutbl: hir::MutMutable, ..
586             }) => Some(true),
587
588             TyArray(..) | TySlice(..) | TyDynamic(..) | TyTuple(..) |
589             TyClosure(..) | TyAdt(..) | TyAnon(..) |
590             TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
591         }.unwrap_or_else(|| {
592             !self.impls_bound(tcx, param_env,
593                               tcx.require_lang_item(lang_items::CopyTraitLangItem),
594                               &param_env.is_copy_cache, span) });
595
596         if !self.has_param_types() && !self.has_self_ty() {
597             self.flags.set(self.flags.get() | if result {
598                 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
599             } else {
600                 TypeFlags::MOVENESS_CACHED
601             });
602         }
603
604         result
605     }
606
607     #[inline]
608     pub fn is_sized(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
609                     param_env: &ParameterEnvironment<'tcx>,
610                     span: Span) -> bool
611     {
612         if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
613             return self.flags.get().intersects(TypeFlags::IS_SIZED);
614         }
615
616         self.is_sized_uncached(tcx, param_env, span)
617     }
618
619     fn is_sized_uncached(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
620                          param_env: &ParameterEnvironment<'tcx>,
621                          span: Span) -> bool {
622         assert!(!self.needs_infer());
623
624         // Fast-path for primitive types
625         let result = match self.sty {
626             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
627             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
628             TyArray(..) | TyTuple(..) | TyClosure(..) | TyNever => Some(true),
629
630             TyStr | TyDynamic(..) | TySlice(_) => Some(false),
631
632             TyAdt(..) | TyProjection(..) | TyParam(..) |
633             TyInfer(..) | TyAnon(..) | TyError => None
634         }.unwrap_or_else(|| {
635             self.impls_bound(tcx, param_env, tcx.require_lang_item(lang_items::SizedTraitLangItem),
636                               &param_env.is_sized_cache, span) });
637
638         if !self.has_param_types() && !self.has_self_ty() {
639             self.flags.set(self.flags.get() | if result {
640                 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
641             } else {
642                 TypeFlags::SIZEDNESS_CACHED
643             });
644         }
645
646         result
647     }
648
649     #[inline]
650     pub fn layout<'lcx>(&'tcx self, infcx: &InferCtxt<'a, 'tcx, 'lcx>)
651                         -> Result<&'tcx Layout, LayoutError<'tcx>> {
652         let tcx = infcx.tcx.global_tcx();
653         let can_cache = !self.has_param_types() && !self.has_self_ty();
654         if can_cache {
655             if let Some(&cached) = tcx.layout_cache.borrow().get(&self) {
656                 return Ok(cached);
657             }
658         }
659
660         let rec_limit = tcx.sess.recursion_limit.get();
661         let depth = tcx.layout_depth.get();
662         if depth > rec_limit {
663             tcx.sess.fatal(
664                 &format!("overflow representing the type `{}`", self));
665         }
666
667         tcx.layout_depth.set(depth+1);
668         let layout = Layout::compute_uncached(self, infcx);
669         tcx.layout_depth.set(depth);
670         let layout = layout?;
671         if can_cache {
672             tcx.layout_cache.borrow_mut().insert(self, layout);
673         }
674         Ok(layout)
675     }
676
677
678     /// Check whether a type is representable. This means it cannot contain unboxed
679     /// structural recursion. This check is needed for structs and enums.
680     pub fn is_representable(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span)
681                             -> Representability {
682
683         // Iterate until something non-representable is found
684         fn find_nonrepresentable<'a, 'tcx, It>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
685                                                sp: Span,
686                                                seen: &mut Vec<Ty<'tcx>>,
687                                                iter: It)
688                                                -> Representability
689         where It: Iterator<Item=Ty<'tcx>> {
690             iter.fold(Representability::Representable,
691                       |r, ty| cmp::max(r, is_type_structurally_recursive(tcx, sp, seen, ty)))
692         }
693
694         fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
695                                                seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
696                                                -> Representability {
697             match ty.sty {
698                 TyTuple(ref ts, _) => {
699                     find_nonrepresentable(tcx, sp, seen, ts.iter().cloned())
700                 }
701                 // Fixed-length vectors.
702                 // FIXME(#11924) Behavior undecided for zero-length vectors.
703                 TyArray(ty, _) => {
704                     is_type_structurally_recursive(tcx, sp, seen, ty)
705                 }
706                 TyAdt(def, substs) => {
707                     find_nonrepresentable(tcx,
708                                           sp,
709                                           seen,
710                                           def.all_fields().map(|f| f.ty(tcx, substs)))
711                 }
712                 TyClosure(..) => {
713                     // this check is run on type definitions, so we don't expect
714                     // to see closure types
715                     bug!("requires check invoked on inapplicable type: {:?}", ty)
716                 }
717                 _ => Representability::Representable,
718             }
719         }
720
721         fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
722             match ty.sty {
723                 TyAdt(ty_def, _) => {
724                      ty_def == def
725                 }
726                 _ => false
727             }
728         }
729
730         fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
731             match (&a.sty, &b.sty) {
732                 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
733                     if did_a != did_b {
734                         return false;
735                     }
736
737                     substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
738                 }
739                 _ => a == b,
740             }
741         }
742
743         // Does the type `ty` directly (without indirection through a pointer)
744         // contain any types on stack `seen`?
745         fn is_type_structurally_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
746                                                     sp: Span,
747                                                     seen: &mut Vec<Ty<'tcx>>,
748                                                     ty: Ty<'tcx>) -> Representability {
749             debug!("is_type_structurally_recursive: {:?}", ty);
750
751             match ty.sty {
752                 TyAdt(def, _) => {
753                     {
754                         // Iterate through stack of previously seen types.
755                         let mut iter = seen.iter();
756
757                         // The first item in `seen` is the type we are actually curious about.
758                         // We want to return SelfRecursive if this type contains itself.
759                         // It is important that we DON'T take generic parameters into account
760                         // for this check, so that Bar<T> in this example counts as SelfRecursive:
761                         //
762                         // struct Foo;
763                         // struct Bar<T> { x: Bar<Foo> }
764
765                         if let Some(&seen_type) = iter.next() {
766                             if same_struct_or_enum(seen_type, def) {
767                                 debug!("SelfRecursive: {:?} contains {:?}",
768                                        seen_type,
769                                        ty);
770                                 return Representability::SelfRecursive;
771                             }
772                         }
773
774                         // We also need to know whether the first item contains other types
775                         // that are structurally recursive. If we don't catch this case, we
776                         // will recurse infinitely for some inputs.
777                         //
778                         // It is important that we DO take generic parameters into account
779                         // here, so that code like this is considered SelfRecursive, not
780                         // ContainsRecursive:
781                         //
782                         // struct Foo { Option<Option<Foo>> }
783
784                         for &seen_type in iter {
785                             if same_type(ty, seen_type) {
786                                 debug!("ContainsRecursive: {:?} contains {:?}",
787                                        seen_type,
788                                        ty);
789                                 return Representability::ContainsRecursive;
790                             }
791                         }
792                     }
793
794                     // For structs and enums, track all previously seen types by pushing them
795                     // onto the 'seen' stack.
796                     seen.push(ty);
797                     let out = are_inner_types_recursive(tcx, sp, seen, ty);
798                     seen.pop();
799                     out
800                 }
801                 _ => {
802                     // No need to push in other cases.
803                     are_inner_types_recursive(tcx, sp, seen, ty)
804                 }
805             }
806         }
807
808         debug!("is_type_representable: {:?}", self);
809
810         // To avoid a stack overflow when checking an enum variant or struct that
811         // contains a different, structurally recursive type, maintain a stack
812         // of seen types and check recursion for each of them (issues #3008, #3779).
813         let mut seen: Vec<Ty> = Vec::new();
814         let r = is_type_structurally_recursive(tcx, sp, &mut seen, self);
815         debug!("is_type_representable: {:?} is {:?}", self, r);
816         r
817     }
818 }