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