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