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