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