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