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