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