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