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