]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/subst.rs
Rollup merge of #106644 - alexcrichton:update-wasi-toolchain, r=cuviper
[rust.git] / compiler / rustc_middle / src / ty / subst.rs
1 // Type substitutions.
2
3 use crate::ty::codec::{TyDecoder, TyEncoder};
4 use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
5 use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts};
6 use crate::ty::visit::{TypeVisitable, TypeVisitor};
7 use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt};
8
9 use rustc_data_structures::intern::Interned;
10 use rustc_hir::def_id::DefId;
11 use rustc_macros::HashStable;
12 use rustc_serialize::{self, Decodable, Encodable};
13 use rustc_type_ir::WithCachedTypeInfo;
14 use smallvec::SmallVec;
15
16 use core::intrinsics;
17 use std::cmp::Ordering;
18 use std::fmt;
19 use std::marker::PhantomData;
20 use std::mem;
21 use std::num::NonZeroUsize;
22 use std::ops::{ControlFlow, Deref};
23 use std::slice;
24
25 /// An entity in the Rust type system, which can be one of
26 /// several kinds (types, lifetimes, and consts).
27 /// To reduce memory usage, a `GenericArg` is an interned pointer,
28 /// with the lowest 2 bits being reserved for a tag to
29 /// indicate the type (`Ty`, `Region`, or `Const`) it points to.
30 ///
31 /// Note: the `PartialEq`, `Eq` and `Hash` derives are only valid because `Ty`,
32 /// `Region` and `Const` are all interned.
33 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
34 pub struct GenericArg<'tcx> {
35     ptr: NonZeroUsize,
36     marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>)>,
37 }
38
39 const TAG_MASK: usize = 0b11;
40 const TYPE_TAG: usize = 0b00;
41 const REGION_TAG: usize = 0b01;
42 const CONST_TAG: usize = 0b10;
43
44 #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord)]
45 pub enum GenericArgKind<'tcx> {
46     Lifetime(ty::Region<'tcx>),
47     Type(Ty<'tcx>),
48     Const(ty::Const<'tcx>),
49 }
50
51 /// This function goes from `&'a [Ty<'tcx>]` to `&'a [GenericArg<'tcx>]`
52 ///
53 /// This is sound as, for types, `GenericArg` is just
54 /// `NonZeroUsize::new_unchecked(ty as *const _ as usize)` as
55 /// long as we use `0` for the `TYPE_TAG`.
56 pub fn ty_slice_as_generic_args<'a, 'tcx>(ts: &'a [Ty<'tcx>]) -> &'a [GenericArg<'tcx>] {
57     assert_eq!(TYPE_TAG, 0);
58     // SAFETY: the whole slice is valid and immutable.
59     // `Ty` and `GenericArg` is explained above.
60     unsafe { slice::from_raw_parts(ts.as_ptr().cast(), ts.len()) }
61 }
62
63 impl<'tcx> List<Ty<'tcx>> {
64     /// Allows to freely switch between `List<Ty<'tcx>>` and `List<GenericArg<'tcx>>`.
65     ///
66     /// As lists are interned, `List<Ty<'tcx>>` and `List<GenericArg<'tcx>>` have
67     /// be interned together, see `intern_type_list` for more details.
68     #[inline]
69     pub fn as_substs(&'tcx self) -> SubstsRef<'tcx> {
70         assert_eq!(TYPE_TAG, 0);
71         // SAFETY: `List<T>` is `#[repr(C)]`. `Ty` and `GenericArg` is explained above.
72         unsafe { &*(self as *const List<Ty<'tcx>> as *const List<GenericArg<'tcx>>) }
73     }
74 }
75
76 impl<'tcx> GenericArgKind<'tcx> {
77     #[inline]
78     fn pack(self) -> GenericArg<'tcx> {
79         let (tag, ptr) = match self {
80             GenericArgKind::Lifetime(lt) => {
81                 // Ensure we can use the tag bits.
82                 assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0);
83                 (REGION_TAG, lt.0.0 as *const ty::RegionKind<'tcx> as usize)
84             }
85             GenericArgKind::Type(ty) => {
86                 // Ensure we can use the tag bits.
87                 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
88                 (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo<ty::TyKind<'tcx>> as usize)
89             }
90             GenericArgKind::Const(ct) => {
91                 // Ensure we can use the tag bits.
92                 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
93                 (CONST_TAG, ct.0.0 as *const ty::ConstData<'tcx> as usize)
94             }
95         };
96
97         GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
98     }
99 }
100
101 impl<'tcx> fmt::Debug for GenericArg<'tcx> {
102     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103         match self.unpack() {
104             GenericArgKind::Lifetime(lt) => lt.fmt(f),
105             GenericArgKind::Type(ty) => ty.fmt(f),
106             GenericArgKind::Const(ct) => ct.fmt(f),
107         }
108     }
109 }
110
111 impl<'tcx> Ord for GenericArg<'tcx> {
112     fn cmp(&self, other: &GenericArg<'tcx>) -> Ordering {
113         self.unpack().cmp(&other.unpack())
114     }
115 }
116
117 impl<'tcx> PartialOrd for GenericArg<'tcx> {
118     fn partial_cmp(&self, other: &GenericArg<'tcx>) -> Option<Ordering> {
119         Some(self.cmp(&other))
120     }
121 }
122
123 impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> {
124     #[inline]
125     fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> {
126         GenericArgKind::Lifetime(r).pack()
127     }
128 }
129
130 impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> {
131     #[inline]
132     fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> {
133         GenericArgKind::Type(ty).pack()
134     }
135 }
136
137 impl<'tcx> From<ty::Const<'tcx>> for GenericArg<'tcx> {
138     #[inline]
139     fn from(c: ty::Const<'tcx>) -> GenericArg<'tcx> {
140         GenericArgKind::Const(c).pack()
141     }
142 }
143
144 impl<'tcx> From<ty::Term<'tcx>> for GenericArg<'tcx> {
145     fn from(value: ty::Term<'tcx>) -> Self {
146         match value.unpack() {
147             ty::TermKind::Ty(t) => t.into(),
148             ty::TermKind::Const(c) => c.into(),
149         }
150     }
151 }
152
153 impl<'tcx> GenericArg<'tcx> {
154     #[inline]
155     pub fn unpack(self) -> GenericArgKind<'tcx> {
156         let ptr = self.ptr.get();
157         // SAFETY: use of `Interned::new_unchecked` here is ok because these
158         // pointers were originally created from `Interned` types in `pack()`,
159         // and this is just going in the other direction.
160         unsafe {
161             match ptr & TAG_MASK {
162                 REGION_TAG => GenericArgKind::Lifetime(ty::Region(Interned::new_unchecked(
163                     &*((ptr & !TAG_MASK) as *const ty::RegionKind<'tcx>),
164                 ))),
165                 TYPE_TAG => GenericArgKind::Type(Ty(Interned::new_unchecked(
166                     &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo<ty::TyKind<'tcx>>),
167                 ))),
168                 CONST_TAG => GenericArgKind::Const(ty::Const(Interned::new_unchecked(
169                     &*((ptr & !TAG_MASK) as *const ty::ConstData<'tcx>),
170                 ))),
171                 _ => intrinsics::unreachable(),
172             }
173         }
174     }
175
176     /// Unpack the `GenericArg` as a region when it is known certainly to be a region.
177     pub fn expect_region(self) -> ty::Region<'tcx> {
178         match self.unpack() {
179             GenericArgKind::Lifetime(lt) => lt,
180             _ => bug!("expected a region, but found another kind"),
181         }
182     }
183
184     /// Unpack the `GenericArg` as a type when it is known certainly to be a type.
185     /// This is true in cases where `Substs` is used in places where the kinds are known
186     /// to be limited (e.g. in tuples, where the only parameters are type parameters).
187     pub fn expect_ty(self) -> Ty<'tcx> {
188         match self.unpack() {
189             GenericArgKind::Type(ty) => ty,
190             _ => bug!("expected a type, but found another kind"),
191         }
192     }
193
194     /// Unpack the `GenericArg` as a const when it is known certainly to be a const.
195     pub fn expect_const(self) -> ty::Const<'tcx> {
196         match self.unpack() {
197             GenericArgKind::Const(c) => c,
198             _ => bug!("expected a const, but found another kind"),
199         }
200     }
201
202     pub fn is_non_region_infer(self) -> bool {
203         match self.unpack() {
204             GenericArgKind::Lifetime(_) => false,
205             GenericArgKind::Type(ty) => ty.is_ty_or_numeric_infer(),
206             GenericArgKind::Const(ct) => ct.is_ct_infer(),
207         }
208     }
209 }
210
211 impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> {
212     type Lifted = GenericArg<'tcx>;
213
214     fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
215         match self.unpack() {
216             GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()),
217             GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()),
218             GenericArgKind::Const(ct) => tcx.lift(ct).map(|ct| ct.into()),
219         }
220     }
221 }
222
223 impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> {
224     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
225         match self.unpack() {
226             GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into),
227             GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into),
228             GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
229         }
230     }
231 }
232
233 impl<'tcx> TypeVisitable<'tcx> for GenericArg<'tcx> {
234     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
235         match self.unpack() {
236             GenericArgKind::Lifetime(lt) => lt.visit_with(visitor),
237             GenericArgKind::Type(ty) => ty.visit_with(visitor),
238             GenericArgKind::Const(ct) => ct.visit_with(visitor),
239         }
240     }
241 }
242
243 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for GenericArg<'tcx> {
244     fn encode(&self, e: &mut E) {
245         self.unpack().encode(e)
246     }
247 }
248
249 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> {
250     fn decode(d: &mut D) -> GenericArg<'tcx> {
251         GenericArgKind::decode(d).pack()
252     }
253 }
254
255 /// List of generic arguments that are gonna be used to substitute generic parameters.
256 pub type InternalSubsts<'tcx> = List<GenericArg<'tcx>>;
257
258 pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>;
259
260 impl<'tcx> InternalSubsts<'tcx> {
261     /// Checks whether all elements of this list are types, if so, transmute.
262     pub fn try_as_type_list(&'tcx self) -> Option<&'tcx List<Ty<'tcx>>> {
263         if self.iter().all(|arg| matches!(arg.unpack(), GenericArgKind::Type(_))) {
264             assert_eq!(TYPE_TAG, 0);
265             // SAFETY: All elements are types, see `List<Ty<'tcx>>::as_substs`.
266             Some(unsafe { &*(self as *const List<GenericArg<'tcx>> as *const List<Ty<'tcx>>) })
267         } else {
268             None
269         }
270     }
271
272     /// Interpret these substitutions as the substitutions of a closure type.
273     /// Closure substitutions have a particular structure controlled by the
274     /// compiler that encodes information like the signature and closure kind;
275     /// see `ty::ClosureSubsts` struct for more comments.
276     pub fn as_closure(&'tcx self) -> ClosureSubsts<'tcx> {
277         ClosureSubsts { substs: self }
278     }
279
280     /// Interpret these substitutions as the substitutions of a generator type.
281     /// Generator substitutions have a particular structure controlled by the
282     /// compiler that encodes information like the signature and generator kind;
283     /// see `ty::GeneratorSubsts` struct for more comments.
284     pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> {
285         GeneratorSubsts { substs: self }
286     }
287
288     /// Interpret these substitutions as the substitutions of an inline const.
289     /// Inline const substitutions have a particular structure controlled by the
290     /// compiler that encodes information like the inferred type;
291     /// see `ty::InlineConstSubsts` struct for more comments.
292     pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> {
293         InlineConstSubsts { substs: self }
294     }
295
296     /// Creates an `InternalSubsts` that maps each generic parameter to itself.
297     pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> {
298         Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param))
299     }
300
301     /// Creates an `InternalSubsts` for generic parameter definitions,
302     /// by calling closures to obtain each kind.
303     /// The closures get to observe the `InternalSubsts` as they're
304     /// being built, which can be used to correctly
305     /// substitute defaults of generic parameters.
306     pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
307     where
308         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
309     {
310         let defs = tcx.generics_of(def_id);
311         let count = defs.count();
312         let mut substs = SmallVec::with_capacity(count);
313         Self::fill_item(&mut substs, tcx, defs, &mut mk_kind);
314         tcx.intern_substs(&substs)
315     }
316
317     pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
318     where
319         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
320     {
321         Self::for_item(tcx, def_id, |param, substs| {
322             self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs))
323         })
324     }
325
326     pub fn fill_item<F>(
327         substs: &mut SmallVec<[GenericArg<'tcx>; 8]>,
328         tcx: TyCtxt<'tcx>,
329         defs: &ty::Generics,
330         mk_kind: &mut F,
331     ) where
332         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
333     {
334         if let Some(def_id) = defs.parent {
335             let parent_defs = tcx.generics_of(def_id);
336             Self::fill_item(substs, tcx, parent_defs, mk_kind);
337         }
338         Self::fill_single(substs, defs, mk_kind)
339     }
340
341     pub fn fill_single<F>(
342         substs: &mut SmallVec<[GenericArg<'tcx>; 8]>,
343         defs: &ty::Generics,
344         mk_kind: &mut F,
345     ) where
346         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
347     {
348         substs.reserve(defs.params.len());
349         for param in &defs.params {
350             let kind = mk_kind(param, substs);
351             assert_eq!(param.index as usize, substs.len(), "{substs:#?}, {defs:#?}");
352             substs.push(kind);
353         }
354     }
355
356     // Extend an `original_substs` list to the full number of substs expected by `def_id`,
357     // filling in the missing parameters with error ty/ct or 'static regions.
358     pub fn extend_with_error(
359         tcx: TyCtxt<'tcx>,
360         def_id: DefId,
361         original_substs: &[GenericArg<'tcx>],
362     ) -> SubstsRef<'tcx> {
363         ty::InternalSubsts::for_item(tcx, def_id, |def, substs| {
364             if let Some(subst) = original_substs.get(def.index as usize) {
365                 *subst
366             } else {
367                 def.to_error(tcx, substs)
368             }
369         })
370     }
371
372     #[inline]
373     pub fn types(&'tcx self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'tcx {
374         self.iter()
375             .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None })
376     }
377
378     #[inline]
379     pub fn regions(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'tcx {
380         self.iter().filter_map(|k| {
381             if let GenericArgKind::Lifetime(lt) = k.unpack() { Some(lt) } else { None }
382         })
383     }
384
385     #[inline]
386     pub fn consts(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Const<'tcx>> + 'tcx {
387         self.iter().filter_map(|k| {
388             if let GenericArgKind::Const(ct) = k.unpack() { Some(ct) } else { None }
389         })
390     }
391
392     #[inline]
393     pub fn non_erasable_generics(
394         &'tcx self,
395     ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'tcx {
396         self.iter().filter_map(|k| match k.unpack() {
397             GenericArgKind::Lifetime(_) => None,
398             generic => Some(generic),
399         })
400     }
401
402     #[inline]
403     #[track_caller]
404     pub fn type_at(&self, i: usize) -> Ty<'tcx> {
405         if let GenericArgKind::Type(ty) = self[i].unpack() {
406             ty
407         } else {
408             bug!("expected type for param #{} in {:?}", i, self);
409         }
410     }
411
412     #[inline]
413     #[track_caller]
414     pub fn region_at(&self, i: usize) -> ty::Region<'tcx> {
415         if let GenericArgKind::Lifetime(lt) = self[i].unpack() {
416             lt
417         } else {
418             bug!("expected region for param #{} in {:?}", i, self);
419         }
420     }
421
422     #[inline]
423     #[track_caller]
424     pub fn const_at(&self, i: usize) -> ty::Const<'tcx> {
425         if let GenericArgKind::Const(ct) = self[i].unpack() {
426             ct
427         } else {
428             bug!("expected const for param #{} in {:?}", i, self);
429         }
430     }
431
432     #[inline]
433     #[track_caller]
434     pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> {
435         self.type_at(def.index as usize).into()
436     }
437
438     /// Transform from substitutions for a child of `source_ancestor`
439     /// (e.g., a trait or impl) to substitutions for the same child
440     /// in a different item, with `target_substs` as the base for
441     /// the target impl/trait, with the source child-specific
442     /// parameters (e.g., method parameters) on top of that base.
443     ///
444     /// For example given:
445     ///
446     /// ```no_run
447     /// trait X<S> { fn f<T>(); }
448     /// impl<U> X<U> for U { fn f<V>() {} }
449     /// ```
450     ///
451     /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait.
452     /// * If `source_ancestor` is the def_id of the trait.
453     /// * If `target_substs` is `[U]`, the substs for the impl.
454     /// * Then we will return `[U, T]`, the subst for `f` in the impl that
455     ///   are needed for it to match the trait.
456     pub fn rebase_onto(
457         &self,
458         tcx: TyCtxt<'tcx>,
459         source_ancestor: DefId,
460         target_substs: SubstsRef<'tcx>,
461     ) -> SubstsRef<'tcx> {
462         let defs = tcx.generics_of(source_ancestor);
463         tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len())))
464     }
465
466     pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> {
467         tcx.mk_substs(self.iter().take(generics.count()))
468     }
469 }
470
471 impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> {
472     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
473         // This code is hot enough that it's worth specializing for the most
474         // common length lists, to avoid the overhead of `SmallVec` creation.
475         // The match arms are in order of frequency. The 1, 2, and 0 cases are
476         // typically hit in 90--99.99% of cases. When folding doesn't change
477         // the substs, it's faster to reuse the existing substs rather than
478         // calling `intern_substs`.
479         match self.len() {
480             1 => {
481                 let param0 = self[0].try_fold_with(folder)?;
482                 if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) }
483             }
484             2 => {
485                 let param0 = self[0].try_fold_with(folder)?;
486                 let param1 = self[1].try_fold_with(folder)?;
487                 if param0 == self[0] && param1 == self[1] {
488                     Ok(self)
489                 } else {
490                     Ok(folder.tcx().intern_substs(&[param0, param1]))
491                 }
492             }
493             0 => Ok(self),
494             _ => ty::util::fold_list(self, folder, |tcx, v| tcx.intern_substs(v)),
495         }
496     }
497 }
498
499 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<Ty<'tcx>> {
500     fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
501         // This code is fairly hot, though not as hot as `SubstsRef`.
502         //
503         // When compiling stage 2, I get the following results:
504         //
505         // len |   total   |   %
506         // --- | --------- | -----
507         //  2  |  15083590 |  48.1
508         //  3  |   7540067 |  24.0
509         //  1  |   5300377 |  16.9
510         //  4  |   1351897 |   4.3
511         //  0  |   1256849 |   4.0
512         //
513         // I've tried it with some private repositories and got
514         // close to the same result, with 4 and 0 swapping places
515         // sometimes.
516         match self.len() {
517             2 => {
518                 let param0 = self[0].try_fold_with(folder)?;
519                 let param1 = self[1].try_fold_with(folder)?;
520                 if param0 == self[0] && param1 == self[1] {
521                     Ok(self)
522                 } else {
523                     Ok(folder.tcx().intern_type_list(&[param0, param1]))
524                 }
525             }
526             _ => ty::util::fold_list(self, folder, |tcx, v| tcx.intern_type_list(v)),
527         }
528     }
529 }
530
531 impl<'tcx, T: TypeVisitable<'tcx>> TypeVisitable<'tcx> for &'tcx ty::List<T> {
532     #[inline]
533     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
534         self.iter().try_for_each(|t| t.visit_with(visitor))
535     }
536 }
537
538 /// Similar to [`super::Binder`] except that it tracks early bound generics, i.e. `struct Foo<T>(T)`
539 /// needs `T` substituted immediately. This type primarily exists to avoid forgetting to call
540 /// `subst`.
541 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
542 #[derive(Encodable, Decodable, HashStable)]
543 pub struct EarlyBinder<T>(pub T);
544
545 /// For early binders, you should first call `subst` before using any visitors.
546 impl<'tcx, T> !TypeFoldable<'tcx> for ty::EarlyBinder<T> {}
547 impl<'tcx, T> !TypeVisitable<'tcx> for ty::EarlyBinder<T> {}
548
549 impl<T> EarlyBinder<T> {
550     pub fn as_ref(&self) -> EarlyBinder<&T> {
551         EarlyBinder(&self.0)
552     }
553
554     pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<U>
555     where
556         F: FnOnce(&T) -> U,
557     {
558         self.as_ref().map_bound(f)
559     }
560
561     pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<U>
562     where
563         F: FnOnce(T) -> U,
564     {
565         let value = f(self.0);
566         EarlyBinder(value)
567     }
568
569     pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<U>, E>
570     where
571         F: FnOnce(T) -> Result<U, E>,
572     {
573         let value = f(self.0)?;
574         Ok(EarlyBinder(value))
575     }
576
577     pub fn rebind<U>(&self, value: U) -> EarlyBinder<U> {
578         EarlyBinder(value)
579     }
580
581     pub fn skip_binder(self) -> T {
582         self.0
583     }
584 }
585
586 impl<T> EarlyBinder<Option<T>> {
587     pub fn transpose(self) -> Option<EarlyBinder<T>> {
588         self.0.map(|v| EarlyBinder(v))
589     }
590 }
591
592 impl<T, U> EarlyBinder<(T, U)> {
593     pub fn transpose_tuple2(self) -> (EarlyBinder<T>, EarlyBinder<U>) {
594         (EarlyBinder(self.0.0), EarlyBinder(self.0.1))
595     }
596 }
597
598 impl<'tcx, 's, I: IntoIterator> EarlyBinder<I>
599 where
600     I::Item: TypeFoldable<'tcx>,
601 {
602     pub fn subst_iter(
603         self,
604         tcx: TyCtxt<'tcx>,
605         substs: &'s [GenericArg<'tcx>],
606     ) -> SubstIter<'s, 'tcx, I> {
607         SubstIter { it: self.0.into_iter(), tcx, substs }
608     }
609 }
610
611 pub struct SubstIter<'s, 'tcx, I: IntoIterator> {
612     it: I::IntoIter,
613     tcx: TyCtxt<'tcx>,
614     substs: &'s [GenericArg<'tcx>],
615 }
616
617 impl<'tcx, I: IntoIterator> Iterator for SubstIter<'_, 'tcx, I>
618 where
619     I::Item: TypeFoldable<'tcx>,
620 {
621     type Item = I::Item;
622
623     fn next(&mut self) -> Option<Self::Item> {
624         Some(EarlyBinder(self.it.next()?).subst(self.tcx, self.substs))
625     }
626
627     fn size_hint(&self) -> (usize, Option<usize>) {
628         self.it.size_hint()
629     }
630 }
631
632 impl<'tcx, I: IntoIterator> DoubleEndedIterator for SubstIter<'_, 'tcx, I>
633 where
634     I::IntoIter: DoubleEndedIterator,
635     I::Item: TypeFoldable<'tcx>,
636 {
637     fn next_back(&mut self) -> Option<Self::Item> {
638         Some(EarlyBinder(self.it.next_back()?).subst(self.tcx, self.substs))
639     }
640 }
641
642 impl<'tcx, 's, I: IntoIterator> EarlyBinder<I>
643 where
644     I::Item: Deref,
645     <I::Item as Deref>::Target: Copy + TypeFoldable<'tcx>,
646 {
647     pub fn subst_iter_copied(
648         self,
649         tcx: TyCtxt<'tcx>,
650         substs: &'s [GenericArg<'tcx>],
651     ) -> SubstIterCopied<'s, 'tcx, I> {
652         SubstIterCopied { it: self.0.into_iter(), tcx, substs }
653     }
654 }
655
656 pub struct SubstIterCopied<'a, 'tcx, I: IntoIterator> {
657     it: I::IntoIter,
658     tcx: TyCtxt<'tcx>,
659     substs: &'a [GenericArg<'tcx>],
660 }
661
662 impl<'tcx, I: IntoIterator> Iterator for SubstIterCopied<'_, 'tcx, I>
663 where
664     I::Item: Deref,
665     <I::Item as Deref>::Target: Copy + TypeFoldable<'tcx>,
666 {
667     type Item = <I::Item as Deref>::Target;
668
669     fn next(&mut self) -> Option<Self::Item> {
670         Some(EarlyBinder(*self.it.next()?).subst(self.tcx, self.substs))
671     }
672
673     fn size_hint(&self) -> (usize, Option<usize>) {
674         self.it.size_hint()
675     }
676 }
677
678 impl<'tcx, I: IntoIterator> DoubleEndedIterator for SubstIterCopied<'_, 'tcx, I>
679 where
680     I::IntoIter: DoubleEndedIterator,
681     I::Item: Deref,
682     <I::Item as Deref>::Target: Copy + TypeFoldable<'tcx>,
683 {
684     fn next_back(&mut self) -> Option<Self::Item> {
685         Some(EarlyBinder(*self.it.next_back()?).subst(self.tcx, self.substs))
686     }
687 }
688
689 pub struct EarlyBinderIter<T> {
690     t: T,
691 }
692
693 impl<T: IntoIterator> EarlyBinder<T> {
694     pub fn transpose_iter(self) -> EarlyBinderIter<T::IntoIter> {
695         EarlyBinderIter { t: self.0.into_iter() }
696     }
697 }
698
699 impl<T: Iterator> Iterator for EarlyBinderIter<T> {
700     type Item = EarlyBinder<T::Item>;
701
702     fn next(&mut self) -> Option<Self::Item> {
703         self.t.next().map(|i| EarlyBinder(i))
704     }
705
706     fn size_hint(&self) -> (usize, Option<usize>) {
707         self.t.size_hint()
708     }
709 }
710
711 impl<'tcx, T: TypeFoldable<'tcx>> ty::EarlyBinder<T> {
712     pub fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> T {
713         let mut folder = SubstFolder { tcx, substs, binders_passed: 0 };
714         self.0.fold_with(&mut folder)
715     }
716 }
717
718 ///////////////////////////////////////////////////////////////////////////
719 // The actual substitution engine itself is a type folder.
720
721 struct SubstFolder<'a, 'tcx> {
722     tcx: TyCtxt<'tcx>,
723     substs: &'a [GenericArg<'tcx>],
724
725     /// Number of region binders we have passed through while doing the substitution
726     binders_passed: u32,
727 }
728
729 impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> {
730     #[inline]
731     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
732         self.tcx
733     }
734
735     fn fold_binder<T: TypeFoldable<'tcx>>(
736         &mut self,
737         t: ty::Binder<'tcx, T>,
738     ) -> ty::Binder<'tcx, T> {
739         self.binders_passed += 1;
740         let t = t.super_fold_with(self);
741         self.binders_passed -= 1;
742         t
743     }
744
745     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
746         #[cold]
747         #[inline(never)]
748         fn region_param_out_of_range(data: ty::EarlyBoundRegion, substs: &[GenericArg<'_>]) -> ! {
749             bug!(
750                 "Region parameter out of range when substituting in region {} (index={}, substs = {:?})",
751                 data.name,
752                 data.index,
753                 substs,
754             )
755         }
756
757         #[cold]
758         #[inline(never)]
759         fn region_param_invalid(data: ty::EarlyBoundRegion, other: GenericArgKind<'_>) -> ! {
760             bug!(
761                 "Unexpected parameter {:?} when substituting in region {} (index={})",
762                 other,
763                 data.name,
764                 data.index
765             )
766         }
767
768         // Note: This routine only handles regions that are bound on
769         // type declarations and other outer declarations, not those
770         // bound in *fn types*. Region substitution of the bound
771         // regions that appear in a function signature is done using
772         // the specialized routine `ty::replace_late_regions()`.
773         match *r {
774             ty::ReEarlyBound(data) => {
775                 let rk = self.substs.get(data.index as usize).map(|k| k.unpack());
776                 match rk {
777                     Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt),
778                     Some(other) => region_param_invalid(data, other),
779                     None => region_param_out_of_range(data, self.substs),
780                 }
781             }
782             _ => r,
783         }
784     }
785
786     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
787         if !t.needs_subst() {
788             return t;
789         }
790
791         match *t.kind() {
792             ty::Param(p) => self.ty_for_param(p, t),
793             _ => t.super_fold_with(self),
794         }
795     }
796
797     fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
798         if let ty::ConstKind::Param(p) = c.kind() {
799             self.const_for_param(p, c)
800         } else {
801             c.super_fold_with(self)
802         }
803     }
804 }
805
806 impl<'a, 'tcx> SubstFolder<'a, 'tcx> {
807     fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
808         // Look up the type in the substitutions. It really should be in there.
809         let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack());
810         let ty = match opt_ty {
811             Some(GenericArgKind::Type(ty)) => ty,
812             Some(kind) => self.type_param_expected(p, source_ty, kind),
813             None => self.type_param_out_of_range(p, source_ty),
814         };
815
816         self.shift_vars_through_binders(ty)
817     }
818
819     #[cold]
820     #[inline(never)]
821     fn type_param_expected(&self, p: ty::ParamTy, ty: Ty<'tcx>, kind: GenericArgKind<'tcx>) -> ! {
822         bug!(
823             "expected type for `{:?}` ({:?}/{}) but found {:?} when substituting, substs={:?}",
824             p,
825             ty,
826             p.index,
827             kind,
828             self.substs,
829         )
830     }
831
832     #[cold]
833     #[inline(never)]
834     fn type_param_out_of_range(&self, p: ty::ParamTy, ty: Ty<'tcx>) -> ! {
835         bug!(
836             "type parameter `{:?}` ({:?}/{}) out of range when substituting, substs={:?}",
837             p,
838             ty,
839             p.index,
840             self.substs,
841         )
842     }
843
844     fn const_for_param(&self, p: ParamConst, source_ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
845         // Look up the const in the substitutions. It really should be in there.
846         let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack());
847         let ct = match opt_ct {
848             Some(GenericArgKind::Const(ct)) => ct,
849             Some(kind) => self.const_param_expected(p, source_ct, kind),
850             None => self.const_param_out_of_range(p, source_ct),
851         };
852
853         self.shift_vars_through_binders(ct)
854     }
855
856     #[cold]
857     #[inline(never)]
858     fn const_param_expected(
859         &self,
860         p: ty::ParamConst,
861         ct: ty::Const<'tcx>,
862         kind: GenericArgKind<'tcx>,
863     ) -> ! {
864         bug!(
865             "expected const for `{:?}` ({:?}/{}) but found {:?} when substituting substs={:?}",
866             p,
867             ct,
868             p.index,
869             kind,
870             self.substs,
871         )
872     }
873
874     #[cold]
875     #[inline(never)]
876     fn const_param_out_of_range(&self, p: ty::ParamConst, ct: ty::Const<'tcx>) -> ! {
877         bug!(
878             "const parameter `{:?}` ({:?}/{}) out of range when substituting substs={:?}",
879             p,
880             ct,
881             p.index,
882             self.substs,
883         )
884     }
885
886     /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs
887     /// when we are substituting a type with escaping bound vars into a context where we have
888     /// passed through binders. That's quite a mouthful. Let's see an example:
889     ///
890     /// ```
891     /// type Func<A> = fn(A);
892     /// type MetaFunc = for<'a> fn(Func<&'a i32>);
893     /// ```
894     ///
895     /// The type `MetaFunc`, when fully expanded, will be
896     /// ```ignore (illustrative)
897     /// for<'a> fn(fn(&'a i32))
898     /// //      ^~ ^~ ^~~
899     /// //      |  |  |
900     /// //      |  |  DebruijnIndex of 2
901     /// //      Binders
902     /// ```
903     /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
904     /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
905     /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the
906     /// definition of `MetaFunc`, the binder is not visible, so the type `&'a i32` will have a
907     /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the
908     /// depth by 1 to account for the binder that we passed through.
909     ///
910     /// As a second example, consider this twist:
911     ///
912     /// ```
913     /// type FuncTuple<A> = (A,fn(A));
914     /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a i32>);
915     /// ```
916     ///
917     /// Here the final type will be:
918     /// ```ignore (illustrative)
919     /// for<'a> fn((&'a i32, fn(&'a i32)))
920     /// //          ^~~         ^~~
921     /// //          |           |
922     /// //   DebruijnIndex of 1 |
923     /// //               DebruijnIndex of 2
924     /// ```
925     /// As indicated in the diagram, here the same type `&'a i32` is substituted once, but in the
926     /// first case we do not increase the De Bruijn index and in the second case we do. The reason
927     /// is that only in the second case have we passed through a fn binder.
928     fn shift_vars_through_binders<T: TypeFoldable<'tcx>>(&self, val: T) -> T {
929         debug!(
930             "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})",
931             val,
932             self.binders_passed,
933             val.has_escaping_bound_vars()
934         );
935
936         if self.binders_passed == 0 || !val.has_escaping_bound_vars() {
937             return val;
938         }
939
940         let result = ty::fold::shift_vars(TypeFolder::tcx(self), val, self.binders_passed);
941         debug!("shift_vars: shifted result = {:?}", result);
942
943         result
944     }
945
946     fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> {
947         if self.binders_passed == 0 || !region.has_escaping_bound_vars() {
948             return region;
949         }
950         ty::fold::shift_region(self.tcx, region, self.binders_passed)
951     }
952 }
953
954 /// Stores the user-given substs to reach some fully qualified path
955 /// (e.g., `<T>::Item` or `<T as Trait>::Item`).
956 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
957 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
958 pub struct UserSubsts<'tcx> {
959     /// The substitutions for the item as given by the user.
960     pub substs: SubstsRef<'tcx>,
961
962     /// The self type, in the case of a `<T>::Item` path (when applied
963     /// to an inherent impl). See `UserSelfTy` below.
964     pub user_self_ty: Option<UserSelfTy<'tcx>>,
965 }
966
967 /// Specifies the user-given self type. In the case of a path that
968 /// refers to a member in an inherent impl, this self type is
969 /// sometimes needed to constrain the type parameters on the impl. For
970 /// example, in this code:
971 ///
972 /// ```ignore (illustrative)
973 /// struct Foo<T> { }
974 /// impl<A> Foo<A> { fn method() { } }
975 /// ```
976 ///
977 /// when you then have a path like `<Foo<&'static u32>>::method`,
978 /// this struct would carry the `DefId` of the impl along with the
979 /// self type `Foo<u32>`. Then we can instantiate the parameters of
980 /// the impl (with the substs from `UserSubsts`) and apply those to
981 /// the self type, giving `Foo<?A>`. Finally, we unify that with
982 /// the self type here, which contains `?A` to be `&'static u32`
983 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
984 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
985 pub struct UserSelfTy<'tcx> {
986     pub impl_def_id: DefId,
987     pub self_ty: Ty<'tcx>,
988 }