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