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