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