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