]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/subst.rs
More methods for str boxes.
[rust.git] / src / librustc / ty / subst.rs
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.
4 //
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.
10
11 // Type substitutions.
12
13 use hir::def_id::DefId;
14 use ty::{self, Slice, Ty, TyCtxt};
15 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
16
17 use serialize::{self, Encodable, Encoder, Decodable, Decoder};
18 use syntax_pos::{Span, DUMMY_SP};
19 use rustc_data_structures::accumulate_vec::AccumulateVec;
20
21 use core::nonzero::NonZero;
22 use std::fmt;
23 use std::iter;
24 use std::marker::PhantomData;
25 use std::mem;
26
27 /// An entity in the Rust typesystem, which can be one of
28 /// several kinds (only types and lifetimes for now).
29 /// To reduce memory usage, a `Kind` is a interned pointer,
30 /// with the lowest 2 bits being reserved for a tag to
31 /// indicate the type (`Ty` or `Region`) it points to.
32 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
33 pub struct Kind<'tcx> {
34     ptr: NonZero<usize>,
35     marker: PhantomData<(Ty<'tcx>, &'tcx ty::Region)>
36 }
37
38 const TAG_MASK: usize = 0b11;
39 const TYPE_TAG: usize = 0b00;
40 const REGION_TAG: usize = 0b01;
41
42 impl<'tcx> From<Ty<'tcx>> for Kind<'tcx> {
43     fn from(ty: Ty<'tcx>) -> Kind<'tcx> {
44         // Ensure we can use the tag bits.
45         assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0);
46
47         let ptr = ty as *const _ as usize;
48         Kind {
49             ptr: unsafe {
50                 NonZero::new(ptr | TYPE_TAG)
51             },
52             marker: PhantomData
53         }
54     }
55 }
56
57 impl<'tcx> From<&'tcx ty::Region> for Kind<'tcx> {
58     fn from(r: &'tcx ty::Region) -> Kind<'tcx> {
59         // Ensure we can use the tag bits.
60         assert_eq!(mem::align_of_val(r) & TAG_MASK, 0);
61
62         let ptr = r as *const _ as usize;
63         Kind {
64             ptr: unsafe {
65                 NonZero::new(ptr | REGION_TAG)
66             },
67             marker: PhantomData
68         }
69     }
70 }
71
72 impl<'tcx> Kind<'tcx> {
73     #[inline]
74     unsafe fn downcast<T>(self, tag: usize) -> Option<&'tcx T> {
75         let ptr = *self.ptr;
76         if ptr & TAG_MASK == tag {
77             Some(&*((ptr & !TAG_MASK) as *const _))
78         } else {
79             None
80         }
81     }
82
83     #[inline]
84     pub fn as_type(self) -> Option<Ty<'tcx>> {
85         unsafe {
86             self.downcast(TYPE_TAG)
87         }
88     }
89
90     #[inline]
91     pub fn as_region(self) -> Option<&'tcx ty::Region> {
92         unsafe {
93             self.downcast(REGION_TAG)
94         }
95     }
96 }
97
98 impl<'tcx> fmt::Debug for Kind<'tcx> {
99     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100         if let Some(ty) = self.as_type() {
101             write!(f, "{:?}", ty)
102         } else if let Some(r) = self.as_region() {
103             write!(f, "{:?}", r)
104         } else {
105             write!(f, "<unknwon @ {:p}>", *self.ptr as *const ())
106         }
107     }
108 }
109
110 impl<'tcx> TypeFoldable<'tcx> for Kind<'tcx> {
111     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
112         if let Some(ty) = self.as_type() {
113             Kind::from(ty.fold_with(folder))
114         } else if let Some(r) = self.as_region() {
115             Kind::from(r.fold_with(folder))
116         } else {
117             bug!()
118         }
119     }
120
121     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
122         if let Some(ty) = self.as_type() {
123             ty.visit_with(visitor)
124         } else if let Some(r) = self.as_region() {
125             r.visit_with(visitor)
126         } else {
127             bug!()
128         }
129     }
130 }
131
132 impl<'tcx> Encodable for Kind<'tcx> {
133     fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
134         e.emit_enum("Kind", |e| {
135             if let Some(ty) = self.as_type() {
136                 e.emit_enum_variant("Ty", TYPE_TAG, 1, |e| {
137                     e.emit_enum_variant_arg(0, |e| ty.encode(e))
138                 })
139             } else if let Some(r) = self.as_region() {
140                 e.emit_enum_variant("Region", REGION_TAG, 1, |e| {
141                     e.emit_enum_variant_arg(0, |e| r.encode(e))
142                 })
143             } else {
144                 bug!()
145             }
146         })
147     }
148 }
149
150 impl<'tcx> Decodable for Kind<'tcx> {
151     fn decode<D: Decoder>(d: &mut D) -> Result<Kind<'tcx>, D::Error> {
152         d.read_enum("Kind", |d| {
153             d.read_enum_variant(&["Ty", "Region"], |d, tag| {
154                 match tag {
155                     TYPE_TAG => Ty::decode(d).map(Kind::from),
156                     REGION_TAG => <&ty::Region>::decode(d).map(Kind::from),
157                     _ => Err(d.error("invalid Kind tag"))
158                 }
159             })
160         })
161     }
162 }
163
164 /// A substitution mapping type/region parameters to new values.
165 pub type Substs<'tcx> = Slice<Kind<'tcx>>;
166
167 impl<'a, 'gcx, 'tcx> Substs<'tcx> {
168     /// Creates a Substs that maps each generic parameter to itself.
169     pub fn identity_for_item(tcx: TyCtxt<'a, 'gcx, 'tcx>, def_id: DefId)
170                              -> &'tcx Substs<'tcx> {
171         Substs::for_item(tcx, def_id, |def, _| {
172             tcx.mk_region(ty::ReEarlyBound(def.to_early_bound_region_data()))
173         }, |def, _| tcx.mk_param_from_def(def))
174     }
175
176     /// Creates a Substs for generic parameter definitions,
177     /// by calling closures to obtain each region and type.
178     /// The closures get to observe the Substs as they're
179     /// being built, which can be used to correctly
180     /// substitute defaults of type parameters.
181     pub fn for_item<FR, FT>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
182                             def_id: DefId,
183                             mut mk_region: FR,
184                             mut mk_type: FT)
185                             -> &'tcx Substs<'tcx>
186     where FR: FnMut(&ty::RegionParameterDef, &[Kind<'tcx>]) -> &'tcx ty::Region,
187           FT: FnMut(&ty::TypeParameterDef, &[Kind<'tcx>]) -> Ty<'tcx> {
188         let defs = tcx.item_generics(def_id);
189         let mut substs = Vec::with_capacity(defs.count());
190         Substs::fill_item(&mut substs, tcx, defs, &mut mk_region, &mut mk_type);
191         tcx.intern_substs(&substs)
192     }
193
194     pub fn extend_to<FR, FT>(&self,
195                              tcx: TyCtxt<'a, 'gcx, 'tcx>,
196                              def_id: DefId,
197                              mut mk_region: FR,
198                              mut mk_type: FT)
199                              -> &'tcx Substs<'tcx>
200     where FR: FnMut(&ty::RegionParameterDef, &[Kind<'tcx>]) -> &'tcx ty::Region,
201           FT: FnMut(&ty::TypeParameterDef, &[Kind<'tcx>]) -> Ty<'tcx>
202     {
203         let defs = tcx.item_generics(def_id);
204         let mut result = Vec::with_capacity(defs.count());
205         result.extend(self[..].iter().cloned());
206         Substs::fill_single(&mut result, defs, &mut mk_region, &mut mk_type);
207         tcx.intern_substs(&result)
208     }
209
210     fn fill_item<FR, FT>(substs: &mut Vec<Kind<'tcx>>,
211                          tcx: TyCtxt<'a, 'gcx, 'tcx>,
212                          defs: &ty::Generics,
213                          mk_region: &mut FR,
214                          mk_type: &mut FT)
215     where FR: FnMut(&ty::RegionParameterDef, &[Kind<'tcx>]) -> &'tcx ty::Region,
216           FT: FnMut(&ty::TypeParameterDef, &[Kind<'tcx>]) -> Ty<'tcx> {
217
218         if let Some(def_id) = defs.parent {
219             let parent_defs = tcx.item_generics(def_id);
220             Substs::fill_item(substs, tcx, parent_defs, mk_region, mk_type);
221         }
222         Substs::fill_single(substs, defs, mk_region, mk_type)
223     }
224
225     fn fill_single<FR, FT>(substs: &mut Vec<Kind<'tcx>>,
226                            defs: &ty::Generics,
227                            mk_region: &mut FR,
228                            mk_type: &mut FT)
229     where FR: FnMut(&ty::RegionParameterDef, &[Kind<'tcx>]) -> &'tcx ty::Region,
230           FT: FnMut(&ty::TypeParameterDef, &[Kind<'tcx>]) -> Ty<'tcx> {
231         // Handle Self first, before all regions.
232         let mut types = defs.types.iter();
233         if defs.parent.is_none() && defs.has_self {
234             let def = types.next().unwrap();
235             let ty = mk_type(def, substs);
236             assert_eq!(def.index as usize, substs.len());
237             substs.push(Kind::from(ty));
238         }
239
240         for def in &defs.regions {
241             let region = mk_region(def, substs);
242             assert_eq!(def.index as usize, substs.len());
243             substs.push(Kind::from(region));
244         }
245
246         for def in types {
247             let ty = mk_type(def, substs);
248             assert_eq!(def.index as usize, substs.len());
249             substs.push(Kind::from(ty));
250         }
251     }
252
253     pub fn is_noop(&self) -> bool {
254         self.is_empty()
255     }
256
257     #[inline]
258     pub fn types(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
259         self.iter().filter_map(|k| k.as_type())
260     }
261
262     #[inline]
263     pub fn regions(&'a self) -> impl DoubleEndedIterator<Item=&'tcx ty::Region> + 'a {
264         self.iter().filter_map(|k| k.as_region())
265     }
266
267     #[inline]
268     pub fn type_at(&self, i: usize) -> Ty<'tcx> {
269         self[i].as_type().unwrap_or_else(|| {
270             bug!("expected type for param #{} in {:?}", i, self);
271         })
272     }
273
274     #[inline]
275     pub fn region_at(&self, i: usize) -> &'tcx ty::Region {
276         self[i].as_region().unwrap_or_else(|| {
277             bug!("expected region for param #{} in {:?}", i, self);
278         })
279     }
280
281     #[inline]
282     pub fn type_for_def(&self, ty_param_def: &ty::TypeParameterDef) -> Ty<'tcx> {
283         self.type_at(ty_param_def.index as usize)
284     }
285
286     #[inline]
287     pub fn region_for_def(&self, def: &ty::RegionParameterDef) -> &'tcx ty::Region {
288         self.region_at(def.index as usize)
289     }
290
291     /// Transform from substitutions for a child of `source_ancestor`
292     /// (e.g. a trait or impl) to substitutions for the same child
293     /// in a different item, with `target_substs` as the base for
294     /// the target impl/trait, with the source child-specific
295     /// parameters (e.g. method parameters) on top of that base.
296     pub fn rebase_onto(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
297                        source_ancestor: DefId,
298                        target_substs: &Substs<'tcx>)
299                        -> &'tcx Substs<'tcx> {
300         let defs = tcx.item_generics(source_ancestor);
301         tcx.mk_substs(target_substs.iter().chain(&self[defs.own_count()..]).cloned())
302     }
303
304     pub fn truncate_to(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, generics: &ty::Generics)
305                        -> &'tcx Substs<'tcx> {
306         tcx.mk_substs(self.iter().take(generics.count()).cloned())
307     }
308 }
309
310 impl<'tcx> TypeFoldable<'tcx> for &'tcx Substs<'tcx> {
311     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
312         let params: AccumulateVec<[_; 8]> = self.iter().map(|k| k.fold_with(folder)).collect();
313
314         // If folding doesn't change the substs, it's faster to avoid
315         // calling `mk_substs` and instead reuse the existing substs.
316         if params[..] == self[..] {
317             self
318         } else {
319             folder.tcx().intern_substs(&params)
320         }
321     }
322
323     fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
324         folder.fold_substs(self)
325     }
326
327     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
328         self.iter().any(|t| t.visit_with(visitor))
329     }
330 }
331
332 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Substs<'tcx> {}
333
334 ///////////////////////////////////////////////////////////////////////////
335 // Public trait `Subst`
336 //
337 // Just call `foo.subst(tcx, substs)` to perform a substitution across
338 // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when
339 // there is more information available (for better errors).
340
341 pub trait Subst<'tcx> : Sized {
342     fn subst<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
343                       substs: &[Kind<'tcx>]) -> Self {
344         self.subst_spanned(tcx, substs, None)
345     }
346
347     fn subst_spanned<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
348                                substs: &[Kind<'tcx>],
349                                span: Option<Span>)
350                                -> Self;
351 }
352
353 impl<'tcx, T:TypeFoldable<'tcx>> Subst<'tcx> for T {
354     fn subst_spanned<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
355                                substs: &[Kind<'tcx>],
356                                span: Option<Span>)
357                                -> T
358     {
359         let mut folder = SubstFolder { tcx: tcx,
360                                        substs: substs,
361                                        span: span,
362                                        root_ty: None,
363                                        ty_stack_depth: 0,
364                                        region_binders_passed: 0 };
365         (*self).fold_with(&mut folder)
366     }
367 }
368
369 ///////////////////////////////////////////////////////////////////////////
370 // The actual substitution engine itself is a type folder.
371
372 struct SubstFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
373     tcx: TyCtxt<'a, 'gcx, 'tcx>,
374     substs: &'a [Kind<'tcx>],
375
376     // The location for which the substitution is performed, if available.
377     span: Option<Span>,
378
379     // The root type that is being substituted, if available.
380     root_ty: Option<Ty<'tcx>>,
381
382     // Depth of type stack
383     ty_stack_depth: usize,
384
385     // Number of region binders we have passed through while doing the substitution
386     region_binders_passed: u32,
387 }
388
389 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for SubstFolder<'a, 'gcx, 'tcx> {
390     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
391
392     fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> {
393         self.region_binders_passed += 1;
394         let t = t.super_fold_with(self);
395         self.region_binders_passed -= 1;
396         t
397     }
398
399     fn fold_region(&mut self, r: &'tcx ty::Region) -> &'tcx ty::Region {
400         // Note: This routine only handles regions that are bound on
401         // type declarations and other outer declarations, not those
402         // bound in *fn types*. Region substitution of the bound
403         // regions that appear in a function signature is done using
404         // the specialized routine `ty::replace_late_regions()`.
405         match *r {
406             ty::ReEarlyBound(data) => {
407                 let r = self.substs.get(data.index as usize)
408                             .and_then(|k| k.as_region());
409                 match r {
410                     Some(r) => {
411                         self.shift_region_through_binders(r)
412                     }
413                     None => {
414                         let span = self.span.unwrap_or(DUMMY_SP);
415                         span_bug!(
416                             span,
417                             "Region parameter out of range \
418                              when substituting in region {} (root type={:?}) \
419                              (index={})",
420                             data.name,
421                             self.root_ty,
422                             data.index);
423                     }
424                 }
425             }
426             _ => r
427         }
428     }
429
430     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
431         if !t.needs_subst() {
432             return t;
433         }
434
435         // track the root type we were asked to substitute
436         let depth = self.ty_stack_depth;
437         if depth == 0 {
438             self.root_ty = Some(t);
439         }
440         self.ty_stack_depth += 1;
441
442         let t1 = match t.sty {
443             ty::TyParam(p) => {
444                 self.ty_for_param(p, t)
445             }
446             _ => {
447                 t.super_fold_with(self)
448             }
449         };
450
451         assert_eq!(depth + 1, self.ty_stack_depth);
452         self.ty_stack_depth -= 1;
453         if depth == 0 {
454             self.root_ty = None;
455         }
456
457         return t1;
458     }
459 }
460
461 impl<'a, 'gcx, 'tcx> SubstFolder<'a, 'gcx, 'tcx> {
462     fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> {
463         // Look up the type in the substitutions. It really should be in there.
464         let opt_ty = self.substs.get(p.idx as usize)
465                          .and_then(|k| k.as_type());
466         let ty = match opt_ty {
467             Some(t) => t,
468             None => {
469                 let span = self.span.unwrap_or(DUMMY_SP);
470                 span_bug!(
471                     span,
472                     "Type parameter `{:?}` ({:?}/{}) out of range \
473                          when substituting (root type={:?}) substs={:?}",
474                     p,
475                     source_ty,
476                     p.idx,
477                     self.root_ty,
478                     self.substs);
479             }
480         };
481
482         self.shift_regions_through_binders(ty)
483     }
484
485     /// It is sometimes necessary to adjust the debruijn indices during substitution. This occurs
486     /// when we are substituting a type with escaping regions into a context where we have passed
487     /// through region binders. That's quite a mouthful. Let's see an example:
488     ///
489     /// ```
490     /// type Func<A> = fn(A);
491     /// type MetaFunc = for<'a> fn(Func<&'a int>)
492     /// ```
493     ///
494     /// The type `MetaFunc`, when fully expanded, will be
495     ///
496     ///     for<'a> fn(fn(&'a int))
497     ///             ^~ ^~ ^~~
498     ///             |  |  |
499     ///             |  |  DebruijnIndex of 2
500     ///             Binders
501     ///
502     /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the
503     /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip
504     /// over the inner binder (remember that we count Debruijn indices from 1). However, in the
505     /// definition of `MetaFunc`, the binder is not visible, so the type `&'a int` will have a
506     /// debruijn index of 1. It's only during the substitution that we can see we must increase the
507     /// depth by 1 to account for the binder that we passed through.
508     ///
509     /// As a second example, consider this twist:
510     ///
511     /// ```
512     /// type FuncTuple<A> = (A,fn(A));
513     /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a int>)
514     /// ```
515     ///
516     /// Here the final type will be:
517     ///
518     ///     for<'a> fn((&'a int, fn(&'a int)))
519     ///                 ^~~         ^~~
520     ///                 |           |
521     ///          DebruijnIndex of 1 |
522     ///                      DebruijnIndex of 2
523     ///
524     /// As indicated in the diagram, here the same type `&'a int` is substituted once, but in the
525     /// first case we do not increase the Debruijn index and in the second case we do. The reason
526     /// is that only in the second case have we passed through a fn binder.
527     fn shift_regions_through_binders(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
528         debug!("shift_regions(ty={:?}, region_binders_passed={:?}, has_escaping_regions={:?})",
529                ty, self.region_binders_passed, ty.has_escaping_regions());
530
531         if self.region_binders_passed == 0 || !ty.has_escaping_regions() {
532             return ty;
533         }
534
535         let result = ty::fold::shift_regions(self.tcx(), self.region_binders_passed, &ty);
536         debug!("shift_regions: shifted result = {:?}", result);
537
538         result
539     }
540
541     fn shift_region_through_binders(&self, region: &'tcx ty::Region) -> &'tcx ty::Region {
542         self.tcx().mk_region(ty::fold::shift_region(*region, self.region_binders_passed))
543     }
544 }
545
546 // Helper methods that modify substitutions.
547
548 impl<'a, 'gcx, 'tcx> ty::TraitRef<'tcx> {
549     pub fn from_method(tcx: TyCtxt<'a, 'gcx, 'tcx>,
550                        trait_id: DefId,
551                        substs: &Substs<'tcx>)
552                        -> ty::TraitRef<'tcx> {
553         let defs = tcx.item_generics(trait_id);
554
555         ty::TraitRef {
556             def_id: trait_id,
557             substs: tcx.intern_substs(&substs[..defs.own_count()])
558         }
559     }
560 }
561
562 impl<'a, 'gcx, 'tcx> ty::ExistentialTraitRef<'tcx> {
563     pub fn erase_self_ty(tcx: TyCtxt<'a, 'gcx, 'tcx>,
564                          trait_ref: ty::TraitRef<'tcx>)
565                          -> ty::ExistentialTraitRef<'tcx> {
566         // Assert there is a Self.
567         trait_ref.substs.type_at(0);
568
569         ty::ExistentialTraitRef {
570             def_id: trait_ref.def_id,
571             substs: tcx.intern_substs(&trait_ref.substs[1..])
572         }
573     }
574 }
575
576 impl<'a, 'gcx, 'tcx> ty::PolyExistentialTraitRef<'tcx> {
577     /// Object types don't have a self-type specified. Therefore, when
578     /// we convert the principal trait-ref into a normal trait-ref,
579     /// you must give *some* self-type. A common choice is `mk_err()`
580     /// or some skolemized type.
581     pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
582                         self_ty: Ty<'tcx>)
583                         -> ty::PolyTraitRef<'tcx>  {
584         // otherwise the escaping regions would be captured by the binder
585         assert!(!self_ty.has_escaping_regions());
586
587         self.map_bound(|trait_ref| {
588             ty::TraitRef {
589                 def_id: trait_ref.def_id,
590                 substs: tcx.mk_substs(
591                     iter::once(Kind::from(self_ty)).chain(trait_ref.substs.iter().cloned()))
592             }
593         })
594     }
595 }