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