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