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