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