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