]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty_fold.rs
debuginfo: Make debuginfo source location assignment more stable (Pt. 1)
[rust.git] / src / librustc / middle / ty_fold.rs
1 // Copyright 2012-2013 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 //! Generalized type folding mechanism. The setup is a bit convoluted
12 //! but allows for convenient usage. Let T be an instance of some
13 //! "foldable type" (one which implements `TypeFoldable`) and F be an
14 //! instance of a "folder" (a type which implements `TypeFolder`). Then
15 //! the setup is intended to be:
16 //!
17 //!     T.fold_with(F) --calls--> F.fold_T(T) --calls--> super_fold_T(F, T)
18 //!
19 //! This way, when you define a new folder F, you can override
20 //! `fold_T()` to customize the behavior, and invoke `super_fold_T()`
21 //! to get the original behavior. Meanwhile, to actually fold
22 //! something, you can just write `T.fold_with(F)`, which is
23 //! convenient. (Note that `fold_with` will also transparently handle
24 //! things like a `Vec<T>` where T is foldable and so on.)
25 //!
26 //! In this ideal setup, the only function that actually *does*
27 //! anything is `super_fold_T`, which traverses the type `T`. Moreover,
28 //! `super_fold_T` should only ever call `T.fold_with()`.
29 //!
30 //! In some cases, we follow a degenerate pattern where we do not have
31 //! a `fold_T` nor `super_fold_T` method. Instead, `T.fold_with`
32 //! traverses the structure directly. This is suboptimal because the
33 //! behavior cannot be overridden, but it's much less work to implement.
34 //! If you ever *do* need an override that doesn't exist, it's not hard
35 //! to convert the degenerate pattern into the proper thing.
36
37 use middle::subst;
38 use middle::subst::VecPerParamSpace;
39 use middle::ty::{self, Ty};
40 use middle::traits;
41 use std::rc::Rc;
42 use syntax::owned_slice::OwnedSlice;
43 use util::ppaux::Repr;
44
45 ///////////////////////////////////////////////////////////////////////////
46 // Two generic traits
47
48 /// The TypeFoldable trait is implemented for every type that can be folded.
49 /// Basically, every type that has a corresponding method in TypeFolder.
50 pub trait TypeFoldable<'tcx> {
51     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self;
52 }
53
54 /// The TypeFolder trait defines the actual *folding*. There is a
55 /// method defined for every foldable type. Each of these has a
56 /// default implementation that does an "identity" fold. Within each
57 /// identity fold, it should invoke `foo.fold_with(self)` to fold each
58 /// sub-item.
59 pub trait TypeFolder<'tcx> : Sized {
60     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
61
62     /// Invoked by the `super_*` routines when we enter a region
63     /// binding level (for example, when entering a function
64     /// signature). This is used by clients that want to track the
65     /// Debruijn index nesting level.
66     fn enter_region_binder(&mut self) { }
67
68     /// Invoked by the `super_*` routines when we exit a region
69     /// binding level. This is used by clients that want to
70     /// track the Debruijn index nesting level.
71     fn exit_region_binder(&mut self) { }
72
73     fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
74         where T : TypeFoldable<'tcx> + Repr<'tcx>
75     {
76         // FIXME(#20526) this should replace `enter_region_binder`/`exit_region_binder`.
77         super_fold_binder(self, t)
78     }
79
80     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
81         super_fold_ty(self, t)
82     }
83
84     fn fold_mt(&mut self, t: &ty::mt<'tcx>) -> ty::mt<'tcx> {
85         super_fold_mt(self, t)
86     }
87
88     fn fold_trait_ref(&mut self, t: &ty::TraitRef<'tcx>) -> ty::TraitRef<'tcx> {
89         super_fold_trait_ref(self, t)
90     }
91
92     fn fold_substs(&mut self,
93                    substs: &subst::Substs<'tcx>)
94                    -> subst::Substs<'tcx> {
95         super_fold_substs(self, substs)
96     }
97
98     fn fold_fn_sig(&mut self,
99                    sig: &ty::FnSig<'tcx>)
100                    -> ty::FnSig<'tcx> {
101         super_fold_fn_sig(self, sig)
102     }
103
104     fn fold_output(&mut self,
105                       output: &ty::FnOutput<'tcx>)
106                       -> ty::FnOutput<'tcx> {
107         super_fold_output(self, output)
108     }
109
110     fn fold_bare_fn_ty(&mut self,
111                        fty: &ty::BareFnTy<'tcx>)
112                        -> ty::BareFnTy<'tcx>
113     {
114         super_fold_bare_fn_ty(self, fty)
115     }
116
117     fn fold_closure_ty(&mut self,
118                        fty: &ty::ClosureTy<'tcx>)
119                        -> ty::ClosureTy<'tcx> {
120         super_fold_closure_ty(self, fty)
121     }
122
123     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
124         r
125     }
126
127     fn fold_trait_store(&mut self, s: ty::TraitStore) -> ty::TraitStore {
128         super_fold_trait_store(self, s)
129     }
130
131     fn fold_existential_bounds(&mut self, s: &ty::ExistentialBounds<'tcx>)
132                                -> ty::ExistentialBounds<'tcx> {
133         super_fold_existential_bounds(self, s)
134     }
135
136     fn fold_autoref(&mut self, ar: &ty::AutoRef<'tcx>) -> ty::AutoRef<'tcx> {
137         super_fold_autoref(self, ar)
138     }
139
140     fn fold_item_substs(&mut self, i: ty::ItemSubsts<'tcx>) -> ty::ItemSubsts<'tcx> {
141         super_fold_item_substs(self, i)
142     }
143 }
144
145 ///////////////////////////////////////////////////////////////////////////
146 // TypeFoldable implementations.
147 //
148 // Ideally, each type should invoke `folder.fold_foo(self)` and
149 // nothing else. In some cases, though, we haven't gotten around to
150 // adding methods on the `folder` yet, and thus the folding is
151 // hard-coded here. This is less-flexible, because folders cannot
152 // override the behavior, but there are a lot of random types and one
153 // can easily refactor the folding into the TypeFolder trait as
154 // needed.
155
156 impl<'tcx> TypeFoldable<'tcx> for () {
157     fn fold_with<F:TypeFolder<'tcx>>(&self, _: &mut F) -> () {
158         ()
159     }
160 }
161
162 impl<'tcx, T:TypeFoldable<'tcx>, U:TypeFoldable<'tcx>> TypeFoldable<'tcx> for (T, U) {
163     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> (T, U) {
164         (self.0.fold_with(folder), self.1.fold_with(folder))
165     }
166 }
167
168 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Option<T> {
169     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Option<T> {
170         self.as_ref().map(|t| t.fold_with(folder))
171     }
172 }
173
174 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Rc<T> {
175     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Rc<T> {
176         Rc::new((**self).fold_with(folder))
177     }
178 }
179
180 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<T> {
181     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Box<T> {
182         let content: T = (**self).fold_with(folder);
183         box content
184     }
185 }
186
187 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec<T> {
188     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Vec<T> {
189         self.iter().map(|t| t.fold_with(folder)).collect()
190     }
191 }
192
193 impl<'tcx, T:TypeFoldable<'tcx>+Repr<'tcx>> TypeFoldable<'tcx> for ty::Binder<T> {
194     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Binder<T> {
195         folder.fold_binder(self)
196     }
197 }
198
199 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for OwnedSlice<T> {
200     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> OwnedSlice<T> {
201         self.iter().map(|t| t.fold_with(folder)).collect()
202     }
203 }
204
205 impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for VecPerParamSpace<T> {
206     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> VecPerParamSpace<T> {
207
208         // Things in the Fn space take place under an additional level
209         // of region binding relative to the other spaces. This is
210         // because those entries are attached to a method, and methods
211         // always introduce a level of region binding.
212
213         let result = self.map_enumerated(|(space, index, elem)| {
214             if space == subst::FnSpace && index == 0 {
215                 // enter new level when/if we reach the first thing in fn space
216                 folder.enter_region_binder();
217             }
218             elem.fold_with(folder)
219         });
220         if result.len(subst::FnSpace) > 0 {
221             // if there was anything in fn space, exit the region binding level
222             folder.exit_region_binder();
223         }
224         result
225     }
226 }
227
228 impl<'tcx> TypeFoldable<'tcx> for ty::TraitStore {
229     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TraitStore {
230         folder.fold_trait_store(*self)
231     }
232 }
233
234 impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> {
235     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Ty<'tcx> {
236         folder.fold_ty(*self)
237     }
238 }
239
240 impl<'tcx> TypeFoldable<'tcx> for ty::BareFnTy<'tcx> {
241     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::BareFnTy<'tcx> {
242         folder.fold_bare_fn_ty(self)
243     }
244 }
245
246 impl<'tcx> TypeFoldable<'tcx> for ty::ClosureTy<'tcx> {
247     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ClosureTy<'tcx> {
248         folder.fold_closure_ty(self)
249     }
250 }
251
252 impl<'tcx> TypeFoldable<'tcx> for ty::mt<'tcx> {
253     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::mt<'tcx> {
254         folder.fold_mt(self)
255     }
256 }
257
258 impl<'tcx> TypeFoldable<'tcx> for ty::FnOutput<'tcx> {
259     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::FnOutput<'tcx> {
260         folder.fold_output(self)
261     }
262 }
263
264 impl<'tcx> TypeFoldable<'tcx> for ty::FnSig<'tcx> {
265     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::FnSig<'tcx> {
266         folder.fold_fn_sig(self)
267     }
268 }
269
270 impl<'tcx> TypeFoldable<'tcx> for ty::TraitRef<'tcx> {
271     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TraitRef<'tcx> {
272         folder.fold_trait_ref(self)
273     }
274 }
275
276 impl<'tcx> TypeFoldable<'tcx> for ty::field<'tcx> {
277     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::field<'tcx> {
278         ty::field {
279             name: self.name,
280             mt: self.mt.fold_with(folder),
281         }
282     }
283 }
284
285 impl<'tcx> TypeFoldable<'tcx> for ty::Region {
286     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Region {
287         folder.fold_region(*self)
288     }
289 }
290
291 impl<'tcx> TypeFoldable<'tcx> for subst::Substs<'tcx> {
292     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> subst::Substs<'tcx> {
293         folder.fold_substs(self)
294     }
295 }
296
297 impl<'tcx> TypeFoldable<'tcx> for ty::ItemSubsts<'tcx> {
298     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ItemSubsts<'tcx> {
299         ty::ItemSubsts {
300             substs: self.substs.fold_with(folder),
301         }
302     }
303 }
304
305 impl<'tcx> TypeFoldable<'tcx> for ty::AutoRef<'tcx> {
306     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::AutoRef<'tcx> {
307         folder.fold_autoref(self)
308     }
309 }
310
311 impl<'tcx> TypeFoldable<'tcx> for ty::MethodOrigin<'tcx> {
312     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::MethodOrigin<'tcx> {
313         match *self {
314             ty::MethodStatic(def_id) => {
315                 ty::MethodStatic(def_id)
316             }
317             ty::MethodStaticUnboxedClosure(def_id) => {
318                 ty::MethodStaticUnboxedClosure(def_id)
319             }
320             ty::MethodTypeParam(ref param) => {
321                 ty::MethodTypeParam(ty::MethodParam {
322                     trait_ref: param.trait_ref.fold_with(folder),
323                     method_num: param.method_num
324                 })
325             }
326             ty::MethodTraitObject(ref object) => {
327                 ty::MethodTraitObject(ty::MethodObject {
328                     trait_ref: object.trait_ref.fold_with(folder),
329                     object_trait_id: object.object_trait_id,
330                     method_num: object.method_num,
331                     real_index: object.real_index
332                 })
333             }
334         }
335     }
336 }
337
338 impl<'tcx> TypeFoldable<'tcx> for ty::vtable_origin<'tcx> {
339     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::vtable_origin<'tcx> {
340         match *self {
341             ty::vtable_static(def_id, ref substs, ref origins) => {
342                 let r_substs = substs.fold_with(folder);
343                 let r_origins = origins.fold_with(folder);
344                 ty::vtable_static(def_id, r_substs, r_origins)
345             }
346             ty::vtable_param(n, b) => {
347                 ty::vtable_param(n, b)
348             }
349             ty::vtable_unboxed_closure(def_id) => {
350                 ty::vtable_unboxed_closure(def_id)
351             }
352             ty::vtable_error => {
353                 ty::vtable_error
354             }
355         }
356     }
357 }
358
359 impl<'tcx> TypeFoldable<'tcx> for ty::BuiltinBounds {
360     fn fold_with<F: TypeFolder<'tcx>>(&self, _folder: &mut F) -> ty::BuiltinBounds {
361         *self
362     }
363 }
364
365 impl<'tcx> TypeFoldable<'tcx> for ty::ExistentialBounds<'tcx> {
366     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ExistentialBounds<'tcx> {
367         folder.fold_existential_bounds(self)
368     }
369 }
370
371 impl<'tcx> TypeFoldable<'tcx> for ty::ParamBounds<'tcx> {
372     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ParamBounds<'tcx> {
373         ty::ParamBounds {
374             region_bounds: self.region_bounds.fold_with(folder),
375             builtin_bounds: self.builtin_bounds.fold_with(folder),
376             trait_bounds: self.trait_bounds.fold_with(folder),
377             projection_bounds: self.projection_bounds.fold_with(folder),
378         }
379     }
380 }
381
382 impl<'tcx> TypeFoldable<'tcx> for ty::TypeParameterDef<'tcx> {
383     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TypeParameterDef<'tcx> {
384         ty::TypeParameterDef {
385             name: self.name,
386             def_id: self.def_id,
387             space: self.space,
388             index: self.index,
389             bounds: self.bounds.fold_with(folder),
390             default: self.default.fold_with(folder),
391         }
392     }
393 }
394
395 impl<'tcx> TypeFoldable<'tcx> for ty::RegionParameterDef {
396     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::RegionParameterDef {
397         ty::RegionParameterDef {
398             name: self.name,
399             def_id: self.def_id,
400             space: self.space,
401             index: self.index,
402             bounds: self.bounds.fold_with(folder)
403         }
404     }
405 }
406
407 impl<'tcx> TypeFoldable<'tcx> for ty::Generics<'tcx> {
408     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Generics<'tcx> {
409         ty::Generics {
410             types: self.types.fold_with(folder),
411             regions: self.regions.fold_with(folder),
412             predicates: self.predicates.fold_with(folder),
413         }
414     }
415 }
416
417 impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> {
418     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Predicate<'tcx> {
419         match *self {
420             ty::Predicate::Trait(ref a) =>
421                 ty::Predicate::Trait(a.fold_with(folder)),
422             ty::Predicate::Equate(ref binder) =>
423                 ty::Predicate::Equate(binder.fold_with(folder)),
424             ty::Predicate::RegionOutlives(ref binder) =>
425                 ty::Predicate::RegionOutlives(binder.fold_with(folder)),
426             ty::Predicate::TypeOutlives(ref binder) =>
427                 ty::Predicate::TypeOutlives(binder.fold_with(folder)),
428             ty::Predicate::Projection(ref binder) =>
429                 ty::Predicate::Projection(binder.fold_with(folder)),
430         }
431     }
432 }
433
434 impl<'tcx> TypeFoldable<'tcx> for ty::ProjectionPredicate<'tcx> {
435     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ProjectionPredicate<'tcx> {
436         ty::ProjectionPredicate {
437             projection_ty: self.projection_ty.fold_with(folder),
438             ty: self.ty.fold_with(folder),
439         }
440     }
441 }
442
443 impl<'tcx> TypeFoldable<'tcx> for ty::ProjectionTy<'tcx> {
444     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ProjectionTy<'tcx> {
445         ty::ProjectionTy {
446             trait_ref: self.trait_ref.fold_with(folder),
447             item_name: self.item_name,
448         }
449     }
450 }
451
452 impl<'tcx> TypeFoldable<'tcx> for ty::GenericBounds<'tcx> {
453     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::GenericBounds<'tcx> {
454         ty::GenericBounds {
455             predicates: self.predicates.fold_with(folder),
456         }
457     }
458 }
459
460 impl<'tcx> TypeFoldable<'tcx> for ty::UnsizeKind<'tcx> {
461     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::UnsizeKind<'tcx> {
462         match *self {
463             ty::UnsizeLength(len) => ty::UnsizeLength(len),
464             ty::UnsizeStruct(box ref k, n) => ty::UnsizeStruct(box k.fold_with(folder), n),
465             ty::UnsizeVtable(ty::TyTrait{ref principal, ref bounds}, self_ty) => {
466                 ty::UnsizeVtable(
467                     ty::TyTrait {
468                         principal: principal.fold_with(folder),
469                         bounds: bounds.fold_with(folder),
470                     },
471                     self_ty.fold_with(folder))
472             }
473         }
474     }
475 }
476
477 impl<'tcx,O> TypeFoldable<'tcx> for traits::Obligation<'tcx,O>
478     where O : TypeFoldable<'tcx>
479 {
480     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::Obligation<'tcx, O> {
481         traits::Obligation {
482             cause: self.cause.clone(),
483             recursion_depth: self.recursion_depth,
484             predicate: self.predicate.fold_with(folder),
485         }
486     }
487 }
488
489 impl<'tcx, N: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::VtableImplData<'tcx, N> {
490     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableImplData<'tcx, N> {
491         traits::VtableImplData {
492             impl_def_id: self.impl_def_id,
493             substs: self.substs.fold_with(folder),
494             nested: self.nested.fold_with(folder),
495         }
496     }
497 }
498
499 impl<'tcx, N: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::VtableBuiltinData<N> {
500     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableBuiltinData<N> {
501         traits::VtableBuiltinData {
502             nested: self.nested.fold_with(folder),
503         }
504     }
505 }
506
507 impl<'tcx, N: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::Vtable<'tcx, N> {
508     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::Vtable<'tcx, N> {
509         match *self {
510             traits::VtableImpl(ref v) => traits::VtableImpl(v.fold_with(folder)),
511             traits::VtableUnboxedClosure(d, ref s) => {
512                 traits::VtableUnboxedClosure(d, s.fold_with(folder))
513             }
514             traits::VtableFnPointer(ref d) => {
515                 traits::VtableFnPointer(d.fold_with(folder))
516             }
517             traits::VtableParam(ref n) => traits::VtableParam(n.fold_with(folder)),
518             traits::VtableBuiltin(ref d) => traits::VtableBuiltin(d.fold_with(folder)),
519             traits::VtableObject(ref d) => traits::VtableObject(d.fold_with(folder)),
520         }
521     }
522 }
523
524 impl<'tcx> TypeFoldable<'tcx> for traits::VtableObjectData<'tcx> {
525     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableObjectData<'tcx> {
526         traits::VtableObjectData {
527             object_ty: self.object_ty.fold_with(folder)
528         }
529     }
530 }
531
532 impl<'tcx> TypeFoldable<'tcx> for ty::EquatePredicate<'tcx> {
533     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::EquatePredicate<'tcx> {
534         ty::EquatePredicate(self.0.fold_with(folder),
535                             self.1.fold_with(folder))
536     }
537 }
538
539 impl<'tcx> TypeFoldable<'tcx> for ty::TraitPredicate<'tcx> {
540     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TraitPredicate<'tcx> {
541         ty::TraitPredicate {
542             trait_ref: self.trait_ref.fold_with(folder)
543         }
544     }
545 }
546
547 impl<'tcx,T,U> TypeFoldable<'tcx> for ty::OutlivesPredicate<T,U>
548     where T : TypeFoldable<'tcx>,
549           U : TypeFoldable<'tcx>,
550 {
551     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::OutlivesPredicate<T,U> {
552         ty::OutlivesPredicate(self.0.fold_with(folder),
553                               self.1.fold_with(folder))
554     }
555 }
556
557 impl<'tcx> TypeFoldable<'tcx> for ty::UnboxedClosureUpvar<'tcx> {
558     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::UnboxedClosureUpvar<'tcx> {
559         ty::UnboxedClosureUpvar {
560             def: self.def,
561             span: self.span,
562             ty: self.ty.fold_with(folder),
563         }
564     }
565 }
566
567 impl<'a, 'tcx> TypeFoldable<'tcx> for ty::ParameterEnvironment<'a, 'tcx> where 'tcx: 'a {
568     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ParameterEnvironment<'a, 'tcx> {
569         ty::ParameterEnvironment {
570             tcx: self.tcx,
571             free_substs: self.free_substs.fold_with(folder),
572             implicit_region_bound: self.implicit_region_bound.fold_with(folder),
573             caller_bounds: self.caller_bounds.fold_with(folder),
574             selection_cache: traits::SelectionCache::new(),
575         }
576     }
577 }
578
579 ///////////////////////////////////////////////////////////////////////////
580 // "super" routines: these are the default implementations for TypeFolder.
581 //
582 // They should invoke `foo.fold_with()` to do recursive folding.
583
584 pub fn super_fold_binder<'tcx, T, U>(this: &mut T,
585                                      binder: &ty::Binder<U>)
586                                      -> ty::Binder<U>
587     where T : TypeFolder<'tcx>, U : TypeFoldable<'tcx>
588 {
589     this.enter_region_binder();
590     let result = ty::Binder(binder.0.fold_with(this));
591     this.exit_region_binder();
592     result
593 }
594
595 pub fn super_fold_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
596                                                 ty: Ty<'tcx>)
597                                                 -> Ty<'tcx> {
598     let sty = match ty.sty {
599         ty::ty_uniq(typ) => {
600             ty::ty_uniq(typ.fold_with(this))
601         }
602         ty::ty_ptr(ref tm) => {
603             ty::ty_ptr(tm.fold_with(this))
604         }
605         ty::ty_vec(typ, sz) => {
606             ty::ty_vec(typ.fold_with(this), sz)
607         }
608         ty::ty_open(typ) => {
609             ty::ty_open(typ.fold_with(this))
610         }
611         ty::ty_enum(tid, ref substs) => {
612             let substs = substs.fold_with(this);
613             ty::ty_enum(tid, this.tcx().mk_substs(substs))
614         }
615         ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
616             ty::ty_trait(box ty::TyTrait {
617                 principal: principal.fold_with(this),
618                 bounds: bounds.fold_with(this),
619             })
620         }
621         ty::ty_tup(ref ts) => {
622             ty::ty_tup(ts.fold_with(this))
623         }
624         ty::ty_bare_fn(opt_def_id, ref f) => {
625             let bfn = f.fold_with(this);
626             ty::ty_bare_fn(opt_def_id, this.tcx().mk_bare_fn(bfn))
627         }
628         ty::ty_rptr(r, ref tm) => {
629             let r = r.fold_with(this);
630             ty::ty_rptr(this.tcx().mk_region(r), tm.fold_with(this))
631         }
632         ty::ty_struct(did, ref substs) => {
633             let substs = substs.fold_with(this);
634             ty::ty_struct(did, this.tcx().mk_substs(substs))
635         }
636         ty::ty_unboxed_closure(did, ref region, ref substs) => {
637             let r = region.fold_with(this);
638             let s = substs.fold_with(this);
639             ty::ty_unboxed_closure(did, this.tcx().mk_region(r), this.tcx().mk_substs(s))
640         }
641         ty::ty_projection(ref data) => {
642             ty::ty_projection(data.fold_with(this))
643         }
644         ty::ty_bool | ty::ty_char | ty::ty_str |
645         ty::ty_int(_) | ty::ty_uint(_) | ty::ty_float(_) |
646         ty::ty_err | ty::ty_infer(_) |
647         ty::ty_param(..) => {
648             ty.sty.clone()
649         }
650     };
651     ty::mk_t(this.tcx(), sty)
652 }
653
654 pub fn super_fold_substs<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
655                                                     substs: &subst::Substs<'tcx>)
656                                                     -> subst::Substs<'tcx> {
657     let regions = match substs.regions {
658         subst::ErasedRegions => {
659             subst::ErasedRegions
660         }
661         subst::NonerasedRegions(ref regions) => {
662             subst::NonerasedRegions(regions.fold_with(this))
663         }
664     };
665
666     subst::Substs { regions: regions,
667                     types: substs.types.fold_with(this) }
668 }
669
670 pub fn super_fold_fn_sig<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
671                                                     sig: &ty::FnSig<'tcx>)
672                                                     -> ty::FnSig<'tcx>
673 {
674     ty::FnSig { inputs: sig.inputs.fold_with(this),
675                 output: sig.output.fold_with(this),
676                 variadic: sig.variadic }
677 }
678
679 pub fn super_fold_output<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
680                                                     output: &ty::FnOutput<'tcx>)
681                                                     -> ty::FnOutput<'tcx> {
682     match *output {
683         ty::FnConverging(ref ty) => ty::FnConverging(ty.fold_with(this)),
684         ty::FnDiverging => ty::FnDiverging
685     }
686 }
687
688 pub fn super_fold_bare_fn_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
689                                                         fty: &ty::BareFnTy<'tcx>)
690                                                         -> ty::BareFnTy<'tcx>
691 {
692     ty::BareFnTy { sig: fty.sig.fold_with(this),
693                    abi: fty.abi,
694                    unsafety: fty.unsafety }
695 }
696
697 pub fn super_fold_closure_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
698                                                         fty: &ty::ClosureTy<'tcx>)
699                                                         -> ty::ClosureTy<'tcx>
700 {
701     ty::ClosureTy {
702         store: fty.store.fold_with(this),
703         sig: fty.sig.fold_with(this),
704         unsafety: fty.unsafety,
705         onceness: fty.onceness,
706         bounds: fty.bounds.fold_with(this),
707         abi: fty.abi,
708     }
709 }
710
711 pub fn super_fold_trait_ref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
712                                                        t: &ty::TraitRef<'tcx>)
713                                                        -> ty::TraitRef<'tcx>
714 {
715     let substs = t.substs.fold_with(this);
716     ty::TraitRef {
717         def_id: t.def_id,
718         substs: this.tcx().mk_substs(substs),
719     }
720 }
721
722 pub fn super_fold_mt<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
723                                                 mt: &ty::mt<'tcx>)
724                                                 -> ty::mt<'tcx> {
725     ty::mt {ty: mt.ty.fold_with(this),
726             mutbl: mt.mutbl}
727 }
728
729 pub fn super_fold_trait_store<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
730                                                          trait_store: ty::TraitStore)
731                                                          -> ty::TraitStore {
732     match trait_store {
733         ty::UniqTraitStore => ty::UniqTraitStore,
734         ty::RegionTraitStore(r, m) => {
735             ty::RegionTraitStore(r.fold_with(this), m)
736         }
737     }
738 }
739
740 pub fn super_fold_existential_bounds<'tcx, T: TypeFolder<'tcx>>(
741     this: &mut T,
742     bounds: &ty::ExistentialBounds<'tcx>)
743     -> ty::ExistentialBounds<'tcx>
744 {
745     ty::ExistentialBounds {
746         region_bound: bounds.region_bound.fold_with(this),
747         builtin_bounds: bounds.builtin_bounds,
748         projection_bounds: bounds.projection_bounds.fold_with(this),
749     }
750 }
751
752 pub fn super_fold_autoref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
753                                                      autoref: &ty::AutoRef<'tcx>)
754                                                      -> ty::AutoRef<'tcx>
755 {
756     match *autoref {
757         ty::AutoPtr(r, m, None) => ty::AutoPtr(this.fold_region(r), m, None),
758         ty::AutoPtr(r, m, Some(ref a)) => {
759             ty::AutoPtr(this.fold_region(r), m, Some(box super_fold_autoref(this, &**a)))
760         }
761         ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
762         ty::AutoUnsafe(m, Some(ref a)) => {
763             ty::AutoUnsafe(m, Some(box super_fold_autoref(this, &**a)))
764         }
765         ty::AutoUnsize(ref k) => ty::AutoUnsize(k.fold_with(this)),
766         ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.fold_with(this)),
767     }
768 }
769
770 pub fn super_fold_item_substs<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
771                                                          substs: ty::ItemSubsts<'tcx>)
772                                                          -> ty::ItemSubsts<'tcx>
773 {
774     ty::ItemSubsts {
775         substs: substs.substs.fold_with(this),
776     }
777 }
778
779 ///////////////////////////////////////////////////////////////////////////
780 // Some sample folders
781
782 pub struct BottomUpFolder<'a, 'tcx: 'a, F> where F: FnMut(Ty<'tcx>) -> Ty<'tcx> {
783     pub tcx: &'a ty::ctxt<'tcx>,
784     pub fldop: F,
785 }
786
787 impl<'a, 'tcx, F> TypeFolder<'tcx> for BottomUpFolder<'a, 'tcx, F> where
788     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
789 {
790     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
791
792     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
793         let t1 = super_fold_ty(self, ty);
794         (self.fldop)(t1)
795     }
796 }
797
798 ///////////////////////////////////////////////////////////////////////////
799 // Region folder
800
801 /// Folds over the substructure of a type, visiting its component
802 /// types and all regions that occur *free* within it.
803 ///
804 /// That is, `Ty` can contain function or method types that bind
805 /// regions at the call site (`ReLateBound`), and occurrences of
806 /// regions (aka "lifetimes") that are bound within a type are not
807 /// visited by this folder; only regions that occur free will be
808 /// visited by `fld_r`.
809
810 pub struct RegionFolder<'a, 'tcx: 'a> {
811     tcx: &'a ty::ctxt<'tcx>,
812     current_depth: u32,
813     fld_r: &'a mut (FnMut(ty::Region, u32) -> ty::Region + 'a),
814 }
815
816 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
817     pub fn new<F>(tcx: &'a ty::ctxt<'tcx>, fld_r: &'a mut F) -> RegionFolder<'a, 'tcx>
818         where F : FnMut(ty::Region, u32) -> ty::Region
819     {
820         RegionFolder {
821             tcx: tcx,
822             current_depth: 1,
823             fld_r: fld_r,
824         }
825     }
826 }
827
828 pub fn collect_regions<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> Vec<ty::Region>
829     where T : TypeFoldable<'tcx>
830 {
831     let mut vec = Vec::new();
832     fold_regions(tcx, value, |r, _| { vec.push(r); r });
833     vec
834 }
835
836 pub fn fold_regions<'tcx,T,F>(tcx: &ty::ctxt<'tcx>,
837                               value: &T,
838                               mut f: F)
839                               -> T
840     where F : FnMut(ty::Region, u32) -> ty::Region,
841           T : TypeFoldable<'tcx>,
842 {
843     value.fold_with(&mut RegionFolder::new(tcx, &mut f))
844 }
845
846 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx>
847 {
848     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
849
850     fn enter_region_binder(&mut self) {
851         self.current_depth += 1;
852     }
853
854     fn exit_region_binder(&mut self) {
855         self.current_depth -= 1;
856     }
857
858     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
859         match r {
860             ty::ReLateBound(debruijn, _) if debruijn.depth < self.current_depth => {
861                 debug!("RegionFolder.fold_region({}) skipped bound region (current depth={})",
862                        r.repr(self.tcx()), self.current_depth);
863                 r
864             }
865             _ => {
866                 debug!("RegionFolder.fold_region({}) folding free region (current_depth={})",
867                        r.repr(self.tcx()), self.current_depth);
868                 (self.fld_r)(r, self.current_depth)
869             }
870         }
871     }
872 }
873
874 ///////////////////////////////////////////////////////////////////////////
875 // Region eraser
876 //
877 // Replaces all free regions with 'static. Useful in contexts, such as
878 // method probing, where precise region relationships are not
879 // important. Note that in trans you should use
880 // `common::erase_regions` instead.
881
882 pub struct RegionEraser<'a, 'tcx: 'a> {
883     tcx: &'a ty::ctxt<'tcx>,
884 }
885
886 pub fn erase_regions<'tcx, T: TypeFoldable<'tcx>>(tcx: &ty::ctxt<'tcx>, t: T) -> T {
887     let mut eraser = RegionEraser { tcx: tcx };
888     t.fold_with(&mut eraser)
889 }
890
891 impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> {
892     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
893
894     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
895         // because whether or not a region is bound affects subtyping,
896         // we can't erase the bound/free distinction, but we can
897         // replace all free regions with 'static
898         match r {
899             ty::ReLateBound(..) | ty::ReEarlyBound(..) => r,
900             _ => ty::ReStatic
901         }
902     }
903 }
904
905 ///////////////////////////////////////////////////////////////////////////
906 // Region shifter
907 //
908 // Shifts the De Bruijn indices on all escaping bound regions by a
909 // fixed amount. Useful in substitution or when otherwise introducing
910 // a binding level that is not intended to capture the existing bound
911 // regions. See comment on `shift_regions_through_binders` method in
912 // `subst.rs` for more details.
913
914 pub fn shift_region(region: ty::Region, amount: u32) -> ty::Region {
915     match region {
916         ty::ReLateBound(debruijn, br) => {
917             ty::ReLateBound(debruijn.shifted(amount), br)
918         }
919         _ => {
920             region
921         }
922     }
923 }
924
925 pub fn shift_regions<'tcx, T:TypeFoldable<'tcx>+Repr<'tcx>>(tcx: &ty::ctxt<'tcx>,
926                                                             amount: u32, value: &T) -> T {
927     debug!("shift_regions(value={}, amount={})",
928            value.repr(tcx), amount);
929
930     value.fold_with(&mut RegionFolder::new(tcx, &mut |region, _current_depth| {
931         shift_region(region, amount)
932     }))
933 }