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