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