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