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