1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Type substitutions.
13 pub use self::ParamSpace::*;
14 pub use self::RegionSubsts::*;
16 use middle::ty::{mod, Ty};
17 use middle::ty_fold::{mod, TypeFoldable, TypeFolder};
18 use util::ppaux::Repr;
21 use std::slice::Items;
23 use syntax::codemap::{Span, DUMMY_SP};
25 ///////////////////////////////////////////////////////////////////////////
27 /// A substitution mapping type/region parameters to new values. We
28 /// identify each in-scope parameter by an *index* and a *parameter
29 /// space* (which indices where the parameter is defined; see
31 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
32 pub struct Substs<'tcx> {
33 pub types: VecPerParamSpace<Ty<'tcx>>,
34 pub regions: RegionSubsts,
37 /// Represents the values to use when substituting lifetime parameters.
38 /// If the value is `ErasedRegions`, then this subst is occurring during
39 /// trans, and all region parameters will be replaced with `ty::ReStatic`.
40 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
41 pub enum RegionSubsts {
43 NonerasedRegions(VecPerParamSpace<ty::Region>)
46 impl<'tcx> Substs<'tcx> {
47 pub fn new(t: VecPerParamSpace<Ty<'tcx>>,
48 r: VecPerParamSpace<ty::Region>)
51 Substs { types: t, regions: NonerasedRegions(r) }
54 pub fn new_type(t: Vec<Ty<'tcx>>,
58 Substs::new(VecPerParamSpace::new(t, Vec::new(), Vec::new(), Vec::new()),
59 VecPerParamSpace::new(r, Vec::new(), Vec::new(), Vec::new()))
62 pub fn new_trait(t: Vec<Ty<'tcx>>,
68 Substs::new(VecPerParamSpace::new(t, vec!(s), a, Vec::new()),
69 VecPerParamSpace::new(r, Vec::new(), Vec::new(), Vec::new()))
72 pub fn erased(t: VecPerParamSpace<Ty<'tcx>>) -> Substs<'tcx>
74 Substs { types: t, regions: ErasedRegions }
77 pub fn empty() -> Substs<'tcx> {
79 types: VecPerParamSpace::empty(),
80 regions: NonerasedRegions(VecPerParamSpace::empty()),
84 pub fn trans_empty() -> Substs<'tcx> {
86 types: VecPerParamSpace::empty(),
87 regions: ErasedRegions
91 pub fn is_noop(&self) -> bool {
92 let regions_is_noop = match self.regions {
93 ErasedRegions => false, // may be used to canonicalize
94 NonerasedRegions(ref regions) => regions.is_empty(),
97 regions_is_noop && self.types.is_empty()
100 pub fn type_for_def(&self, ty_param_def: &ty::TypeParameterDef) -> Ty<'tcx> {
101 *self.types.get(ty_param_def.space, ty_param_def.index)
104 pub fn has_regions_escaping_depth(&self, depth: uint) -> bool {
105 self.types.iter().any(|&t| ty::type_escapes_depth(t, depth)) || {
109 NonerasedRegions(ref regions) =>
110 regions.iter().any(|r| r.escapes_depth(depth)),
115 pub fn self_ty(&self) -> Option<Ty<'tcx>> {
116 self.types.get_self().map(|&t| t)
119 pub fn with_self_ty(&self, self_ty: Ty<'tcx>) -> Substs<'tcx> {
120 assert!(self.self_ty().is_none());
121 let mut s = (*self).clone();
122 s.types.push(SelfSpace, self_ty);
126 pub fn erase_regions(self) -> Substs<'tcx> {
127 let Substs { types, regions: _ } = self;
128 Substs { types: types, regions: ErasedRegions }
131 /// Since ErasedRegions are only to be used in trans, most of the compiler can use this method
132 /// to easily access the set of region substitutions.
133 pub fn regions<'a>(&'a self) -> &'a VecPerParamSpace<ty::Region> {
135 ErasedRegions => panic!("Erased regions only expected in trans"),
136 NonerasedRegions(ref r) => r
140 /// Since ErasedRegions are only to be used in trans, most of the compiler can use this method
141 /// to easily access the set of region substitutions.
142 pub fn mut_regions<'a>(&'a mut self) -> &'a mut VecPerParamSpace<ty::Region> {
144 ErasedRegions => panic!("Erased regions only expected in trans"),
145 NonerasedRegions(ref mut r) => r
149 pub fn with_method(self,
150 m_types: Vec<Ty<'tcx>>,
151 m_regions: Vec<ty::Region>)
154 let Substs { types, regions } = self;
155 let types = types.with_vec(FnSpace, m_types);
156 let regions = regions.map(m_regions,
157 |r, m_regions| r.with_vec(FnSpace, m_regions));
158 Substs { types: types, regions: regions }
165 op: |VecPerParamSpace<ty::Region>, A| -> VecPerParamSpace<ty::Region>)
168 ErasedRegions => ErasedRegions,
169 NonerasedRegions(r) => NonerasedRegions(op(r, a))
173 pub fn is_erased(&self) -> bool {
175 ErasedRegions => true,
176 NonerasedRegions(_) => false,
181 ///////////////////////////////////////////////////////////////////////////
184 #[deriving(PartialOrd, Ord, PartialEq, Eq,
185 Clone, Hash, Encodable, Decodable, Show)]
186 pub enum ParamSpace {
187 TypeSpace, // Type parameters attached to a type definition, trait, or impl
188 SelfSpace, // Self parameter on a trait
189 AssocSpace, // Assoc types defined in a trait/impl
190 FnSpace, // Type parameters attached to a method or fn
194 pub fn all() -> [ParamSpace, ..4] {
195 [TypeSpace, SelfSpace, AssocSpace, FnSpace]
198 pub fn to_uint(self) -> uint {
207 pub fn from_uint(u: uint) -> ParamSpace {
213 _ => panic!("Invalid ParamSpace: {}", u)
218 /// Vector of things sorted by param space. Used to keep
219 /// the set of things declared on the type, self, or method
221 #[deriving(PartialEq, Eq, Clone, Hash, Encodable, Decodable)]
222 pub struct VecPerParamSpace<T> {
223 // This was originally represented as a tuple with one Vec<T> for
224 // each variant of ParamSpace, and that remains the abstraction
225 // that it provides to its clients.
227 // Here is how the representation corresponds to the abstraction
228 // i.e. the "abstraction function" AF:
230 // AF(self) = (self.content[..self.type_limit],
231 // self.content[self.type_limit..self.self_limit],
232 // self.content[self.self_limit..self.assoc_limit],
233 // self.content[self.assoc_limit..])
240 /// The `split` function converts one `VecPerParamSpace` into this
241 /// `SeparateVecsPerParamSpace` structure.
242 pub struct SeparateVecsPerParamSpace<T> {
249 impl<T:fmt::Show> fmt::Show for VecPerParamSpace<T> {
250 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
251 try!(write!(fmt, "VecPerParamSpace {{"));
252 for space in ParamSpace::all().iter() {
253 try!(write!(fmt, "{}: {}, ", *space, self.get_slice(*space)));
255 try!(write!(fmt, "}}"));
260 impl<T> VecPerParamSpace<T> {
261 fn limits(&self, space: ParamSpace) -> (uint, uint) {
263 TypeSpace => (0, self.type_limit),
264 SelfSpace => (self.type_limit, self.self_limit),
265 AssocSpace => (self.self_limit, self.assoc_limit),
266 FnSpace => (self.assoc_limit, self.content.len()),
270 pub fn empty() -> VecPerParamSpace<T> {
279 pub fn params_from_type(types: Vec<T>) -> VecPerParamSpace<T> {
280 VecPerParamSpace::empty().with_vec(TypeSpace, types)
283 /// `t` is the type space.
284 /// `s` is the self space.
285 /// `a` is the assoc space.
286 /// `f` is the fn space.
287 pub fn new(t: Vec<T>, s: Vec<T>, a: Vec<T>, f: Vec<T>) -> VecPerParamSpace<T> {
288 let type_limit = t.len();
289 let self_limit = type_limit + s.len();
290 let assoc_limit = self_limit + a.len();
293 content.extend(s.into_iter());
294 content.extend(a.into_iter());
295 content.extend(f.into_iter());
298 type_limit: type_limit,
299 self_limit: self_limit,
300 assoc_limit: assoc_limit,
305 fn new_internal(content: Vec<T>, type_limit: uint, self_limit: uint, assoc_limit: uint)
306 -> VecPerParamSpace<T>
309 type_limit: type_limit,
310 self_limit: self_limit,
311 assoc_limit: assoc_limit,
316 /// Appends `value` to the vector associated with `space`.
318 /// Unlike the `push` method in `Vec`, this should not be assumed
319 /// to be a cheap operation (even when amortized over many calls).
320 pub fn push(&mut self, space: ParamSpace, value: T) {
321 let (_, limit) = self.limits(space);
323 TypeSpace => { self.type_limit += 1; self.self_limit += 1; self.assoc_limit += 1; }
324 SelfSpace => { self.self_limit += 1; self.assoc_limit += 1; }
325 AssocSpace => { self.assoc_limit += 1; }
328 self.content.insert(limit, value);
331 pub fn pop(&mut self, space: ParamSpace) -> Option<T> {
332 let (start, limit) = self.limits(space);
337 TypeSpace => { self.type_limit -= 1; self.self_limit -= 1; self.assoc_limit -= 1; }
338 SelfSpace => { self.self_limit -= 1; self.assoc_limit -= 1; }
339 AssocSpace => { self.assoc_limit -= 1; }
342 self.content.remove(limit - 1)
346 pub fn truncate(&mut self, space: ParamSpace, len: uint) {
347 // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
348 while self.len(space) > len {
353 pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) {
354 // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
355 self.truncate(space, 0);
356 for t in elems.into_iter() {
361 pub fn get_self<'a>(&'a self) -> Option<&'a T> {
362 let v = self.get_slice(SelfSpace);
363 assert!(v.len() <= 1);
364 if v.len() == 0 { None } else { Some(&v[0]) }
367 pub fn len(&self, space: ParamSpace) -> uint {
368 self.get_slice(space).len()
371 pub fn is_empty_in(&self, space: ParamSpace) -> bool {
375 pub fn get_slice<'a>(&'a self, space: ParamSpace) -> &'a [T] {
376 let (start, limit) = self.limits(space);
377 self.content.slice(start, limit)
380 pub fn get_mut_slice<'a>(&'a mut self, space: ParamSpace) -> &'a mut [T] {
381 let (start, limit) = self.limits(space);
382 self.content.slice_mut(start, limit)
385 pub fn opt_get<'a>(&'a self,
389 let v = self.get_slice(space);
390 if index < v.len() { Some(&v[index]) } else { None }
393 pub fn get<'a>(&'a self, space: ParamSpace, index: uint) -> &'a T {
394 &self.get_slice(space)[index]
397 pub fn iter<'a>(&'a self) -> Items<'a,T> {
401 pub fn iter_enumerated<'a>(&'a self) -> EnumeratedItems<'a,T> {
402 EnumeratedItems::new(self)
405 pub fn as_slice(&self) -> &[T] {
406 self.content.as_slice()
409 pub fn all_vecs(&self, pred: |&[T]| -> bool) -> bool {
410 let spaces = [TypeSpace, SelfSpace, FnSpace];
411 spaces.iter().all(|&space| { pred(self.get_slice(space)) })
414 pub fn all(&self, pred: |&T| -> bool) -> bool {
415 self.iter().all(pred)
418 pub fn any(&self, pred: |&T| -> bool) -> bool {
419 self.iter().any(pred)
422 pub fn is_empty(&self) -> bool {
423 self.all_vecs(|v| v.is_empty())
426 pub fn map<U>(&self, pred: |&T| -> U) -> VecPerParamSpace<U> {
427 let result = self.iter().map(pred).collect();
428 VecPerParamSpace::new_internal(result,
434 pub fn map_enumerated<U>(&self, pred: |(ParamSpace, uint, &T)| -> U) -> VecPerParamSpace<U> {
435 let result = self.iter_enumerated().map(pred).collect();
436 VecPerParamSpace::new_internal(result,
442 pub fn map_move<U>(self, pred: |T| -> U) -> VecPerParamSpace<U> {
443 let SeparateVecsPerParamSpace {
450 VecPerParamSpace::new(t.into_iter().map(|p| pred(p)).collect(),
451 s.into_iter().map(|p| pred(p)).collect(),
452 a.into_iter().map(|p| pred(p)).collect(),
453 f.into_iter().map(|p| pred(p)).collect())
456 pub fn split(self) -> SeparateVecsPerParamSpace<T> {
457 let VecPerParamSpace { type_limit, self_limit, assoc_limit, content } = self;
459 let mut content_iter = content.into_iter();
461 SeparateVecsPerParamSpace {
462 types: content_iter.by_ref().take(type_limit).collect(),
463 selfs: content_iter.by_ref().take(self_limit - type_limit).collect(),
464 assocs: content_iter.by_ref().take(assoc_limit - self_limit).collect(),
465 fns: content_iter.collect()
469 pub fn with_vec(mut self, space: ParamSpace, vec: Vec<T>)
470 -> VecPerParamSpace<T>
472 assert!(self.is_empty_in(space));
473 self.replace(space, vec);
478 pub struct EnumeratedItems<'a,T:'a> {
479 vec: &'a VecPerParamSpace<T>,
484 impl<'a,T> EnumeratedItems<'a,T> {
485 fn new(v: &'a VecPerParamSpace<T>) -> EnumeratedItems<'a,T> {
486 let mut result = EnumeratedItems { vec: v, space_index: 0, elem_index: 0 };
487 result.adjust_space();
491 fn adjust_space(&mut self) {
492 let spaces = ParamSpace::all();
494 self.space_index < spaces.len() &&
495 self.elem_index >= self.vec.len(spaces[self.space_index])
497 self.space_index += 1;
503 impl<'a,T> Iterator<(ParamSpace, uint, &'a T)> for EnumeratedItems<'a,T> {
504 fn next(&mut self) -> Option<(ParamSpace, uint, &'a T)> {
505 let spaces = ParamSpace::all();
506 if self.space_index < spaces.len() {
507 let space = spaces[self.space_index];
508 let index = self.elem_index;
509 let item = self.vec.get(space, index);
511 self.elem_index += 1;
514 Some((space, index, item))
521 ///////////////////////////////////////////////////////////////////////////
522 // Public trait `Subst`
524 // Just call `foo.subst(tcx, substs)` to perform a substitution across
525 // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when
526 // there is more information available (for better errors).
528 pub trait Subst<'tcx> {
529 fn subst(&self, tcx: &ty::ctxt<'tcx>, substs: &Substs<'tcx>) -> Self {
530 self.subst_spanned(tcx, substs, None)
533 fn subst_spanned(&self, tcx: &ty::ctxt<'tcx>,
534 substs: &Substs<'tcx>,
539 impl<'tcx, T:TypeFoldable<'tcx>> Subst<'tcx> for T {
540 fn subst_spanned(&self,
541 tcx: &ty::ctxt<'tcx>,
542 substs: &Substs<'tcx>,
546 let mut folder = SubstFolder { tcx: tcx,
551 region_binders_passed: 0 };
552 (*self).fold_with(&mut folder)
556 ///////////////////////////////////////////////////////////////////////////
557 // The actual substitution engine itself is a type folder.
559 struct SubstFolder<'a, 'tcx: 'a> {
560 tcx: &'a ty::ctxt<'tcx>,
561 substs: &'a Substs<'tcx>,
563 // The location for which the substitution is performed, if available.
566 // The root type that is being substituted, if available.
567 root_ty: Option<Ty<'tcx>>,
569 // Depth of type stack
570 ty_stack_depth: uint,
572 // Number of region binders we have passed through while doing the substitution
573 region_binders_passed: uint,
576 impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> {
577 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx }
579 fn enter_region_binder(&mut self) {
580 self.region_binders_passed += 1;
583 fn exit_region_binder(&mut self) {
584 self.region_binders_passed -= 1;
587 fn fold_region(&mut self, r: ty::Region) -> ty::Region {
588 // Note: This routine only handles regions that are bound on
589 // type declarations and other outer declarations, not those
590 // bound in *fn types*. Region substitution of the bound
591 // regions that appear in a function signature is done using
592 // the specialized routine `ty::replace_late_regions()`.
594 ty::ReEarlyBound(_, space, i, region_name) => {
595 match self.substs.regions {
596 ErasedRegions => ty::ReStatic,
597 NonerasedRegions(ref regions) =>
598 match regions.opt_get(space, i) {
600 self.shift_region_through_binders(r)
603 let span = self.span.unwrap_or(DUMMY_SP);
604 self.tcx().sess.span_bug(
606 format!("Type parameter out of range \
607 when substituting in region {} (root type={}) \
608 (space={}, index={})",
609 region_name.as_str(),
610 self.root_ty.repr(self.tcx()),
611 space, i).as_slice());
620 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
621 if !ty::type_needs_subst(t) {
625 // track the root type we were asked to substitute
626 let depth = self.ty_stack_depth;
628 self.root_ty = Some(t);
630 self.ty_stack_depth += 1;
632 let t1 = match t.sty {
634 self.ty_for_param(p, t)
637 ty_fold::super_fold_ty(self, t)
641 assert_eq!(depth + 1, self.ty_stack_depth);
642 self.ty_stack_depth -= 1;
651 impl<'a,'tcx> SubstFolder<'a,'tcx> {
652 fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
653 // Look up the type in the substitutions. It really should be in there.
654 let opt_ty = self.substs.types.opt_get(p.space, p.idx);
655 let ty = match opt_ty {
658 let span = self.span.unwrap_or(DUMMY_SP);
659 self.tcx().sess.span_bug(
661 format!("Type parameter `{}` ({}/{}/{}) out of range \
662 when substituting (root type={}) substs={}",
664 source_ty.repr(self.tcx()),
667 self.root_ty.repr(self.tcx()),
668 self.substs.repr(self.tcx())).as_slice());
672 self.shift_regions_through_binders(ty)
675 /// It is sometimes necessary to adjust the debruijn indices during substitution. This occurs
676 /// when we are substituting a type with escaping regions into a context where we have passed
677 /// through region binders. That's quite a mouthful. Let's see an example:
680 /// type Func<A> = fn(A);
681 /// type MetaFunc = for<'a> fn(Func<&'a int>)
684 /// The type `MetaFunc`, when fully expanded, will be
686 /// for<'a> fn(fn(&'a int))
689 /// | | DebruijnIndex of 2
692 /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
693 /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
694 /// over the inner binder (remember that we count Debruijn indices from 1). However, in the
695 /// definition of `MetaFunc`, the binder is not visible, so the type `&'a int` will have a
696 /// debruijn index of 1. It's only during the substitution that we can see we must increase the
697 /// depth by 1 to account for the binder that we passed through.
699 /// As a second example, consider this twist:
702 /// type FuncTuple<A> = (A,fn(A));
703 /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a int>)
706 /// Here the final type will be:
708 /// for<'a> fn((&'a int, fn(&'a int)))
711 /// DebruijnIndex of 1 |
712 /// DebruijnIndex of 2
714 /// As indicated in the diagram, here the same type `&'a int` is substituted once, but in the
715 /// first case we do not increase the Debruijn index and in the second case we do. The reason
716 /// is that only in the second case have we passed through a fn binder.
717 fn shift_regions_through_binders(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
718 debug!("shift_regions(ty={}, region_binders_passed={}, type_has_escaping_regions={})",
719 ty.repr(self.tcx()), self.region_binders_passed, ty::type_has_escaping_regions(ty));
721 if self.region_binders_passed == 0 || !ty::type_has_escaping_regions(ty) {
725 let result = ty_fold::shift_regions(self.tcx(), self.region_binders_passed, &ty);
726 debug!("shift_regions: shifted result = {}", result.repr(self.tcx()));
731 fn shift_region_through_binders(&self, region: ty::Region) -> ty::Region {
732 ty_fold::shift_region(region, self.region_binders_passed)