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