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