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