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