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