]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty_fold.rs
rollup merge of #20518: nagisa/weighted-bool
[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_rptr(r, ref tm) => {
608             let r = r.fold_with(this);
609             ty::ty_rptr(this.tcx().mk_region(r), tm.fold_with(this))
610         }
611         ty::ty_struct(did, ref substs) => {
612             let substs = substs.fold_with(this);
613             ty::ty_struct(did, this.tcx().mk_substs(substs))
614         }
615         ty::ty_unboxed_closure(did, ref region, ref substs) => {
616             let r = region.fold_with(this);
617             let s = substs.fold_with(this);
618             ty::ty_unboxed_closure(did, this.tcx().mk_region(r), this.tcx().mk_substs(s))
619         }
620         ty::ty_projection(ref data) => {
621             ty::ty_projection(data.fold_with(this))
622         }
623         ty::ty_bool | ty::ty_char | ty::ty_str |
624         ty::ty_int(_) | ty::ty_uint(_) | ty::ty_float(_) |
625         ty::ty_err | ty::ty_infer(_) |
626         ty::ty_param(..) => {
627             ty.sty.clone()
628         }
629     };
630     ty::mk_t(this.tcx(), sty)
631 }
632
633 pub fn super_fold_substs<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
634                                                     substs: &subst::Substs<'tcx>)
635                                                     -> subst::Substs<'tcx> {
636     let regions = match substs.regions {
637         subst::ErasedRegions => {
638             subst::ErasedRegions
639         }
640         subst::NonerasedRegions(ref regions) => {
641             subst::NonerasedRegions(regions.fold_with(this))
642         }
643     };
644
645     subst::Substs { regions: regions,
646                     types: substs.types.fold_with(this) }
647 }
648
649 pub fn super_fold_fn_sig<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
650                                                     sig: &ty::FnSig<'tcx>)
651                                                     -> ty::FnSig<'tcx>
652 {
653     ty::FnSig { inputs: sig.inputs.fold_with(this),
654                 output: sig.output.fold_with(this),
655                 variadic: sig.variadic }
656 }
657
658 pub fn super_fold_output<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
659                                                     output: &ty::FnOutput<'tcx>)
660                                                     -> ty::FnOutput<'tcx> {
661     match *output {
662         ty::FnConverging(ref ty) => ty::FnConverging(ty.fold_with(this)),
663         ty::FnDiverging => ty::FnDiverging
664     }
665 }
666
667 pub fn super_fold_bare_fn_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
668                                                         fty: &ty::BareFnTy<'tcx>)
669                                                         -> ty::BareFnTy<'tcx>
670 {
671     ty::BareFnTy { sig: fty.sig.fold_with(this),
672                    abi: fty.abi,
673                    unsafety: fty.unsafety }
674 }
675
676 pub fn super_fold_closure_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
677                                                         fty: &ty::ClosureTy<'tcx>)
678                                                         -> ty::ClosureTy<'tcx>
679 {
680     ty::ClosureTy {
681         store: fty.store.fold_with(this),
682         sig: fty.sig.fold_with(this),
683         unsafety: fty.unsafety,
684         onceness: fty.onceness,
685         bounds: fty.bounds.fold_with(this),
686         abi: fty.abi,
687     }
688 }
689
690 pub fn super_fold_trait_ref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
691                                                        t: &ty::TraitRef<'tcx>)
692                                                        -> ty::TraitRef<'tcx>
693 {
694     let substs = t.substs.fold_with(this);
695     ty::TraitRef {
696         def_id: t.def_id,
697         substs: this.tcx().mk_substs(substs),
698     }
699 }
700
701 pub fn super_fold_mt<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
702                                                 mt: &ty::mt<'tcx>)
703                                                 -> ty::mt<'tcx> {
704     ty::mt {ty: mt.ty.fold_with(this),
705             mutbl: mt.mutbl}
706 }
707
708 pub fn super_fold_trait_store<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
709                                                          trait_store: ty::TraitStore)
710                                                          -> ty::TraitStore {
711     match trait_store {
712         ty::UniqTraitStore => ty::UniqTraitStore,
713         ty::RegionTraitStore(r, m) => {
714             ty::RegionTraitStore(r.fold_with(this), m)
715         }
716     }
717 }
718
719 pub fn super_fold_existential_bounds<'tcx, T: TypeFolder<'tcx>>(
720     this: &mut T,
721     bounds: &ty::ExistentialBounds<'tcx>)
722     -> ty::ExistentialBounds<'tcx>
723 {
724     ty::ExistentialBounds {
725         region_bound: bounds.region_bound.fold_with(this),
726         builtin_bounds: bounds.builtin_bounds,
727         projection_bounds: bounds.projection_bounds.fold_with(this),
728     }
729 }
730
731 pub fn super_fold_autoref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
732                                                      autoref: &ty::AutoRef<'tcx>)
733                                                      -> ty::AutoRef<'tcx>
734 {
735     match *autoref {
736         ty::AutoPtr(r, m, None) => ty::AutoPtr(this.fold_region(r), m, None),
737         ty::AutoPtr(r, m, Some(ref a)) => {
738             ty::AutoPtr(this.fold_region(r), m, Some(box super_fold_autoref(this, &**a)))
739         }
740         ty::AutoUnsafe(m, None) => ty::AutoUnsafe(m, None),
741         ty::AutoUnsafe(m, Some(ref a)) => {
742             ty::AutoUnsafe(m, Some(box super_fold_autoref(this, &**a)))
743         }
744         ty::AutoUnsize(ref k) => ty::AutoUnsize(k.fold_with(this)),
745         ty::AutoUnsizeUniq(ref k) => ty::AutoUnsizeUniq(k.fold_with(this)),
746     }
747 }
748
749 pub fn super_fold_item_substs<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
750                                                          substs: ty::ItemSubsts<'tcx>)
751                                                          -> ty::ItemSubsts<'tcx>
752 {
753     ty::ItemSubsts {
754         substs: substs.substs.fold_with(this),
755     }
756 }
757
758 ///////////////////////////////////////////////////////////////////////////
759 // Some sample folders
760
761 pub struct BottomUpFolder<'a, 'tcx: 'a, F> where F: FnMut(Ty<'tcx>) -> Ty<'tcx> {
762     pub tcx: &'a ty::ctxt<'tcx>,
763     pub fldop: F,
764 }
765
766 impl<'a, 'tcx, F> TypeFolder<'tcx> for BottomUpFolder<'a, 'tcx, F> where
767     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
768 {
769     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
770
771     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
772         let t1 = super_fold_ty(self, ty);
773         (self.fldop)(t1)
774     }
775 }
776
777 ///////////////////////////////////////////////////////////////////////////
778 // Region folder
779
780 /// Folds over the substructure of a type, visiting its component
781 /// types and all regions that occur *free* within it.
782 ///
783 /// That is, `Ty` can contain function or method types that bind
784 /// regions at the call site (`ReLateBound`), and occurrences of
785 /// regions (aka "lifetimes") that are bound within a type are not
786 /// visited by this folder; only regions that occur free will be
787 /// visited by `fld_r`.
788
789 pub struct RegionFolder<'a, 'tcx: 'a> {
790     tcx: &'a ty::ctxt<'tcx>,
791     current_depth: u32,
792     fld_r: &'a mut (FnMut(ty::Region, u32) -> ty::Region + 'a),
793 }
794
795 impl<'a, 'tcx> RegionFolder<'a, 'tcx> {
796     pub fn new<F>(tcx: &'a ty::ctxt<'tcx>, fld_r: &'a mut F) -> RegionFolder<'a, 'tcx>
797         where F : FnMut(ty::Region, u32) -> ty::Region
798     {
799         RegionFolder {
800             tcx: tcx,
801             current_depth: 1,
802             fld_r: fld_r,
803         }
804     }
805 }
806
807 pub fn collect_regions<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> Vec<ty::Region>
808     where T : TypeFoldable<'tcx>
809 {
810     let mut vec = Vec::new();
811     fold_regions(tcx, value, |r, _| { vec.push(r); r });
812     vec
813 }
814
815 pub fn fold_regions<'tcx,T,F>(tcx: &ty::ctxt<'tcx>,
816                               value: &T,
817                               mut f: F)
818                               -> T
819     where F : FnMut(ty::Region, u32) -> ty::Region,
820           T : TypeFoldable<'tcx>,
821 {
822     value.fold_with(&mut RegionFolder::new(tcx, &mut f))
823 }
824
825 impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx>
826 {
827     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
828
829     fn enter_region_binder(&mut self) {
830         self.current_depth += 1;
831     }
832
833     fn exit_region_binder(&mut self) {
834         self.current_depth -= 1;
835     }
836
837     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
838         match r {
839             ty::ReLateBound(debruijn, _) if debruijn.depth < self.current_depth => {
840                 debug!("RegionFolder.fold_region({}) skipped bound region (current depth={})",
841                        r.repr(self.tcx()), self.current_depth);
842                 r
843             }
844             _ => {
845                 debug!("RegionFolder.fold_region({}) folding free region (current_depth={})",
846                        r.repr(self.tcx()), self.current_depth);
847                 self.fld_r.call_mut((r, self.current_depth))
848             }
849         }
850     }
851 }
852
853 ///////////////////////////////////////////////////////////////////////////
854 // Region eraser
855 //
856 // Replaces all free regions with 'static. Useful in trans.
857
858 pub struct RegionEraser<'a, 'tcx: 'a> {
859     tcx: &'a ty::ctxt<'tcx>,
860 }
861
862 pub fn erase_regions<'tcx, T: TypeFoldable<'tcx>>(tcx: &ty::ctxt<'tcx>, t: T) -> T {
863     let mut eraser = RegionEraser { tcx: tcx };
864     t.fold_with(&mut eraser)
865 }
866
867 impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> {
868     fn tcx(&self) -> &ty::ctxt<'tcx> { self.tcx }
869
870     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
871         match r {
872             ty::ReLateBound(..) | ty::ReEarlyBound(..) => r,
873             _ => ty::ReStatic
874         }
875     }
876 }
877
878 ///////////////////////////////////////////////////////////////////////////
879 // Region shifter
880 //
881 // Shifts the De Bruijn indices on all escaping bound regions by a
882 // fixed amount. Useful in substitution or when otherwise introducing
883 // a binding level that is not intended to capture the existing bound
884 // regions. See comment on `shift_regions_through_binders` method in
885 // `subst.rs` for more details.
886
887 pub fn shift_region(region: ty::Region, amount: u32) -> ty::Region {
888     match region {
889         ty::ReLateBound(debruijn, br) => {
890             ty::ReLateBound(debruijn.shifted(amount), br)
891         }
892         _ => {
893             region
894         }
895     }
896 }
897
898 pub fn shift_regions<'tcx, T:TypeFoldable<'tcx>+Repr<'tcx>>(tcx: &ty::ctxt<'tcx>,
899                                                             amount: u32, value: &T) -> T {
900     debug!("shift_regions(value={}, amount={})",
901            value.repr(tcx), amount);
902
903     value.fold_with(&mut RegionFolder::new(tcx, &mut |region, _current_depth| {
904         shift_region(region, amount)
905     }))
906 }