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