]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/fold.rs
ba20b46090afc9aa9e357d15a517cfdd13fafb87
[rust.git] / src / librustc_front / fold.rs
1 // Copyright 2012-2015 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 //! A Folder represents an HIR->HIR fold; it accepts a HIR piece,
12 //! and returns a piece of the same type.
13
14 use hir::*;
15 use syntax::ast::{Ident, NodeId, DUMMY_NODE_ID};
16 use hir;
17 use syntax::codemap::{respan, Span, Spanned};
18 use syntax::owned_slice::OwnedSlice;
19 use syntax::ptr::P;
20 use syntax::parse::token;
21 use std::ptr;
22 use syntax::util::small_vector::SmallVector;
23
24
25 // This could have a better place to live.
26 pub trait MoveMap<T> {
27     fn move_map<F>(self, f: F) -> Self where F: FnMut(T) -> T;
28 }
29
30 impl<T> MoveMap<T> for Vec<T> {
31     fn move_map<F>(mut self, mut f: F) -> Vec<T> where F: FnMut(T) -> T {
32         for p in &mut self {
33             unsafe {
34                 // FIXME(#5016) this shouldn't need to zero to be safe.
35                 ptr::write(p, f(ptr::read_and_drop(p)));
36             }
37         }
38         self
39     }
40 }
41
42 impl<T> MoveMap<T> for OwnedSlice<T> {
43     fn move_map<F>(self, f: F) -> OwnedSlice<T> where F: FnMut(T) -> T {
44         OwnedSlice::from_vec(self.into_vec().move_map(f))
45     }
46 }
47
48 pub trait Folder : Sized {
49     // Any additions to this trait should happen in form
50     // of a call to a public `noop_*` function that only calls
51     // out to the folder again, not other `noop_*` functions.
52     //
53     // This is a necessary API workaround to the problem of not
54     // being able to call out to the super default method
55     // in an overridden default method.
56
57     fn fold_crate(&mut self, c: Crate) -> Crate {
58         noop_fold_crate(c, self)
59     }
60
61     fn fold_meta_items(&mut self, meta_items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
62         noop_fold_meta_items(meta_items, self)
63     }
64
65     fn fold_meta_item(&mut self, meta_item: P<MetaItem>) -> P<MetaItem> {
66         noop_fold_meta_item(meta_item, self)
67     }
68
69     fn fold_view_path(&mut self, view_path: P<ViewPath>) -> P<ViewPath> {
70         noop_fold_view_path(view_path, self)
71     }
72
73     fn fold_foreign_item(&mut self, ni: P<ForeignItem>) -> P<ForeignItem> {
74         noop_fold_foreign_item(ni, self)
75     }
76
77     fn fold_item(&mut self, i: P<Item>) -> SmallVector<P<Item>> {
78         noop_fold_item(i, self)
79     }
80
81     fn fold_item_simple(&mut self, i: Item) -> Item {
82         noop_fold_item_simple(i, self)
83     }
84
85     fn fold_struct_field(&mut self, sf: StructField) -> StructField {
86         noop_fold_struct_field(sf, self)
87     }
88
89     fn fold_item_underscore(&mut self, i: Item_) -> Item_ {
90         noop_fold_item_underscore(i, self)
91     }
92
93     fn fold_trait_item(&mut self, i: P<TraitItem>) -> SmallVector<P<TraitItem>> {
94         noop_fold_trait_item(i, self)
95     }
96
97     fn fold_impl_item(&mut self, i: P<ImplItem>) -> SmallVector<P<ImplItem>> {
98         noop_fold_impl_item(i, self)
99     }
100
101     fn fold_fn_decl(&mut self, d: P<FnDecl>) -> P<FnDecl> {
102         noop_fold_fn_decl(d, self)
103     }
104
105     fn fold_block(&mut self, b: P<Block>) -> P<Block> {
106         noop_fold_block(b, self)
107     }
108
109     fn fold_stmt(&mut self, s: P<Stmt>) -> SmallVector<P<Stmt>> {
110         s.and_then(|s| noop_fold_stmt(s, self))
111     }
112
113     fn fold_arm(&mut self, a: Arm) -> Arm {
114         noop_fold_arm(a, self)
115     }
116
117     fn fold_pat(&mut self, p: P<Pat>) -> P<Pat> {
118         noop_fold_pat(p, self)
119     }
120
121     fn fold_decl(&mut self, d: P<Decl>) -> SmallVector<P<Decl>> {
122         noop_fold_decl(d, self)
123     }
124
125     fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
126         e.map(|e| noop_fold_expr(e, self))
127     }
128
129     fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> {
130         noop_fold_ty(t, self)
131     }
132
133     fn fold_ty_binding(&mut self, t: P<TypeBinding>) -> P<TypeBinding> {
134         noop_fold_ty_binding(t, self)
135     }
136
137     fn fold_mod(&mut self, m: Mod) -> Mod {
138         noop_fold_mod(m, self)
139     }
140
141     fn fold_foreign_mod(&mut self, nm: ForeignMod) -> ForeignMod {
142         noop_fold_foreign_mod(nm, self)
143     }
144
145     fn fold_variant(&mut self, v: P<Variant>) -> P<Variant> {
146         noop_fold_variant(v, self)
147     }
148
149     fn fold_ident(&mut self, i: Ident) -> Ident {
150         noop_fold_ident(i, self)
151     }
152
153     fn fold_usize(&mut self, i: usize) -> usize {
154         noop_fold_usize(i, self)
155     }
156
157     fn fold_path(&mut self, p: Path) -> Path {
158         noop_fold_path(p, self)
159     }
160
161     fn fold_path_parameters(&mut self, p: PathParameters) -> PathParameters {
162         noop_fold_path_parameters(p, self)
163     }
164
165     fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData)
166                                            -> AngleBracketedParameterData
167     {
168         noop_fold_angle_bracketed_parameter_data(p, self)
169     }
170
171     fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedParameterData)
172                                          -> ParenthesizedParameterData
173     {
174         noop_fold_parenthesized_parameter_data(p, self)
175     }
176
177     fn fold_local(&mut self, l: P<Local>) -> P<Local> {
178         noop_fold_local(l, self)
179     }
180
181     fn fold_explicit_self(&mut self, es: ExplicitSelf) -> ExplicitSelf {
182         noop_fold_explicit_self(es, self)
183     }
184
185     fn fold_explicit_self_underscore(&mut self, es: ExplicitSelf_) -> ExplicitSelf_ {
186         noop_fold_explicit_self_underscore(es, self)
187     }
188
189     fn fold_lifetime(&mut self, l: Lifetime) -> Lifetime {
190         noop_fold_lifetime(l, self)
191     }
192
193     fn fold_lifetime_def(&mut self, l: LifetimeDef) -> LifetimeDef {
194         noop_fold_lifetime_def(l, self)
195     }
196
197     fn fold_attribute(&mut self, at: Attribute) -> Option<Attribute> {
198         noop_fold_attribute(at, self)
199     }
200
201     fn fold_arg(&mut self, a: Arg) -> Arg {
202         noop_fold_arg(a, self)
203     }
204
205     fn fold_generics(&mut self, generics: Generics) -> Generics {
206         noop_fold_generics(generics, self)
207     }
208
209     fn fold_trait_ref(&mut self, p: TraitRef) -> TraitRef {
210         noop_fold_trait_ref(p, self)
211     }
212
213     fn fold_poly_trait_ref(&mut self, p: PolyTraitRef) -> PolyTraitRef {
214         noop_fold_poly_trait_ref(p, self)
215     }
216
217     fn fold_struct_def(&mut self, struct_def: P<StructDef>) -> P<StructDef> {
218         noop_fold_struct_def(struct_def, self)
219     }
220
221     fn fold_lifetimes(&mut self, lts: Vec<Lifetime>) -> Vec<Lifetime> {
222         noop_fold_lifetimes(lts, self)
223     }
224
225     fn fold_lifetime_defs(&mut self, lts: Vec<LifetimeDef>) -> Vec<LifetimeDef> {
226         noop_fold_lifetime_defs(lts, self)
227     }
228
229     fn fold_ty_param(&mut self, tp: TyParam) -> TyParam {
230         noop_fold_ty_param(tp, self)
231     }
232
233     fn fold_ty_params(&mut self, tps: OwnedSlice<TyParam>) -> OwnedSlice<TyParam> {
234         noop_fold_ty_params(tps, self)
235     }
236
237     fn fold_opt_lifetime(&mut self, o_lt: Option<Lifetime>) -> Option<Lifetime> {
238         noop_fold_opt_lifetime(o_lt, self)
239     }
240
241     fn fold_variant_arg(&mut self, va: VariantArg) -> VariantArg {
242         noop_fold_variant_arg(va, self)
243     }
244
245     fn fold_opt_bounds(&mut self, b: Option<OwnedSlice<TyParamBound>>)
246                        -> Option<OwnedSlice<TyParamBound>> {
247         noop_fold_opt_bounds(b, self)
248     }
249
250     fn fold_bounds(&mut self, b: OwnedSlice<TyParamBound>)
251                        -> OwnedSlice<TyParamBound> {
252         noop_fold_bounds(b, self)
253     }
254
255     fn fold_ty_param_bound(&mut self, tpb: TyParamBound) -> TyParamBound {
256         noop_fold_ty_param_bound(tpb, self)
257     }
258
259     fn fold_mt(&mut self, mt: MutTy) -> MutTy {
260         noop_fold_mt(mt, self)
261     }
262
263     fn fold_field(&mut self, field: Field) -> Field {
264         noop_fold_field(field, self)
265     }
266
267     fn fold_where_clause(&mut self, where_clause: WhereClause)
268                          -> WhereClause {
269         noop_fold_where_clause(where_clause, self)
270     }
271
272     fn fold_where_predicate(&mut self, where_predicate: WherePredicate)
273                             -> WherePredicate {
274         noop_fold_where_predicate(where_predicate, self)
275     }
276
277     fn new_id(&mut self, i: NodeId) -> NodeId {
278         i
279     }
280
281     fn new_span(&mut self, sp: Span) -> Span {
282         sp
283     }
284 }
285
286 pub fn noop_fold_meta_items<T: Folder>(meta_items: Vec<P<MetaItem>>, fld: &mut T)
287                                        -> Vec<P<MetaItem>> {
288     meta_items.move_map(|x| fld.fold_meta_item(x))
289 }
290
291 pub fn noop_fold_view_path<T: Folder>(view_path: P<ViewPath>, fld: &mut T) -> P<ViewPath> {
292     view_path.map(|Spanned {node, span}| Spanned {
293         node: match node {
294             ViewPathSimple(ident, path) => {
295                 ViewPathSimple(ident, fld.fold_path(path))
296             }
297             ViewPathGlob(path) => {
298                 ViewPathGlob(fld.fold_path(path))
299             }
300             ViewPathList(path, path_list_idents) => {
301                 ViewPathList(fld.fold_path(path),
302                              path_list_idents.move_map(|path_list_ident| {
303                                 Spanned {
304                                     node: match path_list_ident.node {
305                                         PathListIdent { id, name, rename } =>
306                                             PathListIdent {
307                                                 id: fld.new_id(id),
308                                                 name: name,
309                                                 rename: rename,
310                                             },
311                                         PathListMod { id, rename } =>
312                                             PathListMod {
313                                                 id: fld.new_id(id),
314                                                 rename: rename,
315                                             }
316                                     },
317                                     span: fld.new_span(path_list_ident.span)
318                                 }
319                              }))
320             }
321         },
322         span: fld.new_span(span)
323     })
324 }
325
326 pub fn fold_attrs<T: Folder>(attrs: Vec<Attribute>, fld: &mut T) -> Vec<Attribute> {
327     attrs.into_iter().flat_map(|x| fld.fold_attribute(x)).collect()
328 }
329
330 pub fn noop_fold_arm<T: Folder>(Arm {attrs, pats, guard, body}: Arm, fld: &mut T) -> Arm {
331     Arm {
332         attrs: fold_attrs(attrs, fld),
333         pats: pats.move_map(|x| fld.fold_pat(x)),
334         guard: guard.map(|x| fld.fold_expr(x)),
335         body: fld.fold_expr(body),
336     }
337 }
338
339 pub fn noop_fold_decl<T: Folder>(d: P<Decl>, fld: &mut T) -> SmallVector<P<Decl>> {
340     d.and_then(|Spanned {node, span}| match node {
341         DeclLocal(l) => SmallVector::one(P(Spanned {
342             node: DeclLocal(fld.fold_local(l)),
343             span: fld.new_span(span)
344         })),
345         DeclItem(it) => fld.fold_item(it).into_iter().map(|i| P(Spanned {
346             node: DeclItem(i),
347             span: fld.new_span(span)
348         })).collect()
349     })
350 }
351
352 pub fn noop_fold_ty_binding<T: Folder>(b: P<TypeBinding>, fld: &mut T) -> P<TypeBinding> {
353     b.map(|TypeBinding { id, ident, ty, span }| TypeBinding {
354         id: fld.new_id(id),
355         ident: ident,
356         ty: fld.fold_ty(ty),
357         span: fld.new_span(span),
358     })
359 }
360
361 pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
362     t.map(|Ty {id, node, span}| Ty {
363         id: fld.new_id(id),
364         node: match node {
365             TyInfer => node,
366             TyVec(ty) => TyVec(fld.fold_ty(ty)),
367             TyPtr(mt) => TyPtr(fld.fold_mt(mt)),
368             TyRptr(region, mt) => {
369                 TyRptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt))
370             }
371             TyBareFn(f) => {
372                 TyBareFn(f.map(|BareFnTy {lifetimes, unsafety, abi, decl}| BareFnTy {
373                     lifetimes: fld.fold_lifetime_defs(lifetimes),
374                     unsafety: unsafety,
375                     abi: abi,
376                     decl: fld.fold_fn_decl(decl)
377                 }))
378             }
379             TyTup(tys) => TyTup(tys.move_map(|ty| fld.fold_ty(ty))),
380             TyParen(ty) => TyParen(fld.fold_ty(ty)),
381             TyPath(qself, path) => {
382                 let qself = qself.map(|QSelf { ty, position }| {
383                     QSelf {
384                         ty: fld.fold_ty(ty),
385                         position: position
386                     }
387                 });
388                 TyPath(qself, fld.fold_path(path))
389             }
390             TyObjectSum(ty, bounds) => {
391                 TyObjectSum(fld.fold_ty(ty),
392                             fld.fold_bounds(bounds))
393             }
394             TyFixedLengthVec(ty, e) => {
395                 TyFixedLengthVec(fld.fold_ty(ty), fld.fold_expr(e))
396             }
397             TyTypeof(expr) => {
398                 TyTypeof(fld.fold_expr(expr))
399             }
400             TyPolyTraitRef(bounds) => {
401                 TyPolyTraitRef(bounds.move_map(|b| fld.fold_ty_param_bound(b)))
402             }
403         },
404         span: fld.new_span(span)
405     })
406 }
407
408 pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, items}: ForeignMod,
409                                         fld: &mut T) -> ForeignMod {
410     ForeignMod {
411         abi: abi,
412         items: items.move_map(|x| fld.fold_foreign_item(x)),
413     }
414 }
415
416 pub fn noop_fold_variant<T: Folder>(v: P<Variant>, fld: &mut T) -> P<Variant> {
417     v.map(|Spanned {node: Variant_ {id, name, attrs, kind, disr_expr, vis}, span}| Spanned {
418         node: Variant_ {
419             id: fld.new_id(id),
420             name: name,
421             attrs: fold_attrs(attrs, fld),
422             kind: match kind {
423                 TupleVariantKind(variant_args) => {
424                     TupleVariantKind(variant_args.move_map(|x|
425                         fld.fold_variant_arg(x)))
426                 }
427                 StructVariantKind(struct_def) => {
428                     StructVariantKind(fld.fold_struct_def(struct_def))
429                 }
430             },
431             disr_expr: disr_expr.map(|e| fld.fold_expr(e)),
432             vis: vis,
433         },
434         span: fld.new_span(span),
435     })
436 }
437
438 pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident {
439     i
440 }
441
442 pub fn noop_fold_usize<T: Folder>(i: usize, _: &mut T) -> usize {
443     i
444 }
445
446 pub fn noop_fold_path<T: Folder>(Path {global, segments, span}: Path, fld: &mut T) -> Path {
447     Path {
448         global: global,
449         segments: segments.move_map(|PathSegment {identifier, parameters}| PathSegment {
450             identifier: fld.fold_ident(identifier),
451             parameters: fld.fold_path_parameters(parameters),
452         }),
453         span: fld.new_span(span)
454     }
455 }
456
457 pub fn noop_fold_path_parameters<T: Folder>(path_parameters: PathParameters, fld: &mut T)
458                                             -> PathParameters
459 {
460     match path_parameters {
461         AngleBracketedParameters(data) =>
462             AngleBracketedParameters(fld.fold_angle_bracketed_parameter_data(data)),
463         ParenthesizedParameters(data) =>
464             ParenthesizedParameters(fld.fold_parenthesized_parameter_data(data)),
465     }
466 }
467
468 pub fn noop_fold_angle_bracketed_parameter_data<T: Folder>(data: AngleBracketedParameterData,
469                                                            fld: &mut T)
470                                                            -> AngleBracketedParameterData
471 {
472     let AngleBracketedParameterData { lifetimes, types, bindings } = data;
473     AngleBracketedParameterData { lifetimes: fld.fold_lifetimes(lifetimes),
474                                   types: types.move_map(|ty| fld.fold_ty(ty)),
475                                   bindings: bindings.move_map(|b| fld.fold_ty_binding(b)) }
476 }
477
478 pub fn noop_fold_parenthesized_parameter_data<T: Folder>(data: ParenthesizedParameterData,
479                                                          fld: &mut T)
480                                                          -> ParenthesizedParameterData
481 {
482     let ParenthesizedParameterData { inputs, output, span } = data;
483     ParenthesizedParameterData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)),
484                                  output: output.map(|ty| fld.fold_ty(ty)),
485                                  span: fld.new_span(span) }
486 }
487
488 pub fn noop_fold_local<T: Folder>(l: P<Local>, fld: &mut T) -> P<Local> {
489     l.map(|Local {id, pat, ty, init, span}| Local {
490         id: fld.new_id(id),
491         ty: ty.map(|t| fld.fold_ty(t)),
492         pat: fld.fold_pat(pat),
493         init: init.map(|e| fld.fold_expr(e)),
494         span: fld.new_span(span)
495     })
496 }
497
498 pub fn noop_fold_attribute<T: Folder>(at: Attribute, fld: &mut T) -> Option<Attribute> {
499     let Spanned {node: Attribute_ {id, style, value, is_sugared_doc}, span} = at;
500     Some(Spanned {
501         node: Attribute_ {
502             id: id,
503             style: style,
504             value: fld.fold_meta_item(value),
505             is_sugared_doc: is_sugared_doc
506         },
507         span: fld.new_span(span)
508     })
509 }
510
511 pub fn noop_fold_explicit_self_underscore<T: Folder>(es: ExplicitSelf_, fld: &mut T)
512                                                      -> ExplicitSelf_ {
513     match es {
514         SelfStatic | SelfValue(_) => es,
515         SelfRegion(lifetime, m, ident) => {
516             SelfRegion(fld.fold_opt_lifetime(lifetime), m, ident)
517         }
518         SelfExplicit(typ, ident) => {
519             SelfExplicit(fld.fold_ty(typ), ident)
520         }
521     }
522 }
523
524 pub fn noop_fold_explicit_self<T: Folder>(Spanned {span, node}: ExplicitSelf, fld: &mut T)
525                                           -> ExplicitSelf {
526     Spanned {
527         node: fld.fold_explicit_self_underscore(node),
528         span: fld.new_span(span)
529     }
530 }
531
532 pub fn noop_fold_meta_item<T: Folder>(mi: P<MetaItem>, fld: &mut T) -> P<MetaItem> {
533     mi.map(|Spanned {node, span}| Spanned {
534         node: match node {
535             MetaWord(id) => MetaWord(id),
536             MetaList(id, mis) => {
537                 MetaList(id, mis.move_map(|e| fld.fold_meta_item(e)))
538             }
539             MetaNameValue(id, s) => MetaNameValue(id, s)
540         },
541         span: fld.new_span(span)
542     })
543 }
544
545 pub fn noop_fold_arg<T: Folder>(Arg {id, pat, ty}: Arg, fld: &mut T) -> Arg {
546     Arg {
547         id: fld.new_id(id),
548         pat: fld.fold_pat(pat),
549         ty: fld.fold_ty(ty)
550     }
551 }
552
553 pub fn noop_fold_fn_decl<T: Folder>(decl: P<FnDecl>, fld: &mut T) -> P<FnDecl> {
554     decl.map(|FnDecl {inputs, output, variadic}| FnDecl {
555         inputs: inputs.move_map(|x| fld.fold_arg(x)),
556         output: match output {
557             Return(ty) => Return(fld.fold_ty(ty)),
558             DefaultReturn(span) => DefaultReturn(span),
559             NoReturn(span) => NoReturn(span)
560         },
561         variadic: variadic
562     })
563 }
564
565 pub fn noop_fold_ty_param_bound<T>(tpb: TyParamBound, fld: &mut T)
566                                    -> TyParamBound
567                                    where T: Folder {
568     match tpb {
569         TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier),
570         RegionTyParamBound(lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)),
571     }
572 }
573
574 pub fn noop_fold_ty_param<T: Folder>(tp: TyParam, fld: &mut T) -> TyParam {
575     let TyParam {id, ident, bounds, default, span} = tp;
576     TyParam {
577         id: fld.new_id(id),
578         ident: ident,
579         bounds: fld.fold_bounds(bounds),
580         default: default.map(|x| fld.fold_ty(x)),
581         span: span
582     }
583 }
584
585 pub fn noop_fold_ty_params<T: Folder>(tps: OwnedSlice<TyParam>, fld: &mut T)
586                                       -> OwnedSlice<TyParam> {
587     tps.move_map(|tp| fld.fold_ty_param(tp))
588 }
589
590 pub fn noop_fold_lifetime<T: Folder>(l: Lifetime, fld: &mut T) -> Lifetime {
591     Lifetime {
592         id: fld.new_id(l.id),
593         name: l.name,
594         span: fld.new_span(l.span)
595     }
596 }
597
598 pub fn noop_fold_lifetime_def<T: Folder>(l: LifetimeDef, fld: &mut T)
599                                          -> LifetimeDef {
600     LifetimeDef {
601         lifetime: fld.fold_lifetime(l.lifetime),
602         bounds: fld.fold_lifetimes(l.bounds),
603     }
604 }
605
606 pub fn noop_fold_lifetimes<T: Folder>(lts: Vec<Lifetime>, fld: &mut T) -> Vec<Lifetime> {
607     lts.move_map(|l| fld.fold_lifetime(l))
608 }
609
610 pub fn noop_fold_lifetime_defs<T: Folder>(lts: Vec<LifetimeDef>, fld: &mut T)
611                                           -> Vec<LifetimeDef> {
612     lts.move_map(|l| fld.fold_lifetime_def(l))
613 }
614
615 pub fn noop_fold_opt_lifetime<T: Folder>(o_lt: Option<Lifetime>, fld: &mut T)
616                                          -> Option<Lifetime> {
617     o_lt.map(|lt| fld.fold_lifetime(lt))
618 }
619
620 pub fn noop_fold_generics<T: Folder>(Generics {ty_params, lifetimes, where_clause}: Generics,
621                                      fld: &mut T) -> Generics {
622     Generics {
623         ty_params: fld.fold_ty_params(ty_params),
624         lifetimes: fld.fold_lifetime_defs(lifetimes),
625         where_clause: fld.fold_where_clause(where_clause),
626     }
627 }
628
629 pub fn noop_fold_where_clause<T: Folder>(
630                               WhereClause {id, predicates}: WhereClause,
631                               fld: &mut T)
632                               -> WhereClause {
633     WhereClause {
634         id: fld.new_id(id),
635         predicates: predicates.move_map(|predicate| {
636             fld.fold_where_predicate(predicate)
637         })
638     }
639 }
640
641 pub fn noop_fold_where_predicate<T: Folder>(
642                                  pred: WherePredicate,
643                                  fld: &mut T)
644                                  -> WherePredicate {
645     match pred {
646         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{bound_lifetimes,
647                                                                      bounded_ty,
648                                                                      bounds,
649                                                                      span}) => {
650             hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
651                 bound_lifetimes: fld.fold_lifetime_defs(bound_lifetimes),
652                 bounded_ty: fld.fold_ty(bounded_ty),
653                 bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)),
654                 span: fld.new_span(span)
655             })
656         }
657         hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{lifetime,
658                                                                        bounds,
659                                                                        span}) => {
660             hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
661                 span: fld.new_span(span),
662                 lifetime: fld.fold_lifetime(lifetime),
663                 bounds: bounds.move_map(|bound| fld.fold_lifetime(bound))
664             })
665         }
666         hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{id,
667                                                                path,
668                                                                ty,
669                                                                span}) => {
670             hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{
671                 id: fld.new_id(id),
672                 path: fld.fold_path(path),
673                 ty:fld.fold_ty(ty),
674                 span: fld.new_span(span)
675             })
676         }
677     }
678 }
679
680 pub fn noop_fold_struct_def<T: Folder>(struct_def: P<StructDef>, fld: &mut T) -> P<StructDef> {
681     struct_def.map(|StructDef { fields, ctor_id }| StructDef {
682         fields: fields.move_map(|f| fld.fold_struct_field(f)),
683         ctor_id: ctor_id.map(|cid| fld.new_id(cid)),
684     })
685 }
686
687 pub fn noop_fold_trait_ref<T: Folder>(p: TraitRef, fld: &mut T) -> TraitRef {
688     let id = fld.new_id(p.ref_id);
689     let TraitRef {
690         path,
691         ref_id: _,
692     } = p;
693     hir::TraitRef {
694         path: fld.fold_path(path),
695         ref_id: id,
696     }
697 }
698
699 pub fn noop_fold_poly_trait_ref<T: Folder>(p: PolyTraitRef, fld: &mut T) -> PolyTraitRef {
700     hir::PolyTraitRef {
701         bound_lifetimes: fld.fold_lifetime_defs(p.bound_lifetimes),
702         trait_ref: fld.fold_trait_ref(p.trait_ref),
703         span: fld.new_span(p.span),
704     }
705 }
706
707 pub fn noop_fold_struct_field<T: Folder>(f: StructField, fld: &mut T) -> StructField {
708     let StructField {node: StructField_ {id, kind, ty, attrs}, span} = f;
709     Spanned {
710         node: StructField_ {
711             id: fld.new_id(id),
712             kind: kind,
713             ty: fld.fold_ty(ty),
714             attrs: fold_attrs(attrs, fld),
715         },
716         span: fld.new_span(span)
717     }
718 }
719
720 pub fn noop_fold_field<T: Folder>(Field {ident, expr, span}: Field, folder: &mut T) -> Field {
721     Field {
722         ident: respan(ident.span, folder.fold_ident(ident.node)),
723         expr: folder.fold_expr(expr),
724         span: folder.new_span(span)
725     }
726 }
727
728 pub fn noop_fold_mt<T: Folder>(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutTy {
729     MutTy {
730         ty: folder.fold_ty(ty),
731         mutbl: mutbl,
732     }
733 }
734
735 pub fn noop_fold_opt_bounds<T: Folder>(b: Option<OwnedSlice<TyParamBound>>, folder: &mut T)
736                                        -> Option<OwnedSlice<TyParamBound>> {
737     b.map(|bounds| folder.fold_bounds(bounds))
738 }
739
740 fn noop_fold_bounds<T: Folder>(bounds: TyParamBounds, folder: &mut T)
741                           -> TyParamBounds {
742     bounds.move_map(|bound| folder.fold_ty_param_bound(bound))
743 }
744
745 fn noop_fold_variant_arg<T: Folder>(VariantArg {id, ty}: VariantArg, folder: &mut T)
746                                     -> VariantArg {
747     VariantArg {
748         id: folder.new_id(id),
749         ty: folder.fold_ty(ty)
750     }
751 }
752
753 pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> {
754     b.map(|Block {id, stmts, expr, rules, span}| Block {
755         id: folder.new_id(id),
756         stmts: stmts.into_iter().flat_map(|s| folder.fold_stmt(s).into_iter()).collect(),
757         expr: expr.map(|x| folder.fold_expr(x)),
758         rules: rules,
759         span: folder.new_span(span),
760     })
761 }
762
763 pub fn noop_fold_item_underscore<T: Folder>(i: Item_, folder: &mut T) -> Item_ {
764     match i {
765         ItemExternCrate(string) => ItemExternCrate(string),
766         ItemUse(view_path) => {
767             ItemUse(folder.fold_view_path(view_path))
768         }
769         ItemStatic(t, m, e) => {
770             ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e))
771         }
772         ItemConst(t, e) => {
773             ItemConst(folder.fold_ty(t), folder.fold_expr(e))
774         }
775         ItemFn(decl, unsafety, constness, abi, generics, body) => {
776             ItemFn(
777                 folder.fold_fn_decl(decl),
778                 unsafety,
779                 constness,
780                 abi,
781                 folder.fold_generics(generics),
782                 folder.fold_block(body)
783             )
784         }
785         ItemMod(m) => ItemMod(folder.fold_mod(m)),
786         ItemForeignMod(nm) => ItemForeignMod(folder.fold_foreign_mod(nm)),
787         ItemTy(t, generics) => {
788             ItemTy(folder.fold_ty(t), folder.fold_generics(generics))
789         }
790         ItemEnum(enum_definition, generics) => {
791             ItemEnum(
792                 hir::EnumDef {
793                     variants: enum_definition.variants.move_map(|x| folder.fold_variant(x)),
794                 },
795                 folder.fold_generics(generics))
796         }
797         ItemStruct(struct_def, generics) => {
798             let struct_def = folder.fold_struct_def(struct_def);
799             ItemStruct(struct_def, folder.fold_generics(generics))
800         }
801         ItemDefaultImpl(unsafety, ref trait_ref) => {
802             ItemDefaultImpl(unsafety, folder.fold_trait_ref((*trait_ref).clone()))
803         }
804         ItemImpl(unsafety, polarity, generics, ifce, ty, impl_items) => {
805             let new_impl_items = impl_items.into_iter().flat_map(|item| {
806                 folder.fold_impl_item(item).into_iter()
807             }).collect();
808             let ifce = match ifce {
809                 None => None,
810                 Some(ref trait_ref) => {
811                     Some(folder.fold_trait_ref((*trait_ref).clone()))
812                 }
813             };
814             ItemImpl(unsafety,
815                      polarity,
816                      folder.fold_generics(generics),
817                      ifce,
818                      folder.fold_ty(ty),
819                      new_impl_items)
820         }
821         ItemTrait(unsafety, generics, bounds, items) => {
822             let bounds = folder.fold_bounds(bounds);
823             let items = items.into_iter().flat_map(|item| {
824                 folder.fold_trait_item(item).into_iter()
825             }).collect();
826             ItemTrait(unsafety,
827                       folder.fold_generics(generics),
828                       bounds,
829                       items)
830         }
831     }
832 }
833
834 pub fn noop_fold_trait_item<T: Folder>(i: P<TraitItem>, folder: &mut T)
835                                        -> SmallVector<P<TraitItem>> {
836     SmallVector::one(i.map(|TraitItem {id, ident, attrs, node, span}| TraitItem {
837         id: folder.new_id(id),
838         ident: folder.fold_ident(ident),
839         attrs: fold_attrs(attrs, folder),
840         node: match node {
841             ConstTraitItem(ty, default) => {
842                 ConstTraitItem(folder.fold_ty(ty),
843                                default.map(|x| folder.fold_expr(x)))
844             }
845             MethodTraitItem(sig, body) => {
846                 MethodTraitItem(noop_fold_method_sig(sig, folder),
847                                 body.map(|x| folder.fold_block(x)))
848             }
849             TypeTraitItem(bounds, default) => {
850                 TypeTraitItem(folder.fold_bounds(bounds),
851                               default.map(|x| folder.fold_ty(x)))
852             }
853         },
854         span: folder.new_span(span)
855     }))
856 }
857
858 pub fn noop_fold_impl_item<T: Folder>(i: P<ImplItem>, folder: &mut T)
859                                       -> SmallVector<P<ImplItem>> {
860     SmallVector::one(i.map(|ImplItem {id, ident, attrs, node, vis, span}| ImplItem {
861         id: folder.new_id(id),
862         ident: folder.fold_ident(ident),
863         attrs: fold_attrs(attrs, folder),
864         vis: vis,
865         node: match node  {
866             ConstImplItem(ty, expr) => {
867                 ConstImplItem(folder.fold_ty(ty), folder.fold_expr(expr))
868             }
869             MethodImplItem(sig, body) => {
870                 MethodImplItem(noop_fold_method_sig(sig, folder),
871                                folder.fold_block(body))
872             }
873             TypeImplItem(ty) => TypeImplItem(folder.fold_ty(ty)),
874         },
875         span: folder.new_span(span)
876     }))
877 }
878
879 pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod {
880     Mod {
881         inner: folder.new_span(inner),
882         items: items.into_iter().flat_map(|x| folder.fold_item(x).into_iter()).collect(),
883     }
884 }
885
886 pub fn noop_fold_crate<T: Folder>(Crate {module, attrs, config, span, exported_macros}: Crate,
887                                   folder: &mut T) -> Crate {
888     let config = folder.fold_meta_items(config);
889
890     let mut items = folder.fold_item(P(hir::Item {
891         ident: token::special_idents::invalid,
892         attrs: attrs,
893         id: DUMMY_NODE_ID,
894         vis: hir::Public,
895         span: span,
896         node: hir::ItemMod(module),
897     })).into_iter();
898
899     let (module, attrs, span) = match items.next() {
900         Some(item) => {
901             assert!(items.next().is_none(),
902                     "a crate cannot expand to more than one item");
903             item.and_then(|hir::Item { attrs, span, node, .. }| {
904                 match node {
905                     hir::ItemMod(m) => (m, attrs, span),
906                     _ => panic!("fold converted a module to not a module"),
907                 }
908             })
909         }
910         None => (hir::Mod {
911             inner: span,
912             items: vec![],
913         }, vec![], span)
914     };
915
916     Crate {
917         module: module,
918         attrs: attrs,
919         config: config,
920         span: span,
921         exported_macros: exported_macros,
922     }
923 }
924
925 // fold one item into possibly many items
926 pub fn noop_fold_item<T: Folder>(i: P<Item>, folder: &mut T) -> SmallVector<P<Item>> {
927     SmallVector::one(i.map(|i| folder.fold_item_simple(i)))
928 }
929
930 // fold one item into exactly one item
931 pub fn noop_fold_item_simple<T: Folder>(Item {id, ident, attrs, node, vis, span}: Item,
932                                         folder: &mut T) -> Item {
933     let id = folder.new_id(id);
934     let node = folder.fold_item_underscore(node);
935     // FIXME: we should update the impl_pretty_name, but it uses pretty printing.
936     // let ident = match node {
937     //     // The node may have changed, recompute the "pretty" impl name.
938     //     ItemImpl(_, _, _, ref maybe_trait, ref ty, _) => {
939     //         impl_pretty_name(maybe_trait, Some(&**ty))
940     //     }
941     //     _ => ident
942     // };
943
944     Item {
945         id: id,
946         ident: folder.fold_ident(ident),
947         attrs: fold_attrs(attrs, folder),
948         node: node,
949         vis: vis,
950         span: folder.new_span(span)
951     }
952 }
953
954 pub fn noop_fold_foreign_item<T: Folder>(ni: P<ForeignItem>, folder: &mut T) -> P<ForeignItem> {
955     ni.map(|ForeignItem {id, ident, attrs, node, span, vis}| ForeignItem {
956         id: folder.new_id(id),
957         ident: folder.fold_ident(ident),
958         attrs: fold_attrs(attrs, folder),
959         node: match node {
960             ForeignItemFn(fdec, generics) => {
961                 ForeignItemFn(folder.fold_fn_decl(fdec), folder.fold_generics(generics))
962             }
963             ForeignItemStatic(t, m) => {
964                 ForeignItemStatic(folder.fold_ty(t), m)
965             }
966         },
967         vis: vis,
968         span: folder.new_span(span)
969     })
970 }
971
972 pub fn noop_fold_method_sig<T: Folder>(sig: MethodSig, folder: &mut T) -> MethodSig {
973     MethodSig {
974         generics: folder.fold_generics(sig.generics),
975         abi: sig.abi,
976         explicit_self: folder.fold_explicit_self(sig.explicit_self),
977         unsafety: sig.unsafety,
978         constness: sig.constness,
979         decl: folder.fold_fn_decl(sig.decl)
980     }
981 }
982
983 pub fn noop_fold_pat<T: Folder>(p: P<Pat>, folder: &mut T) -> P<Pat> {
984     p.map(|Pat {id, node, span}| Pat {
985         id: folder.new_id(id),
986         node: match node {
987             PatWild(k) => PatWild(k),
988             PatIdent(binding_mode, pth1, sub) => {
989                 PatIdent(binding_mode,
990                         Spanned{span: folder.new_span(pth1.span),
991                                 node: folder.fold_ident(pth1.node)},
992                         sub.map(|x| folder.fold_pat(x)))
993             }
994             PatLit(e) => PatLit(folder.fold_expr(e)),
995             PatEnum(pth, pats) => {
996                 PatEnum(folder.fold_path(pth),
997                         pats.map(|pats| pats.move_map(|x| folder.fold_pat(x))))
998             }
999             PatQPath(qself, pth) => {
1000                 let qself = QSelf {ty: folder.fold_ty(qself.ty), .. qself};
1001                 PatQPath(qself, folder.fold_path(pth))
1002             }
1003             PatStruct(pth, fields, etc) => {
1004                 let pth = folder.fold_path(pth);
1005                 let fs = fields.move_map(|f| {
1006                     Spanned { span: folder.new_span(f.span),
1007                               node: hir::FieldPat {
1008                                   ident: f.node.ident,
1009                                   pat: folder.fold_pat(f.node.pat),
1010                                   is_shorthand: f.node.is_shorthand,
1011                               }}
1012                 });
1013                 PatStruct(pth, fs, etc)
1014             }
1015             PatTup(elts) => PatTup(elts.move_map(|x| folder.fold_pat(x))),
1016             PatBox(inner) => PatBox(folder.fold_pat(inner)),
1017             PatRegion(inner, mutbl) => PatRegion(folder.fold_pat(inner), mutbl),
1018             PatRange(e1, e2) => {
1019                 PatRange(folder.fold_expr(e1), folder.fold_expr(e2))
1020             },
1021             PatVec(before, slice, after) => {
1022                 PatVec(before.move_map(|x| folder.fold_pat(x)),
1023                        slice.map(|x| folder.fold_pat(x)),
1024                        after.move_map(|x| folder.fold_pat(x)))
1025             }
1026         },
1027         span: folder.new_span(span)
1028     })
1029 }
1030
1031 pub fn noop_fold_expr<T: Folder>(Expr {id, node, span}: Expr, folder: &mut T) -> Expr {
1032     Expr {
1033         id: folder.new_id(id),
1034         node: match node {
1035             ExprBox(p, e) => {
1036                 ExprBox(p.map(|e|folder.fold_expr(e)), folder.fold_expr(e))
1037             }
1038             ExprVec(exprs) => {
1039                 ExprVec(exprs.move_map(|x| folder.fold_expr(x)))
1040             }
1041             ExprRepeat(expr, count) => {
1042                 ExprRepeat(folder.fold_expr(expr), folder.fold_expr(count))
1043             }
1044             ExprTup(elts) => ExprTup(elts.move_map(|x| folder.fold_expr(x))),
1045             ExprCall(f, args) => {
1046                 ExprCall(folder.fold_expr(f),
1047                          args.move_map(|x| folder.fold_expr(x)))
1048             }
1049             ExprMethodCall(i, tps, args) => {
1050                 ExprMethodCall(
1051                     respan(folder.new_span(i.span), folder.fold_ident(i.node)),
1052                     tps.move_map(|x| folder.fold_ty(x)),
1053                     args.move_map(|x| folder.fold_expr(x)))
1054             }
1055             ExprBinary(binop, lhs, rhs) => {
1056                 ExprBinary(binop,
1057                         folder.fold_expr(lhs),
1058                         folder.fold_expr(rhs))
1059             }
1060             ExprUnary(binop, ohs) => {
1061                 ExprUnary(binop, folder.fold_expr(ohs))
1062             }
1063             ExprLit(l) => ExprLit(l),
1064             ExprCast(expr, ty) => {
1065                 ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
1066             }
1067             ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
1068             ExprIf(cond, tr, fl) => {
1069                 ExprIf(folder.fold_expr(cond),
1070                        folder.fold_block(tr),
1071                        fl.map(|x| folder.fold_expr(x)))
1072             }
1073             ExprWhile(cond, body, opt_ident) => {
1074                 ExprWhile(folder.fold_expr(cond),
1075                           folder.fold_block(body),
1076                           opt_ident.map(|i| folder.fold_ident(i)))
1077             }
1078             ExprLoop(body, opt_ident) => {
1079                 ExprLoop(folder.fold_block(body),
1080                         opt_ident.map(|i| folder.fold_ident(i)))
1081             }
1082             ExprMatch(expr, arms, source) => {
1083                 ExprMatch(folder.fold_expr(expr),
1084                         arms.move_map(|x| folder.fold_arm(x)),
1085                         source)
1086             }
1087             ExprClosure(capture_clause, decl, body) => {
1088                 ExprClosure(capture_clause,
1089                             folder.fold_fn_decl(decl),
1090                             folder.fold_block(body))
1091             }
1092             ExprBlock(blk) => ExprBlock(folder.fold_block(blk)),
1093             ExprAssign(el, er) => {
1094                 ExprAssign(folder.fold_expr(el), folder.fold_expr(er))
1095             }
1096             ExprAssignOp(op, el, er) => {
1097                 ExprAssignOp(op,
1098                             folder.fold_expr(el),
1099                             folder.fold_expr(er))
1100             }
1101             ExprField(el, ident) => {
1102                 ExprField(folder.fold_expr(el),
1103                           respan(folder.new_span(ident.span),
1104                                  folder.fold_ident(ident.node)))
1105             }
1106             ExprTupField(el, ident) => {
1107                 ExprTupField(folder.fold_expr(el),
1108                              respan(folder.new_span(ident.span),
1109                                     folder.fold_usize(ident.node)))
1110             }
1111             ExprIndex(el, er) => {
1112                 ExprIndex(folder.fold_expr(el), folder.fold_expr(er))
1113             }
1114             ExprRange(e1, e2) => {
1115                 ExprRange(e1.map(|x| folder.fold_expr(x)),
1116                           e2.map(|x| folder.fold_expr(x)))
1117             }
1118             ExprPath(qself, path) => {
1119                 let qself = qself.map(|QSelf { ty, position }| {
1120                     QSelf {
1121                         ty: folder.fold_ty(ty),
1122                         position: position
1123                     }
1124                 });
1125                 ExprPath(qself, folder.fold_path(path))
1126             }
1127             ExprBreak(opt_ident) => ExprBreak(opt_ident.map(|label|
1128                 respan(folder.new_span(label.span),
1129                        folder.fold_ident(label.node)))
1130             ),
1131             ExprAgain(opt_ident) => ExprAgain(opt_ident.map(|label|
1132                 respan(folder.new_span(label.span),
1133                        folder.fold_ident(label.node)))
1134             ),
1135             ExprRet(e) => ExprRet(e.map(|x| folder.fold_expr(x))),
1136             ExprInlineAsm(InlineAsm {
1137                 inputs,
1138                 outputs,
1139                 asm,
1140                 asm_str_style,
1141                 clobbers,
1142                 volatile,
1143                 alignstack,
1144                 dialect,
1145                 expn_id,
1146             }) => ExprInlineAsm(InlineAsm {
1147                 inputs: inputs.move_map(|(c, input)| {
1148                     (c, folder.fold_expr(input))
1149                 }),
1150                 outputs: outputs.move_map(|(c, out, is_rw)| {
1151                     (c, folder.fold_expr(out), is_rw)
1152                 }),
1153                 asm: asm,
1154                 asm_str_style: asm_str_style,
1155                 clobbers: clobbers,
1156                 volatile: volatile,
1157                 alignstack: alignstack,
1158                 dialect: dialect,
1159                 expn_id: expn_id,
1160             }),
1161             ExprStruct(path, fields, maybe_expr) => {
1162                 ExprStruct(folder.fold_path(path),
1163                         fields.move_map(|x| folder.fold_field(x)),
1164                         maybe_expr.map(|x| folder.fold_expr(x)))
1165             },
1166             ExprParen(ex) => ExprParen(folder.fold_expr(ex))
1167         },
1168         span: folder.new_span(span)
1169     }
1170 }
1171
1172 pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T)
1173                                  -> SmallVector<P<Stmt>> {
1174     let span = folder.new_span(span);
1175     match node {
1176         StmtDecl(d, id) => {
1177             let id = folder.new_id(id);
1178             folder.fold_decl(d).into_iter().map(|d| P(Spanned {
1179                 node: StmtDecl(d, id),
1180                 span: span
1181             })).collect()
1182         }
1183         StmtExpr(e, id) => {
1184             let id = folder.new_id(id);
1185             SmallVector::one(P(Spanned {
1186                 node: StmtExpr(folder.fold_expr(e), id),
1187                 span: span
1188             }))
1189         }
1190         StmtSemi(e, id) => {
1191             let id = folder.new_id(id);
1192             SmallVector::one(P(Spanned {
1193                 node: StmtSemi(folder.fold_expr(e), id),
1194                 span: span
1195             }))
1196         }
1197     }
1198 }