]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/util.rs
Auto merge of #41864 - malbarbo:android-docker, 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::subst::{Subst, Kind};
23 use ty::TypeVariants::*;
24 use util::common::ErrorReported;
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use middle::lang_items;
27
28 use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
29 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
30                                            HashStable};
31 use std::cell::RefCell;
32 use std::cmp;
33 use std::hash::Hash;
34 use std::intrinsics;
35 use syntax::ast::{self, Name};
36 use syntax::attr::{self, SignedInt, UnsignedInt};
37 use syntax_pos::{Span, DUMMY_SP};
38
39 use hir;
40
41 type Disr = ConstInt;
42
43 pub trait IntTypeExt {
44     fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
45     fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
46                            -> Option<Disr>;
47     fn assert_ty_matches(&self, val: Disr);
48     fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr;
49 }
50
51
52 macro_rules! typed_literal {
53     ($tcx:expr, $ty:expr, $lit:expr) => {
54         match $ty {
55             SignedInt(ast::IntTy::I8)    => ConstInt::I8($lit),
56             SignedInt(ast::IntTy::I16)   => ConstInt::I16($lit),
57             SignedInt(ast::IntTy::I32)   => ConstInt::I32($lit),
58             SignedInt(ast::IntTy::I64)   => ConstInt::I64($lit),
59             SignedInt(ast::IntTy::I128)   => ConstInt::I128($lit),
60             SignedInt(ast::IntTy::Is) => match $tcx.sess.target.int_type {
61                 ast::IntTy::I16 => ConstInt::Isize(ConstIsize::Is16($lit)),
62                 ast::IntTy::I32 => ConstInt::Isize(ConstIsize::Is32($lit)),
63                 ast::IntTy::I64 => ConstInt::Isize(ConstIsize::Is64($lit)),
64                 _ => bug!(),
65             },
66             UnsignedInt(ast::UintTy::U8)  => ConstInt::U8($lit),
67             UnsignedInt(ast::UintTy::U16) => ConstInt::U16($lit),
68             UnsignedInt(ast::UintTy::U32) => ConstInt::U32($lit),
69             UnsignedInt(ast::UintTy::U64) => ConstInt::U64($lit),
70             UnsignedInt(ast::UintTy::U128) => ConstInt::U128($lit),
71             UnsignedInt(ast::UintTy::Us) => match $tcx.sess.target.uint_type {
72                 ast::UintTy::U16 => ConstInt::Usize(ConstUsize::Us16($lit)),
73                 ast::UintTy::U32 => ConstInt::Usize(ConstUsize::Us32($lit)),
74                 ast::UintTy::U64 => ConstInt::Usize(ConstUsize::Us64($lit)),
75                 _ => bug!(),
76             },
77         }
78     }
79 }
80
81 impl IntTypeExt for attr::IntType {
82     fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
83         match *self {
84             SignedInt(ast::IntTy::I8)      => tcx.types.i8,
85             SignedInt(ast::IntTy::I16)     => tcx.types.i16,
86             SignedInt(ast::IntTy::I32)     => tcx.types.i32,
87             SignedInt(ast::IntTy::I64)     => tcx.types.i64,
88             SignedInt(ast::IntTy::I128)     => tcx.types.i128,
89             SignedInt(ast::IntTy::Is)   => tcx.types.isize,
90             UnsignedInt(ast::UintTy::U8)    => tcx.types.u8,
91             UnsignedInt(ast::UintTy::U16)   => tcx.types.u16,
92             UnsignedInt(ast::UintTy::U32)   => tcx.types.u32,
93             UnsignedInt(ast::UintTy::U64)   => tcx.types.u64,
94             UnsignedInt(ast::UintTy::U128)   => tcx.types.u128,
95             UnsignedInt(ast::UintTy::Us) => tcx.types.usize,
96         }
97     }
98
99     fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr {
100         typed_literal!(tcx, *self, 0)
101     }
102
103     fn assert_ty_matches(&self, val: Disr) {
104         match (*self, val) {
105             (SignedInt(ast::IntTy::I8), ConstInt::I8(_)) => {},
106             (SignedInt(ast::IntTy::I16), ConstInt::I16(_)) => {},
107             (SignedInt(ast::IntTy::I32), ConstInt::I32(_)) => {},
108             (SignedInt(ast::IntTy::I64), ConstInt::I64(_)) => {},
109             (SignedInt(ast::IntTy::I128), ConstInt::I128(_)) => {},
110             (SignedInt(ast::IntTy::Is), ConstInt::Isize(_)) => {},
111             (UnsignedInt(ast::UintTy::U8), ConstInt::U8(_)) => {},
112             (UnsignedInt(ast::UintTy::U16), ConstInt::U16(_)) => {},
113             (UnsignedInt(ast::UintTy::U32), ConstInt::U32(_)) => {},
114             (UnsignedInt(ast::UintTy::U64), ConstInt::U64(_)) => {},
115             (UnsignedInt(ast::UintTy::U128), ConstInt::U128(_)) => {},
116             (UnsignedInt(ast::UintTy::Us), ConstInt::Usize(_)) => {},
117             _ => bug!("disr type mismatch: {:?} vs {:?}", self, val),
118         }
119     }
120
121     fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>)
122                            -> Option<Disr> {
123         if let Some(val) = val {
124             self.assert_ty_matches(val);
125             (val + typed_literal!(tcx, *self, 1)).ok()
126         } else {
127             Some(self.initial_discriminant(tcx))
128         }
129     }
130 }
131
132
133 #[derive(Copy, Clone)]
134 pub enum CopyImplementationError<'tcx> {
135     InfrigingField(&'tcx ty::FieldDef),
136     NotAnAdt,
137     HasDestructor,
138 }
139
140 /// Describes whether a type is representable. For types that are not
141 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
142 /// distinguish between types that are recursive with themselves and types that
143 /// contain a different recursive type. These cases can therefore be treated
144 /// differently when reporting errors.
145 ///
146 /// The ordering of the cases is significant. They are sorted so that cmp::max
147 /// will keep the "more erroneous" of two values.
148 #[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
149 pub enum Representability {
150     Representable,
151     ContainsRecursive,
152     SelfRecursive(Vec<Span>),
153 }
154
155 impl<'tcx> ParameterEnvironment<'tcx> {
156     pub fn can_type_implement_copy<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
157                                        self_type: Ty<'tcx>, span: Span)
158                                        -> Result<(), CopyImplementationError> {
159         // FIXME: (@jroesch) float this code up
160         tcx.infer_ctxt(self.clone(), Reveal::UserFacing).enter(|infcx| {
161             let (adt, substs) = match self_type.sty {
162                 ty::TyAdt(adt, substs) => (adt, substs),
163                 _ => return Err(CopyImplementationError::NotAnAdt),
164             };
165
166             let field_implements_copy = |field: &ty::FieldDef| {
167                 let cause = traits::ObligationCause::dummy();
168                 match traits::fully_normalize(&infcx, cause, &field.ty(tcx, substs)) {
169                     Ok(ty) => !infcx.type_moves_by_default(ty, span),
170                     Err(..) => false,
171                 }
172             };
173
174             for variant in &adt.variants {
175                 for field in &variant.fields {
176                     if !field_implements_copy(field) {
177                         return Err(CopyImplementationError::InfrigingField(field));
178                     }
179                 }
180             }
181
182             if adt.has_dtor(tcx) {
183                 return Err(CopyImplementationError::HasDestructor);
184             }
185
186             Ok(())
187         })
188     }
189 }
190
191 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
192     /// Creates a hash of the type `Ty` which will be the same no matter what crate
193     /// context it's calculated within. This is used by the `type_id` intrinsic.
194     pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
195         let mut hasher = StableHasher::new();
196         let mut hcx = StableHashingContext::new(self);
197
198         hcx.while_hashing_spans(false, |hcx| {
199             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
200                 ty.hash_stable(hcx, &mut hasher);
201             });
202         });
203         hasher.finish()
204     }
205 }
206
207 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
208     pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
209         match ty.sty {
210             ty::TyAdt(def, substs) => {
211                 for field in def.all_fields() {
212                     let field_ty = field.ty(self, substs);
213                     if let TyError = field_ty.sty {
214                         return true;
215                     }
216                 }
217             }
218             _ => (),
219         }
220         false
221     }
222
223     /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
224     /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
225     pub fn positional_element_ty(self,
226                                  ty: Ty<'tcx>,
227                                  i: usize,
228                                  variant: Option<DefId>) -> Option<Ty<'tcx>> {
229         match (&ty.sty, variant) {
230             (&TyAdt(adt, substs), Some(vid)) => {
231                 adt.variant_with_id(vid).fields.get(i).map(|f| f.ty(self, substs))
232             }
233             (&TyAdt(adt, substs), None) => {
234                 // Don't use `struct_variant`, this may be a univariant enum.
235                 adt.variants[0].fields.get(i).map(|f| f.ty(self, substs))
236             }
237             (&TyTuple(ref v, _), None) => v.get(i).cloned(),
238             _ => None,
239         }
240     }
241
242     /// Returns the type of element at field `n` in struct or struct-like type `t`.
243     /// For an enum `t`, `variant` must be some def id.
244     pub fn named_element_ty(self,
245                             ty: Ty<'tcx>,
246                             n: Name,
247                             variant: Option<DefId>) -> Option<Ty<'tcx>> {
248         match (&ty.sty, variant) {
249             (&TyAdt(adt, substs), Some(vid)) => {
250                 adt.variant_with_id(vid).find_field_named(n).map(|f| f.ty(self, substs))
251             }
252             (&TyAdt(adt, substs), None) => {
253                 adt.struct_variant().find_field_named(n).map(|f| f.ty(self, substs))
254             }
255             _ => return None
256         }
257     }
258
259     /// Returns the deeply last field of nested structures, or the same type,
260     /// if not a structure at all. Corresponds to the only possible unsized
261     /// field, and its type can be used to determine unsizing strategy.
262     pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
263         while let TyAdt(def, substs) = ty.sty {
264             if !def.is_struct() {
265                 break;
266             }
267             match def.struct_variant().fields.last() {
268                 Some(f) => ty = f.ty(self, substs),
269                 None => break,
270             }
271         }
272         ty
273     }
274
275     /// Same as applying struct_tail on `source` and `target`, but only
276     /// keeps going as long as the two types are instances of the same
277     /// structure definitions.
278     /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
279     /// whereas struct_tail produces `T`, and `Trait`, respectively.
280     pub fn struct_lockstep_tails(self,
281                                  source: Ty<'tcx>,
282                                  target: Ty<'tcx>)
283                                  -> (Ty<'tcx>, Ty<'tcx>) {
284         let (mut a, mut b) = (source, target);
285         while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
286             if a_def != b_def || !a_def.is_struct() {
287                 break;
288             }
289             match a_def.struct_variant().fields.last() {
290                 Some(f) => {
291                     a = f.ty(self, a_substs);
292                     b = f.ty(self, b_substs);
293                 }
294                 _ => break,
295             }
296         }
297         (a, b)
298     }
299
300     /// Given a set of predicates that apply to an object type, returns
301     /// the region bounds that the (erased) `Self` type must
302     /// outlive. Precisely *because* the `Self` type is erased, the
303     /// parameter `erased_self_ty` must be supplied to indicate what type
304     /// has been used to represent `Self` in the predicates
305     /// themselves. This should really be a unique type; `FreshTy(0)` is a
306     /// popular choice.
307     ///
308     /// NB: in some cases, particularly around higher-ranked bounds,
309     /// this function returns a kind of conservative approximation.
310     /// That is, all regions returned by this function are definitely
311     /// required, but there may be other region bounds that are not
312     /// returned, as well as requirements like `for<'a> T: 'a`.
313     ///
314     /// Requires that trait definitions have been processed so that we can
315     /// elaborate predicates and walk supertraits.
316     ///
317     /// FIXME callers may only have a &[Predicate], not a Vec, so that's
318     /// what this code should accept.
319     pub fn required_region_bounds(self,
320                                   erased_self_ty: Ty<'tcx>,
321                                   predicates: Vec<ty::Predicate<'tcx>>)
322                                   -> Vec<ty::Region<'tcx>>    {
323         debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
324                erased_self_ty,
325                predicates);
326
327         assert!(!erased_self_ty.has_escaping_regions());
328
329         traits::elaborate_predicates(self, predicates)
330             .filter_map(|predicate| {
331                 match predicate {
332                     ty::Predicate::Projection(..) |
333                     ty::Predicate::Trait(..) |
334                     ty::Predicate::Equate(..) |
335                     ty::Predicate::Subtype(..) |
336                     ty::Predicate::WellFormed(..) |
337                     ty::Predicate::ObjectSafe(..) |
338                     ty::Predicate::ClosureKind(..) |
339                     ty::Predicate::RegionOutlives(..) => {
340                         None
341                     }
342                     ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
343                         // Search for a bound of the form `erased_self_ty
344                         // : 'a`, but be wary of something like `for<'a>
345                         // erased_self_ty : 'a` (we interpret a
346                         // higher-ranked bound like that as 'static,
347                         // though at present the code in `fulfill.rs`
348                         // considers such bounds to be unsatisfiable, so
349                         // it's kind of a moot point since you could never
350                         // construct such an object, but this seems
351                         // correct even if that code changes).
352                         if t == erased_self_ty && !r.has_escaping_regions() {
353                             Some(r)
354                         } else {
355                             None
356                         }
357                     }
358                 }
359             })
360             .collect()
361     }
362
363     /// Calculate the destructor of a given type.
364     pub fn calculate_dtor(
365         self,
366         adt_did: DefId,
367         validate: &mut FnMut(Self, DefId) -> Result<(), ErrorReported>
368     ) -> Option<ty::Destructor> {
369         let drop_trait = if let Some(def_id) = self.lang_items.drop_trait() {
370             def_id
371         } else {
372             return None;
373         };
374
375         self.coherent_trait((LOCAL_CRATE, drop_trait));
376
377         let mut dtor_did = None;
378         let ty = self.type_of(adt_did);
379         self.trait_def(drop_trait).for_each_relevant_impl(self, ty, |impl_did| {
380             if let Some(item) = self.associated_items(impl_did).next() {
381                 if let Ok(()) = validate(self, impl_did) {
382                     dtor_did = Some(item.def_id);
383                 }
384             }
385         });
386
387         let dtor_did = match dtor_did {
388             Some(dtor) => dtor,
389             None => return None,
390         };
391
392         Some(ty::Destructor { did: dtor_did })
393     }
394
395     /// Return the set of types that are required to be alive in
396     /// order to run the destructor of `def` (see RFCs 769 and
397     /// 1238).
398     ///
399     /// Note that this returns only the constraints for the
400     /// destructor of `def` itself. For the destructors of the
401     /// contents, you need `adt_dtorck_constraint`.
402     pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
403                                   -> Vec<ty::subst::Kind<'tcx>>
404     {
405         let dtor = match def.destructor(self) {
406             None => {
407                 debug!("destructor_constraints({:?}) - no dtor", def.did);
408                 return vec![]
409             }
410             Some(dtor) => dtor.did
411         };
412
413         // RFC 1238: if the destructor method is tagged with the
414         // attribute `unsafe_destructor_blind_to_params`, then the
415         // compiler is being instructed to *assume* that the
416         // destructor will not access borrowed data,
417         // even if such data is otherwise reachable.
418         //
419         // Such access can be in plain sight (e.g. dereferencing
420         // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
421         // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
422         if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
423             debug!("destructor_constraint({:?}) - blind", def.did);
424             return vec![];
425         }
426
427         let impl_def_id = self.associated_item(dtor).container.id();
428         let impl_generics = self.generics_of(impl_def_id);
429
430         // We have a destructor - all the parameters that are not
431         // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
432         // must be live.
433
434         // We need to return the list of parameters from the ADTs
435         // generics/substs that correspond to impure parameters on the
436         // impl's generics. This is a bit ugly, but conceptually simple:
437         //
438         // Suppose our ADT looks like the following
439         //
440         //     struct S<X, Y, Z>(X, Y, Z);
441         //
442         // and the impl is
443         //
444         //     impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
445         //
446         // We want to return the parameters (X, Y). For that, we match
447         // up the item-substs <X, Y, Z> with the substs on the impl ADT,
448         // <P1, P2, P0>, and then look up which of the impl substs refer to
449         // parameters marked as pure.
450
451         let impl_substs = match self.type_of(impl_def_id).sty {
452             ty::TyAdt(def_, substs) if def_ == def => substs,
453             _ => bug!()
454         };
455
456         let item_substs = match self.type_of(def.did).sty {
457             ty::TyAdt(def_, substs) if def_ == def => substs,
458             _ => bug!()
459         };
460
461         let result = item_substs.iter().zip(impl_substs.iter())
462             .filter(|&(_, &k)| {
463                 if let Some(&ty::RegionKind::ReEarlyBound(ref ebr)) = k.as_region() {
464                     !impl_generics.region_param(ebr).pure_wrt_drop
465                 } else if let Some(&ty::TyS {
466                     sty: ty::TypeVariants::TyParam(ref pt), ..
467                 }) = k.as_type() {
468                     !impl_generics.type_param(pt).pure_wrt_drop
469                 } else {
470                     // not a type or region param - this should be reported
471                     // as an error.
472                     false
473                 }
474             }).map(|(&item_param, _)| item_param).collect();
475         debug!("destructor_constraint({:?}) = {:?}", def.did, result);
476         result
477     }
478
479     /// Return a set of constraints that needs to be satisfied in
480     /// order for `ty` to be valid for destruction.
481     pub fn dtorck_constraint_for_ty(self,
482                                     span: Span,
483                                     for_ty: Ty<'tcx>,
484                                     depth: usize,
485                                     ty: Ty<'tcx>)
486                                     -> Result<ty::DtorckConstraint<'tcx>, ErrorReported>
487     {
488         debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})",
489                span, for_ty, depth, ty);
490
491         if depth >= self.sess.recursion_limit.get() {
492             let mut err = struct_span_err!(
493                 self.sess, span, E0320,
494                 "overflow while adding drop-check rules for {}", for_ty);
495             err.note(&format!("overflowed on {}", ty));
496             err.emit();
497             return Err(ErrorReported);
498         }
499
500         let result = match ty.sty {
501             ty::TyBool | ty::TyChar | ty::TyInt(_) | ty::TyUint(_) |
502             ty::TyFloat(_) | ty::TyStr | ty::TyNever |
503             ty::TyRawPtr(..) | ty::TyRef(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => {
504                 // these types never have a destructor
505                 Ok(ty::DtorckConstraint::empty())
506             }
507
508             ty::TyArray(ety, _) | ty::TySlice(ety) => {
509                 // single-element containers, behave like their element
510                 self.dtorck_constraint_for_ty(span, for_ty, depth+1, ety)
511             }
512
513             ty::TyTuple(tys, _) => {
514                 tys.iter().map(|ty| {
515                     self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
516                 }).collect()
517             }
518
519             ty::TyClosure(def_id, substs) => {
520                 substs.upvar_tys(def_id, self).map(|ty| {
521                     self.dtorck_constraint_for_ty(span, for_ty, depth+1, ty)
522                 }).collect()
523             }
524
525             ty::TyAdt(def, substs) => {
526                 let ty::DtorckConstraint {
527                     dtorck_types, outlives
528                 } = self.at(span).adt_dtorck_constraint(def.did);
529                 Ok(ty::DtorckConstraint {
530                     // FIXME: we can try to recursively `dtorck_constraint_on_ty`
531                     // there, but that needs some way to handle cycles.
532                     dtorck_types: dtorck_types.subst(self, substs),
533                     outlives: outlives.subst(self, substs)
534                 })
535             }
536
537             // Objects must be alive in order for their destructor
538             // to be called.
539             ty::TyDynamic(..) => Ok(ty::DtorckConstraint {
540                 outlives: vec![Kind::from(ty)],
541                 dtorck_types: vec![],
542             }),
543
544             // Types that can't be resolved. Pass them forward.
545             ty::TyProjection(..) | ty::TyAnon(..) | ty::TyParam(..) => {
546                 Ok(ty::DtorckConstraint {
547                     outlives: vec![],
548                     dtorck_types: vec![ty],
549                 })
550             }
551
552             ty::TyInfer(..) | ty::TyError => {
553                 self.sess.delay_span_bug(span, "unresolved type in dtorck");
554                 Err(ErrorReported)
555             }
556         };
557
558         debug!("dtorck_constraint_for_ty({:?}) = {:?}", ty, result);
559         result
560     }
561
562     pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
563         let mut def_id = def_id;
564         while self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr {
565             def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
566                 bug!("closure {:?} has no parent", def_id);
567             });
568         }
569         def_id
570     }
571
572     /// Given the def-id of some item that has no type parameters, make
573     /// a suitable "empty substs" for it.
574     pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx ty::Substs<'tcx> {
575         ty::Substs::for_item(self, item_def_id,
576                              |_, _| self.types.re_erased,
577                              |_, _| {
578             bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
579         })
580     }
581 }
582
583 pub struct TypeIdHasher<'a, 'gcx: 'a+'tcx, 'tcx: 'a, W> {
584     tcx: TyCtxt<'a, 'gcx, 'tcx>,
585     state: StableHasher<W>,
586 }
587
588 impl<'a, 'gcx, 'tcx, W> TypeIdHasher<'a, 'gcx, 'tcx, W>
589     where W: StableHasherResult
590 {
591     pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
592         TypeIdHasher { tcx: tcx, state: StableHasher::new() }
593     }
594
595     pub fn finish(self) -> W {
596         self.state.finish()
597     }
598
599     pub fn hash<T: Hash>(&mut self, x: T) {
600         x.hash(&mut self.state);
601     }
602
603     fn hash_discriminant_u8<T>(&mut self, x: &T) {
604         let v = unsafe {
605             intrinsics::discriminant_value(x)
606         };
607         let b = v as u8;
608         assert_eq!(v, b as u64);
609         self.hash(b)
610     }
611
612     fn def_id(&mut self, did: DefId) {
613         // Hash the DefPath corresponding to the DefId, which is independent
614         // of compiler internal state. We already have a stable hash value of
615         // all DefPaths available via tcx.def_path_hash(), so we just feed that
616         // into the hasher.
617         let hash = self.tcx.def_path_hash(did);
618         self.hash(hash);
619     }
620 }
621
622 impl<'a, 'gcx, 'tcx, W> TypeVisitor<'tcx> for TypeIdHasher<'a, 'gcx, 'tcx, W>
623     where W: StableHasherResult
624 {
625     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
626         // Distinguish between the Ty variants uniformly.
627         self.hash_discriminant_u8(&ty.sty);
628
629         match ty.sty {
630             TyInt(i) => self.hash(i),
631             TyUint(u) => self.hash(u),
632             TyFloat(f) => self.hash(f),
633             TyArray(_, n) => self.hash(n),
634             TyRawPtr(m) |
635             TyRef(_, m) => self.hash(m.mutbl),
636             TyClosure(def_id, _) |
637             TyAnon(def_id, _) |
638             TyFnDef(def_id, ..) => self.def_id(def_id),
639             TyAdt(d, _) => self.def_id(d.did),
640             TyFnPtr(f) => {
641                 self.hash(f.unsafety());
642                 self.hash(f.abi());
643                 self.hash(f.variadic());
644                 self.hash(f.inputs().skip_binder().len());
645             }
646             TyDynamic(ref data, ..) => {
647                 if let Some(p) = data.principal() {
648                     self.def_id(p.def_id());
649                 }
650                 for d in data.auto_traits() {
651                     self.def_id(d);
652                 }
653             }
654             TyTuple(tys, defaulted) => {
655                 self.hash(tys.len());
656                 self.hash(defaulted);
657             }
658             TyParam(p) => {
659                 self.hash(p.idx);
660                 self.hash(p.name.as_str());
661             }
662             TyProjection(ref data) => {
663                 self.def_id(data.trait_ref.def_id);
664                 self.hash(data.item_name.as_str());
665             }
666             TyNever |
667             TyBool |
668             TyChar |
669             TyStr |
670             TySlice(_) => {}
671
672             TyError |
673             TyInfer(_) => bug!("TypeIdHasher: unexpected type {}", ty)
674         }
675
676         ty.super_visit_with(self)
677     }
678
679     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
680         self.hash_discriminant_u8(r);
681         match *r {
682             ty::ReErased |
683             ty::ReStatic |
684             ty::ReEmpty => {
685                 // No variant fields to hash for these ...
686             }
687             ty::ReLateBound(db, ty::BrAnon(i)) => {
688                 self.hash(db.depth);
689                 self.hash(i);
690             }
691             ty::ReEarlyBound(ty::EarlyBoundRegion { index, name }) => {
692                 self.hash(index);
693                 self.hash(name.as_str());
694             }
695             ty::ReLateBound(..) |
696             ty::ReFree(..) |
697             ty::ReScope(..) |
698             ty::ReVar(..) |
699             ty::ReSkolemized(..) => {
700                 bug!("TypeIdHasher: unexpected region {:?}", r)
701             }
702         }
703         false
704     }
705
706     fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, x: &ty::Binder<T>) -> bool {
707         // Anonymize late-bound regions so that, for example:
708         // `for<'a, b> fn(&'a &'b T)` and `for<'a, b> fn(&'b &'a T)`
709         // result in the same TypeId (the two types are equivalent).
710         self.tcx.anonymize_late_bound_regions(x).super_visit_with(self)
711     }
712 }
713
714 impl<'a, 'tcx> ty::TyS<'tcx> {
715     fn impls_bound(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
716                    param_env: &ParameterEnvironment<'tcx>,
717                    def_id: DefId,
718                    cache: &RefCell<FxHashMap<Ty<'tcx>, bool>>,
719                    span: Span) -> bool
720     {
721         if self.has_param_types() || self.has_self_ty() {
722             if let Some(result) = cache.borrow().get(self) {
723                 return *result;
724             }
725         }
726         let result =
727             tcx.infer_ctxt(param_env.clone(), Reveal::UserFacing)
728             .enter(|infcx| {
729                 traits::type_known_to_meet_bound(&infcx, self, def_id, span)
730             });
731         if self.has_param_types() || self.has_self_ty() {
732             cache.borrow_mut().insert(self, result);
733         }
734         return result;
735     }
736
737     // FIXME (@jroesch): I made this public to use it, not sure if should be private
738     pub fn moves_by_default(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
739                             param_env: &ParameterEnvironment<'tcx>,
740                             span: Span) -> bool {
741         if self.flags.get().intersects(TypeFlags::MOVENESS_CACHED) {
742             return self.flags.get().intersects(TypeFlags::MOVES_BY_DEFAULT);
743         }
744
745         assert!(!self.needs_infer());
746
747         // Fast-path for primitive types
748         let result = match self.sty {
749             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) | TyNever |
750             TyRawPtr(..) | TyFnDef(..) | TyFnPtr(_) | TyRef(_, TypeAndMut {
751                 mutbl: hir::MutImmutable, ..
752             }) => Some(false),
753
754             TyStr | TyRef(_, TypeAndMut {
755                 mutbl: hir::MutMutable, ..
756             }) => Some(true),
757
758             TyArray(..) | TySlice(..) | TyDynamic(..) | TyTuple(..) |
759             TyClosure(..) | TyAdt(..) | TyAnon(..) |
760             TyProjection(..) | TyParam(..) | TyInfer(..) | TyError => None
761         }.unwrap_or_else(|| {
762             !self.impls_bound(tcx, param_env,
763                               tcx.require_lang_item(lang_items::CopyTraitLangItem),
764                               &param_env.is_copy_cache, span) });
765
766         if !self.has_param_types() && !self.has_self_ty() {
767             self.flags.set(self.flags.get() | if result {
768                 TypeFlags::MOVENESS_CACHED | TypeFlags::MOVES_BY_DEFAULT
769             } else {
770                 TypeFlags::MOVENESS_CACHED
771             });
772         }
773
774         result
775     }
776
777     #[inline]
778     pub fn is_sized(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
779                     param_env: &ParameterEnvironment<'tcx>,
780                     span: Span) -> bool
781     {
782         if self.flags.get().intersects(TypeFlags::SIZEDNESS_CACHED) {
783             return self.flags.get().intersects(TypeFlags::IS_SIZED);
784         }
785
786         self.is_sized_uncached(tcx, param_env, span)
787     }
788
789     fn is_sized_uncached(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
790                          param_env: &ParameterEnvironment<'tcx>,
791                          span: Span) -> bool {
792         assert!(!self.needs_infer());
793
794         // Fast-path for primitive types
795         let result = match self.sty {
796             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
797             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
798             TyArray(..) | TyTuple(..) | TyClosure(..) | TyNever => Some(true),
799
800             TyStr | TyDynamic(..) | TySlice(_) => Some(false),
801
802             TyAdt(..) | TyProjection(..) | TyParam(..) |
803             TyInfer(..) | TyAnon(..) | TyError => None
804         }.unwrap_or_else(|| {
805             self.impls_bound(tcx, param_env, tcx.require_lang_item(lang_items::SizedTraitLangItem),
806                               &param_env.is_sized_cache, span) });
807
808         if !self.has_param_types() && !self.has_self_ty() {
809             self.flags.set(self.flags.get() | if result {
810                 TypeFlags::SIZEDNESS_CACHED | TypeFlags::IS_SIZED
811             } else {
812                 TypeFlags::SIZEDNESS_CACHED
813             });
814         }
815
816         result
817     }
818
819     /// Returns `true` if and only if there are no `UnsafeCell`s
820     /// nested within the type (ignoring `PhantomData` or pointers).
821     #[inline]
822     pub fn is_freeze(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
823                      param_env: &ParameterEnvironment<'tcx>,
824                      span: Span) -> bool
825     {
826         if self.flags.get().intersects(TypeFlags::FREEZENESS_CACHED) {
827             return self.flags.get().intersects(TypeFlags::IS_FREEZE);
828         }
829
830         self.is_freeze_uncached(tcx, param_env, span)
831     }
832
833     fn is_freeze_uncached(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
834                           param_env: &ParameterEnvironment<'tcx>,
835                           span: Span) -> bool {
836         assert!(!self.needs_infer());
837
838         // Fast-path for primitive types
839         let result = match self.sty {
840             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
841             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
842             TyStr | TyNever => Some(true),
843
844             TyArray(..) | TySlice(_) |
845             TyTuple(..) | TyClosure(..) | TyAdt(..) |
846             TyDynamic(..) | TyProjection(..) | TyParam(..) |
847             TyInfer(..) | TyAnon(..) | TyError => None
848         }.unwrap_or_else(|| {
849             self.impls_bound(tcx, param_env, tcx.require_lang_item(lang_items::FreezeTraitLangItem),
850                               &param_env.is_freeze_cache, span) });
851
852         if !self.has_param_types() && !self.has_self_ty() {
853             self.flags.set(self.flags.get() | if result {
854                 TypeFlags::FREEZENESS_CACHED | TypeFlags::IS_FREEZE
855             } else {
856                 TypeFlags::FREEZENESS_CACHED
857             });
858         }
859
860         result
861     }
862
863     /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
864     /// non-copy and *might* have a destructor attached; if it returns
865     /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
866     ///
867     /// (Note that this implies that if `ty` has a destructor attached,
868     /// then `needs_drop` will definitely return `true` for `ty`.)
869     #[inline]
870     pub fn needs_drop(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
871                     param_env: &ty::ParameterEnvironment<'tcx>) -> bool {
872         if self.flags.get().intersects(TypeFlags::NEEDS_DROP_CACHED) {
873             return self.flags.get().intersects(TypeFlags::NEEDS_DROP);
874         }
875
876         self.needs_drop_uncached(tcx, param_env, &mut FxHashSet())
877     }
878
879     fn needs_drop_inner(&'tcx self,
880                         tcx: TyCtxt<'a, 'tcx, 'tcx>,
881                         param_env: &ty::ParameterEnvironment<'tcx>,
882                         stack: &mut FxHashSet<Ty<'tcx>>)
883                         -> bool {
884         if self.flags.get().intersects(TypeFlags::NEEDS_DROP_CACHED) {
885             return self.flags.get().intersects(TypeFlags::NEEDS_DROP);
886         }
887
888         // This should be reported as an error by `check_representable`.
889         //
890         // Consider the type as not needing drop in the meanwhile to avoid
891         // further errors.
892         if let Some(_) = stack.replace(self) {
893             return false;
894         }
895
896         let needs_drop = self.needs_drop_uncached(tcx, param_env, stack);
897
898         // "Pop" the cycle detection "stack".
899         stack.remove(self);
900
901         needs_drop
902     }
903
904     fn needs_drop_uncached(&'tcx self,
905                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
906                            param_env: &ty::ParameterEnvironment<'tcx>,
907                            stack: &mut FxHashSet<Ty<'tcx>>)
908                            -> bool {
909         assert!(!self.needs_infer());
910
911         let result = match self.sty {
912             // Fast-path for primitive types
913             ty::TyInfer(ty::FreshIntTy(_)) | ty::TyInfer(ty::FreshFloatTy(_)) |
914             ty::TyBool | ty::TyInt(_) | ty::TyUint(_) | ty::TyFloat(_) | ty::TyNever |
915             ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyChar |
916             ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyStr => false,
917
918             // Issue #22536: We first query type_moves_by_default.  It sees a
919             // normalized version of the type, and therefore will definitely
920             // know whether the type implements Copy (and thus needs no
921             // cleanup/drop/zeroing) ...
922             _ if !self.moves_by_default(tcx, param_env, DUMMY_SP) => false,
923
924             // ... (issue #22536 continued) but as an optimization, still use
925             // prior logic of asking for the structural "may drop".
926
927             // FIXME(#22815): Note that this is a conservative heuristic;
928             // it may report that the type "may drop" when actual type does
929             // not actually have a destructor associated with it. But since
930             // the type absolutely did not have the `Copy` bound attached
931             // (see above), it is sound to treat it as having a destructor.
932
933             // User destructors are the only way to have concrete drop types.
934             ty::TyAdt(def, _) if def.has_dtor(tcx) => true,
935
936             // Can refer to a type which may drop.
937             // FIXME(eddyb) check this against a ParameterEnvironment.
938             ty::TyDynamic(..) | ty::TyProjection(..) | ty::TyParam(_) |
939             ty::TyAnon(..) | ty::TyInfer(_) | ty::TyError => true,
940
941             // Structural recursion.
942             ty::TyArray(ty, _) | ty::TySlice(ty) => {
943                 ty.needs_drop_inner(tcx, param_env, stack)
944             }
945
946             ty::TyClosure(def_id, ref substs) => {
947                 substs.upvar_tys(def_id, tcx)
948                     .any(|ty| ty.needs_drop_inner(tcx, param_env, stack))
949             }
950
951             ty::TyTuple(ref tys, _) => {
952                 tys.iter().any(|ty| ty.needs_drop_inner(tcx, param_env, stack))
953             }
954
955             // unions don't have destructors regardless of the child types
956             ty::TyAdt(def, _) if def.is_union() => false,
957
958             ty::TyAdt(def, substs) => {
959                 def.variants.iter().any(|v| {
960                     v.fields.iter().any(|f| {
961                         f.ty(tcx, substs).needs_drop_inner(tcx, param_env, stack)
962                     })
963                 })
964             }
965         };
966
967         if !self.has_param_types() && !self.has_self_ty() {
968             self.flags.set(self.flags.get() | if result {
969                 TypeFlags::NEEDS_DROP_CACHED | TypeFlags::NEEDS_DROP
970             } else {
971                 TypeFlags::NEEDS_DROP_CACHED
972             });
973         }
974
975         result
976     }
977
978     #[inline]
979     pub fn layout<'lcx>(&'tcx self, infcx: &InferCtxt<'a, 'tcx, 'lcx>)
980                         -> Result<&'tcx Layout, LayoutError<'tcx>> {
981         let tcx = infcx.tcx.global_tcx();
982         let can_cache = !self.has_param_types() && !self.has_self_ty();
983         if can_cache {
984             if let Some(&cached) = tcx.layout_cache.borrow().get(&self) {
985                 return Ok(cached);
986             }
987         }
988
989         let rec_limit = tcx.sess.recursion_limit.get();
990         let depth = tcx.layout_depth.get();
991         if depth > rec_limit {
992             tcx.sess.fatal(
993                 &format!("overflow representing the type `{}`", self));
994         }
995
996         tcx.layout_depth.set(depth+1);
997         let layout = Layout::compute_uncached(self, infcx);
998         tcx.layout_depth.set(depth);
999         let layout = layout?;
1000         if can_cache {
1001             tcx.layout_cache.borrow_mut().insert(self, layout);
1002         }
1003         Ok(layout)
1004     }
1005
1006
1007     /// Check whether a type is representable. This means it cannot contain unboxed
1008     /// structural recursion. This check is needed for structs and enums.
1009     pub fn is_representable(&'tcx self,
1010                             tcx: TyCtxt<'a, 'tcx, 'tcx>,
1011                             sp: Span)
1012                             -> Representability {
1013
1014         // Iterate until something non-representable is found
1015         fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
1016             iter.fold(Representability::Representable, |r1, r2| {
1017                 match (r1, r2) {
1018                     (Representability::SelfRecursive(v1),
1019                      Representability::SelfRecursive(v2)) => {
1020                         Representability::SelfRecursive(v1.iter().map(|s| *s).chain(v2).collect())
1021                     }
1022                     (r1, r2) => cmp::max(r1, r2)
1023                 }
1024             })
1025         }
1026
1027         fn are_inner_types_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
1028                                                seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
1029                                                -> Representability {
1030             match ty.sty {
1031                 TyTuple(ref ts, _) => {
1032                     // Find non representable
1033                     fold_repr(ts.iter().map(|ty| {
1034                         is_type_structurally_recursive(tcx, sp, seen, ty)
1035                     }))
1036                 }
1037                 // Fixed-length vectors.
1038                 // FIXME(#11924) Behavior undecided for zero-length vectors.
1039                 TyArray(ty, _) => {
1040                     is_type_structurally_recursive(tcx, sp, seen, ty)
1041                 }
1042                 TyAdt(def, substs) => {
1043                     // Find non representable fields with their spans
1044                     fold_repr(def.all_fields().map(|field| {
1045                         let ty = field.ty(tcx, substs);
1046                         let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
1047                         match is_type_structurally_recursive(tcx, span, seen, ty) {
1048                             Representability::SelfRecursive(_) => {
1049                                 Representability::SelfRecursive(vec![span])
1050                             }
1051                             x => x,
1052                         }
1053                     }))
1054                 }
1055                 TyClosure(..) => {
1056                     // this check is run on type definitions, so we don't expect
1057                     // to see closure types
1058                     bug!("requires check invoked on inapplicable type: {:?}", ty)
1059                 }
1060                 _ => Representability::Representable,
1061             }
1062         }
1063
1064         fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
1065             match ty.sty {
1066                 TyAdt(ty_def, _) => {
1067                      ty_def == def
1068                 }
1069                 _ => false
1070             }
1071         }
1072
1073         fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1074             match (&a.sty, &b.sty) {
1075                 (&TyAdt(did_a, substs_a), &TyAdt(did_b, substs_b)) => {
1076                     if did_a != did_b {
1077                         return false;
1078                     }
1079
1080                     substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
1081                 }
1082                 _ => a == b,
1083             }
1084         }
1085
1086         // Does the type `ty` directly (without indirection through a pointer)
1087         // contain any types on stack `seen`?
1088         fn is_type_structurally_recursive<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1089                                                     sp: Span,
1090                                                     seen: &mut Vec<Ty<'tcx>>,
1091                                                     ty: Ty<'tcx>) -> Representability {
1092             debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
1093
1094             match ty.sty {
1095                 TyAdt(def, _) => {
1096                     {
1097                         // Iterate through stack of previously seen types.
1098                         let mut iter = seen.iter();
1099
1100                         // The first item in `seen` is the type we are actually curious about.
1101                         // We want to return SelfRecursive if this type contains itself.
1102                         // It is important that we DON'T take generic parameters into account
1103                         // for this check, so that Bar<T> in this example counts as SelfRecursive:
1104                         //
1105                         // struct Foo;
1106                         // struct Bar<T> { x: Bar<Foo> }
1107
1108                         if let Some(&seen_type) = iter.next() {
1109                             if same_struct_or_enum(seen_type, def) {
1110                                 debug!("SelfRecursive: {:?} contains {:?}",
1111                                        seen_type,
1112                                        ty);
1113                                 return Representability::SelfRecursive(vec![sp]);
1114                             }
1115                         }
1116
1117                         // We also need to know whether the first item contains other types
1118                         // that are structurally recursive. If we don't catch this case, we
1119                         // will recurse infinitely for some inputs.
1120                         //
1121                         // It is important that we DO take generic parameters into account
1122                         // here, so that code like this is considered SelfRecursive, not
1123                         // ContainsRecursive:
1124                         //
1125                         // struct Foo { Option<Option<Foo>> }
1126
1127                         for &seen_type in iter {
1128                             if same_type(ty, seen_type) {
1129                                 debug!("ContainsRecursive: {:?} contains {:?}",
1130                                        seen_type,
1131                                        ty);
1132                                 return Representability::ContainsRecursive;
1133                             }
1134                         }
1135                     }
1136
1137                     // For structs and enums, track all previously seen types by pushing them
1138                     // onto the 'seen' stack.
1139                     seen.push(ty);
1140                     let out = are_inner_types_recursive(tcx, sp, seen, ty);
1141                     seen.pop();
1142                     out
1143                 }
1144                 _ => {
1145                     // No need to push in other cases.
1146                     are_inner_types_recursive(tcx, sp, seen, ty)
1147                 }
1148             }
1149         }
1150
1151         debug!("is_type_representable: {:?}", self);
1152
1153         // To avoid a stack overflow when checking an enum variant or struct that
1154         // contains a different, structurally recursive type, maintain a stack
1155         // of seen types and check recursion for each of them (issues #3008, #3779).
1156         let mut seen: Vec<Ty> = Vec::new();
1157         let r = is_type_structurally_recursive(tcx, sp, &mut seen, self);
1158         debug!("is_type_representable: {:?} is {:?}", self, r);
1159         r
1160     }
1161 }