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