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