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