]> git.proxmox.com Git - rustc.git/blame - src/librustc/ty/util.rs
New upstream version 1.31.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;
ff7c6d11 14use hir::def_id::DefId;
b7449926
XL
15use hir::map::DefPathData;
16use hir::{self, Node};
ea8adc8c 17use ich::NodeIdHashingMode;
94b46f34
XL
18use traits::{self, ObligationCause};
19use ty::{self, Ty, TyCtxt, GenericParamDefKind, TypeFoldable};
20use ty::subst::{Substs, UnpackedKind};
21use ty::query::TyCtxtAt;
b7449926 22use ty::TyKind::*;
83c7162d 23use ty::layout::{Integer, IntegerExt};
8bb4bdeb 24use util::common::ErrorReported;
476ff2be 25use middle::lang_items;
54a0048b 26
94b46f34 27use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
041b39d2 28use rustc_data_structures::fx::FxHashMap;
0531ce1d 29use std::{cmp, fmt};
83c7162d 30use syntax::ast;
a7813a04 31use syntax::attr::{self, SignedInt, UnsignedInt};
8bb4bdeb 32use syntax_pos::{Span, DUMMY_SP};
e9174d1e 33
0531ce1d
XL
34#[derive(Copy, Clone, Debug)]
35pub struct Discr<'tcx> {
36 /// bit representation of the discriminant, so `-128i8` is `0xFF_u128`
37 pub val: u128,
38 pub ty: Ty<'tcx>
39}
8bb4bdeb 40
0531ce1d 41impl<'tcx> fmt::Display for Discr<'tcx> {
0bf4aa26 42 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
0531ce1d 43 match self.ty.sty {
b7449926 44 ty::Int(ity) => {
0531ce1d
XL
45 let bits = ty::tls::with(|tcx| {
46 Integer::from_attr(tcx, SignedInt(ity)).size().bits()
47 });
48 let x = self.val as i128;
49 // sign extend the raw representation to be an i128
50 let x = (x << (128 - bits)) >> (128 - bits);
51 write!(fmt, "{}", x)
52 },
53 _ => write!(fmt, "{}", self.val),
54 }
55 }
cc61c64b 56}
8bb4bdeb 57
0531ce1d
XL
58impl<'tcx> Discr<'tcx> {
59 /// Adds 1 to the value and wraps around if the maximum for the type is reached
60 pub fn wrap_incr<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
61 self.checked_add(tcx, 1).0
62 }
63 pub fn checked_add<'a, 'gcx>(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, n: u128) -> (Self, bool) {
64 let (int, signed) = match self.ty.sty {
b7449926
XL
65 Int(ity) => (Integer::from_attr(tcx, SignedInt(ity)), true),
66 Uint(uty) => (Integer::from_attr(tcx, UnsignedInt(uty)), false),
0531ce1d
XL
67 _ => bug!("non integer discriminant"),
68 };
8bb4bdeb 69
0531ce1d 70 let bit_size = int.size().bits();
94b46f34 71 let shift = 128 - bit_size;
0531ce1d
XL
72 if signed {
73 let sext = |u| {
74 let i = u as i128;
94b46f34 75 (i << shift) >> shift
0531ce1d
XL
76 };
77 let min = sext(1_u128 << (bit_size - 1));
94b46f34 78 let max = i128::max_value() >> shift;
0531ce1d
XL
79 let val = sext(self.val);
80 assert!(n < (i128::max_value() as u128));
81 let n = n as i128;
82 let oflo = val > max - n;
83 let val = if oflo {
84 min + (n - (max - val) - 1)
85 } else {
86 val + n
87 };
88 // zero the upper bits
89 let val = val as u128;
94b46f34 90 let val = (val << shift) >> shift;
0531ce1d
XL
91 (Self {
92 val: val as u128,
93 ty: self.ty,
94 }, oflo)
95 } else {
94b46f34 96 let max = u128::max_value() >> shift;
0531ce1d
XL
97 let val = self.val;
98 let oflo = val > max - n;
99 let val = if oflo {
100 n - (max - val) - 1
101 } else {
102 val + n
103 };
104 (Self {
105 val: val,
106 ty: self.ty,
107 }, oflo)
8bb4bdeb
XL
108 }
109 }
e9174d1e
SL
110}
111
0531ce1d
XL
112pub trait IntTypeExt {
113 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>;
114 fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Discr<'tcx>>)
115 -> Option<Discr<'tcx>>;
116 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx>;
117}
118
e9174d1e 119impl IntTypeExt for attr::IntType {
8bb4bdeb 120 fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
e9174d1e 121 match *self {
0bf4aa26
XL
122 SignedInt(ast::IntTy::I8) => tcx.types.i8,
123 SignedInt(ast::IntTy::I16) => tcx.types.i16,
124 SignedInt(ast::IntTy::I32) => tcx.types.i32,
125 SignedInt(ast::IntTy::I64) => tcx.types.i64,
32a655c1 126 SignedInt(ast::IntTy::I128) => tcx.types.i128,
0bf4aa26 127 SignedInt(ast::IntTy::Isize) => tcx.types.isize,
a7813a04
XL
128 UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
129 UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
130 UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
131 UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
0bf4aa26 132 UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
2c00a5a8 133 UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
e9174d1e
SL
134 }
135 }
136
0531ce1d
XL
137 fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Discr<'tcx> {
138 Discr {
139 val: 0,
140 ty: self.to_ty(tcx)
e9174d1e
SL
141 }
142 }
143
0531ce1d
XL
144 fn disr_incr<'a, 'tcx>(
145 &self,
146 tcx: TyCtxt<'a, 'tcx, 'tcx>,
147 val: Option<Discr<'tcx>>,
148 ) -> Option<Discr<'tcx>> {
a7813a04 149 if let Some(val) = val {
0531ce1d
XL
150 assert_eq!(self.to_ty(tcx), val.ty);
151 let (new, oflo) = val.checked_add(tcx, 1);
152 if oflo {
153 None
154 } else {
155 Some(new)
156 }
a7813a04
XL
157 } else {
158 Some(self.initial_discriminant(tcx))
159 }
e9174d1e
SL
160 }
161}
162
163
94b46f34 164#[derive(Clone)]
32a655c1 165pub enum CopyImplementationError<'tcx> {
94b46f34 166 InfrigingFields(Vec<&'tcx ty::FieldDef>),
e9174d1e 167 NotAnAdt,
cc61c64b 168 HasDestructor,
e9174d1e
SL
169}
170
171/// Describes whether a type is representable. For types that are not
172/// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
173/// distinguish between types that are recursive with themselves and types that
174/// contain a different recursive type. These cases can therefore be treated
175/// differently when reporting errors.
176///
177/// The ordering of the cases is significant. They are sorted so that cmp::max
178/// will keep the "more erroneous" of two values.
7cac9316 179#[derive(Clone, PartialOrd, Ord, Eq, PartialEq, Debug)]
e9174d1e
SL
180pub enum Representability {
181 Representable,
182 ContainsRecursive,
7cac9316 183 SelfRecursive(Vec<Span>),
e9174d1e
SL
184}
185
7cac9316 186impl<'tcx> ty::ParamEnv<'tcx> {
7cac9316
XL
187 pub fn can_type_implement_copy<'a>(self,
188 tcx: TyCtxt<'a, 'tcx, 'tcx>,
94b46f34 189 self_type: Ty<'tcx>)
7cac9316 190 -> Result<(), CopyImplementationError<'tcx>> {
e9174d1e 191 // FIXME: (@jroesch) float this code up
041b39d2 192 tcx.infer_ctxt().enter(|infcx| {
32a655c1 193 let (adt, substs) = match self_type.sty {
83c7162d
XL
194 // These types used to have a builtin impl.
195 // Now libcore provides that impl.
b7449926
XL
196 ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
197 ty::Char | ty::RawPtr(..) | ty::Never |
198 ty::Ref(_, _, hir::MutImmutable) => return Ok(()),
83c7162d 199
b7449926 200 ty::Adt(adt, substs) => (adt, substs),
83c7162d 201
cc61c64b 202 _ => return Err(CopyImplementationError::NotAnAdt),
a7813a04 203 };
e9174d1e 204
94b46f34 205 let mut infringing = Vec::new();
32a655c1
SL
206 for variant in &adt.variants {
207 for field in &variant.fields {
94b46f34
XL
208 let ty = field.ty(tcx, substs);
209 if ty.references_error() {
210 continue;
32a655c1 211 }
0bf4aa26 212 let span = tcx.def_span(field.did);
94b46f34
XL
213 let cause = ObligationCause { span, ..ObligationCause::dummy() };
214 let ctx = traits::FulfillmentContext::new();
215 match traits::fully_normalize(&infcx, ctx, cause, self, &ty) {
216 Ok(ty) => if infcx.type_moves_by_default(self, ty, span) {
217 infringing.push(field);
218 }
219 Err(errors) => {
220 infcx.report_fulfillment_errors(&errors, None, false);
221 }
222 };
32a655c1
SL
223 }
224 }
94b46f34
XL
225 if !infringing.is_empty() {
226 return Err(CopyImplementationError::InfrigingFields(infringing));
227 }
8bb4bdeb 228 if adt.has_dtor(tcx) {
a7813a04
XL
229 return Err(CopyImplementationError::HasDestructor);
230 }
e9174d1e 231
a7813a04
XL
232 Ok(())
233 })
e9174d1e
SL
234 }
235}
236
cc61c64b
XL
237impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
238 /// Creates a hash of the type `Ty` which will be the same no matter what crate
239 /// context it's calculated within. This is used by the `type_id` intrinsic.
240 pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 {
241 let mut hasher = StableHasher::new();
ea8adc8c 242 let mut hcx = self.create_stable_hashing_context();
cc61c64b 243
3b2f2976
XL
244 // We want the type_id be independent of the types free regions, so we
245 // erase them. The erase_regions() call will also anonymize bound
246 // regions, which is desirable too.
247 let ty = self.erase_regions(&ty);
248
cc61c64b
XL
249 hcx.while_hashing_spans(false, |hcx| {
250 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
251 ty.hash_stable(hcx, &mut hasher);
252 });
253 });
254 hasher.finish()
255 }
256}
257
a7813a04 258impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
5bcae85e 259 pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
0bf4aa26
XL
260 if let ty::Adt(def, substs) = ty.sty {
261 for field in def.all_fields() {
262 let field_ty = field.ty(self, substs);
263 if let Error = field_ty.sty {
264 return true;
5bcae85e
SL
265 }
266 }
5bcae85e
SL
267 }
268 false
269 }
270
e9174d1e
SL
271 /// Returns the deeply last field of nested structures, or the same type,
272 /// if not a structure at all. Corresponds to the only possible unsized
273 /// field, and its type can be used to determine unsizing strategy.
a7813a04 274 pub fn struct_tail(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
7cac9316
XL
275 loop {
276 match ty.sty {
b7449926 277 ty::Adt(def, substs) => {
7cac9316
XL
278 if !def.is_struct() {
279 break;
280 }
2c00a5a8 281 match def.non_enum_variant().fields.last() {
7cac9316
XL
282 Some(f) => ty = f.ty(self, substs),
283 None => break,
284 }
285 }
286
b7449926 287 ty::Tuple(tys) => {
7cac9316
XL
288 if let Some((&last_ty, _)) = tys.split_last() {
289 ty = last_ty;
290 } else {
291 break;
292 }
293 }
294
295 _ => {
296 break;
297 }
e9174d1e
SL
298 }
299 }
300 ty
301 }
302
303 /// Same as applying struct_tail on `source` and `target`, but only
304 /// keeps going as long as the two types are instances of the same
305 /// structure definitions.
306 /// For `(Foo<Foo<T>>, Foo<Trait>)`, the result will be `(Foo<T>, Trait)`,
307 /// whereas struct_tail produces `T`, and `Trait`, respectively.
a7813a04 308 pub fn struct_lockstep_tails(self,
e9174d1e
SL
309 source: Ty<'tcx>,
310 target: Ty<'tcx>)
311 -> (Ty<'tcx>, Ty<'tcx>) {
312 let (mut a, mut b) = (source, target);
041b39d2
XL
313 loop {
314 match (&a.sty, &b.sty) {
b7449926 315 (&Adt(a_def, a_substs), &Adt(b_def, b_substs))
041b39d2 316 if a_def == b_def && a_def.is_struct() => {
2c00a5a8 317 if let Some(f) = a_def.non_enum_variant().fields.last() {
041b39d2
XL
318 a = f.ty(self, a_substs);
319 b = f.ty(self, b_substs);
320 } else {
321 break;
322 }
323 },
b7449926 324 (&Tuple(a_tys), &Tuple(b_tys))
041b39d2
XL
325 if a_tys.len() == b_tys.len() => {
326 if let Some(a_last) = a_tys.last() {
327 a = a_last;
328 b = b_tys.last().unwrap();
329 } else {
330 break;
331 }
332 },
cc61c64b 333 _ => break,
e9174d1e
SL
334 }
335 }
336 (a, b)
337 }
338
e9174d1e
SL
339 /// Given a set of predicates that apply to an object type, returns
340 /// the region bounds that the (erased) `Self` type must
341 /// outlive. Precisely *because* the `Self` type is erased, the
342 /// parameter `erased_self_ty` must be supplied to indicate what type
343 /// has been used to represent `Self` in the predicates
344 /// themselves. This should really be a unique type; `FreshTy(0)` is a
345 /// popular choice.
346 ///
347 /// NB: in some cases, particularly around higher-ranked bounds,
348 /// this function returns a kind of conservative approximation.
349 /// That is, all regions returned by this function are definitely
350 /// required, but there may be other region bounds that are not
351 /// returned, as well as requirements like `for<'a> T: 'a`.
352 ///
353 /// Requires that trait definitions have been processed so that we can
354 /// elaborate predicates and walk supertraits.
7cac9316
XL
355 ///
356 /// FIXME callers may only have a &[Predicate], not a Vec, so that's
357 /// what this code should accept.
a7813a04 358 pub fn required_region_bounds(self,
e9174d1e
SL
359 erased_self_ty: Ty<'tcx>,
360 predicates: Vec<ty::Predicate<'tcx>>)
7cac9316 361 -> Vec<ty::Region<'tcx>> {
e9174d1e
SL
362 debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})",
363 erased_self_ty,
364 predicates);
365
366 assert!(!erased_self_ty.has_escaping_regions());
367
368 traits::elaborate_predicates(self, predicates)
369 .filter_map(|predicate| {
370 match predicate {
371 ty::Predicate::Projection(..) |
372 ty::Predicate::Trait(..) |
cc61c64b 373 ty::Predicate::Subtype(..) |
e9174d1e
SL
374 ty::Predicate::WellFormed(..) |
375 ty::Predicate::ObjectSafe(..) |
a7813a04 376 ty::Predicate::ClosureKind(..) |
ea8adc8c
XL
377 ty::Predicate::RegionOutlives(..) |
378 ty::Predicate::ConstEvaluatable(..) => {
e9174d1e
SL
379 None
380 }
83c7162d 381 ty::Predicate::TypeOutlives(predicate) => {
e9174d1e
SL
382 // Search for a bound of the form `erased_self_ty
383 // : 'a`, but be wary of something like `for<'a>
384 // erased_self_ty : 'a` (we interpret a
385 // higher-ranked bound like that as 'static,
386 // though at present the code in `fulfill.rs`
387 // considers such bounds to be unsatisfiable, so
388 // it's kind of a moot point since you could never
389 // construct such an object, but this seems
390 // correct even if that code changes).
83c7162d
XL
391 let ty::OutlivesPredicate(ref t, ref r) = predicate.skip_binder();
392 if t == &erased_self_ty && !r.has_escaping_regions() {
393 Some(*r)
e9174d1e
SL
394 } else {
395 None
396 }
397 }
398 }
399 })
400 .collect()
401 }
402
8bb4bdeb
XL
403 /// Calculate the destructor of a given type.
404 pub fn calculate_dtor(
405 self,
406 adt_did: DefId,
0531ce1d 407 validate: &mut dyn FnMut(Self, DefId) -> Result<(), ErrorReported>
8bb4bdeb 408 ) -> Option<ty::Destructor> {
ea8adc8c 409 let drop_trait = if let Some(def_id) = self.lang_items().drop_trait() {
8bb4bdeb
XL
410 def_id
411 } else {
412 return None;
413 };
414
94b46f34 415 ty::query::queries::coherent_trait::ensure(self, drop_trait);
8bb4bdeb
XL
416
417 let mut dtor_did = None;
7cac9316 418 let ty = self.type_of(adt_did);
041b39d2 419 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
8bb4bdeb 420 if let Some(item) = self.associated_items(impl_did).next() {
0bf4aa26 421 if validate(self, impl_did).is_ok() {
8bb4bdeb
XL
422 dtor_did = Some(item.def_id);
423 }
424 }
425 });
426
ff7c6d11 427 Some(ty::Destructor { did: dtor_did? })
cc61c64b
XL
428 }
429
430 /// Return the set of types that are required to be alive in
431 /// order to run the destructor of `def` (see RFCs 769 and
432 /// 1238).
433 ///
434 /// Note that this returns only the constraints for the
435 /// destructor of `def` itself. For the destructors of the
436 /// contents, you need `adt_dtorck_constraint`.
437 pub fn destructor_constraints(self, def: &'tcx ty::AdtDef)
438 -> Vec<ty::subst::Kind<'tcx>>
439 {
440 let dtor = match def.destructor(self) {
441 None => {
442 debug!("destructor_constraints({:?}) - no dtor", def.did);
443 return vec![]
444 }
445 Some(dtor) => dtor.did
e9174d1e 446 };
b039eaaf
SL
447
448 // RFC 1238: if the destructor method is tagged with the
449 // attribute `unsafe_destructor_blind_to_params`, then the
450 // compiler is being instructed to *assume* that the
451 // destructor will not access borrowed data,
452 // even if such data is otherwise reachable.
e9174d1e 453 //
b039eaaf
SL
454 // Such access can be in plain sight (e.g. dereferencing
455 // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden
456 // (e.g. calling `foo.0.clone()` of `Foo<T:Clone>`).
cc61c64b
XL
457 if self.has_attr(dtor, "unsafe_destructor_blind_to_params") {
458 debug!("destructor_constraint({:?}) - blind", def.did);
459 return vec![];
460 }
461
462 let impl_def_id = self.associated_item(dtor).container.id();
7cac9316 463 let impl_generics = self.generics_of(impl_def_id);
cc61c64b
XL
464
465 // We have a destructor - all the parameters that are not
466 // pure_wrt_drop (i.e, don't have a #[may_dangle] attribute)
467 // must be live.
468
469 // We need to return the list of parameters from the ADTs
470 // generics/substs that correspond to impure parameters on the
471 // impl's generics. This is a bit ugly, but conceptually simple:
472 //
473 // Suppose our ADT looks like the following
474 //
475 // struct S<X, Y, Z>(X, Y, Z);
476 //
477 // and the impl is
478 //
479 // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0>
480 //
481 // We want to return the parameters (X, Y). For that, we match
482 // up the item-substs <X, Y, Z> with the substs on the impl ADT,
483 // <P1, P2, P0>, and then look up which of the impl substs refer to
484 // parameters marked as pure.
485
7cac9316 486 let impl_substs = match self.type_of(impl_def_id).sty {
b7449926 487 ty::Adt(def_, substs) if def_ == def => substs,
cc61c64b
XL
488 _ => bug!()
489 };
490
7cac9316 491 let item_substs = match self.type_of(def.did).sty {
b7449926 492 ty::Adt(def_, substs) if def_ == def => substs,
cc61c64b
XL
493 _ => bug!()
494 };
495
496 let result = item_substs.iter().zip(impl_substs.iter())
497 .filter(|&(_, &k)| {
0531ce1d
XL
498 match k.unpack() {
499 UnpackedKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => {
500 !impl_generics.region_param(ebr, self).pure_wrt_drop
501 }
502 UnpackedKind::Type(&ty::TyS {
b7449926 503 sty: ty::Param(ref pt), ..
0531ce1d
XL
504 }) => {
505 !impl_generics.type_param(pt, self).pure_wrt_drop
506 }
507 UnpackedKind::Lifetime(_) | UnpackedKind::Type(_) => {
508 // not a type or region param - this should be reported
509 // as an error.
510 false
511 }
cc61c64b 512 }
0bf4aa26
XL
513 })
514 .map(|(&item_param, _)| item_param)
515 .collect();
cc61c64b
XL
516 debug!("destructor_constraint({:?}) = {:?}", def.did, result);
517 result
b039eaaf 518 }
9e0c209e 519
8faf50e0
XL
520 /// True if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
521 /// that closures have a def-id, but the closure *expression* also
522 /// has a `HirId` that is located within the context where the
523 /// closure appears (and, sadly, a corresponding `NodeId`, since
524 /// those are not yet phased out). The parent of the closure's
525 /// def-id will also be the context where it appears.
abe05a73
XL
526 pub fn is_closure(self, def_id: DefId) -> bool {
527 self.def_key(def_id).disambiguated_data.data == DefPathData::ClosureExpr
528 }
529
8faf50e0
XL
530 /// True if `def_id` refers to a trait (e.g., `trait Foo { ... }`).
531 pub fn is_trait(self, def_id: DefId) -> bool {
532 if let DefPathData::Trait(_) = self.def_key(def_id).disambiguated_data.data {
533 true
534 } else {
535 false
536 }
537 }
538
539 /// True if this def-id refers to the implicit constructor for
540 /// a tuple struct like `struct Foo(u32)`.
541 pub fn is_struct_constructor(self, def_id: DefId) -> bool {
542 self.def_key(def_id).disambiguated_data.data == DefPathData::StructCtor
543 }
544
ff7c6d11
XL
545 /// Given the `DefId` of a fn or closure, returns the `DefId` of
546 /// the innermost fn item that the closure is contained within.
547 /// This is a significant def-id because, when we do
548 /// type-checking, we type-check this fn item and all of its
549 /// (transitive) closures together. Therefore, when we fetch the
550 /// `typeck_tables_of` the closure, for example, we really wind up
551 /// fetching the `typeck_tables_of` the enclosing fn item.
cc61c64b 552 pub fn closure_base_def_id(self, def_id: DefId) -> DefId {
476ff2be 553 let mut def_id = def_id;
abe05a73 554 while self.is_closure(def_id) {
476ff2be
SL
555 def_id = self.parent_def_id(def_id).unwrap_or_else(|| {
556 bug!("closure {:?} has no parent", def_id);
557 });
558 }
559 def_id
9e0c209e 560 }
cc61c64b 561
ff7c6d11
XL
562 /// Given the def-id and substs a closure, creates the type of
563 /// `self` argument that the closure expects. For example, for a
564 /// `Fn` closure, this would return a reference type `&T` where
565 /// `T=closure_ty`.
566 ///
567 /// Returns `None` if this closure's kind has not yet been inferred.
568 /// This should only be possible during type checking.
569 ///
570 /// Note that the return value is a late-bound region and hence
571 /// wrapped in a binder.
572 pub fn closure_env_ty(self,
573 closure_def_id: DefId,
574 closure_substs: ty::ClosureSubsts<'tcx>)
575 -> Option<ty::Binder<Ty<'tcx>>>
576 {
577 let closure_ty = self.mk_closure(closure_def_id, closure_substs);
94b46f34 578 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
ff7c6d11
XL
579 let closure_kind_ty = closure_substs.closure_kind_ty(closure_def_id, self);
580 let closure_kind = closure_kind_ty.to_opt_closure_kind()?;
581 let env_ty = match closure_kind {
582 ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty),
583 ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty),
584 ty::ClosureKind::FnOnce => closure_ty,
585 };
83c7162d 586 Some(ty::Binder::bind(env_ty))
ff7c6d11
XL
587 }
588
cc61c64b
XL
589 /// Given the def-id of some item that has no type parameters, make
590 /// a suitable "empty substs" for it.
94b46f34
XL
591 pub fn empty_substs_for_def_id(self, item_def_id: DefId) -> &'tcx Substs<'tcx> {
592 Substs::for_item(self, item_def_id, |param, _| {
593 match param.kind {
594 GenericParamDefKind::Lifetime => self.types.re_erased.into(),
595 GenericParamDefKind::Type {..} => {
596 bug!("empty_substs_for_def_id: {:?} has type parameters", item_def_id)
597 }
598 }
cc61c64b
XL
599 })
600 }
7cac9316 601
0531ce1d
XL
602 /// Return whether the node pointed to by def_id is a static item, and its mutability
603 pub fn is_static(&self, def_id: DefId) -> Option<hir::Mutability> {
abe05a73
XL
604 if let Some(node) = self.hir.get_if_local(def_id) {
605 match node {
b7449926 606 Node::Item(&hir::Item {
8faf50e0 607 node: hir::ItemKind::Static(_, mutbl, _), ..
0531ce1d 608 }) => Some(mutbl),
b7449926 609 Node::ForeignItem(&hir::ForeignItem {
8faf50e0 610 node: hir::ForeignItemKind::Static(_, is_mutbl), ..
0531ce1d
XL
611 }) =>
612 Some(if is_mutbl {
613 hir::Mutability::MutMutable
614 } else {
615 hir::Mutability::MutImmutable
616 }),
617 _ => None
abe05a73
XL
618 }
619 } else {
620 match self.describe_def(def_id) {
0531ce1d
XL
621 Some(Def::Static(_, is_mutbl)) =>
622 Some(if is_mutbl {
623 hir::Mutability::MutMutable
624 } else {
625 hir::Mutability::MutImmutable
626 }),
627 _ => None
abe05a73
XL
628 }
629 }
630 }
9e0c209e
SL
631}
632
a7813a04 633impl<'a, 'tcx> ty::TyS<'tcx> {
7cac9316
XL
634 pub fn moves_by_default(&'tcx self,
635 tcx: TyCtxt<'a, 'tcx, 'tcx>,
636 param_env: ty::ParamEnv<'tcx>,
637 span: Span)
638 -> bool {
639 !tcx.at(span).is_copy_raw(param_env.and(self))
e9174d1e
SL
640 }
641
7cac9316 642 pub fn is_sized(&'tcx self,
0531ce1d
XL
643 tcx_at: TyCtxtAt<'a, 'tcx, 'tcx>,
644 param_env: ty::ParamEnv<'tcx>)-> bool
e9174d1e 645 {
0531ce1d 646 tcx_at.is_sized_raw(param_env.and(self))
e9174d1e
SL
647 }
648
7cac9316
XL
649 pub fn is_freeze(&'tcx self,
650 tcx: TyCtxt<'a, 'tcx, 'tcx>,
651 param_env: ty::ParamEnv<'tcx>,
652 span: Span)-> bool
cc61c64b 653 {
7cac9316 654 tcx.at(span).is_freeze_raw(param_env.and(self))
cc61c64b
XL
655 }
656
657 /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely
658 /// non-copy and *might* have a destructor attached; if it returns
659 /// `false`, then `ty` definitely has no destructor (i.e. no drop glue).
660 ///
661 /// (Note that this implies that if `ty` has a destructor attached,
662 /// then `needs_drop` will definitely return `true` for `ty`.)
663 #[inline]
7cac9316
XL
664 pub fn needs_drop(&'tcx self,
665 tcx: TyCtxt<'a, 'tcx, 'tcx>,
666 param_env: ty::ParamEnv<'tcx>)
667 -> bool {
668 tcx.needs_drop_raw(param_env.and(self))
cc61c64b
XL
669 }
670
e9174d1e
SL
671 /// Check whether a type is representable. This means it cannot contain unboxed
672 /// structural recursion. This check is needed for structs and enums.
7cac9316
XL
673 pub fn is_representable(&'tcx self,
674 tcx: TyCtxt<'a, 'tcx, 'tcx>,
675 sp: Span)
0bf4aa26
XL
676 -> Representability
677 {
e9174d1e 678 // Iterate until something non-representable is found
7cac9316
XL
679 fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
680 iter.fold(Representability::Representable, |r1, r2| {
681 match (r1, r2) {
682 (Representability::SelfRecursive(v1),
683 Representability::SelfRecursive(v2)) => {
0bf4aa26 684 Representability::SelfRecursive(v1.into_iter().chain(v2).collect())
7cac9316
XL
685 }
686 (r1, r2) => cmp::max(r1, r2)
687 }
688 })
e9174d1e
SL
689 }
690
041b39d2
XL
691 fn are_inner_types_recursive<'a, 'tcx>(
692 tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span,
693 seen: &mut Vec<Ty<'tcx>>,
694 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
695 ty: Ty<'tcx>)
696 -> Representability
697 {
e9174d1e 698 match ty.sty {
b7449926 699 Tuple(ref ts) => {
7cac9316
XL
700 // Find non representable
701 fold_repr(ts.iter().map(|ty| {
041b39d2 702 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
7cac9316 703 }))
e9174d1e
SL
704 }
705 // Fixed-length vectors.
706 // FIXME(#11924) Behavior undecided for zero-length vectors.
b7449926 707 Array(ty, _) => {
041b39d2 708 is_type_structurally_recursive(tcx, sp, seen, representable_cache, ty)
e9174d1e 709 }
b7449926 710 Adt(def, substs) => {
7cac9316
XL
711 // Find non representable fields with their spans
712 fold_repr(def.all_fields().map(|field| {
713 let ty = field.ty(tcx, substs);
714 let span = tcx.hir.span_if_local(field.did).unwrap_or(sp);
041b39d2
XL
715 match is_type_structurally_recursive(tcx, span, seen,
716 representable_cache, ty)
717 {
7cac9316
XL
718 Representability::SelfRecursive(_) => {
719 Representability::SelfRecursive(vec![span])
720 }
721 x => x,
722 }
723 }))
e9174d1e 724 }
b7449926 725 Closure(..) => {
e9174d1e
SL
726 // this check is run on type definitions, so we don't expect
727 // to see closure types
54a0048b 728 bug!("requires check invoked on inapplicable type: {:?}", ty)
e9174d1e
SL
729 }
730 _ => Representability::Representable,
731 }
732 }
733
476ff2be 734 fn same_struct_or_enum<'tcx>(ty: Ty<'tcx>, def: &'tcx ty::AdtDef) -> bool {
e9174d1e 735 match ty.sty {
b7449926 736 Adt(ty_def, _) => {
e9174d1e
SL
737 ty_def == def
738 }
739 _ => false
740 }
741 }
742
743 fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
744 match (&a.sty, &b.sty) {
b7449926 745 (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {
e9174d1e
SL
746 if did_a != did_b {
747 return false;
748 }
749
9e0c209e 750 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type(a, b))
e9174d1e 751 }
cc61c64b 752 _ => a == b,
e9174d1e
SL
753 }
754 }
755
756 // Does the type `ty` directly (without indirection through a pointer)
757 // contain any types on stack `seen`?
041b39d2
XL
758 fn is_type_structurally_recursive<'a, 'tcx>(
759 tcx: TyCtxt<'a, 'tcx, 'tcx>,
760 sp: Span,
761 seen: &mut Vec<Ty<'tcx>>,
762 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
763 ty: Ty<'tcx>) -> Representability
764 {
7cac9316 765 debug!("is_type_structurally_recursive: {:?} {:?}", ty, sp);
041b39d2
XL
766 if let Some(representability) = representable_cache.get(ty) {
767 debug!("is_type_structurally_recursive: {:?} {:?} - (cached) {:?}",
768 ty, sp, representability);
769 return representability.clone();
770 }
771
772 let representability = is_type_structurally_recursive_inner(
773 tcx, sp, seen, representable_cache, ty);
774
775 representable_cache.insert(ty, representability.clone());
776 representability
777 }
e9174d1e 778
041b39d2
XL
779 fn is_type_structurally_recursive_inner<'a, 'tcx>(
780 tcx: TyCtxt<'a, 'tcx, 'tcx>,
781 sp: Span,
782 seen: &mut Vec<Ty<'tcx>>,
783 representable_cache: &mut FxHashMap<Ty<'tcx>, Representability>,
784 ty: Ty<'tcx>) -> Representability
785 {
e9174d1e 786 match ty.sty {
b7449926 787 Adt(def, _) => {
e9174d1e
SL
788 {
789 // Iterate through stack of previously seen types.
790 let mut iter = seen.iter();
791
792 // The first item in `seen` is the type we are actually curious about.
793 // We want to return SelfRecursive if this type contains itself.
794 // It is important that we DON'T take generic parameters into account
795 // for this check, so that Bar<T> in this example counts as SelfRecursive:
796 //
797 // struct Foo;
798 // struct Bar<T> { x: Bar<Foo> }
799
3157f602
XL
800 if let Some(&seen_type) = iter.next() {
801 if same_struct_or_enum(seen_type, def) {
802 debug!("SelfRecursive: {:?} contains {:?}",
803 seen_type,
804 ty);
7cac9316 805 return Representability::SelfRecursive(vec![sp]);
e9174d1e 806 }
e9174d1e
SL
807 }
808
809 // We also need to know whether the first item contains other types
810 // that are structurally recursive. If we don't catch this case, we
811 // will recurse infinitely for some inputs.
812 //
813 // It is important that we DO take generic parameters into account
814 // here, so that code like this is considered SelfRecursive, not
815 // ContainsRecursive:
816 //
817 // struct Foo { Option<Option<Foo>> }
818
819 for &seen_type in iter {
820 if same_type(ty, seen_type) {
821 debug!("ContainsRecursive: {:?} contains {:?}",
822 seen_type,
823 ty);
824 return Representability::ContainsRecursive;
825 }
826 }
827 }
828
829 // For structs and enums, track all previously seen types by pushing them
830 // onto the 'seen' stack.
831 seen.push(ty);
041b39d2 832 let out = are_inner_types_recursive(tcx, sp, seen, representable_cache, ty);
e9174d1e
SL
833 seen.pop();
834 out
835 }
836 _ => {
837 // No need to push in other cases.
041b39d2 838 are_inner_types_recursive(tcx, sp, seen, representable_cache, ty)
e9174d1e
SL
839 }
840 }
841 }
842
843 debug!("is_type_representable: {:?}", self);
844
845 // To avoid a stack overflow when checking an enum variant or struct that
846 // contains a different, structurally recursive type, maintain a stack
847 // of seen types and check recursion for each of them (issues #3008, #3779).
0bf4aa26
XL
848 let mut seen: Vec<Ty<'_>> = Vec::new();
849 let mut representable_cache = FxHashMap::default();
041b39d2
XL
850 let r = is_type_structurally_recursive(
851 tcx, sp, &mut seen, &mut representable_cache, self);
e9174d1e
SL
852 debug!("is_type_representable: {:?} is {:?}", self, r);
853 r
854 }
855}
7cac9316
XL
856
857fn is_copy_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
858 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
859 -> bool
860{
861 let (param_env, ty) = query.into_parts();
862 let trait_def_id = tcx.require_lang_item(lang_items::CopyTraitLangItem);
041b39d2 863 tcx.infer_ctxt()
7cac9316
XL
864 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
865 param_env,
866 ty,
867 trait_def_id,
868 DUMMY_SP))
869}
870
871fn is_sized_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
872 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
873 -> bool
874{
875 let (param_env, ty) = query.into_parts();
876 let trait_def_id = tcx.require_lang_item(lang_items::SizedTraitLangItem);
041b39d2 877 tcx.infer_ctxt()
7cac9316
XL
878 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
879 param_env,
880 ty,
881 trait_def_id,
882 DUMMY_SP))
883}
884
885fn is_freeze_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
886 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
887 -> bool
888{
889 let (param_env, ty) = query.into_parts();
890 let trait_def_id = tcx.require_lang_item(lang_items::FreezeTraitLangItem);
041b39d2 891 tcx.infer_ctxt()
7cac9316
XL
892 .enter(|infcx| traits::type_known_to_meet_bound(&infcx,
893 param_env,
894 ty,
895 trait_def_id,
896 DUMMY_SP))
897}
898
899fn needs_drop_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
900 query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
901 -> bool
902{
903 let (param_env, ty) = query.into_parts();
904
905 let needs_drop = |ty: Ty<'tcx>| -> bool {
0bf4aa26
XL
906 tcx.try_needs_drop_raw(DUMMY_SP, param_env.and(ty)).unwrap_or_else(|mut bug| {
907 // Cycles should be reported as an error by `check_representable`.
908 //
909 // Consider the type as not needing drop in the meanwhile to
910 // avoid further errors.
911 //
912 // In case we forgot to emit a bug elsewhere, delay our
913 // diagnostic to get emitted as a compiler bug.
914 bug.delay_as_bug();
915 false
916 })
7cac9316
XL
917 };
918
919 assert!(!ty.needs_infer());
920
921 match ty.sty {
922 // Fast-path for primitive types
b7449926
XL
923 ty::Infer(ty::FreshIntTy(_)) | ty::Infer(ty::FreshFloatTy(_)) |
924 ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never |
925 ty::FnDef(..) | ty::FnPtr(_) | ty::Char | ty::GeneratorWitness(..) |
926 ty::RawPtr(_) | ty::Ref(..) | ty::Str => false,
7cac9316 927
abe05a73 928 // Foreign types can never have destructors
b7449926 929 ty::Foreign(..) => false,
abe05a73 930
8faf50e0 931 // `ManuallyDrop` doesn't have a destructor regardless of field types.
b7449926 932 ty::Adt(def, _) if Some(def.did) == tcx.lang_items().manually_drop() => false,
8faf50e0 933
7cac9316
XL
934 // Issue #22536: We first query type_moves_by_default. It sees a
935 // normalized version of the type, and therefore will definitely
936 // know whether the type implements Copy (and thus needs no
937 // cleanup/drop/zeroing) ...
938 _ if !ty.moves_by_default(tcx, param_env, DUMMY_SP) => false,
939
940 // ... (issue #22536 continued) but as an optimization, still use
941 // prior logic of asking for the structural "may drop".
942
943 // FIXME(#22815): Note that this is a conservative heuristic;
944 // it may report that the type "may drop" when actual type does
945 // not actually have a destructor associated with it. But since
946 // the type absolutely did not have the `Copy` bound attached
947 // (see above), it is sound to treat it as having a destructor.
948
949 // User destructors are the only way to have concrete drop types.
b7449926 950 ty::Adt(def, _) if def.has_dtor(tcx) => true,
7cac9316
XL
951
952 // Can refer to a type which may drop.
953 // FIXME(eddyb) check this against a ParamEnv.
b7449926
XL
954 ty::Dynamic(..) | ty::Projection(..) | ty::Param(_) |
955 ty::Opaque(..) | ty::Infer(_) | ty::Error => true,
7cac9316 956
0bf4aa26
XL
957 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
958
7cac9316 959 // Structural recursion.
b7449926 960 ty::Array(ty, _) | ty::Slice(ty) => needs_drop(ty),
7cac9316 961
b7449926 962 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, tcx).any(needs_drop),
7cac9316 963
ea8adc8c
XL
964 // Pessimistically assume that all generators will require destructors
965 // as we don't know if a destructor is a noop or not until after the MIR
966 // state transformation pass
b7449926 967 ty::Generator(..) => true,
ea8adc8c 968
b7449926 969 ty::Tuple(ref tys) => tys.iter().cloned().any(needs_drop),
7cac9316 970
8faf50e0
XL
971 // unions don't have destructors because of the child types,
972 // only if they manually implement `Drop` (handled above).
b7449926 973 ty::Adt(def, _) if def.is_union() => false,
7cac9316 974
b7449926 975 ty::Adt(def, substs) =>
7cac9316
XL
976 def.variants.iter().any(
977 |variant| variant.fields.iter().any(
978 |field| needs_drop(field.ty(tcx, substs)))),
979 }
980}
981
abe05a73
XL
982pub enum ExplicitSelf<'tcx> {
983 ByValue,
984 ByReference(ty::Region<'tcx>, hir::Mutability),
ff7c6d11 985 ByRawPointer(hir::Mutability),
abe05a73
XL
986 ByBox,
987 Other
988}
989
990impl<'tcx> ExplicitSelf<'tcx> {
991 /// Categorizes an explicit self declaration like `self: SomeType`
992 /// into either `self`, `&self`, `&mut self`, `Box<self>`, or
993 /// `Other`.
994 /// This is mainly used to require the arbitrary_self_types feature
995 /// in the case of `Other`, to improve error messages in the common cases,
996 /// and to make `Other` non-object-safe.
997 ///
998 /// Examples:
999 ///
1000 /// ```
1001 /// impl<'a> Foo for &'a T {
1002 /// // Legal declarations:
1003 /// fn method1(self: &&'a T); // ExplicitSelf::ByReference
1004 /// fn method2(self: &'a T); // ExplicitSelf::ByValue
1005 /// fn method3(self: Box<&'a T>); // ExplicitSelf::ByBox
1006 /// fn method4(self: Rc<&'a T>); // ExplicitSelf::Other
1007 ///
1008 /// // Invalid cases will be caught by `check_method_receiver`:
1009 /// fn method_err1(self: &'a mut T); // ExplicitSelf::Other
1010 /// fn method_err2(self: &'static T) // ExplicitSelf::ByValue
1011 /// fn method_err3(self: &&T) // ExplicitSelf::ByReference
1012 /// }
1013 /// ```
1014 ///
1015 pub fn determine<P>(
1016 self_arg_ty: Ty<'tcx>,
1017 is_self_ty: P
1018 ) -> ExplicitSelf<'tcx>
1019 where
1020 P: Fn(Ty<'tcx>) -> bool
1021 {
1022 use self::ExplicitSelf::*;
1023
1024 match self_arg_ty.sty {
1025 _ if is_self_ty(self_arg_ty) => ByValue,
b7449926 1026 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => {
abe05a73
XL
1027 ByReference(region, mutbl)
1028 }
b7449926 1029 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) if is_self_ty(ty) => {
ff7c6d11
XL
1030 ByRawPointer(mutbl)
1031 }
b7449926 1032 ty::Adt(def, _) if def.is_box() && is_self_ty(self_arg_ty.boxed_ty()) => {
ff7c6d11
XL
1033 ByBox
1034 }
abe05a73
XL
1035 _ => Other
1036 }
1037 }
1038}
1039
0bf4aa26 1040pub fn provide(providers: &mut ty::query::Providers<'_>) {
94b46f34 1041 *providers = ty::query::Providers {
7cac9316
XL
1042 is_copy_raw,
1043 is_sized_raw,
1044 is_freeze_raw,
1045 needs_drop_raw,
7cac9316
XL
1046 ..*providers
1047 };
1048}