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