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