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