]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/fold.rs
mk: The beta channel produces things called 'beta'
[rust.git] / src / libsyntax / fold.rs
1 // Copyright 2012-2014 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 AST->AST fold; it accepts an AST piece,
12 //! and returns a piece of the same type. So, for instance, macro
13 //! expansion is a Folder that walks over an AST and produces another
14 //! AST.
15 //!
16 //! Note: using a Folder (other than the MacroExpander Folder) on
17 //! an AST before macro expansion is probably a bad idea. For instance,
18 //! a folder renaming item names in a module will miss all of those
19 //! that are created by the expansion of a macro.
20
21 use ast::*;
22 use ast;
23 use ast_util;
24 use codemap::{respan, Span, Spanned};
25 use owned_slice::OwnedSlice;
26 use parse::token;
27 use ptr::P;
28 use std::ptr;
29 use util::small_vector::SmallVector;
30
31 use std::rc::Rc;
32
33 // This could have a better place to live.
34 pub trait MoveMap<T> {
35     fn move_map<F>(self, f: F) -> Self where F: FnMut(T) -> T;
36 }
37
38 impl<T> MoveMap<T> for Vec<T> {
39     fn move_map<F>(mut self, mut f: F) -> Vec<T> where F: FnMut(T) -> T {
40         for p in self.iter_mut() {
41             unsafe {
42                 // FIXME(#5016) this shouldn't need to zero to be safe.
43                 ptr::write(p, f(ptr::read_and_zero(p)));
44             }
45         }
46         self
47     }
48 }
49
50 impl<T> MoveMap<T> for OwnedSlice<T> {
51     fn move_map<F>(self, f: F) -> OwnedSlice<T> where F: FnMut(T) -> T {
52         OwnedSlice::from_vec(self.into_vec().move_map(f))
53     }
54 }
55
56 pub trait Folder : Sized {
57     // Any additions to this trait should happen in form
58     // of a call to a public `noop_*` function that only calls
59     // out to the folder again, not other `noop_*` functions.
60     //
61     // This is a necessary API workaround to the problem of not
62     // being able to call out to the super default method
63     // in an overridden default method.
64
65     fn fold_crate(&mut self, c: Crate) -> Crate {
66         noop_fold_crate(c, self)
67     }
68
69     fn fold_meta_items(&mut self, meta_items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
70         noop_fold_meta_items(meta_items, self)
71     }
72
73     fn fold_meta_item(&mut self, meta_item: P<MetaItem>) -> P<MetaItem> {
74         noop_fold_meta_item(meta_item, self)
75     }
76
77     fn fold_view_path(&mut self, view_path: P<ViewPath>) -> P<ViewPath> {
78         noop_fold_view_path(view_path, self)
79     }
80
81     fn fold_view_item(&mut self, vi: ViewItem) -> ViewItem {
82         noop_fold_view_item(vi, self)
83     }
84
85     fn fold_foreign_item(&mut self, ni: P<ForeignItem>) -> P<ForeignItem> {
86         noop_fold_foreign_item(ni, self)
87     }
88
89     fn fold_item(&mut self, i: P<Item>) -> SmallVector<P<Item>> {
90         noop_fold_item(i, self)
91     }
92
93     fn fold_item_simple(&mut self, i: Item) -> Item {
94         noop_fold_item_simple(i, self)
95     }
96
97     fn fold_struct_field(&mut self, sf: StructField) -> StructField {
98         noop_fold_struct_field(sf, self)
99     }
100
101     fn fold_item_underscore(&mut self, i: Item_) -> Item_ {
102         noop_fold_item_underscore(i, self)
103     }
104
105     fn fold_fn_decl(&mut self, d: P<FnDecl>) -> P<FnDecl> {
106         noop_fold_fn_decl(d, self)
107     }
108
109     fn fold_type_method(&mut self, m: TypeMethod) -> TypeMethod {
110         noop_fold_type_method(m, self)
111     }
112
113     fn fold_method(&mut self, m: P<Method>) -> SmallVector<P<Method>> {
114         noop_fold_method(m, self)
115     }
116
117     fn fold_block(&mut self, b: P<Block>) -> P<Block> {
118         noop_fold_block(b, self)
119     }
120
121     fn fold_stmt(&mut self, s: P<Stmt>) -> SmallVector<P<Stmt>> {
122         s.and_then(|s| noop_fold_stmt(s, self))
123     }
124
125     fn fold_arm(&mut self, a: Arm) -> Arm {
126         noop_fold_arm(a, self)
127     }
128
129     fn fold_pat(&mut self, p: P<Pat>) -> P<Pat> {
130         noop_fold_pat(p, self)
131     }
132
133     fn fold_decl(&mut self, d: P<Decl>) -> SmallVector<P<Decl>> {
134         noop_fold_decl(d, self)
135     }
136
137     fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
138         e.map(|e| noop_fold_expr(e, self))
139     }
140
141     fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> {
142         noop_fold_ty(t, self)
143     }
144
145     fn fold_qpath(&mut self, t: P<QPath>) -> P<QPath> {
146         noop_fold_qpath(t, self)
147     }
148
149     fn fold_ty_binding(&mut self, t: P<TypeBinding>) -> P<TypeBinding> {
150         noop_fold_ty_binding(t, self)
151     }
152
153     fn fold_mod(&mut self, m: Mod) -> Mod {
154         noop_fold_mod(m, self)
155     }
156
157     fn fold_foreign_mod(&mut self, nm: ForeignMod) -> ForeignMod {
158         noop_fold_foreign_mod(nm, self)
159     }
160
161     fn fold_variant(&mut self, v: P<Variant>) -> P<Variant> {
162         noop_fold_variant(v, self)
163     }
164
165     fn fold_ident(&mut self, i: Ident) -> Ident {
166         noop_fold_ident(i, self)
167     }
168
169     fn fold_uint(&mut self, i: uint) -> uint {
170         noop_fold_uint(i, self)
171     }
172
173     fn fold_path(&mut self, p: Path) -> Path {
174         noop_fold_path(p, self)
175     }
176
177     fn fold_path_parameters(&mut self, p: PathParameters) -> PathParameters {
178         noop_fold_path_parameters(p, self)
179     }
180
181     fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData)
182                                            -> AngleBracketedParameterData
183     {
184         noop_fold_angle_bracketed_parameter_data(p, self)
185     }
186
187     fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedParameterData)
188                                          -> ParenthesizedParameterData
189     {
190         noop_fold_parenthesized_parameter_data(p, self)
191     }
192
193     fn fold_local(&mut self, l: P<Local>) -> P<Local> {
194         noop_fold_local(l, self)
195     }
196
197     fn fold_mac(&mut self, _mac: Mac) -> Mac {
198         panic!("fold_mac disabled by default");
199         // NB: see note about macros above.
200         // if you really want a folder that
201         // works on macros, use this
202         // definition in your trait impl:
203         // fold::noop_fold_mac(_mac, self)
204     }
205
206     fn fold_explicit_self(&mut self, es: ExplicitSelf) -> ExplicitSelf {
207         noop_fold_explicit_self(es, self)
208     }
209
210     fn fold_explicit_self_underscore(&mut self, es: ExplicitSelf_) -> ExplicitSelf_ {
211         noop_fold_explicit_self_underscore(es, self)
212     }
213
214     fn fold_lifetime(&mut self, l: Lifetime) -> Lifetime {
215         noop_fold_lifetime(l, self)
216     }
217
218     fn fold_lifetime_def(&mut self, l: LifetimeDef) -> LifetimeDef {
219         noop_fold_lifetime_def(l, self)
220     }
221
222     fn fold_attribute(&mut self, at: Attribute) -> Attribute {
223         noop_fold_attribute(at, self)
224     }
225
226     fn fold_arg(&mut self, a: Arg) -> Arg {
227         noop_fold_arg(a, self)
228     }
229
230     fn fold_generics(&mut self, generics: Generics) -> Generics {
231         noop_fold_generics(generics, self)
232     }
233
234     fn fold_trait_ref(&mut self, p: TraitRef) -> TraitRef {
235         noop_fold_trait_ref(p, self)
236     }
237
238     fn fold_poly_trait_ref(&mut self, p: PolyTraitRef) -> PolyTraitRef {
239         noop_fold_poly_trait_ref(p, self)
240     }
241
242     fn fold_struct_def(&mut self, struct_def: P<StructDef>) -> P<StructDef> {
243         noop_fold_struct_def(struct_def, self)
244     }
245
246     fn fold_lifetimes(&mut self, lts: Vec<Lifetime>) -> Vec<Lifetime> {
247         noop_fold_lifetimes(lts, self)
248     }
249
250     fn fold_lifetime_defs(&mut self, lts: Vec<LifetimeDef>) -> Vec<LifetimeDef> {
251         noop_fold_lifetime_defs(lts, self)
252     }
253
254     fn fold_ty_param(&mut self, tp: TyParam) -> TyParam {
255         noop_fold_ty_param(tp, self)
256     }
257
258     fn fold_ty_params(&mut self, tps: OwnedSlice<TyParam>) -> OwnedSlice<TyParam> {
259         noop_fold_ty_params(tps, self)
260     }
261
262     fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
263         noop_fold_tt(tt, self)
264     }
265
266     fn fold_tts(&mut self, tts: &[TokenTree]) -> Vec<TokenTree> {
267         noop_fold_tts(tts, self)
268     }
269
270     fn fold_token(&mut self, t: token::Token) -> token::Token {
271         noop_fold_token(t, self)
272     }
273
274     fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal {
275         noop_fold_interpolated(nt, self)
276     }
277
278     fn fold_opt_lifetime(&mut self, o_lt: Option<Lifetime>) -> Option<Lifetime> {
279         noop_fold_opt_lifetime(o_lt, self)
280     }
281
282     fn fold_variant_arg(&mut self, va: VariantArg) -> VariantArg {
283         noop_fold_variant_arg(va, self)
284     }
285
286     fn fold_opt_bounds(&mut self, b: Option<OwnedSlice<TyParamBound>>)
287                        -> Option<OwnedSlice<TyParamBound>> {
288         noop_fold_opt_bounds(b, self)
289     }
290
291     fn fold_bounds(&mut self, b: OwnedSlice<TyParamBound>)
292                        -> OwnedSlice<TyParamBound> {
293         noop_fold_bounds(b, self)
294     }
295
296     fn fold_ty_param_bound(&mut self, tpb: TyParamBound) -> TyParamBound {
297         noop_fold_ty_param_bound(tpb, self)
298     }
299
300     fn fold_mt(&mut self, mt: MutTy) -> MutTy {
301         noop_fold_mt(mt, self)
302     }
303
304     fn fold_field(&mut self, field: Field) -> Field {
305         noop_fold_field(field, self)
306     }
307
308     fn fold_where_clause(&mut self, where_clause: WhereClause)
309                          -> WhereClause {
310         noop_fold_where_clause(where_clause, self)
311     }
312
313     fn fold_where_predicate(&mut self, where_predicate: WherePredicate)
314                             -> WherePredicate {
315         noop_fold_where_predicate(where_predicate, self)
316     }
317
318     fn fold_typedef(&mut self, typedef: Typedef) -> Typedef {
319         noop_fold_typedef(typedef, self)
320     }
321
322     fn fold_associated_type(&mut self, associated_type: AssociatedType)
323                             -> AssociatedType {
324         noop_fold_associated_type(associated_type, self)
325     }
326
327     fn new_id(&mut self, i: NodeId) -> NodeId {
328         i
329     }
330
331     fn new_span(&mut self, sp: Span) -> Span {
332         sp
333     }
334 }
335
336 pub fn noop_fold_meta_items<T: Folder>(meta_items: Vec<P<MetaItem>>, fld: &mut T)
337                                        -> Vec<P<MetaItem>> {
338     meta_items.move_map(|x| fld.fold_meta_item(x))
339 }
340
341 pub fn noop_fold_view_path<T: Folder>(view_path: P<ViewPath>, fld: &mut T) -> P<ViewPath> {
342     view_path.map(|Spanned {node, span}| Spanned {
343         node: match node {
344             ViewPathSimple(ident, path, node_id) => {
345                 let id = fld.new_id(node_id);
346                 ViewPathSimple(ident, fld.fold_path(path), id)
347             }
348             ViewPathGlob(path, node_id) => {
349                 let id = fld.new_id(node_id);
350                 ViewPathGlob(fld.fold_path(path), id)
351             }
352             ViewPathList(path, path_list_idents, node_id) => {
353                 let id = fld.new_id(node_id);
354                 ViewPathList(fld.fold_path(path),
355                              path_list_idents.move_map(|path_list_ident| {
356                                 Spanned {
357                                     node: match path_list_ident.node {
358                                         PathListIdent { id, name } =>
359                                             PathListIdent {
360                                                 id: fld.new_id(id),
361                                                 name: name
362                                             },
363                                         PathListMod { id } =>
364                                             PathListMod { id: fld.new_id(id) }
365                                     },
366                                     span: fld.new_span(path_list_ident.span)
367                                 }
368                              }),
369                              id)
370             }
371         },
372         span: fld.new_span(span)
373     })
374 }
375
376 pub fn noop_fold_arm<T: Folder>(Arm {attrs, pats, guard, body}: Arm, fld: &mut T) -> Arm {
377     Arm {
378         attrs: attrs.move_map(|x| fld.fold_attribute(x)),
379         pats: pats.move_map(|x| fld.fold_pat(x)),
380         guard: guard.map(|x| fld.fold_expr(x)),
381         body: fld.fold_expr(body),
382     }
383 }
384
385 pub fn noop_fold_decl<T: Folder>(d: P<Decl>, fld: &mut T) -> SmallVector<P<Decl>> {
386     d.and_then(|Spanned {node, span}| match node {
387         DeclLocal(l) => SmallVector::one(P(Spanned {
388             node: DeclLocal(fld.fold_local(l)),
389             span: fld.new_span(span)
390         })),
391         DeclItem(it) => fld.fold_item(it).into_iter().map(|i| P(Spanned {
392             node: DeclItem(i),
393             span: fld.new_span(span)
394         })).collect()
395     })
396 }
397
398 pub fn noop_fold_ty_binding<T: Folder>(b: P<TypeBinding>, fld: &mut T) -> P<TypeBinding> {
399     b.map(|TypeBinding { id, ident, ty, span }| TypeBinding {
400         id: fld.new_id(id),
401         ident: ident,
402         ty: fld.fold_ty(ty),
403         span: fld.new_span(span),
404     })
405 }
406
407 pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
408     t.map(|Ty {id, node, span}| Ty {
409         id: fld.new_id(id),
410         node: match node {
411             TyInfer => node,
412             TyVec(ty) => TyVec(fld.fold_ty(ty)),
413             TyPtr(mt) => TyPtr(fld.fold_mt(mt)),
414             TyRptr(region, mt) => {
415                 TyRptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt))
416             }
417             TyBareFn(f) => {
418                 TyBareFn(f.map(|BareFnTy {lifetimes, unsafety, abi, decl}| BareFnTy {
419                     lifetimes: fld.fold_lifetime_defs(lifetimes),
420                     unsafety: unsafety,
421                     abi: abi,
422                     decl: fld.fold_fn_decl(decl)
423                 }))
424             }
425             TyTup(tys) => TyTup(tys.move_map(|ty| fld.fold_ty(ty))),
426             TyParen(ty) => TyParen(fld.fold_ty(ty)),
427             TyPath(path, id) => {
428                 let id = fld.new_id(id);
429                 TyPath(fld.fold_path(path), id)
430             }
431             TyObjectSum(ty, bounds) => {
432                 TyObjectSum(fld.fold_ty(ty),
433                             fld.fold_bounds(bounds))
434             }
435             TyQPath(qpath) => {
436                 TyQPath(fld.fold_qpath(qpath))
437             }
438             TyFixedLengthVec(ty, e) => {
439                 TyFixedLengthVec(fld.fold_ty(ty), fld.fold_expr(e))
440             }
441             TyTypeof(expr) => {
442                 TyTypeof(fld.fold_expr(expr))
443             }
444             TyPolyTraitRef(bounds) => {
445                 TyPolyTraitRef(bounds.move_map(|b| fld.fold_ty_param_bound(b)))
446             }
447         },
448         span: fld.new_span(span)
449     })
450 }
451
452 pub fn noop_fold_qpath<T: Folder>(qpath: P<QPath>, fld: &mut T) -> P<QPath> {
453     qpath.map(|qpath| {
454         QPath {
455             self_type: fld.fold_ty(qpath.self_type),
456             trait_ref: qpath.trait_ref.map(|tr| fld.fold_trait_ref(tr)),
457             item_name: fld.fold_ident(qpath.item_name),
458         }
459     })
460 }
461
462 pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, view_items, items}: ForeignMod,
463                                         fld: &mut T) -> ForeignMod {
464     ForeignMod {
465         abi: abi,
466         view_items: view_items.move_map(|x| fld.fold_view_item(x)),
467         items: items.move_map(|x| fld.fold_foreign_item(x)),
468     }
469 }
470
471 pub fn noop_fold_variant<T: Folder>(v: P<Variant>, fld: &mut T) -> P<Variant> {
472     v.map(|Spanned {node: Variant_ {id, name, attrs, kind, disr_expr, vis}, span}| Spanned {
473         node: Variant_ {
474             id: fld.new_id(id),
475             name: name,
476             attrs: attrs.move_map(|x| fld.fold_attribute(x)),
477             kind: match kind {
478                 TupleVariantKind(variant_args) => {
479                     TupleVariantKind(variant_args.move_map(|x|
480                         fld.fold_variant_arg(x)))
481                 }
482                 StructVariantKind(struct_def) => {
483                     StructVariantKind(fld.fold_struct_def(struct_def))
484                 }
485             },
486             disr_expr: disr_expr.map(|e| fld.fold_expr(e)),
487             vis: vis,
488         },
489         span: fld.new_span(span),
490     })
491 }
492
493 pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident {
494     i
495 }
496
497 pub fn noop_fold_uint<T: Folder>(i: uint, _: &mut T) -> uint {
498     i
499 }
500
501 pub fn noop_fold_path<T: Folder>(Path {global, segments, span}: Path, fld: &mut T) -> Path {
502     Path {
503         global: global,
504         segments: segments.move_map(|PathSegment {identifier, parameters}| PathSegment {
505             identifier: fld.fold_ident(identifier),
506             parameters: fld.fold_path_parameters(parameters),
507         }),
508         span: fld.new_span(span)
509     }
510 }
511
512 pub fn noop_fold_path_parameters<T: Folder>(path_parameters: PathParameters, fld: &mut T)
513                                             -> PathParameters
514 {
515     match path_parameters {
516         AngleBracketedParameters(data) =>
517             AngleBracketedParameters(fld.fold_angle_bracketed_parameter_data(data)),
518         ParenthesizedParameters(data) =>
519             ParenthesizedParameters(fld.fold_parenthesized_parameter_data(data)),
520     }
521 }
522
523 pub fn noop_fold_angle_bracketed_parameter_data<T: Folder>(data: AngleBracketedParameterData,
524                                                            fld: &mut T)
525                                                            -> AngleBracketedParameterData
526 {
527     let AngleBracketedParameterData { lifetimes, types, bindings } = data;
528     AngleBracketedParameterData { lifetimes: fld.fold_lifetimes(lifetimes),
529                                   types: types.move_map(|ty| fld.fold_ty(ty)),
530                                   bindings: bindings.move_map(|b| fld.fold_ty_binding(b)) }
531 }
532
533 pub fn noop_fold_parenthesized_parameter_data<T: Folder>(data: ParenthesizedParameterData,
534                                                          fld: &mut T)
535                                                          -> ParenthesizedParameterData
536 {
537     let ParenthesizedParameterData { inputs, output } = data;
538     ParenthesizedParameterData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)),
539                                  output: output.map(|ty| fld.fold_ty(ty)) }
540 }
541
542 pub fn noop_fold_local<T: Folder>(l: P<Local>, fld: &mut T) -> P<Local> {
543     l.map(|Local {id, pat, ty, init, source, span}| Local {
544         id: fld.new_id(id),
545         ty: ty.map(|t| fld.fold_ty(t)),
546         pat: fld.fold_pat(pat),
547         init: init.map(|e| fld.fold_expr(e)),
548         source: source,
549         span: fld.new_span(span)
550     })
551 }
552
553 pub fn noop_fold_attribute<T: Folder>(at: Attribute, fld: &mut T) -> Attribute {
554     let Spanned {node: Attribute_ {id, style, value, is_sugared_doc}, span} = at;
555     Spanned {
556         node: Attribute_ {
557             id: id,
558             style: style,
559             value: fld.fold_meta_item(value),
560             is_sugared_doc: is_sugared_doc
561         },
562         span: fld.new_span(span)
563     }
564 }
565
566 pub fn noop_fold_explicit_self_underscore<T: Folder>(es: ExplicitSelf_, fld: &mut T)
567                                                      -> ExplicitSelf_ {
568     match es {
569         SelfStatic | SelfValue(_) => es,
570         SelfRegion(lifetime, m, ident) => {
571             SelfRegion(fld.fold_opt_lifetime(lifetime), m, ident)
572         }
573         SelfExplicit(typ, ident) => {
574             SelfExplicit(fld.fold_ty(typ), ident)
575         }
576     }
577 }
578
579 pub fn noop_fold_explicit_self<T: Folder>(Spanned {span, node}: ExplicitSelf, fld: &mut T)
580                                           -> ExplicitSelf {
581     Spanned {
582         node: fld.fold_explicit_self_underscore(node),
583         span: fld.new_span(span)
584     }
585 }
586
587
588 pub fn noop_fold_mac<T: Folder>(Spanned {node, span}: Mac, fld: &mut T) -> Mac {
589     Spanned {
590         node: match node {
591             MacInvocTT(p, tts, ctxt) => {
592                 MacInvocTT(fld.fold_path(p), fld.fold_tts(tts.as_slice()), ctxt)
593             }
594         },
595         span: fld.new_span(span)
596     }
597 }
598
599 pub fn noop_fold_meta_item<T: Folder>(mi: P<MetaItem>, fld: &mut T) -> P<MetaItem> {
600     mi.map(|Spanned {node, span}| Spanned {
601         node: match node {
602             MetaWord(id) => MetaWord(id),
603             MetaList(id, mis) => {
604                 MetaList(id, mis.move_map(|e| fld.fold_meta_item(e)))
605             }
606             MetaNameValue(id, s) => MetaNameValue(id, s)
607         },
608         span: fld.new_span(span)
609     })
610 }
611
612 pub fn noop_fold_arg<T: Folder>(Arg {id, pat, ty}: Arg, fld: &mut T) -> Arg {
613     Arg {
614         id: fld.new_id(id),
615         pat: fld.fold_pat(pat),
616         ty: fld.fold_ty(ty)
617     }
618 }
619
620 pub fn noop_fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree {
621     match *tt {
622         TtToken(span, ref tok) =>
623             TtToken(span, fld.fold_token(tok.clone())),
624         TtDelimited(span, ref delimed) => {
625             TtDelimited(span, Rc::new(
626                             Delimited {
627                                 delim: delimed.delim,
628                                 open_span: delimed.open_span,
629                                 tts: fld.fold_tts(delimed.tts.as_slice()),
630                                 close_span: delimed.close_span,
631                             }
632                         ))
633         },
634         TtSequence(span, ref seq) =>
635             TtSequence(span,
636                        Rc::new(SequenceRepetition {
637                            tts: fld.fold_tts(seq.tts.as_slice()),
638                            separator: seq.separator.clone().map(|tok| fld.fold_token(tok)),
639                            ..**seq
640                        })),
641     }
642 }
643
644 pub fn noop_fold_tts<T: Folder>(tts: &[TokenTree], fld: &mut T) -> Vec<TokenTree> {
645     tts.iter().map(|tt| fld.fold_tt(tt)).collect()
646 }
647
648 // apply ident folder if it's an ident, apply other folds to interpolated nodes
649 pub fn noop_fold_token<T: Folder>(t: token::Token, fld: &mut T) -> token::Token {
650     match t {
651         token::Ident(id, followed_by_colons) => {
652             token::Ident(fld.fold_ident(id), followed_by_colons)
653         }
654         token::Lifetime(id) => token::Lifetime(fld.fold_ident(id)),
655         token::Interpolated(nt) => token::Interpolated(fld.fold_interpolated(nt)),
656         token::SubstNt(ident, namep) => {
657             token::SubstNt(fld.fold_ident(ident), namep)
658         }
659         token::MatchNt(name, kind, namep, kindp) => {
660             token::MatchNt(fld.fold_ident(name), fld.fold_ident(kind), namep, kindp)
661         }
662         _ => t
663     }
664 }
665
666 /// apply folder to elements of interpolated nodes
667 //
668 // NB: this can occur only when applying a fold to partially expanded code, where
669 // parsed pieces have gotten implanted ito *other* macro invocations. This is relevant
670 // for macro hygiene, but possibly not elsewhere.
671 //
672 // One problem here occurs because the types for fold_item, fold_stmt, etc. allow the
673 // folder to return *multiple* items; this is a problem for the nodes here, because
674 // they insist on having exactly one piece. One solution would be to mangle the fold
675 // trait to include one-to-many and one-to-one versions of these entry points, but that
676 // would probably confuse a lot of people and help very few. Instead, I'm just going
677 // to put in dynamic checks. I think the performance impact of this will be pretty much
678 // nonexistent. The danger is that someone will apply a fold to a partially expanded
679 // node, and will be confused by the fact that their "fold_item" or "fold_stmt" isn't
680 // getting called on NtItem or NtStmt nodes. Hopefully they'll wind up reading this
681 // comment, and doing something appropriate.
682 //
683 // BTW, design choice: I considered just changing the type of, e.g., NtItem to contain
684 // multiple items, but decided against it when I looked at parse_item_or_view_item and
685 // tried to figure out what I would do with multiple items there....
686 pub fn noop_fold_interpolated<T: Folder>(nt: token::Nonterminal, fld: &mut T)
687                                          -> token::Nonterminal {
688     match nt {
689         token::NtItem(item) =>
690             token::NtItem(fld.fold_item(item)
691                           // this is probably okay, because the only folds likely
692                           // to peek inside interpolated nodes will be renamings/markings,
693                           // which map single items to single items
694                           .expect_one("expected fold to produce exactly one item")),
695         token::NtBlock(block) => token::NtBlock(fld.fold_block(block)),
696         token::NtStmt(stmt) =>
697             token::NtStmt(fld.fold_stmt(stmt)
698                           // this is probably okay, because the only folds likely
699                           // to peek inside interpolated nodes will be renamings/markings,
700                           // which map single items to single items
701                           .expect_one("expected fold to produce exactly one statement")),
702         token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)),
703         token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)),
704         token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)),
705         token::NtIdent(box id, is_mod_name) =>
706             token::NtIdent(box fld.fold_ident(id), is_mod_name),
707         token::NtMeta(meta_item) => token::NtMeta(fld.fold_meta_item(meta_item)),
708         token::NtPath(box path) => token::NtPath(box fld.fold_path(path)),
709         token::NtTT(tt) => token::NtTT(P(fld.fold_tt(&*tt))),
710     }
711 }
712
713 pub fn noop_fold_fn_decl<T: Folder>(decl: P<FnDecl>, fld: &mut T) -> P<FnDecl> {
714     decl.map(|FnDecl {inputs, output, variadic}| FnDecl {
715         inputs: inputs.move_map(|x| fld.fold_arg(x)),
716         output: match output {
717             Return(ty) => Return(fld.fold_ty(ty)),
718             NoReturn(span) => NoReturn(span)
719         },
720         variadic: variadic
721     })
722 }
723
724 pub fn noop_fold_ty_param_bound<T>(tpb: TyParamBound, fld: &mut T)
725                                    -> TyParamBound
726                                    where T: Folder {
727     match tpb {
728         TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier),
729         RegionTyParamBound(lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)),
730     }
731 }
732
733 pub fn noop_fold_ty_param<T: Folder>(tp: TyParam, fld: &mut T) -> TyParam {
734     let TyParam {id, ident, bounds, default, span} = tp;
735     TyParam {
736         id: fld.new_id(id),
737         ident: ident,
738         bounds: fld.fold_bounds(bounds),
739         default: default.map(|x| fld.fold_ty(x)),
740         span: span
741     }
742 }
743
744 pub fn noop_fold_ty_params<T: Folder>(tps: OwnedSlice<TyParam>, fld: &mut T)
745                                       -> OwnedSlice<TyParam> {
746     tps.move_map(|tp| fld.fold_ty_param(tp))
747 }
748
749 pub fn noop_fold_lifetime<T: Folder>(l: Lifetime, fld: &mut T) -> Lifetime {
750     Lifetime {
751         id: fld.new_id(l.id),
752         name: l.name,
753         span: fld.new_span(l.span)
754     }
755 }
756
757 pub fn noop_fold_lifetime_def<T: Folder>(l: LifetimeDef, fld: &mut T)
758                                          -> LifetimeDef {
759     LifetimeDef {
760         lifetime: fld.fold_lifetime(l.lifetime),
761         bounds: fld.fold_lifetimes(l.bounds),
762     }
763 }
764
765 pub fn noop_fold_lifetimes<T: Folder>(lts: Vec<Lifetime>, fld: &mut T) -> Vec<Lifetime> {
766     lts.move_map(|l| fld.fold_lifetime(l))
767 }
768
769 pub fn noop_fold_lifetime_defs<T: Folder>(lts: Vec<LifetimeDef>, fld: &mut T)
770                                           -> Vec<LifetimeDef> {
771     lts.move_map(|l| fld.fold_lifetime_def(l))
772 }
773
774 pub fn noop_fold_opt_lifetime<T: Folder>(o_lt: Option<Lifetime>, fld: &mut T)
775                                          -> Option<Lifetime> {
776     o_lt.map(|lt| fld.fold_lifetime(lt))
777 }
778
779 pub fn noop_fold_generics<T: Folder>(Generics {ty_params, lifetimes, where_clause}: Generics,
780                                      fld: &mut T) -> Generics {
781     Generics {
782         ty_params: fld.fold_ty_params(ty_params),
783         lifetimes: fld.fold_lifetime_defs(lifetimes),
784         where_clause: fld.fold_where_clause(where_clause),
785     }
786 }
787
788 pub fn noop_fold_where_clause<T: Folder>(
789                               WhereClause {id, predicates}: WhereClause,
790                               fld: &mut T)
791                               -> WhereClause {
792     WhereClause {
793         id: fld.new_id(id),
794         predicates: predicates.move_map(|predicate| {
795             fld.fold_where_predicate(predicate)
796         })
797     }
798 }
799
800 pub fn noop_fold_where_predicate<T: Folder>(
801                                  pred: WherePredicate,
802                                  fld: &mut T)
803                                  -> WherePredicate {
804     match pred {
805         ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{bounded_ty,
806                                                                      bounds,
807                                                                      span}) => {
808             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
809                 bounded_ty: fld.fold_ty(bounded_ty),
810                 bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)),
811                 span: fld.new_span(span)
812             })
813         }
814         ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{lifetime,
815                                                                        bounds,
816                                                                        span}) => {
817             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
818                 span: fld.new_span(span),
819                 lifetime: fld.fold_lifetime(lifetime),
820                 bounds: bounds.move_map(|bound| fld.fold_lifetime(bound))
821             })
822         }
823         ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{id,
824                                                                path,
825                                                                ty,
826                                                                span}) => {
827             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{
828                 id: fld.new_id(id),
829                 path: fld.fold_path(path),
830                 ty:fld.fold_ty(ty),
831                 span: fld.new_span(span)
832             })
833         }
834     }
835 }
836
837 pub fn noop_fold_typedef<T>(t: Typedef, folder: &mut T)
838                             -> Typedef
839                             where T: Folder {
840     let new_id = folder.new_id(t.id);
841     let new_span = folder.new_span(t.span);
842     let new_attrs = t.attrs.iter().map(|attr| {
843         folder.fold_attribute((*attr).clone())
844     }).collect();
845     let new_ident = folder.fold_ident(t.ident);
846     let new_type = folder.fold_ty(t.typ);
847     ast::Typedef {
848         ident: new_ident,
849         typ: new_type,
850         id: new_id,
851         span: new_span,
852         vis: t.vis,
853         attrs: new_attrs,
854     }
855 }
856
857 pub fn noop_fold_associated_type<T>(at: AssociatedType, folder: &mut T)
858                                     -> AssociatedType
859                                     where T: Folder
860 {
861     let new_attrs = at.attrs
862                       .iter()
863                       .map(|attr| folder.fold_attribute((*attr).clone()))
864                       .collect();
865     let new_param = folder.fold_ty_param(at.ty_param);
866     ast::AssociatedType {
867         attrs: new_attrs,
868         ty_param: new_param,
869     }
870 }
871
872 pub fn noop_fold_struct_def<T: Folder>(struct_def: P<StructDef>, fld: &mut T) -> P<StructDef> {
873     struct_def.map(|StructDef { fields, ctor_id }| StructDef {
874         fields: fields.move_map(|f| fld.fold_struct_field(f)),
875         ctor_id: ctor_id.map(|cid| fld.new_id(cid)),
876     })
877 }
878
879 pub fn noop_fold_trait_ref<T: Folder>(p: TraitRef, fld: &mut T) -> TraitRef {
880     let id = fld.new_id(p.ref_id);
881     let TraitRef {
882         path,
883         ref_id: _,
884     } = p;
885     ast::TraitRef {
886         path: fld.fold_path(path),
887         ref_id: id,
888     }
889 }
890
891 pub fn noop_fold_poly_trait_ref<T: Folder>(p: PolyTraitRef, fld: &mut T) -> PolyTraitRef {
892     ast::PolyTraitRef {
893         bound_lifetimes: fld.fold_lifetime_defs(p.bound_lifetimes),
894         trait_ref: fld.fold_trait_ref(p.trait_ref)
895     }
896 }
897
898 pub fn noop_fold_struct_field<T: Folder>(f: StructField, fld: &mut T) -> StructField {
899     let StructField {node: StructField_ {id, kind, ty, attrs}, span} = f;
900     Spanned {
901         node: StructField_ {
902             id: fld.new_id(id),
903             kind: kind,
904             ty: fld.fold_ty(ty),
905             attrs: attrs.move_map(|a| fld.fold_attribute(a))
906         },
907         span: fld.new_span(span)
908     }
909 }
910
911 pub fn noop_fold_field<T: Folder>(Field {ident, expr, span}: Field, folder: &mut T) -> Field {
912     Field {
913         ident: respan(ident.span, folder.fold_ident(ident.node)),
914         expr: folder.fold_expr(expr),
915         span: folder.new_span(span)
916     }
917 }
918
919 pub fn noop_fold_mt<T: Folder>(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutTy {
920     MutTy {
921         ty: folder.fold_ty(ty),
922         mutbl: mutbl,
923     }
924 }
925
926 pub fn noop_fold_opt_bounds<T: Folder>(b: Option<OwnedSlice<TyParamBound>>, folder: &mut T)
927                                        -> Option<OwnedSlice<TyParamBound>> {
928     b.map(|bounds| folder.fold_bounds(bounds))
929 }
930
931 fn noop_fold_bounds<T: Folder>(bounds: TyParamBounds, folder: &mut T)
932                           -> TyParamBounds {
933     bounds.move_map(|bound| folder.fold_ty_param_bound(bound))
934 }
935
936 fn noop_fold_variant_arg<T: Folder>(VariantArg {id, ty}: VariantArg, folder: &mut T)
937                                     -> VariantArg {
938     VariantArg {
939         id: folder.new_id(id),
940         ty: folder.fold_ty(ty)
941     }
942 }
943
944 pub fn noop_fold_view_item<T: Folder>(ViewItem {node, attrs, vis, span}: ViewItem,
945                                       folder: &mut T) -> ViewItem {
946     ViewItem {
947         node: match node {
948             ViewItemExternCrate(ident, string, node_id) => {
949                 ViewItemExternCrate(ident, string,
950                                     folder.new_id(node_id))
951             }
952             ViewItemUse(view_path) => {
953                 ViewItemUse(folder.fold_view_path(view_path))
954             }
955         },
956         attrs: attrs.move_map(|a| folder.fold_attribute(a)),
957         vis: vis,
958         span: folder.new_span(span)
959     }
960 }
961
962 pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> {
963     b.map(|Block {id, view_items, stmts, expr, rules, span}| Block {
964         id: folder.new_id(id),
965         view_items: view_items.move_map(|x| folder.fold_view_item(x)),
966         stmts: stmts.into_iter().flat_map(|s| folder.fold_stmt(s).into_iter()).collect(),
967         expr: expr.map(|x| folder.fold_expr(x)),
968         rules: rules,
969         span: folder.new_span(span),
970     })
971 }
972
973 pub fn noop_fold_item_underscore<T: Folder>(i: Item_, folder: &mut T) -> Item_ {
974     match i {
975         ItemStatic(t, m, e) => {
976             ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e))
977         }
978         ItemConst(t, e) => {
979             ItemConst(folder.fold_ty(t), folder.fold_expr(e))
980         }
981         ItemFn(decl, unsafety, abi, generics, body) => {
982             ItemFn(
983                 folder.fold_fn_decl(decl),
984                 unsafety,
985                 abi,
986                 folder.fold_generics(generics),
987                 folder.fold_block(body)
988             )
989         }
990         ItemMod(m) => ItemMod(folder.fold_mod(m)),
991         ItemForeignMod(nm) => ItemForeignMod(folder.fold_foreign_mod(nm)),
992         ItemTy(t, generics) => {
993             ItemTy(folder.fold_ty(t), folder.fold_generics(generics))
994         }
995         ItemEnum(enum_definition, generics) => {
996             ItemEnum(
997                 ast::EnumDef {
998                     variants: enum_definition.variants.move_map(|x| folder.fold_variant(x)),
999                 },
1000                 folder.fold_generics(generics))
1001         }
1002         ItemStruct(struct_def, generics) => {
1003             let struct_def = folder.fold_struct_def(struct_def);
1004             ItemStruct(struct_def, folder.fold_generics(generics))
1005         }
1006         ItemImpl(unsafety, polarity, generics, ifce, ty, impl_items) => {
1007             let mut new_impl_items = Vec::new();
1008             for impl_item in impl_items.iter() {
1009                 match *impl_item {
1010                     MethodImplItem(ref x) => {
1011                         for method in folder.fold_method((*x).clone())
1012                                             .into_iter() {
1013                             new_impl_items.push(MethodImplItem(method))
1014                         }
1015                     }
1016                     TypeImplItem(ref t) => {
1017                         new_impl_items.push(TypeImplItem(
1018                                 P(folder.fold_typedef((**t).clone()))));
1019                     }
1020                 }
1021             }
1022             let ifce = match ifce {
1023                 None => None,
1024                 Some(ref trait_ref) => {
1025                     Some(folder.fold_trait_ref((*trait_ref).clone()))
1026                 }
1027             };
1028             ItemImpl(unsafety,
1029                      polarity,
1030                      folder.fold_generics(generics),
1031                      ifce,
1032                      folder.fold_ty(ty),
1033                      new_impl_items)
1034         }
1035         ItemTrait(unsafety, generics, bounds, methods) => {
1036             let bounds = folder.fold_bounds(bounds);
1037             let methods = methods.into_iter().flat_map(|method| {
1038                 let r = match method {
1039                     RequiredMethod(m) => {
1040                             SmallVector::one(RequiredMethod(
1041                                     folder.fold_type_method(m)))
1042                                 .into_iter()
1043                     }
1044                     ProvidedMethod(method) => {
1045                         // the awkward collect/iter idiom here is because
1046                         // even though an iter and a map satisfy the same
1047                         // trait bound, they're not actually the same type, so
1048                         // the method arms don't unify.
1049                         let methods: SmallVector<ast::TraitItem> =
1050                             folder.fold_method(method).into_iter()
1051                             .map(|m| ProvidedMethod(m)).collect();
1052                         methods.into_iter()
1053                     }
1054                     TypeTraitItem(at) => {
1055                         SmallVector::one(TypeTraitItem(P(
1056                                     folder.fold_associated_type(
1057                                         (*at).clone()))))
1058                             .into_iter()
1059                     }
1060                 };
1061                 r
1062             }).collect();
1063             ItemTrait(unsafety,
1064                       folder.fold_generics(generics),
1065                       bounds,
1066                       methods)
1067         }
1068         ItemMac(m) => ItemMac(folder.fold_mac(m)),
1069     }
1070 }
1071
1072 pub fn noop_fold_type_method<T: Folder>(m: TypeMethod, fld: &mut T) -> TypeMethod {
1073     let TypeMethod {
1074         id,
1075         ident,
1076         attrs,
1077         unsafety,
1078         abi,
1079         decl,
1080         generics,
1081         explicit_self,
1082         vis,
1083         span
1084     } = m;
1085     TypeMethod {
1086         id: fld.new_id(id),
1087         ident: fld.fold_ident(ident),
1088         attrs: attrs.move_map(|a| fld.fold_attribute(a)),
1089         unsafety: unsafety,
1090         abi: abi,
1091         decl: fld.fold_fn_decl(decl),
1092         generics: fld.fold_generics(generics),
1093         explicit_self: fld.fold_explicit_self(explicit_self),
1094         vis: vis,
1095         span: fld.new_span(span)
1096     }
1097 }
1098
1099 pub fn noop_fold_mod<T: Folder>(Mod {inner, view_items, items}: Mod, folder: &mut T) -> Mod {
1100     Mod {
1101         inner: folder.new_span(inner),
1102         view_items: view_items.move_map(|x| folder.fold_view_item(x)),
1103         items: items.into_iter().flat_map(|x| folder.fold_item(x).into_iter()).collect(),
1104     }
1105 }
1106
1107 pub fn noop_fold_crate<T: Folder>(Crate {module, attrs, config, mut exported_macros, span}: Crate,
1108                                   folder: &mut T) -> Crate {
1109     let config = folder.fold_meta_items(config);
1110
1111     let mut items = folder.fold_item(P(ast::Item {
1112         ident: token::special_idents::invalid,
1113         attrs: attrs,
1114         id: ast::DUMMY_NODE_ID,
1115         vis: ast::Public,
1116         span: span,
1117         node: ast::ItemMod(module),
1118     })).into_iter();
1119
1120     let (module, attrs, span) = match items.next() {
1121         Some(item) => {
1122             assert!(items.next().is_none(),
1123                     "a crate cannot expand to more than one item");
1124             item.and_then(|ast::Item { attrs, span, node, .. }| {
1125                 match node {
1126                     ast::ItemMod(m) => (m, attrs, span),
1127                     _ => panic!("fold converted a module to not a module"),
1128                 }
1129             })
1130         }
1131         None => (ast::Mod {
1132             inner: span,
1133             view_items: Vec::new(),
1134             items: Vec::new(),
1135         }, Vec::new(), span)
1136     };
1137
1138     for def in exported_macros.iter_mut() {
1139         def.id = folder.new_id(def.id);
1140     }
1141
1142     Crate {
1143         module: module,
1144         attrs: attrs,
1145         config: config,
1146         exported_macros: exported_macros,
1147         span: span,
1148     }
1149 }
1150
1151 // fold one item into possibly many items
1152 pub fn noop_fold_item<T: Folder>(i: P<Item>, folder: &mut T) -> SmallVector<P<Item>> {
1153     SmallVector::one(i.map(|i| folder.fold_item_simple(i)))
1154 }
1155
1156 // fold one item into exactly one item
1157 pub fn noop_fold_item_simple<T: Folder>(Item {id, ident, attrs, node, vis, span}: Item,
1158                                         folder: &mut T) -> Item {
1159     let id = folder.new_id(id);
1160     let node = folder.fold_item_underscore(node);
1161     let ident = match node {
1162         // The node may have changed, recompute the "pretty" impl name.
1163         ItemImpl(_, _, _, ref maybe_trait, ref ty, _) => {
1164             ast_util::impl_pretty_name(maybe_trait, &**ty)
1165         }
1166         _ => ident
1167     };
1168
1169     Item {
1170         id: id,
1171         ident: folder.fold_ident(ident),
1172         attrs: attrs.move_map(|e| folder.fold_attribute(e)),
1173         node: node,
1174         vis: vis,
1175         span: folder.new_span(span)
1176     }
1177 }
1178
1179 pub fn noop_fold_foreign_item<T: Folder>(ni: P<ForeignItem>, folder: &mut T) -> P<ForeignItem> {
1180     ni.map(|ForeignItem {id, ident, attrs, node, span, vis}| ForeignItem {
1181         id: folder.new_id(id),
1182         ident: folder.fold_ident(ident),
1183         attrs: attrs.move_map(|x| folder.fold_attribute(x)),
1184         node: match node {
1185             ForeignItemFn(fdec, generics) => {
1186                 ForeignItemFn(fdec.map(|FnDecl {inputs, output, variadic}| FnDecl {
1187                     inputs: inputs.move_map(|a| folder.fold_arg(a)),
1188                     output: match output {
1189                         Return(ty) => Return(folder.fold_ty(ty)),
1190                         NoReturn(span) => NoReturn(span)
1191                     },
1192                     variadic: variadic
1193                 }), folder.fold_generics(generics))
1194             }
1195             ForeignItemStatic(t, m) => {
1196                 ForeignItemStatic(folder.fold_ty(t), m)
1197             }
1198         },
1199         vis: vis,
1200         span: folder.new_span(span)
1201     })
1202 }
1203
1204 // Default fold over a method.
1205 // Invariant: produces exactly one method.
1206 pub fn noop_fold_method<T: Folder>(m: P<Method>, folder: &mut T) -> SmallVector<P<Method>> {
1207     SmallVector::one(m.map(|Method {id, attrs, node, span}| Method {
1208         id: folder.new_id(id),
1209         attrs: attrs.move_map(|a| folder.fold_attribute(a)),
1210         node: match node {
1211             MethDecl(ident,
1212                      generics,
1213                      abi,
1214                      explicit_self,
1215                      unsafety,
1216                      decl,
1217                      body,
1218                      vis) => {
1219                 MethDecl(folder.fold_ident(ident),
1220                          folder.fold_generics(generics),
1221                          abi,
1222                          folder.fold_explicit_self(explicit_self),
1223                          unsafety,
1224                          folder.fold_fn_decl(decl),
1225                          folder.fold_block(body),
1226                          vis)
1227             },
1228             MethMac(mac) => MethMac(folder.fold_mac(mac)),
1229         },
1230         span: folder.new_span(span)
1231     }))
1232 }
1233
1234 pub fn noop_fold_pat<T: Folder>(p: P<Pat>, folder: &mut T) -> P<Pat> {
1235     p.map(|Pat {id, node, span}| Pat {
1236         id: folder.new_id(id),
1237         node: match node {
1238             PatWild(k) => PatWild(k),
1239             PatIdent(binding_mode, pth1, sub) => {
1240                 PatIdent(binding_mode,
1241                         Spanned{span: folder.new_span(pth1.span),
1242                                 node: folder.fold_ident(pth1.node)},
1243                         sub.map(|x| folder.fold_pat(x)))
1244             }
1245             PatLit(e) => PatLit(folder.fold_expr(e)),
1246             PatEnum(pth, pats) => {
1247                 PatEnum(folder.fold_path(pth),
1248                         pats.map(|pats| pats.move_map(|x| folder.fold_pat(x))))
1249             }
1250             PatStruct(pth, fields, etc) => {
1251                 let pth = folder.fold_path(pth);
1252                 let fs = fields.move_map(|f| {
1253                     Spanned { span: folder.new_span(f.span),
1254                               node: ast::FieldPat {
1255                                   ident: f.node.ident,
1256                                   pat: folder.fold_pat(f.node.pat),
1257                                   is_shorthand: f.node.is_shorthand,
1258                               }}
1259                 });
1260                 PatStruct(pth, fs, etc)
1261             }
1262             PatTup(elts) => PatTup(elts.move_map(|x| folder.fold_pat(x))),
1263             PatBox(inner) => PatBox(folder.fold_pat(inner)),
1264             PatRegion(inner, mutbl) => PatRegion(folder.fold_pat(inner), mutbl),
1265             PatRange(e1, e2) => {
1266                 PatRange(folder.fold_expr(e1), folder.fold_expr(e2))
1267             },
1268             PatVec(before, slice, after) => {
1269                 PatVec(before.move_map(|x| folder.fold_pat(x)),
1270                        slice.map(|x| folder.fold_pat(x)),
1271                        after.move_map(|x| folder.fold_pat(x)))
1272             }
1273             PatMac(mac) => PatMac(folder.fold_mac(mac))
1274         },
1275         span: folder.new_span(span)
1276     })
1277 }
1278
1279 pub fn noop_fold_expr<T: Folder>(Expr {id, node, span}: Expr, folder: &mut T) -> Expr {
1280     Expr {
1281         id: folder.new_id(id),
1282         node: match node {
1283             ExprBox(p, e) => {
1284                 ExprBox(p.map(|e|folder.fold_expr(e)), folder.fold_expr(e))
1285             }
1286             ExprVec(exprs) => {
1287                 ExprVec(exprs.move_map(|x| folder.fold_expr(x)))
1288             }
1289             ExprRepeat(expr, count) => {
1290                 ExprRepeat(folder.fold_expr(expr), folder.fold_expr(count))
1291             }
1292             ExprTup(elts) => ExprTup(elts.move_map(|x| folder.fold_expr(x))),
1293             ExprCall(f, args) => {
1294                 ExprCall(folder.fold_expr(f),
1295                          args.move_map(|x| folder.fold_expr(x)))
1296             }
1297             ExprMethodCall(i, tps, args) => {
1298                 ExprMethodCall(
1299                     respan(i.span, folder.fold_ident(i.node)),
1300                     tps.move_map(|x| folder.fold_ty(x)),
1301                     args.move_map(|x| folder.fold_expr(x)))
1302             }
1303             ExprBinary(binop, lhs, rhs) => {
1304                 ExprBinary(binop,
1305                         folder.fold_expr(lhs),
1306                         folder.fold_expr(rhs))
1307             }
1308             ExprUnary(binop, ohs) => {
1309                 ExprUnary(binop, folder.fold_expr(ohs))
1310             }
1311             ExprLit(l) => ExprLit(l),
1312             ExprCast(expr, ty) => {
1313                 ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
1314             }
1315             ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
1316             ExprIf(cond, tr, fl) => {
1317                 ExprIf(folder.fold_expr(cond),
1318                        folder.fold_block(tr),
1319                        fl.map(|x| folder.fold_expr(x)))
1320             }
1321             ExprIfLet(pat, expr, tr, fl) => {
1322                 ExprIfLet(folder.fold_pat(pat),
1323                           folder.fold_expr(expr),
1324                           folder.fold_block(tr),
1325                           fl.map(|x| folder.fold_expr(x)))
1326             }
1327             ExprWhile(cond, body, opt_ident) => {
1328                 ExprWhile(folder.fold_expr(cond),
1329                           folder.fold_block(body),
1330                           opt_ident.map(|i| folder.fold_ident(i)))
1331             }
1332             ExprWhileLet(pat, expr, body, opt_ident) => {
1333                 ExprWhileLet(folder.fold_pat(pat),
1334                              folder.fold_expr(expr),
1335                              folder.fold_block(body),
1336                              opt_ident.map(|i| folder.fold_ident(i)))
1337             }
1338             ExprForLoop(pat, iter, body, opt_ident) => {
1339                 ExprForLoop(folder.fold_pat(pat),
1340                             folder.fold_expr(iter),
1341                             folder.fold_block(body),
1342                             opt_ident.map(|i| folder.fold_ident(i)))
1343             }
1344             ExprLoop(body, opt_ident) => {
1345                 ExprLoop(folder.fold_block(body),
1346                         opt_ident.map(|i| folder.fold_ident(i)))
1347             }
1348             ExprMatch(expr, arms, source) => {
1349                 ExprMatch(folder.fold_expr(expr),
1350                         arms.move_map(|x| folder.fold_arm(x)),
1351                         source)
1352             }
1353             ExprClosure(capture_clause, opt_kind, decl, body) => {
1354                 ExprClosure(capture_clause,
1355                             opt_kind,
1356                             folder.fold_fn_decl(decl),
1357                             folder.fold_block(body))
1358             }
1359             ExprBlock(blk) => ExprBlock(folder.fold_block(blk)),
1360             ExprAssign(el, er) => {
1361                 ExprAssign(folder.fold_expr(el), folder.fold_expr(er))
1362             }
1363             ExprAssignOp(op, el, er) => {
1364                 ExprAssignOp(op,
1365                             folder.fold_expr(el),
1366                             folder.fold_expr(er))
1367             }
1368             ExprField(el, ident) => {
1369                 ExprField(folder.fold_expr(el),
1370                           respan(ident.span, folder.fold_ident(ident.node)))
1371             }
1372             ExprTupField(el, ident) => {
1373                 ExprTupField(folder.fold_expr(el),
1374                              respan(ident.span, folder.fold_uint(ident.node)))
1375             }
1376             ExprIndex(el, er) => {
1377                 ExprIndex(folder.fold_expr(el), folder.fold_expr(er))
1378             }
1379             ExprRange(e1, e2) => {
1380                 ExprRange(e1.map(|x| folder.fold_expr(x)),
1381                           e2.map(|x| folder.fold_expr(x)))
1382             }
1383             ExprPath(pth) => ExprPath(folder.fold_path(pth)),
1384             ExprBreak(opt_ident) => ExprBreak(opt_ident.map(|x| folder.fold_ident(x))),
1385             ExprAgain(opt_ident) => ExprAgain(opt_ident.map(|x| folder.fold_ident(x))),
1386             ExprRet(e) => ExprRet(e.map(|x| folder.fold_expr(x))),
1387             ExprInlineAsm(InlineAsm {
1388                 inputs,
1389                 outputs,
1390                 asm,
1391                 asm_str_style,
1392                 clobbers,
1393                 volatile,
1394                 alignstack,
1395                 dialect,
1396                 expn_id,
1397             }) => ExprInlineAsm(InlineAsm {
1398                 inputs: inputs.move_map(|(c, input)| {
1399                     (c, folder.fold_expr(input))
1400                 }),
1401                 outputs: outputs.move_map(|(c, out, is_rw)| {
1402                     (c, folder.fold_expr(out), is_rw)
1403                 }),
1404                 asm: asm,
1405                 asm_str_style: asm_str_style,
1406                 clobbers: clobbers,
1407                 volatile: volatile,
1408                 alignstack: alignstack,
1409                 dialect: dialect,
1410                 expn_id: expn_id,
1411             }),
1412             ExprMac(mac) => ExprMac(folder.fold_mac(mac)),
1413             ExprStruct(path, fields, maybe_expr) => {
1414                 ExprStruct(folder.fold_path(path),
1415                         fields.move_map(|x| folder.fold_field(x)),
1416                         maybe_expr.map(|x| folder.fold_expr(x)))
1417             },
1418             ExprParen(ex) => ExprParen(folder.fold_expr(ex))
1419         },
1420         span: folder.new_span(span)
1421     }
1422 }
1423
1424 pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T)
1425                                  -> SmallVector<P<Stmt>> {
1426     let span = folder.new_span(span);
1427     match node {
1428         StmtDecl(d, id) => {
1429             let id = folder.new_id(id);
1430             folder.fold_decl(d).into_iter().map(|d| P(Spanned {
1431                 node: StmtDecl(d, id),
1432                 span: span
1433             })).collect()
1434         }
1435         StmtExpr(e, id) => {
1436             let id = folder.new_id(id);
1437             SmallVector::one(P(Spanned {
1438                 node: StmtExpr(folder.fold_expr(e), id),
1439                 span: span
1440             }))
1441         }
1442         StmtSemi(e, id) => {
1443             let id = folder.new_id(id);
1444             SmallVector::one(P(Spanned {
1445                 node: StmtSemi(folder.fold_expr(e), id),
1446                 span: span
1447             }))
1448         }
1449         StmtMac(mac, semi) => SmallVector::one(P(Spanned {
1450             node: StmtMac(mac.map(|m| folder.fold_mac(m)), semi),
1451             span: span
1452         }))
1453     }
1454 }
1455
1456 #[cfg(test)]
1457 mod test {
1458     use std::io;
1459     use ast;
1460     use util::parser_testing::{string_to_crate, matches_codepattern};
1461     use parse::token;
1462     use print::pprust;
1463     use fold;
1464     use super::*;
1465
1466     // this version doesn't care about getting comments or docstrings in.
1467     fn fake_print_crate(s: &mut pprust::State,
1468                         krate: &ast::Crate) -> io::IoResult<()> {
1469         s.print_mod(&krate.module, krate.attrs.as_slice())
1470     }
1471
1472     // change every identifier to "zz"
1473     struct ToZzIdentFolder;
1474
1475     impl Folder for ToZzIdentFolder {
1476         fn fold_ident(&mut self, _: ast::Ident) -> ast::Ident {
1477             token::str_to_ident("zz")
1478         }
1479         fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1480             fold::noop_fold_mac(mac, self)
1481         }
1482     }
1483
1484     // maybe add to expand.rs...
1485     macro_rules! assert_pred {
1486         ($pred:expr, $predname:expr, $a:expr , $b:expr) => (
1487             {
1488                 let pred_val = $pred;
1489                 let a_val = $a;
1490                 let b_val = $b;
1491                 if !(pred_val(a_val.as_slice(),b_val.as_slice())) {
1492                     panic!("expected args satisfying {}, got {} and {}",
1493                           $predname, a_val, b_val);
1494                 }
1495             }
1496         )
1497     }
1498
1499     // make sure idents get transformed everywhere
1500     #[test] fn ident_transformation () {
1501         let mut zz_fold = ToZzIdentFolder;
1502         let ast = string_to_crate(
1503             "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
1504         let folded_crate = zz_fold.fold_crate(ast);
1505         assert_pred!(
1506             matches_codepattern,
1507             "matches_codepattern",
1508             pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
1509             "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string());
1510     }
1511
1512     // even inside macro defs....
1513     #[test] fn ident_transformation_in_defs () {
1514         let mut zz_fold = ToZzIdentFolder;
1515         let ast = string_to_crate(
1516             "macro_rules! a {(b $c:expr $(d $e:token)f+ => \
1517              (g $(d $d $e)+))} ".to_string());
1518         let folded_crate = zz_fold.fold_crate(ast);
1519         assert_pred!(
1520             matches_codepattern,
1521             "matches_codepattern",
1522             pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
1523             "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)));".to_string());
1524     }
1525 }