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