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