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