]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/ty/subst.rs
1529f1173b391caea5df017e76d86b1e957eb646
[rust.git] / src / librustc_middle / ty / subst.rs
1 // Type substitutions.
2
3 use crate::infer::canonical::Canonical;
4 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
5 use crate::ty::sty::{ClosureSubsts, GeneratorSubsts};
6 use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt};
7
8 use rustc_hir::def_id::DefId;
9 use rustc_macros::HashStable;
10 use rustc_serialize::{self, Decodable, Decoder, Encodable, Encoder};
11 use rustc_span::{Span, DUMMY_SP};
12 use smallvec::SmallVec;
13
14 use core::intrinsics;
15 use std::cmp::Ordering;
16 use std::fmt;
17 use std::marker::PhantomData;
18 use std::mem;
19 use std::num::NonZeroUsize;
20
21 /// An entity in the Rust type system, which can be one of
22 /// several kinds (types, lifetimes, and consts).
23 /// To reduce memory usage, a `GenericArg` is a interned pointer,
24 /// with the lowest 2 bits being reserved for a tag to
25 /// indicate the type (`Ty`, `Region`, or `Const`) it points to.
26 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
27 pub struct GenericArg<'tcx> {
28     ptr: NonZeroUsize,
29     marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>,
30 }
31
32 const TAG_MASK: usize = 0b11;
33 const TYPE_TAG: usize = 0b00;
34 const REGION_TAG: usize = 0b01;
35 const CONST_TAG: usize = 0b10;
36
37 #[derive(Debug, RustcEncodable, RustcDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)]
38 pub enum GenericArgKind<'tcx> {
39     Lifetime(ty::Region<'tcx>),
40     Type(Ty<'tcx>),
41     Const(&'tcx ty::Const<'tcx>),
42 }
43
44 impl<'tcx> GenericArgKind<'tcx> {
45     fn pack(self) -> GenericArg<'tcx> {
46         let (tag, ptr) = match self {
47             GenericArgKind::Lifetime(lt) => {
48                 // Ensure we can use the tag bits.
49                 assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0);
50                 (REGION_TAG, lt as *const _ as usize)
51             }
52             GenericArgKind::Type(ty) => {
53                 // Ensure we can use the tag bits.
54                 assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0);
55                 (TYPE_TAG, ty as *const _ as usize)
56             }
57             GenericArgKind::Const(ct) => {
58                 // Ensure we can use the tag bits.
59                 assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0);
60                 (CONST_TAG, ct as *const _ as usize)
61             }
62         };
63
64         GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData }
65     }
66 }
67
68 impl fmt::Debug for GenericArg<'tcx> {
69     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70         match self.unpack() {
71             GenericArgKind::Lifetime(lt) => lt.fmt(f),
72             GenericArgKind::Type(ty) => ty.fmt(f),
73             GenericArgKind::Const(ct) => ct.fmt(f),
74         }
75     }
76 }
77
78 impl<'tcx> Ord for GenericArg<'tcx> {
79     fn cmp(&self, other: &GenericArg<'_>) -> Ordering {
80         self.unpack().cmp(&other.unpack())
81     }
82 }
83
84 impl<'tcx> PartialOrd for GenericArg<'tcx> {
85     fn partial_cmp(&self, other: &GenericArg<'_>) -> Option<Ordering> {
86         Some(self.cmp(&other))
87     }
88 }
89
90 impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> {
91     fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> {
92         GenericArgKind::Lifetime(r).pack()
93     }
94 }
95
96 impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> {
97     fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> {
98         GenericArgKind::Type(ty).pack()
99     }
100 }
101
102 impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> {
103     fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> {
104         GenericArgKind::Const(c).pack()
105     }
106 }
107
108 impl<'tcx> GenericArg<'tcx> {
109     #[inline]
110     pub fn unpack(self) -> GenericArgKind<'tcx> {
111         let ptr = self.ptr.get();
112         unsafe {
113             match ptr & TAG_MASK {
114                 REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)),
115                 TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)),
116                 CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)),
117                 _ => intrinsics::unreachable(),
118             }
119         }
120     }
121
122     /// Unpack the `GenericArg` as a type when it is known certainly to be a type.
123     /// This is true in cases where `Substs` is used in places where the kinds are known
124     /// to be limited (e.g. in tuples, where the only parameters are type parameters).
125     pub fn expect_ty(self) -> Ty<'tcx> {
126         match self.unpack() {
127             GenericArgKind::Type(ty) => ty,
128             _ => bug!("expected a type, but found another kind"),
129         }
130     }
131
132     /// Unpack the `GenericArg` as a const when it is known certainly to be a const.
133     pub fn expect_const(self) -> &'tcx ty::Const<'tcx> {
134         match self.unpack() {
135             GenericArgKind::Const(c) => c,
136             _ => bug!("expected a const, but found another kind"),
137         }
138     }
139 }
140
141 impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> {
142     type Lifted = GenericArg<'tcx>;
143
144     fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
145         match self.unpack() {
146             GenericArgKind::Lifetime(lt) => tcx.lift(&lt).map(|lt| lt.into()),
147             GenericArgKind::Type(ty) => tcx.lift(&ty).map(|ty| ty.into()),
148             GenericArgKind::Const(ct) => tcx.lift(&ct).map(|ct| ct.into()),
149         }
150     }
151 }
152
153 impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> {
154     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
155         match self.unpack() {
156             GenericArgKind::Lifetime(lt) => lt.fold_with(folder).into(),
157             GenericArgKind::Type(ty) => ty.fold_with(folder).into(),
158             GenericArgKind::Const(ct) => ct.fold_with(folder).into(),
159         }
160     }
161
162     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
163         match self.unpack() {
164             GenericArgKind::Lifetime(lt) => lt.visit_with(visitor),
165             GenericArgKind::Type(ty) => ty.visit_with(visitor),
166             GenericArgKind::Const(ct) => ct.visit_with(visitor),
167         }
168     }
169 }
170
171 impl<'tcx> Encodable for GenericArg<'tcx> {
172     fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
173         self.unpack().encode(e)
174     }
175 }
176
177 impl<'tcx> Decodable for GenericArg<'tcx> {
178     fn decode<D: Decoder>(d: &mut D) -> Result<GenericArg<'tcx>, D::Error> {
179         Ok(GenericArgKind::decode(d)?.pack())
180     }
181 }
182
183 /// A substitution mapping generic parameters to new values.
184 pub type InternalSubsts<'tcx> = List<GenericArg<'tcx>>;
185
186 pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>;
187
188 impl<'a, 'tcx> InternalSubsts<'tcx> {
189     /// Interpret these substitutions as the substitutions of a closure type.
190     /// Closure substitutions have a particular structure controlled by the
191     /// compiler that encodes information like the signature and closure kind;
192     /// see `ty::ClosureSubsts` struct for more comments.
193     pub fn as_closure(&'a self) -> ClosureSubsts<'a> {
194         ClosureSubsts { substs: self }
195     }
196
197     /// Interpret these substitutions as the substitutions of a generator type.
198     /// Closure substitutions have a particular structure controlled by the
199     /// compiler that encodes information like the signature and generator kind;
200     /// see `ty::GeneratorSubsts` struct for more comments.
201     pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> {
202         GeneratorSubsts { substs: self }
203     }
204
205     /// Creates a `InternalSubsts` that maps each generic parameter to itself.
206     pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> {
207         Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param))
208     }
209
210     /// Creates a `InternalSubsts` for generic parameter definitions,
211     /// by calling closures to obtain each kind.
212     /// The closures get to observe the `InternalSubsts` as they're
213     /// being built, which can be used to correctly
214     /// substitute defaults of generic parameters.
215     pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
216     where
217         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
218     {
219         let defs = tcx.generics_of(def_id);
220         let count = defs.count();
221         let mut substs = SmallVec::with_capacity(count);
222         Self::fill_item(&mut substs, tcx, defs, &mut mk_kind);
223         tcx.intern_substs(&substs)
224     }
225
226     pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
227     where
228         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
229     {
230         Self::for_item(tcx, def_id, |param, substs| {
231             self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs))
232         })
233     }
234
235     fn fill_item<F>(
236         substs: &mut SmallVec<[GenericArg<'tcx>; 8]>,
237         tcx: TyCtxt<'tcx>,
238         defs: &ty::Generics,
239         mk_kind: &mut F,
240     ) where
241         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
242     {
243         if let Some(def_id) = defs.parent {
244             let parent_defs = tcx.generics_of(def_id);
245             Self::fill_item(substs, tcx, parent_defs, mk_kind);
246         }
247         Self::fill_single(substs, defs, mk_kind)
248     }
249
250     fn fill_single<F>(
251         substs: &mut SmallVec<[GenericArg<'tcx>; 8]>,
252         defs: &ty::Generics,
253         mk_kind: &mut F,
254     ) where
255         F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>,
256     {
257         substs.reserve(defs.params.len());
258         for param in &defs.params {
259             let kind = mk_kind(param, substs);
260             assert_eq!(param.index as usize, substs.len());
261             substs.push(kind);
262         }
263     }
264
265     pub fn is_noop(&self) -> bool {
266         self.is_empty()
267     }
268
269     #[inline]
270     pub fn types(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
271         self.iter()
272             .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None })
273     }
274
275     #[inline]
276     pub fn regions(&'a self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'a {
277         self.iter().filter_map(|k| {
278             if let GenericArgKind::Lifetime(lt) = k.unpack() { Some(lt) } else { None }
279         })
280     }
281
282     #[inline]
283     pub fn consts(&'a self) -> impl DoubleEndedIterator<Item = &'tcx ty::Const<'tcx>> + 'a {
284         self.iter().filter_map(|k| {
285             if let GenericArgKind::Const(ct) = k.unpack() { Some(ct) } else { None }
286         })
287     }
288
289     #[inline]
290     pub fn non_erasable_generics(
291         &'a self,
292     ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'a {
293         self.iter().filter_map(|k| match k.unpack() {
294             GenericArgKind::Lifetime(_) => None,
295             generic => Some(generic),
296         })
297     }
298
299     #[inline]
300     pub fn type_at(&self, i: usize) -> Ty<'tcx> {
301         if let GenericArgKind::Type(ty) = self[i].unpack() {
302             ty
303         } else {
304             bug!("expected type for param #{} in {:?}", i, self);
305         }
306     }
307
308     #[inline]
309     pub fn region_at(&self, i: usize) -> ty::Region<'tcx> {
310         if let GenericArgKind::Lifetime(lt) = self[i].unpack() {
311             lt
312         } else {
313             bug!("expected region for param #{} in {:?}", i, self);
314         }
315     }
316
317     #[inline]
318     pub fn const_at(&self, i: usize) -> &'tcx ty::Const<'tcx> {
319         if let GenericArgKind::Const(ct) = self[i].unpack() {
320             ct
321         } else {
322             bug!("expected const for param #{} in {:?}", i, self);
323         }
324     }
325
326     #[inline]
327     pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> {
328         self.type_at(def.index as usize).into()
329     }
330
331     /// Transform from substitutions for a child of `source_ancestor`
332     /// (e.g., a trait or impl) to substitutions for the same child
333     /// in a different item, with `target_substs` as the base for
334     /// the target impl/trait, with the source child-specific
335     /// parameters (e.g., method parameters) on top of that base.
336     pub fn rebase_onto(
337         &self,
338         tcx: TyCtxt<'tcx>,
339         source_ancestor: DefId,
340         target_substs: SubstsRef<'tcx>,
341     ) -> SubstsRef<'tcx> {
342         let defs = tcx.generics_of(source_ancestor);
343         tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len())))
344     }
345
346     pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> {
347         tcx.mk_substs(self.iter().take(generics.count()))
348     }
349 }
350
351 impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> {
352     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
353         // This code is hot enough that it's worth specializing for the most
354         // common length lists, to avoid the overhead of `SmallVec` creation.
355         // The match arms are in order of frequency. The 1, 2, and 0 cases are
356         // typically hit in 90--99.99% of cases. When folding doesn't change
357         // the substs, it's faster to reuse the existing substs rather than
358         // calling `intern_substs`.
359         match self.len() {
360             1 => {
361                 let param0 = self[0].fold_with(folder);
362                 if param0 == self[0] { self } else { folder.tcx().intern_substs(&[param0]) }
363             }
364             2 => {
365                 let param0 = self[0].fold_with(folder);
366                 let param1 = self[1].fold_with(folder);
367                 if param0 == self[0] && param1 == self[1] {
368                     self
369                 } else {
370                     folder.tcx().intern_substs(&[param0, param1])
371                 }
372             }
373             0 => self,
374             _ => {
375                 let params: SmallVec<[_; 8]> = self.iter().map(|k| k.fold_with(folder)).collect();
376                 if params[..] == self[..] { self } else { folder.tcx().intern_substs(&params) }
377             }
378         }
379     }
380
381     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
382         self.iter().any(|t| t.visit_with(visitor))
383     }
384 }
385
386 impl<'tcx> rustc_serialize::UseSpecializedDecodable for SubstsRef<'tcx> {}
387
388 ///////////////////////////////////////////////////////////////////////////
389 // Public trait `Subst`
390 //
391 // Just call `foo.subst(tcx, substs)` to perform a substitution across
392 // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when
393 // there is more information available (for better errors).
394
395 pub trait Subst<'tcx>: Sized {
396     fn subst(&self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> Self {
397         self.subst_spanned(tcx, substs, None)
398     }
399
400     fn subst_spanned(
401         &self,
402         tcx: TyCtxt<'tcx>,
403         substs: &[GenericArg<'tcx>],
404         span: Option<Span>,
405     ) -> Self;
406 }
407
408 impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T {
409     fn subst_spanned(
410         &self,
411         tcx: TyCtxt<'tcx>,
412         substs: &[GenericArg<'tcx>],
413         span: Option<Span>,
414     ) -> T {
415         let mut folder =
416             SubstFolder { tcx, substs, span, root_ty: None, ty_stack_depth: 0, binders_passed: 0 };
417         (*self).fold_with(&mut folder)
418     }
419 }
420
421 ///////////////////////////////////////////////////////////////////////////
422 // The actual substitution engine itself is a type folder.
423
424 struct SubstFolder<'a, 'tcx> {
425     tcx: TyCtxt<'tcx>,
426     substs: &'a [GenericArg<'tcx>],
427
428     /// The location for which the substitution is performed, if available.
429     span: Option<Span>,
430
431     /// The root type that is being substituted, if available.
432     root_ty: Option<Ty<'tcx>>,
433
434     /// Depth of type stack
435     ty_stack_depth: usize,
436
437     /// Number of region binders we have passed through while doing the substitution
438     binders_passed: u32,
439 }
440
441 impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> {
442     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
443         self.tcx
444     }
445
446     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
447         self.binders_passed += 1;
448         let t = t.super_fold_with(self);
449         self.binders_passed -= 1;
450         t
451     }
452
453     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
454         // Note: This routine only handles regions that are bound on
455         // type declarations and other outer declarations, not those
456         // bound in *fn types*. Region substitution of the bound
457         // regions that appear in a function signature is done using
458         // the specialized routine `ty::replace_late_regions()`.
459         match *r {
460             ty::ReEarlyBound(data) => {
461                 let rk = self.substs.get(data.index as usize).map(|k| k.unpack());
462                 match rk {
463                     Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt),
464                     _ => {
465                         let span = self.span.unwrap_or(DUMMY_SP);
466                         let msg = format!(
467                             "Region parameter out of range \
468                              when substituting in region {} (root type={:?}) \
469                              (index={})",
470                             data.name, self.root_ty, data.index
471                         );
472                         span_bug!(span, "{}", msg);
473                     }
474                 }
475             }
476             _ => r,
477         }
478     }
479
480     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
481         if !t.needs_subst() {
482             return t;
483         }
484
485         // track the root type we were asked to substitute
486         let depth = self.ty_stack_depth;
487         if depth == 0 {
488             self.root_ty = Some(t);
489         }
490         self.ty_stack_depth += 1;
491
492         let t1 = match t.kind {
493             ty::Param(p) => self.ty_for_param(p, t),
494             _ => t.super_fold_with(self),
495         };
496
497         assert_eq!(depth + 1, self.ty_stack_depth);
498         self.ty_stack_depth -= 1;
499         if depth == 0 {
500             self.root_ty = None;
501         }
502
503         t1
504     }
505
506     fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
507         if !c.needs_subst() {
508             return c;
509         }
510
511         if let ty::ConstKind::Param(p) = c.val {
512             self.const_for_param(p, c)
513         } else {
514             c.super_fold_with(self)
515         }
516     }
517 }
518
519 impl<'a, 'tcx> SubstFolder<'a, 'tcx> {
520     fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
521         // Look up the type in the substitutions. It really should be in there.
522         let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack());
523         let ty = match opt_ty {
524             Some(GenericArgKind::Type(ty)) => ty,
525             Some(kind) => {
526                 let span = self.span.unwrap_or(DUMMY_SP);
527                 span_bug!(
528                     span,
529                     "expected type for `{:?}` ({:?}/{}) but found {:?} \
530                      when substituting (root type={:?}) substs={:?}",
531                     p,
532                     source_ty,
533                     p.index,
534                     kind,
535                     self.root_ty,
536                     self.substs,
537                 );
538             }
539             None => {
540                 let span = self.span.unwrap_or(DUMMY_SP);
541                 span_bug!(
542                     span,
543                     "type parameter `{:?}` ({:?}/{}) out of range \
544                      when substituting (root type={:?}) substs={:?}",
545                     p,
546                     source_ty,
547                     p.index,
548                     self.root_ty,
549                     self.substs,
550                 );
551             }
552         };
553
554         self.shift_vars_through_binders(ty)
555     }
556
557     fn const_for_param(
558         &self,
559         p: ParamConst,
560         source_ct: &'tcx ty::Const<'tcx>,
561     ) -> &'tcx ty::Const<'tcx> {
562         // Look up the const in the substitutions. It really should be in there.
563         let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack());
564         let ct = match opt_ct {
565             Some(GenericArgKind::Const(ct)) => ct,
566             Some(kind) => {
567                 let span = self.span.unwrap_or(DUMMY_SP);
568                 span_bug!(
569                     span,
570                     "expected const for `{:?}` ({:?}/{}) but found {:?} \
571                      when substituting substs={:?}",
572                     p,
573                     source_ct,
574                     p.index,
575                     kind,
576                     self.substs,
577                 );
578             }
579             None => {
580                 let span = self.span.unwrap_or(DUMMY_SP);
581                 span_bug!(
582                     span,
583                     "const parameter `{:?}` ({:?}/{}) out of range \
584                      when substituting substs={:?}",
585                     p,
586                     source_ct,
587                     p.index,
588                     self.substs,
589                 );
590             }
591         };
592
593         self.shift_vars_through_binders(ct)
594     }
595
596     /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs
597     /// when we are substituting a type with escaping bound vars into a context where we have
598     /// passed through binders. That's quite a mouthful. Let's see an example:
599     ///
600     /// ```
601     /// type Func<A> = fn(A);
602     /// type MetaFunc = for<'a> fn(Func<&'a int>)
603     /// ```
604     ///
605     /// The type `MetaFunc`, when fully expanded, will be
606     ///
607     ///     for<'a> fn(fn(&'a int))
608     ///             ^~ ^~ ^~~
609     ///             |  |  |
610     ///             |  |  DebruijnIndex of 2
611     ///             Binders
612     ///
613     /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
614     /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
615     /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the
616     /// definition of `MetaFunc`, the binder is not visible, so the type `&'a int` will have a
617     /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the
618     /// depth by 1 to account for the binder that we passed through.
619     ///
620     /// As a second example, consider this twist:
621     ///
622     /// ```
623     /// type FuncTuple<A> = (A,fn(A));
624     /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a int>)
625     /// ```
626     ///
627     /// Here the final type will be:
628     ///
629     ///     for<'a> fn((&'a int, fn(&'a int)))
630     ///                 ^~~         ^~~
631     ///                 |           |
632     ///          DebruijnIndex of 1 |
633     ///                      DebruijnIndex of 2
634     ///
635     /// As indicated in the diagram, here the same type `&'a int` is substituted once, but in the
636     /// first case we do not increase the De Bruijn index and in the second case we do. The reason
637     /// is that only in the second case have we passed through a fn binder.
638     fn shift_vars_through_binders<T: TypeFoldable<'tcx>>(&self, val: T) -> T {
639         debug!(
640             "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})",
641             val,
642             self.binders_passed,
643             val.has_escaping_bound_vars()
644         );
645
646         if self.binders_passed == 0 || !val.has_escaping_bound_vars() {
647             return val;
648         }
649
650         let result = ty::fold::shift_vars(self.tcx(), &val, self.binders_passed);
651         debug!("shift_vars: shifted result = {:?}", result);
652
653         result
654     }
655
656     fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> {
657         if self.binders_passed == 0 || !region.has_escaping_bound_vars() {
658             return region;
659         }
660         ty::fold::shift_region(self.tcx, region, self.binders_passed)
661     }
662 }
663
664 pub type CanonicalUserSubsts<'tcx> = Canonical<'tcx, UserSubsts<'tcx>>;
665
666 /// Stores the user-given substs to reach some fully qualified path
667 /// (e.g., `<T>::Item` or `<T as Trait>::Item`).
668 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
669 #[derive(HashStable, TypeFoldable, Lift)]
670 pub struct UserSubsts<'tcx> {
671     /// The substitutions for the item as given by the user.
672     pub substs: SubstsRef<'tcx>,
673
674     /// The self type, in the case of a `<T>::Item` path (when applied
675     /// to an inherent impl). See `UserSelfTy` below.
676     pub user_self_ty: Option<UserSelfTy<'tcx>>,
677 }
678
679 /// Specifies the user-given self type. In the case of a path that
680 /// refers to a member in an inherent impl, this self type is
681 /// sometimes needed to constrain the type parameters on the impl. For
682 /// example, in this code:
683 ///
684 /// ```
685 /// struct Foo<T> { }
686 /// impl<A> Foo<A> { fn method() { } }
687 /// ```
688 ///
689 /// when you then have a path like `<Foo<&'static u32>>::method`,
690 /// this struct would carry the `DefId` of the impl along with the
691 /// self type `Foo<u32>`. Then we can instantiate the parameters of
692 /// the impl (with the substs from `UserSubsts`) and apply those to
693 /// the self type, giving `Foo<?A>`. Finally, we unify that with
694 /// the self type here, which contains `?A` to be `&'static u32`
695 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
696 #[derive(HashStable, TypeFoldable, Lift)]
697 pub struct UserSelfTy<'tcx> {
698     pub impl_def_id: DefId,
699     pub self_ty: Ty<'tcx>,
700 }