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