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