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