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.
15 use middle::ty_fold::{TypeFoldable, TypeFolder};
16 use util::ppaux::Repr;
21 use std::slice::{Items, MutItems};
23 use syntax::codemap::{Span, DUMMY_SP};
25 ///////////////////////////////////////////////////////////////////////////
26 // HomogeneousTuple3 trait
28 // This could be moved into standard library at some point.
30 trait HomogeneousTuple3<T> {
31 fn len(&self) -> uint;
32 fn as_slice<'a>(&'a self) -> &'a [T];
33 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T];
34 fn iter<'a>(&'a self) -> Items<'a, T>;
35 fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T>;
36 fn get<'a>(&'a self, index: uint) -> Option<&'a T>;
37 fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T>;
40 impl<T> HomogeneousTuple3<T> for (T, T, T) {
41 fn len(&self) -> uint {
45 fn as_slice<'a>(&'a self) -> &'a [T] {
47 let ptr: *const T = mem::transmute(self);
48 let slice = raw::Slice { data: ptr, len: 3 };
53 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
55 let ptr: *const T = mem::transmute(self);
56 let slice = raw::Slice { data: ptr, len: 3 };
61 fn iter<'a>(&'a self) -> Items<'a, T> {
62 let slice: &'a [T] = self.as_slice();
66 fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
67 self.as_mut_slice().iter_mut()
70 fn get<'a>(&'a self, index: uint) -> Option<&'a T> {
71 self.as_slice().get(index)
74 fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> {
75 Some(&mut self.as_mut_slice()[index]) // wrong: fallible
79 ///////////////////////////////////////////////////////////////////////////
82 * A substitution mapping type/region parameters to new values. We
83 * identify each in-scope parameter by an *index* and a *parameter
84 * space* (which indices where the parameter is defined; see
87 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
89 pub types: VecPerParamSpace<ty::t>,
90 pub regions: RegionSubsts,
94 * Represents the values to use when substituting lifetime parameters.
95 * If the value is `ErasedRegions`, then this subst is occurring during
96 * trans, and all region parameters will be replaced with `ty::ReStatic`. */
97 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
98 pub enum RegionSubsts {
100 NonerasedRegions(VecPerParamSpace<ty::Region>)
104 pub fn new(t: VecPerParamSpace<ty::t>,
105 r: VecPerParamSpace<ty::Region>)
108 Substs { types: t, regions: NonerasedRegions(r) }
111 pub fn new_type(t: Vec<ty::t>,
115 Substs::new(VecPerParamSpace::new(t, Vec::new(), Vec::new()),
116 VecPerParamSpace::new(r, Vec::new(), Vec::new()))
119 pub fn new_trait(t: Vec<ty::t>,
124 Substs::new(VecPerParamSpace::new(t, vec!(s), Vec::new()),
125 VecPerParamSpace::new(r, Vec::new(), Vec::new()))
128 pub fn erased(t: VecPerParamSpace<ty::t>) -> Substs
130 Substs { types: t, regions: ErasedRegions }
133 pub fn empty() -> Substs {
135 types: VecPerParamSpace::empty(),
136 regions: NonerasedRegions(VecPerParamSpace::empty()),
140 pub fn trans_empty() -> Substs {
142 types: VecPerParamSpace::empty(),
143 regions: ErasedRegions
147 pub fn is_noop(&self) -> bool {
148 let regions_is_noop = match self.regions {
149 ErasedRegions => false, // may be used to canonicalize
150 NonerasedRegions(ref regions) => regions.is_empty(),
153 regions_is_noop && self.types.is_empty()
156 pub fn self_ty(&self) -> Option<ty::t> {
157 self.types.get_self().map(|&t| t)
160 pub fn with_self_ty(&self, self_ty: ty::t) -> Substs {
161 assert!(self.self_ty().is_none());
162 let mut s = (*self).clone();
163 s.types.push(SelfSpace, self_ty);
167 pub fn erase_regions(self) -> Substs {
168 let Substs { types, regions: _ } = self;
169 Substs { types: types, regions: ErasedRegions }
172 pub fn regions<'a>(&'a self) -> &'a VecPerParamSpace<ty::Region> {
174 * Since ErasedRegions are only to be used in trans, most of
175 * the compiler can use this method to easily access the set
176 * of region substitutions.
180 ErasedRegions => fail!("Erased regions only expected in trans"),
181 NonerasedRegions(ref r) => r
185 pub fn mut_regions<'a>(&'a mut self) -> &'a mut VecPerParamSpace<ty::Region> {
187 * Since ErasedRegions are only to be used in trans, most of
188 * the compiler can use this method to easily access the set
189 * of region substitutions.
193 ErasedRegions => fail!("Erased regions only expected in trans"),
194 NonerasedRegions(ref mut r) => r
198 pub fn with_method(self,
200 m_regions: Vec<ty::Region>)
203 let Substs { types, regions } = self;
204 let types = types.with_vec(FnSpace, m_types);
205 let regions = regions.map(m_regions,
206 |r, m_regions| r.with_vec(FnSpace, m_regions));
207 Substs { types: types, regions: regions }
214 op: |VecPerParamSpace<ty::Region>, A| -> VecPerParamSpace<ty::Region>)
217 ErasedRegions => ErasedRegions,
218 NonerasedRegions(r) => NonerasedRegions(op(r, a))
223 ///////////////////////////////////////////////////////////////////////////
226 #[deriving(PartialOrd, Ord, PartialEq, Eq,
227 Clone, Hash, Encodable, Decodable, Show)]
228 pub enum ParamSpace {
229 TypeSpace, // Type parameters attached to a type definition, trait, or impl
230 SelfSpace, // Self parameter on a trait
231 FnSpace, // Type parameters attached to a method or fn
235 pub fn all() -> [ParamSpace, ..3] {
236 [TypeSpace, SelfSpace, FnSpace]
239 pub fn to_uint(self) -> uint {
247 pub fn from_uint(u: uint) -> ParamSpace {
252 _ => fail!("Invalid ParamSpace: {}", u)
258 * Vector of things sorted by param space. Used to keep
259 * the set of things declared on the type, self, or method
262 #[deriving(PartialEq, Eq, Clone, Hash, Encodable, Decodable)]
263 pub struct VecPerParamSpace<T> {
264 // This was originally represented as a tuple with one Vec<T> for
265 // each variant of ParamSpace, and that remains the abstraction
266 // that it provides to its clients.
268 // Here is how the representation corresponds to the abstraction
269 // i.e. the "abstraction function" AF:
271 // AF(self) = (self.content.slice_to(self.type_limit),
272 // self.content.slice(self.type_limit, self.self_limit),
273 // self.content.slice_from(self.self_limit))
279 impl<T:fmt::Show> fmt::Show for VecPerParamSpace<T> {
280 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
281 try!(write!(fmt, "VecPerParamSpace {{"));
282 for space in ParamSpace::all().iter() {
283 try!(write!(fmt, "{}: {}, ", *space, self.get_slice(*space)));
285 try!(write!(fmt, "}}"));
290 impl<T> VecPerParamSpace<T> {
291 fn limits(&self, space: ParamSpace) -> (uint, uint) {
293 TypeSpace => (0, self.type_limit),
294 SelfSpace => (self.type_limit, self.self_limit),
295 FnSpace => (self.self_limit, self.content.len()),
299 pub fn empty() -> VecPerParamSpace<T> {
307 pub fn params_from_type(types: Vec<T>) -> VecPerParamSpace<T> {
308 VecPerParamSpace::empty().with_vec(TypeSpace, types)
311 /// `t` is the type space.
312 /// `s` is the self space.
313 /// `f` is the fn space.
314 pub fn new(t: Vec<T>, s: Vec<T>, f: Vec<T>) -> VecPerParamSpace<T> {
315 let type_limit = t.len();
316 let self_limit = t.len() + s.len();
318 content.extend(s.into_iter());
319 content.extend(f.into_iter());
321 type_limit: type_limit,
322 self_limit: self_limit,
327 fn new_internal(content: Vec<T>, type_limit: uint, self_limit: uint)
328 -> VecPerParamSpace<T>
331 type_limit: type_limit,
332 self_limit: self_limit,
337 /// Appends `value` to the vector associated with `space`.
339 /// Unlike the `push` method in `Vec`, this should not be assumed
340 /// to be a cheap operation (even when amortized over many calls).
341 pub fn push(&mut self, space: ParamSpace, value: T) {
342 let (_, limit) = self.limits(space);
344 TypeSpace => { self.type_limit += 1; self.self_limit += 1; }
345 SelfSpace => { self.self_limit += 1; }
348 self.content.insert(limit, value);
351 pub fn pop(&mut self, space: ParamSpace) -> Option<T> {
352 let (start, limit) = self.limits(space);
357 TypeSpace => { self.type_limit -= 1; self.self_limit -= 1; }
358 SelfSpace => { self.self_limit -= 1; }
361 self.content.remove(limit - 1)
365 pub fn truncate(&mut self, space: ParamSpace, len: uint) {
366 // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
367 while self.len(space) > len {
372 pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) {
373 // FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
374 self.truncate(space, 0);
375 for t in elems.into_iter() {
380 pub fn get_self<'a>(&'a self) -> Option<&'a T> {
381 let v = self.get_slice(SelfSpace);
382 assert!(v.len() <= 1);
383 if v.len() == 0 { None } else { Some(&v[0]) }
386 pub fn len(&self, space: ParamSpace) -> uint {
387 self.get_slice(space).len()
390 pub fn is_empty_in(&self, space: ParamSpace) -> bool {
394 pub fn get_slice<'a>(&'a self, space: ParamSpace) -> &'a [T] {
395 let (start, limit) = self.limits(space);
396 self.content.slice(start, limit)
399 pub fn get_mut_slice<'a>(&'a mut self, space: ParamSpace) -> &'a mut [T] {
400 let (start, limit) = self.limits(space);
401 self.content.slice_mut(start, limit)
404 pub fn opt_get<'a>(&'a self,
408 let v = self.get_slice(space);
409 if index < v.len() { Some(&v[index]) } else { None }
412 pub fn get<'a>(&'a self, space: ParamSpace, index: uint) -> &'a T {
413 &self.get_slice(space)[index]
416 pub fn iter<'a>(&'a self) -> Items<'a,T> {
420 pub fn as_slice(&self) -> &[T] {
421 self.content.as_slice()
424 pub fn all_vecs(&self, pred: |&[T]| -> bool) -> bool {
425 let spaces = [TypeSpace, SelfSpace, FnSpace];
426 spaces.iter().all(|&space| { pred(self.get_slice(space)) })
429 pub fn all(&self, pred: |&T| -> bool) -> bool {
430 self.iter().all(pred)
433 pub fn any(&self, pred: |&T| -> bool) -> bool {
434 self.iter().any(pred)
437 pub fn is_empty(&self) -> bool {
438 self.all_vecs(|v| v.is_empty())
441 pub fn map<U>(&self, pred: |&T| -> U) -> VecPerParamSpace<U> {
442 let result = self.iter().map(pred).collect();
443 VecPerParamSpace::new_internal(result,
448 pub fn map_move<U>(self, pred: |T| -> U) -> VecPerParamSpace<U> {
449 let (t, s, f) = self.split();
450 VecPerParamSpace::new(t.into_iter().map(|p| pred(p)).collect(),
451 s.into_iter().map(|p| pred(p)).collect(),
452 f.into_iter().map(|p| pred(p)).collect())
455 pub fn split(self) -> (Vec<T>, Vec<T>, Vec<T>) {
456 // FIXME (#15418): this does two traversals when in principle
457 // one would suffice. i.e. change to use `move_iter`.
458 let VecPerParamSpace { type_limit, self_limit, content } = self;
460 let (prefix, fn_vec) = content.partition(|_| {
461 let on_left = i < self_limit;
467 let (type_vec, self_vec) = prefix.partition(|_| {
468 let on_left = i < type_limit;
473 (type_vec, self_vec, fn_vec)
476 pub fn with_vec(mut self, space: ParamSpace, vec: Vec<T>)
477 -> VecPerParamSpace<T>
479 assert!(self.is_empty_in(space));
480 self.replace(space, vec);
485 ///////////////////////////////////////////////////////////////////////////
486 // Public trait `Subst`
488 // Just call `foo.subst(tcx, substs)` to perform a substitution across
489 // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when
490 // there is more information available (for better errors).
493 fn subst(&self, tcx: &ty::ctxt, substs: &Substs) -> Self {
494 self.subst_spanned(tcx, substs, None)
497 fn subst_spanned(&self, tcx: &ty::ctxt,
503 impl<T:TypeFoldable> Subst for T {
504 fn subst_spanned(&self,
510 let mut folder = SubstFolder { tcx: tcx,
515 (*self).fold_with(&mut folder)
519 ///////////////////////////////////////////////////////////////////////////
520 // The actual substitution engine itself is a type folder.
522 struct SubstFolder<'a, 'tcx: 'a> {
523 tcx: &'a ty::ctxt<'tcx>,
526 // The location for which the substitution is performed, if available.
529 // The root type that is being substituted, if available.
530 root_ty: Option<ty::t>,
532 // Depth of type stack
533 ty_stack_depth: uint,
536 impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> {
537 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx }
539 fn fold_region(&mut self, r: ty::Region) -> ty::Region {
540 // Note: This routine only handles regions that are bound on
541 // type declarations and other outer declarations, not those
542 // bound in *fn types*. Region substitution of the bound
543 // regions that appear in a function signature is done using
544 // the specialized routine
545 // `middle::typeck::check::regionmanip::replace_late_regions_in_fn_sig()`.
547 ty::ReEarlyBound(_, space, i, region_name) => {
548 match self.substs.regions {
549 ErasedRegions => ty::ReStatic,
550 NonerasedRegions(ref regions) =>
551 match regions.opt_get(space, i) {
554 let span = self.span.unwrap_or(DUMMY_SP);
555 self.tcx().sess.span_bug(
557 format!("Type parameter out of range \
558 when substituting in region {} (root type={}) \
559 (space={}, index={})",
560 region_name.as_str(),
561 self.root_ty.repr(self.tcx()),
562 space, i).as_slice());
571 fn fold_ty(&mut self, t: ty::t) -> ty::t {
572 if !ty::type_needs_subst(t) {
576 // track the root type we were asked to substitute
577 let depth = self.ty_stack_depth;
579 self.root_ty = Some(t);
581 self.ty_stack_depth += 1;
583 let t1 = match ty::get(t).sty {
588 self.substs.types.opt_get(p.space, p.idx),
593 ty_fold::super_fold_ty(self, t)
597 assert_eq!(depth + 1, self.ty_stack_depth);
598 self.ty_stack_depth -= 1;
605 fn check(this: &SubstFolder,
608 opt_ty: Option<&ty::t>,
615 let span = this.span.unwrap_or(DUMMY_SP);
616 this.tcx().sess.span_bug(
618 format!("Type parameter `{}` ({}/{}/{}) out of range \
619 when substituting (root type={})",
621 source_ty.repr(this.tcx()),
624 this.root_ty.repr(this.tcx())).as_slice());