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