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