]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/subst.rs
Rollup merge of #63505 - jgalenson:sysroot-hash, r=alexcrichton
[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 rustc_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(&self, tcx: TyCtxt<'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<F: TypeFolder<'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, 'tcx> InternalSubsts<'tcx> {
186     /// Creates a `InternalSubsts` that maps each generic parameter to itself.
187     pub fn identity_for_item(tcx: TyCtxt<'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(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> {
198         Self::for_item(tcx, def_id, |param, _| {
199             match param.kind {
200                 ty::GenericParamDefKind::Type { .. } => {
201                     tcx.mk_ty(
202                         ty::Bound(ty::INNERMOST, ty::BoundTy {
203                             var: ty::BoundVar::from(param.index),
204                             kind: ty::BoundTyKind::Param(param.name),
205                         })
206                     ).into()
207                 }
208
209                 ty::GenericParamDefKind::Lifetime => {
210                     tcx.mk_region(ty::RegionKind::ReLateBound(
211                         ty::INNERMOST,
212                         ty::BoundRegion::BrNamed(param.def_id, param.name)
213                     )).into()
214                 }
215
216                 ty::GenericParamDefKind::Const => {
217                     tcx.mk_const(ty::Const {
218                         val: ConstValue::Infer(
219                             InferConst::Canonical(ty::INNERMOST, ty::BoundVar::from(param.index))
220                         ),
221                         ty: tcx.type_of(def_id),
222                     }).into()
223                 }
224             }
225         })
226     }
227
228     /// Creates a `InternalSubsts` for generic parameter definitions,
229     /// by calling closures to obtain each kind.
230     /// The closures get to observe the `InternalSubsts` as they're
231     /// being built, which can be used to correctly
232     /// substitute defaults of generic parameters.
233     pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
234     where
235         F: FnMut(&ty::GenericParamDef, &[Kind<'tcx>]) -> Kind<'tcx>,
236     {
237         let defs = tcx.generics_of(def_id);
238         let count = defs.count();
239         let mut substs = SmallVec::with_capacity(count);
240         Self::fill_item(&mut substs, tcx, defs, &mut mk_kind);
241         tcx.intern_substs(&substs)
242     }
243
244     pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx>
245     where
246         F: FnMut(&ty::GenericParamDef, &[Kind<'tcx>]) -> Kind<'tcx>,
247     {
248         Self::for_item(tcx, def_id, |param, substs| {
249             self.get(param.index as usize)
250                 .cloned()
251                 .unwrap_or_else(|| mk_kind(param, substs))
252         })
253     }
254
255     fn fill_item<F>(
256         substs: &mut SmallVec<[Kind<'tcx>; 8]>,
257         tcx: TyCtxt<'tcx>,
258         defs: &ty::Generics,
259         mk_kind: &mut F,
260     ) where
261         F: FnMut(&ty::GenericParamDef, &[Kind<'tcx>]) -> Kind<'tcx>,
262     {
263         if let Some(def_id) = defs.parent {
264             let parent_defs = tcx.generics_of(def_id);
265             Self::fill_item(substs, tcx, parent_defs, mk_kind);
266         }
267         Self::fill_single(substs, defs, mk_kind)
268     }
269
270     fn fill_single<F>(substs: &mut SmallVec<[Kind<'tcx>; 8]>,
271                       defs: &ty::Generics,
272                       mk_kind: &mut F)
273     where F: FnMut(&ty::GenericParamDef, &[Kind<'tcx>]) -> Kind<'tcx>
274     {
275         substs.reserve(defs.params.len());
276         for param in &defs.params {
277             let kind = mk_kind(param, substs);
278             assert_eq!(param.index as usize, substs.len());
279             substs.push(kind);
280         }
281     }
282
283     pub fn is_noop(&self) -> bool {
284         self.is_empty()
285     }
286
287     #[inline]
288     pub fn types(&'a self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'a {
289         self.iter().filter_map(|k| {
290             if let UnpackedKind::Type(ty) = k.unpack() {
291                 Some(ty)
292             } else {
293                 None
294             }
295         })
296     }
297
298     #[inline]
299     pub fn regions(&'a self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'a {
300         self.iter().filter_map(|k| {
301             if let UnpackedKind::Lifetime(lt) = k.unpack() {
302                 Some(lt)
303             } else {
304                 None
305             }
306         })
307     }
308
309     #[inline]
310     pub fn consts(&'a self) -> impl DoubleEndedIterator<Item = &'tcx ty::Const<'tcx>> + 'a {
311         self.iter().filter_map(|k| {
312             if let UnpackedKind::Const(ct) = k.unpack() {
313                 Some(ct)
314             } else {
315                 None
316             }
317         })
318     }
319
320     #[inline]
321     pub fn non_erasable_generics(
322         &'a self
323     ) -> impl DoubleEndedIterator<Item = UnpackedKind<'tcx>> + 'a {
324         self.iter().filter_map(|k| {
325             match k.unpack() {
326                 UnpackedKind::Lifetime(_) => None,
327                 generic => Some(generic),
328             }
329         })
330     }
331
332     #[inline]
333     pub fn type_at(&self, i: usize) -> Ty<'tcx> {
334         if let UnpackedKind::Type(ty) = self[i].unpack() {
335             ty
336         } else {
337             bug!("expected type for param #{} in {:?}", i, self);
338         }
339     }
340
341     #[inline]
342     pub fn region_at(&self, i: usize) -> ty::Region<'tcx> {
343         if let UnpackedKind::Lifetime(lt) = self[i].unpack() {
344             lt
345         } else {
346             bug!("expected region for param #{} in {:?}", i, self);
347         }
348     }
349
350     #[inline]
351     pub fn const_at(&self, i: usize) -> &'tcx ty::Const<'tcx> {
352         if let UnpackedKind::Const(ct) = self[i].unpack() {
353             ct
354         } else {
355             bug!("expected const for param #{} in {:?}", i, self);
356         }
357     }
358
359     #[inline]
360     pub fn type_for_def(&self, def: &ty::GenericParamDef) -> Kind<'tcx> {
361         self.type_at(def.index as usize).into()
362     }
363
364     /// Transform from substitutions for a child of `source_ancestor`
365     /// (e.g., a trait or impl) to substitutions for the same child
366     /// in a different item, with `target_substs` as the base for
367     /// the target impl/trait, with the source child-specific
368     /// parameters (e.g., method parameters) on top of that base.
369     pub fn rebase_onto(
370         &self,
371         tcx: TyCtxt<'tcx>,
372         source_ancestor: DefId,
373         target_substs: SubstsRef<'tcx>,
374     ) -> SubstsRef<'tcx> {
375         let defs = tcx.generics_of(source_ancestor);
376         tcx.mk_substs(target_substs.iter().chain(&self[defs.params.len()..]).cloned())
377     }
378
379     pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> {
380         tcx.mk_substs(self.iter().take(generics.count()).cloned())
381     }
382 }
383
384 impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> {
385     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
386         let params: SmallVec<[_; 8]> = self.iter().map(|k| k.fold_with(folder)).collect();
387
388         // If folding doesn't change the substs, it's faster to avoid
389         // calling `mk_substs` and instead reuse the existing substs.
390         if params[..] == self[..] {
391             self
392         } else {
393             folder.tcx().intern_substs(&params)
394         }
395     }
396
397     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
398         self.iter().any(|t| t.visit_with(visitor))
399     }
400 }
401
402 impl<'tcx> rustc_serialize::UseSpecializedDecodable for SubstsRef<'tcx> {}
403
404 ///////////////////////////////////////////////////////////////////////////
405 // Public trait `Subst`
406 //
407 // Just call `foo.subst(tcx, substs)` to perform a substitution across
408 // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when
409 // there is more information available (for better errors).
410
411 pub trait Subst<'tcx>: Sized {
412     fn subst(&self, tcx: TyCtxt<'tcx>, substs: &[Kind<'tcx>]) -> Self {
413         self.subst_spanned(tcx, substs, None)
414     }
415
416     fn subst_spanned(&self, tcx: TyCtxt<'tcx>, substs: &[Kind<'tcx>], span: Option<Span>) -> Self;
417 }
418
419 impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T {
420     fn subst_spanned(&self, tcx: TyCtxt<'tcx>, substs: &[Kind<'tcx>], span: Option<Span>) -> T {
421         let mut folder = SubstFolder { tcx,
422                                        substs,
423                                        span,
424                                        root_ty: None,
425                                        ty_stack_depth: 0,
426                                        binders_passed: 0 };
427         (*self).fold_with(&mut folder)
428     }
429 }
430
431 ///////////////////////////////////////////////////////////////////////////
432 // The actual substitution engine itself is a type folder.
433
434 struct SubstFolder<'a, 'tcx> {
435     tcx: TyCtxt<'tcx>,
436     substs: &'a [Kind<'tcx>],
437
438     /// The location for which the substitution is performed, if available.
439     span: Option<Span>,
440
441     /// The root type that is being substituted, if available.
442     root_ty: Option<Ty<'tcx>>,
443
444     /// Depth of type stack
445     ty_stack_depth: usize,
446
447     /// Number of region binders we have passed through while doing the substitution
448     binders_passed: u32,
449 }
450
451 impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> {
452     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.tcx }
453
454     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
455         self.binders_passed += 1;
456         let t = t.super_fold_with(self);
457         self.binders_passed -= 1;
458         t
459     }
460
461     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
462         // Note: This routine only handles regions that are bound on
463         // type declarations and other outer declarations, not those
464         // bound in *fn types*. Region substitution of the bound
465         // regions that appear in a function signature is done using
466         // the specialized routine `ty::replace_late_regions()`.
467         match *r {
468             ty::ReEarlyBound(data) => {
469                 let rk = self.substs.get(data.index as usize).map(|k| k.unpack());
470                 match rk {
471                     Some(UnpackedKind::Lifetime(lt)) => {
472                         self.shift_region_through_binders(lt)
473                     }
474                     _ => {
475                         let span = self.span.unwrap_or(DUMMY_SP);
476                         let msg = format!(
477                             "Region parameter out of range \
478                              when substituting in region {} (root type={:?}) \
479                              (index={})",
480                             data.name,
481                             self.root_ty,
482                             data.index);
483                         self.tcx.sess.delay_span_bug(span, &msg);
484                         r
485                     }
486                 }
487             }
488             _ => r
489         }
490     }
491
492     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
493         if !t.needs_subst() {
494             return t;
495         }
496
497         // track the root type we were asked to substitute
498         let depth = self.ty_stack_depth;
499         if depth == 0 {
500             self.root_ty = Some(t);
501         }
502         self.ty_stack_depth += 1;
503
504         let t1 = match t.sty {
505             ty::Param(p) => {
506                 self.ty_for_param(p, t)
507             }
508             _ => {
509                 t.super_fold_with(self)
510             }
511         };
512
513         assert_eq!(depth + 1, self.ty_stack_depth);
514         self.ty_stack_depth -= 1;
515         if depth == 0 {
516             self.root_ty = None;
517         }
518
519         return t1;
520     }
521
522     fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
523         if !c.needs_subst() {
524             return c;
525         }
526
527         if let ConstValue::Param(p) = c.val {
528             self.const_for_param(p, c)
529         } else {
530             c.super_fold_with(self)
531         }
532     }
533 }
534
535 impl<'a, 'tcx> SubstFolder<'a, 'tcx> {
536     fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
537         // Look up the type in the substitutions. It really should be in there.
538         let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack());
539         let ty = match opt_ty {
540             Some(UnpackedKind::Type(ty)) => ty,
541             Some(kind) => {
542                 let span = self.span.unwrap_or(DUMMY_SP);
543                 span_bug!(
544                     span,
545                     "expected type for `{:?}` ({:?}/{}) but found {:?} \
546                      when substituting (root type={:?}) substs={:?}",
547                     p,
548                     source_ty,
549                     p.index,
550                     kind,
551                     self.root_ty,
552                     self.substs,
553                 );
554             }
555             None => {
556                 let span = self.span.unwrap_or(DUMMY_SP);
557                 span_bug!(
558                     span,
559                     "type parameter `{:?}` ({:?}/{}) out of range \
560                      when substituting (root type={:?}) substs={:?}",
561                     p,
562                     source_ty,
563                     p.index,
564                     self.root_ty,
565                     self.substs,
566                 );
567             }
568         };
569
570         self.shift_vars_through_binders(ty)
571     }
572
573     fn const_for_param(
574         &self,
575         p: ParamConst,
576         source_ct: &'tcx ty::Const<'tcx>
577     ) -> &'tcx ty::Const<'tcx> {
578         // Look up the const in the substitutions. It really should be in there.
579         let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack());
580         let ct = match opt_ct {
581             Some(UnpackedKind::Const(ct)) => ct,
582             Some(kind) => {
583                 let span = self.span.unwrap_or(DUMMY_SP);
584                 span_bug!(
585                     span,
586                     "expected const for `{:?}` ({:?}/{}) but found {:?} \
587                      when substituting substs={:?}",
588                     p,
589                     source_ct,
590                     p.index,
591                     kind,
592                     self.substs,
593                 );
594             }
595             None => {
596                 let span = self.span.unwrap_or(DUMMY_SP);
597                 span_bug!(
598                     span,
599                     "const parameter `{:?}` ({:?}/{}) out of range \
600                      when substituting substs={:?}",
601                     p,
602                     source_ct,
603                     p.index,
604                     self.substs,
605                 );
606             }
607         };
608
609         self.shift_vars_through_binders(ct)
610     }
611
612     /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs
613     /// when we are substituting a type with escaping bound vars into a context where we have
614     /// passed through binders. That's quite a mouthful. Let's see an example:
615     ///
616     /// ```
617     /// type Func<A> = fn(A);
618     /// type MetaFunc = for<'a> fn(Func<&'a int>)
619     /// ```
620     ///
621     /// The type `MetaFunc`, when fully expanded, will be
622     ///
623     ///     for<'a> fn(fn(&'a int))
624     ///             ^~ ^~ ^~~
625     ///             |  |  |
626     ///             |  |  DebruijnIndex of 2
627     ///             Binders
628     ///
629     /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
630     /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
631     /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the
632     /// definition of `MetaFunc`, the binder is not visible, so the type `&'a int` will have a
633     /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the
634     /// depth by 1 to account for the binder that we passed through.
635     ///
636     /// As a second example, consider this twist:
637     ///
638     /// ```
639     /// type FuncTuple<A> = (A,fn(A));
640     /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a int>)
641     /// ```
642     ///
643     /// Here the final type will be:
644     ///
645     ///     for<'a> fn((&'a int, fn(&'a int)))
646     ///                 ^~~         ^~~
647     ///                 |           |
648     ///          DebruijnIndex of 1 |
649     ///                      DebruijnIndex of 2
650     ///
651     /// As indicated in the diagram, here the same type `&'a int` is substituted once, but in the
652     /// first case we do not increase the De Bruijn index and in the second case we do. The reason
653     /// is that only in the second case have we passed through a fn binder.
654     fn shift_vars_through_binders<T: TypeFoldable<'tcx>>(&self, val: T) -> T {
655         debug!("shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})",
656                val, self.binders_passed, val.has_escaping_bound_vars());
657
658         if self.binders_passed == 0 || !val.has_escaping_bound_vars() {
659             return val;
660         }
661
662         let result = ty::fold::shift_vars(self.tcx(), &val, self.binders_passed);
663         debug!("shift_vars: shifted result = {:?}", result);
664
665         result
666     }
667
668     fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> {
669         if self.binders_passed == 0 || !region.has_escaping_bound_vars() {
670             return region;
671         }
672         ty::fold::shift_region(self.tcx, region, self.binders_passed)
673     }
674 }
675
676 pub type CanonicalUserSubsts<'tcx> = Canonical<'tcx, UserSubsts<'tcx>>;
677
678 /// Stores the user-given substs to reach some fully qualified path
679 /// (e.g., `<T>::Item` or `<T as Trait>::Item`).
680 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
681 pub struct UserSubsts<'tcx> {
682     /// The substitutions for the item as given by the user.
683     pub substs: SubstsRef<'tcx>,
684
685     /// The self type, in the case of a `<T>::Item` path (when applied
686     /// to an inherent impl). See `UserSelfTy` below.
687     pub user_self_ty: Option<UserSelfTy<'tcx>>,
688 }
689
690 BraceStructTypeFoldableImpl! {
691     impl<'tcx> TypeFoldable<'tcx> for UserSubsts<'tcx> {
692         substs,
693         user_self_ty,
694     }
695 }
696
697 BraceStructLiftImpl! {
698     impl<'a, 'tcx> Lift<'tcx> for UserSubsts<'a> {
699         type Lifted = UserSubsts<'tcx>;
700         substs,
701         user_self_ty,
702     }
703 }
704
705 /// Specifies the user-given self type. In the case of a path that
706 /// refers to a member in an inherent impl, this self type is
707 /// sometimes needed to constrain the type parameters on the impl. For
708 /// example, in this code:
709 ///
710 /// ```
711 /// struct Foo<T> { }
712 /// impl<A> Foo<A> { fn method() { } }
713 /// ```
714 ///
715 /// when you then have a path like `<Foo<&'static u32>>::method`,
716 /// this struct would carry the `DefId` of the impl along with the
717 /// self type `Foo<u32>`. Then we can instantiate the parameters of
718 /// the impl (with the substs from `UserSubsts`) and apply those to
719 /// the self type, giving `Foo<?A>`. Finally, we unify that with
720 /// the self type here, which contains `?A` to be `&'static u32`
721 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
722 pub struct UserSelfTy<'tcx> {
723     pub impl_def_id: DefId,
724     pub self_ty: Ty<'tcx>,
725 }
726
727 BraceStructTypeFoldableImpl! {
728     impl<'tcx> TypeFoldable<'tcx> for UserSelfTy<'tcx> {
729         impl_def_id,
730         self_ty,
731     }
732 }
733
734 BraceStructLiftImpl! {
735     impl<'a, 'tcx> Lift<'tcx> for UserSelfTy<'a> {
736         type Lifted = UserSelfTy<'tcx>;
737         impl_def_id,
738         self_ty,
739     }
740 }