]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty_fold.rs
Merge pull request #20510 from tshepang/patch-6
[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 overriden, 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::Region {
277     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Region {
278         folder.fold_region(*self)
279     }
280 }
281
282 impl<'tcx> TypeFoldable<'tcx> for subst::Substs<'tcx> {
283     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> subst::Substs<'tcx> {
284         folder.fold_substs(self)
285     }
286 }
287
288 impl<'tcx> TypeFoldable<'tcx> for ty::ItemSubsts<'tcx> {
289     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ItemSubsts<'tcx> {
290         ty::ItemSubsts {
291             substs: self.substs.fold_with(folder),
292         }
293     }
294 }
295
296 impl<'tcx> TypeFoldable<'tcx> for ty::AutoRef<'tcx> {
297     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::AutoRef<'tcx> {
298         folder.fold_autoref(self)
299     }
300 }
301
302 impl<'tcx> TypeFoldable<'tcx> for ty::MethodOrigin<'tcx> {
303     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::MethodOrigin<'tcx> {
304         match *self {
305             ty::MethodStatic(def_id) => {
306                 ty::MethodStatic(def_id)
307             }
308             ty::MethodStaticUnboxedClosure(def_id) => {
309                 ty::MethodStaticUnboxedClosure(def_id)
310             }
311             ty::MethodTypeParam(ref param) => {
312                 ty::MethodTypeParam(ty::MethodParam {
313                     trait_ref: param.trait_ref.fold_with(folder),
314                     method_num: param.method_num
315                 })
316             }
317             ty::MethodTraitObject(ref object) => {
318                 ty::MethodTraitObject(ty::MethodObject {
319                     trait_ref: object.trait_ref.fold_with(folder),
320                     object_trait_id: object.object_trait_id,
321                     method_num: object.method_num,
322                     real_index: object.real_index
323                 })
324             }
325         }
326     }
327 }
328
329 impl<'tcx> TypeFoldable<'tcx> for ty::vtable_origin<'tcx> {
330     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::vtable_origin<'tcx> {
331         match *self {
332             ty::vtable_static(def_id, ref substs, ref origins) => {
333                 let r_substs = substs.fold_with(folder);
334                 let r_origins = origins.fold_with(folder);
335                 ty::vtable_static(def_id, r_substs, r_origins)
336             }
337             ty::vtable_param(n, b) => {
338                 ty::vtable_param(n, b)
339             }
340             ty::vtable_unboxed_closure(def_id) => {
341                 ty::vtable_unboxed_closure(def_id)
342             }
343             ty::vtable_error => {
344                 ty::vtable_error
345             }
346         }
347     }
348 }
349
350 impl<'tcx> TypeFoldable<'tcx> for ty::BuiltinBounds {
351     fn fold_with<F: TypeFolder<'tcx>>(&self, _folder: &mut F) -> ty::BuiltinBounds {
352         *self
353     }
354 }
355
356 impl<'tcx> TypeFoldable<'tcx> for ty::ExistentialBounds<'tcx> {
357     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ExistentialBounds<'tcx> {
358         folder.fold_existential_bounds(self)
359     }
360 }
361
362 impl<'tcx> TypeFoldable<'tcx> for ty::ParamBounds<'tcx> {
363     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ParamBounds<'tcx> {
364         ty::ParamBounds {
365             region_bounds: self.region_bounds.fold_with(folder),
366             builtin_bounds: self.builtin_bounds.fold_with(folder),
367             trait_bounds: self.trait_bounds.fold_with(folder),
368             projection_bounds: self.projection_bounds.fold_with(folder),
369         }
370     }
371 }
372
373 impl<'tcx> TypeFoldable<'tcx> for ty::TypeParameterDef<'tcx> {
374     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TypeParameterDef<'tcx> {
375         ty::TypeParameterDef {
376             name: self.name,
377             def_id: self.def_id,
378             space: self.space,
379             index: self.index,
380             bounds: self.bounds.fold_with(folder),
381             default: self.default.fold_with(folder),
382         }
383     }
384 }
385
386 impl<'tcx> TypeFoldable<'tcx> for ty::RegionParameterDef {
387     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::RegionParameterDef {
388         ty::RegionParameterDef {
389             name: self.name,
390             def_id: self.def_id,
391             space: self.space,
392             index: self.index,
393             bounds: self.bounds.fold_with(folder)
394         }
395     }
396 }
397
398 impl<'tcx> TypeFoldable<'tcx> for ty::Generics<'tcx> {
399     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Generics<'tcx> {
400         ty::Generics {
401             types: self.types.fold_with(folder),
402             regions: self.regions.fold_with(folder),
403             predicates: self.predicates.fold_with(folder),
404         }
405     }
406 }
407
408 impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> {
409     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Predicate<'tcx> {
410         match *self {
411             ty::Predicate::Trait(ref a) =>
412                 ty::Predicate::Trait(a.fold_with(folder)),
413             ty::Predicate::Equate(ref binder) =>
414                 ty::Predicate::Equate(binder.fold_with(folder)),
415             ty::Predicate::RegionOutlives(ref binder) =>
416                 ty::Predicate::RegionOutlives(binder.fold_with(folder)),
417             ty::Predicate::TypeOutlives(ref binder) =>
418                 ty::Predicate::TypeOutlives(binder.fold_with(folder)),
419             ty::Predicate::Projection(ref binder) =>
420                 ty::Predicate::Projection(binder.fold_with(folder)),
421         }
422     }
423 }
424
425 impl<'tcx> TypeFoldable<'tcx> for ty::ProjectionPredicate<'tcx> {
426     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ProjectionPredicate<'tcx> {
427         ty::ProjectionPredicate {
428             projection_ty: self.projection_ty.fold_with(folder),
429             ty: self.ty.fold_with(folder),
430         }
431     }
432 }
433
434 impl<'tcx> TypeFoldable<'tcx> for ty::ProjectionTy<'tcx> {
435     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ProjectionTy<'tcx> {
436         ty::ProjectionTy {
437             trait_ref: self.trait_ref.fold_with(folder),
438             item_name: self.item_name,
439         }
440     }
441 }
442
443 impl<'tcx> TypeFoldable<'tcx> for ty::GenericBounds<'tcx> {
444     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::GenericBounds<'tcx> {
445         ty::GenericBounds {
446             predicates: self.predicates.fold_with(folder),
447         }
448     }
449 }
450
451 impl<'tcx> TypeFoldable<'tcx> for ty::UnsizeKind<'tcx> {
452     fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::UnsizeKind<'tcx> {
453         match *self {
454             ty::UnsizeLength(len) => ty::UnsizeLength(len),
455             ty::UnsizeStruct(box ref k, n) => ty::UnsizeStruct(box k.fold_with(folder), n),
456             ty::UnsizeVtable(ty::TyTrait{ref principal, ref bounds}, self_ty) => {
457                 ty::UnsizeVtable(
458                     ty::TyTrait {
459                         principal: principal.fold_with(folder),
460                         bounds: bounds.fold_with(folder),
461                     },
462                     self_ty.fold_with(folder))
463             }
464         }
465     }
466 }
467
468 impl<'tcx,O> TypeFoldable<'tcx> for traits::Obligation<'tcx,O>
469     where O : TypeFoldable<'tcx>
470 {
471     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::Obligation<'tcx, O> {
472         traits::Obligation {
473             cause: self.cause.clone(),
474             recursion_depth: self.recursion_depth,
475             predicate: self.predicate.fold_with(folder),
476         }
477     }
478 }
479
480 impl<'tcx, N: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::VtableImplData<'tcx, N> {
481     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableImplData<'tcx, N> {
482         traits::VtableImplData {
483             impl_def_id: self.impl_def_id,
484             substs: self.substs.fold_with(folder),
485             nested: self.nested.fold_with(folder),
486         }
487     }
488 }
489
490 impl<'tcx, N: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::VtableBuiltinData<N> {
491     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableBuiltinData<N> {
492         traits::VtableBuiltinData {
493             nested: self.nested.fold_with(folder),
494         }
495     }
496 }
497
498 impl<'tcx, N: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::Vtable<'tcx, N> {
499     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::Vtable<'tcx, N> {
500         match *self {
501             traits::VtableImpl(ref v) => traits::VtableImpl(v.fold_with(folder)),
502             traits::VtableUnboxedClosure(d, ref s) => {
503                 traits::VtableUnboxedClosure(d, s.fold_with(folder))
504             }
505             traits::VtableFnPointer(ref d) => {
506                 traits::VtableFnPointer(d.fold_with(folder))
507             }
508             traits::VtableParam => traits::VtableParam,
509             traits::VtableBuiltin(ref d) => traits::VtableBuiltin(d.fold_with(folder)),
510             traits::VtableObject(ref d) => traits::VtableObject(d.fold_with(folder)),
511         }
512     }
513 }
514
515 impl<'tcx> TypeFoldable<'tcx> for traits::VtableObjectData<'tcx> {
516     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableObjectData<'tcx> {
517         traits::VtableObjectData {
518             object_ty: self.object_ty.fold_with(folder)
519         }
520     }
521 }
522
523 impl<'tcx> TypeFoldable<'tcx> for ty::EquatePredicate<'tcx> {
524     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::EquatePredicate<'tcx> {
525         ty::EquatePredicate(self.0.fold_with(folder),
526                             self.1.fold_with(folder))
527     }
528 }
529
530 impl<'tcx> TypeFoldable<'tcx> for ty::TraitPredicate<'tcx> {
531     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TraitPredicate<'tcx> {
532         ty::TraitPredicate {
533             trait_ref: self.trait_ref.fold_with(folder)
534         }
535     }
536 }
537
538 impl<'tcx,T,U> TypeFoldable<'tcx> for ty::OutlivesPredicate<T,U>
539     where T : TypeFoldable<'tcx>,
540           U : TypeFoldable<'tcx>,
541 {
542     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::OutlivesPredicate<T,U> {
543         ty::OutlivesPredicate(self.0.fold_with(folder),
544                               self.1.fold_with(folder))
545     }
546 }
547
548 impl<'tcx> TypeFoldable<'tcx> for ty::UnboxedClosureUpvar<'tcx> {
549     fn fold_with<F:TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::UnboxedClosureUpvar<'tcx> {
550         ty::UnboxedClosureUpvar {
551             def: self.def,
552             span: self.span,
553             ty: self.ty.fold_with(folder),
554         }
555     }
556 }
557
558 ///////////////////////////////////////////////////////////////////////////
559 // "super" routines: these are the default implementations for TypeFolder.
560 //
561 // They should invoke `foo.fold_with()` to do recursive folding.
562
563 pub fn super_fold_binder<'tcx, T, U>(this: &mut T,
564                                      binder: &ty::Binder<U>)
565                                      -> ty::Binder<U>
566     where T : TypeFolder<'tcx>, U : TypeFoldable<'tcx>
567 {
568     this.enter_region_binder();
569     let result = ty::Binder(binder.0.fold_with(this));
570     this.exit_region_binder();
571     result
572 }
573
574 pub fn super_fold_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
575                                                 ty: Ty<'tcx>)
576                                                 -> Ty<'tcx> {
577     let sty = match ty.sty {
578         ty::ty_uniq(typ) => {
579             ty::ty_uniq(typ.fold_with(this))
580         }
581         ty::ty_ptr(ref tm) => {
582             ty::ty_ptr(tm.fold_with(this))
583         }
584         ty::ty_vec(typ, sz) => {
585             ty::ty_vec(typ.fold_with(this), sz)
586         }
587         ty::ty_open(typ) => {
588             ty::ty_open(typ.fold_with(this))
589         }
590         ty::ty_enum(tid, ref substs) => {
591             let substs = substs.fold_with(this);
592             ty::ty_enum(tid, this.tcx().mk_substs(substs))
593         }
594         ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
595             ty::ty_trait(box ty::TyTrait {
596                 principal: principal.fold_with(this),
597                 bounds: bounds.fold_with(this),
598             })
599         }
600         ty::ty_tup(ref ts) => {
601             ty::ty_tup(ts.fold_with(this))
602         }
603         ty::ty_bare_fn(opt_def_id, ref f) => {
604             let bfn = f.fold_with(this);
605             ty::ty_bare_fn(opt_def_id, this.tcx().mk_bare_fn(bfn))
606         }
607         ty::ty_closure(ref f) => {
608             ty::ty_closure(f.fold_with(this))
609         }
610         ty::ty_rptr(r, ref tm) => {
611             let r = r.fold_with(this);
612             ty::ty_rptr(this.tcx().mk_region(r), tm.fold_with(this))
613         }
614         ty::ty_struct(did, ref substs) => {
615             let substs = substs.fold_with(this);
616             ty::ty_struct(did, this.tcx().mk_substs(substs))
617         }
618         ty::ty_unboxed_closure(did, ref region, ref substs) => {
619             let r = region.fold_with(this);
620             let s = substs.fold_with(this);
621             ty::ty_unboxed_closure(did, this.tcx().mk_region(r), this.tcx().mk_substs(s))
622         }
623         ty::ty_projection(ref data) => {
624             ty::ty_projection(data.fold_with(this))
625         }
626         ty::ty_bool | ty::ty_char | ty::ty_str |
627         ty::ty_int(_) | ty::ty_uint(_) | ty::ty_float(_) |
628         ty::ty_err | ty::ty_infer(_) |
629         ty::ty_param(..) => {
630             ty.sty.clone()
631         }
632     };
633     ty::mk_t(this.tcx(), sty)
634 }
635
636 pub fn super_fold_substs<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
637                                                     substs: &subst::Substs<'tcx>)
638                                                     -> subst::Substs<'tcx> {
639     let regions = match substs.regions {
640         subst::ErasedRegions => {
641             subst::ErasedRegions
642         }
643         subst::NonerasedRegions(ref regions) => {
644             subst::NonerasedRegions(regions.fold_with(this))
645         }
646     };
647
648     subst::Substs { regions: regions,
649                     types: substs.types.fold_with(this) }
650 }
651
652 pub fn super_fold_fn_sig<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
653                                                     sig: &ty::FnSig<'tcx>)
654                                                     -> ty::FnSig<'tcx>
655 {
656     ty::FnSig { inputs: sig.inputs.fold_with(this),
657                 output: sig.output.fold_with(this),
658                 variadic: sig.variadic }
659 }
660
661 pub fn super_fold_output<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
662                                                     output: &ty::FnOutput<'tcx>)
663                                                     -> ty::FnOutput<'tcx> {
664     match *output {
665         ty::FnConverging(ref ty) => ty::FnConverging(ty.fold_with(this)),
666         ty::FnDiverging => ty::FnDiverging
667     }
668 }
669
670 pub fn super_fold_bare_fn_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
671                                                         fty: &ty::BareFnTy<'tcx>)
672                                                         -> ty::BareFnTy<'tcx>
673 {
674     ty::BareFnTy { sig: fty.sig.fold_with(this),
675                    abi: fty.abi,
676                    unsafety: fty.unsafety }
677 }
678
679 pub fn super_fold_closure_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
680                                                         fty: &ty::ClosureTy<'tcx>)
681                                                         -> ty::ClosureTy<'tcx>
682 {
683     ty::ClosureTy {
684         store: fty.store.fold_with(this),
685         sig: fty.sig.fold_with(this),
686         unsafety: fty.unsafety,
687         onceness: fty.onceness,
688         bounds: fty.bounds.fold_with(this),
689         abi: fty.abi,
690     }
691 }
692
693 pub fn super_fold_trait_ref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
694                                                        t: &ty::TraitRef<'tcx>)
695                                                        -> ty::TraitRef<'tcx>
696 {
697     let substs = t.substs.fold_with(this);
698     ty::TraitRef {
699         def_id: t.def_id,
700         substs: this.tcx().mk_substs(substs),
701     }
702 }
703
704 pub fn super_fold_mt<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
705                                                 mt: &ty::mt<'tcx>)
706                                                 -> ty::mt<'tcx> {
707     ty::mt {ty: mt.ty.fold_with(this),
708             mutbl: mt.mutbl}
709 }
710
711 pub fn super_fold_trait_store<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
712                                                          trait_store: ty::TraitStore)
713                                                          -> ty::TraitStore {
714     match trait_store {
715         ty::UniqTraitStore => ty::UniqTraitStore,
716         ty::RegionTraitStore(r, m) => {
717             ty::RegionTraitStore(r.fold_with(this), m)
718         }
719     }
720 }
721
722 pub fn super_fold_existential_bounds<'tcx, T: TypeFolder<'tcx>>(
723     this: &mut T,
724     bounds: &ty::ExistentialBounds<'tcx>)
725     -> ty::ExistentialBounds<'tcx>
726 {
727     ty::ExistentialBounds {
728         region_bound: bounds.region_bound.fold_with(this),
729         builtin_bounds: bounds.builtin_bounds,
730         projection_bounds: bounds.projection_bounds.fold_with(this),
731     }
732 }
733
734 pub fn super_fold_autoref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
735                                                      autoref: &ty::AutoRef<'tcx>)
736                                                      -> ty::AutoRef<'tcx>
737 {
738     match *autoref {
739         ty::AutoPtr(r, m, None) => ty::AutoPtr(this.fold_region(r), m, None),
740         ty::AutoPtr(r, m, Some(ref a)) => {
741             ty::AutoPtr(this.fold_region(r), m, Some(box super_fold_autoref(this, &**a)))
742         }
743         ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
744         ty::AutoUnsafe(m, Some(ref a)) => {
745             ty::AutoUnsafe(m, Some(box super_fold_autoref(this, &**a)))
746         }
747         ty::AutoUnsize(ref k) => ty::AutoUnsize(k.fold_with(this)),
748         ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.fold_with(this)),
749     }
750 }
751
752 pub fn super_fold_item_substs<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
753                                                          substs: ty::ItemSubsts<'tcx>)
754                                                          -> ty::ItemSubsts<'tcx>
755 {
756     ty::ItemSubsts {
757         substs: substs.substs.fold_with(this),
758     }
759 }
760
761 ///////////////////////////////////////////////////////////////////////////
762 // Some sample folders
763
764 pub struct BottomUpFolder<'a, 'tcx: 'a, F> where F: FnMut(Ty<'tcx>) -> Ty<'tcx> {
765     pub tcx: &'a ty::ctxt<'tcx>,
766     pub fldop: F,
767 }
768
769 impl<'a, 'tcx, F> TypeFolder<'tcx> for BottomUpFolder<'a, 'tcx, F> where
770     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
771 {
772     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
773
774     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
775         let t1 = super_fold_ty(self, ty);
776         (self.fldop)(t1)
777     }
778 }
779
780 ///////////////////////////////////////////////////////////////////////////
781 // Region folder
782
783 /// Folds over the substructure of a type, visiting its component
784 /// types and all regions that occur *free* within it.
785 ///
786 /// That is, `Ty` can contain function or method types that bind
787 /// regions at the call site (`ReLateBound`), and occurrences of
788 /// regions (aka "lifetimes") that are bound within a type are not
789 /// visited by this folder; only regions that occur free will be
790 /// visited by `fld_r`.
791
792 pub struct RegionFolder<'a, 'tcx: 'a> {
793     tcx: &'a ty::ctxt<'tcx>,
794     current_depth: u32,
795     fld_r: &'a mut (FnMut(ty::Region, u32) -> ty::Region + 'a),
796 }
797
798 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
799     pub fn new<F>(tcx: &'a ty::ctxt<'tcx>, fld_r: &'a mut F) -> RegionFolder<'a, 'tcx>
800         where F : FnMut(ty::Region, u32) -> ty::Region
801     {
802         RegionFolder {
803             tcx: tcx,
804             current_depth: 1,
805             fld_r: fld_r,
806         }
807     }
808 }
809
810 pub fn collect_regions<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> Vec<ty::Region>
811     where T : TypeFoldable<'tcx>
812 {
813     let mut vec = Vec::new();
814     fold_regions(tcx, value, |r, _| { vec.push(r); r });
815     vec
816 }
817
818 pub fn fold_regions<'tcx,T,F>(tcx: &ty::ctxt<'tcx>,
819                               value: &T,
820                               mut f: F)
821                               -> T
822     where F : FnMut(ty::Region, u32) -> ty::Region,
823           T : TypeFoldable<'tcx>,
824 {
825     value.fold_with(&mut RegionFolder::new(tcx, &mut f))
826 }
827
828 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx>
829 {
830     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
831
832     fn enter_region_binder(&mut self) {
833         self.current_depth += 1;
834     }
835
836     fn exit_region_binder(&mut self) {
837         self.current_depth -= 1;
838     }
839
840     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
841         match r {
842             ty::ReLateBound(debruijn, _) if debruijn.depth < self.current_depth => {
843                 debug!("RegionFolder.fold_region({}) skipped bound region (current depth={})",
844                        r.repr(self.tcx()), self.current_depth);
845                 r
846             }
847             _ => {
848                 debug!("RegionFolder.fold_region({}) folding free region (current_depth={})",
849                        r.repr(self.tcx()), self.current_depth);
850                 self.fld_r.call_mut((r, self.current_depth))
851             }
852         }
853     }
854 }
855
856 ///////////////////////////////////////////////////////////////////////////
857 // Region eraser
858 //
859 // Replaces all free regions with 'static. Useful in trans.
860
861 pub struct RegionEraser<'a, 'tcx: 'a> {
862     tcx: &'a ty::ctxt<'tcx>,
863 }
864
865 pub fn erase_regions<'tcx, T: TypeFoldable<'tcx>>(tcx: &ty::ctxt<'tcx>, t: T) -> T {
866     let mut eraser = RegionEraser { tcx: tcx };
867     t.fold_with(&mut eraser)
868 }
869
870 impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> {
871     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
872
873     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
874         match r {
875             ty::ReLateBound(..) | ty::ReEarlyBound(..) => r,
876             _ => ty::ReStatic
877         }
878     }
879 }
880
881 ///////////////////////////////////////////////////////////////////////////
882 // Region shifter
883 //
884 // Shifts the De Bruijn indices on all escaping bound regions by a
885 // fixed amount. Useful in substitution or when otherwise introducing
886 // a binding level that is not intended to capture the existing bound
887 // regions. See comment on `shift_regions_through_binders` method in
888 // `subst.rs` for more details.
889
890 pub fn shift_region(region: ty::Region, amount: u32) -> ty::Region {
891     match region {
892         ty::ReLateBound(debruijn, br) => {
893             ty::ReLateBound(debruijn.shifted(amount), br)
894         }
895         _ => {
896             region
897         }
898     }
899 }
900
901 pub fn shift_regions<'tcx, T:TypeFoldable<'tcx>+Repr<'tcx>>(tcx: &ty::ctxt<'tcx>,
902                                                             amount: u32, value: &T) -> T {
903     debug!("shift_regions(value={}, amount={})",
904            value.repr(tcx), amount);
905
906     value.fold_with(&mut RegionFolder::new(tcx, &mut |region, _current_depth| {
907         shift_region(region, amount)
908     }))
909 }