]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/fold.rs
37bc00d5827b9f252cb9d7633398308a8763118e
[rust.git] / src / libsyntax / fold.rs
1 // Copyright 2012 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 use ast::*;
12 use ast;
13 use codemap::{Span, Spanned};
14 use parse::token;
15 use opt_vec::OptVec;
16
17 // We may eventually want to be able to fold over type parameters, too.
18 pub trait ast_fold {
19     fn fold_crate(&self, c: Crate) -> Crate {
20         noop_fold_crate(c, self)
21     }
22
23     fn fold_meta_items(&self, meta_items: &[@MetaItem]) -> ~[@MetaItem] {
24         meta_items.map(|x| fold_meta_item_(*x, self))
25     }
26
27     fn fold_view_paths(&self, view_paths: &[@view_path]) -> ~[@view_path] {
28         view_paths.map(|view_path| {
29             let inner_view_path = match view_path.node {
30                 view_path_simple(ref ident, ref path, node_id) => {
31                     view_path_simple(ident.clone(),
32                                      self.fold_path(path),
33                                      self.new_id(node_id))
34                 }
35                 view_path_glob(ref path, node_id) => {
36                     view_path_glob(self.fold_path(path), self.new_id(node_id))
37                 }
38                 view_path_list(ref path, ref path_list_idents, node_id) => {
39                     view_path_list(self.fold_path(path),
40                                    path_list_idents.map(|path_list_ident| {
41                                     let id = self.new_id(path_list_ident.node
42                                                                         .id);
43                                     Spanned {
44                                         node: path_list_ident_ {
45                                             name: path_list_ident.node
46                                                                  .name
47                                                                  .clone(),
48                                             id: id,
49                                         },
50                                         span: self.new_span(
51                                             path_list_ident.span)
52                                    }
53                                   }),
54                                   self.new_id(node_id))
55                 }
56             };
57             @Spanned {
58                 node: inner_view_path,
59                 span: self.new_span(view_path.span),
60             }
61         })
62     }
63
64     fn fold_view_item(&self, vi: &view_item) -> view_item {
65         let inner_view_item = match vi.node {
66             view_item_extern_mod(ref ident,
67                                  string,
68                                  ref meta_items,
69                                  node_id) => {
70                 view_item_extern_mod(ident.clone(),
71                                      string,
72                                      self.fold_meta_items(*meta_items),
73                                      self.new_id(node_id))
74             }
75             view_item_use(ref view_paths) => {
76                 view_item_use(self.fold_view_paths(*view_paths))
77             }
78         };
79         view_item {
80             node: inner_view_item,
81             attrs: vi.attrs.map(|a| fold_attribute_(*a, self)),
82             vis: vi.vis,
83             span: self.new_span(vi.span),
84         }
85     }
86
87     fn fold_foreign_item(&self, ni: @foreign_item) -> @foreign_item {
88         let fold_attribute = |x| fold_attribute_(x, self);
89
90         @ast::foreign_item {
91             ident: self.fold_ident(ni.ident),
92             attrs: ni.attrs.map(|x| fold_attribute(*x)),
93             node:
94                 match ni.node {
95                     foreign_item_fn(ref fdec, ref generics) => {
96                         foreign_item_fn(
97                             ast::fn_decl {
98                                 inputs: fdec.inputs.map(|a| fold_arg_(a,
99                                                                       self)),
100                                 output: self.fold_ty(&fdec.output),
101                                 cf: fdec.cf,
102                             },
103                             fold_generics(generics, self))
104                     }
105                     foreign_item_static(ref t, m) => {
106                         foreign_item_static(self.fold_ty(t), m)
107                     }
108                 },
109             id: self.new_id(ni.id),
110             span: self.new_span(ni.span),
111             vis: ni.vis,
112         }
113     }
114
115     fn fold_item(&self, i: @item) -> Option<@item> {
116         noop_fold_item(i, self)
117     }
118
119     fn fold_struct_field(&self, sf: @struct_field) -> @struct_field {
120         let fold_attribute = |x| fold_attribute_(x, self);
121
122         @Spanned {
123             node: ast::struct_field_ {
124                 kind: sf.node.kind,
125                 id: self.new_id(sf.node.id),
126                 ty: self.fold_ty(&sf.node.ty),
127                 attrs: sf.node.attrs.map(|e| fold_attribute(*e))
128             },
129             span: self.new_span(sf.span)
130         }
131     }
132
133     fn fold_item_underscore(&self, i: &item_) -> item_ {
134         noop_fold_item_underscore(i, self)
135     }
136
137     fn fold_type_method(&self, m: &TypeMethod) -> TypeMethod {
138         noop_fold_type_method(m, self)
139     }
140
141     fn fold_method(&self, m: @method) -> @method {
142         @ast::method {
143             ident: self.fold_ident(m.ident),
144             attrs: m.attrs.map(|a| fold_attribute_(*a, self)),
145             generics: fold_generics(&m.generics, self),
146             explicit_self: m.explicit_self,
147             purity: m.purity,
148             decl: fold_fn_decl(&m.decl, self),
149             body: self.fold_block(&m.body),
150             id: self.new_id(m.id),
151             span: self.new_span(m.span),
152             self_id: self.new_id(m.self_id),
153             vis: m.vis,
154         }
155     }
156
157     fn fold_block(&self, b: &Block) -> Block {
158         noop_fold_block(b, self)
159     }
160
161     fn fold_stmt(&self, s: &Stmt) -> Option<@Stmt> {
162         noop_fold_stmt(s, self)
163     }
164
165     fn fold_arm(&self, a: &Arm) -> Arm {
166         Arm {
167             pats: a.pats.map(|x| self.fold_pat(*x)),
168             guard: a.guard.map(|x| self.fold_expr(x)),
169             body: self.fold_block(&a.body),
170         }
171     }
172
173     fn fold_pat(&self, p: @Pat) -> @Pat {
174         let node = match p.node {
175             PatWild => PatWild,
176             PatIdent(binding_mode, ref pth, ref sub) => {
177                 PatIdent(binding_mode,
178                          self.fold_path(pth),
179                          sub.map(|x| self.fold_pat(x)))
180             }
181             PatLit(e) => PatLit(self.fold_expr(e)),
182             PatEnum(ref pth, ref pats) => {
183                 PatEnum(self.fold_path(pth),
184                         pats.as_ref().map(|pats| pats.map(|x| self.fold_pat(*x))))
185             }
186             PatStruct(ref pth, ref fields, etc) => {
187                 let pth_ = self.fold_path(pth);
188                 let fs = do fields.map |f| {
189                     ast::FieldPat {
190                         ident: f.ident,
191                         pat: self.fold_pat(f.pat)
192                     }
193                 };
194                 PatStruct(pth_, fs, etc)
195             }
196             PatTup(ref elts) => PatTup(elts.map(|x| self.fold_pat(*x))),
197             PatBox(inner) => PatBox(self.fold_pat(inner)),
198             PatUniq(inner) => PatUniq(self.fold_pat(inner)),
199             PatRegion(inner) => PatRegion(self.fold_pat(inner)),
200             PatRange(e1, e2) => {
201                 PatRange(self.fold_expr(e1), self.fold_expr(e2))
202             },
203             PatVec(ref before, ref slice, ref after) => {
204                 PatVec(before.map(|x| self.fold_pat(*x)),
205                        slice.map(|x| self.fold_pat(x)),
206                        after.map(|x| self.fold_pat(*x)))
207             }
208         };
209
210         @Pat {
211             id: self.new_id(p.id),
212             span: self.new_span(p.span),
213             node: node,
214         }
215     }
216
217     fn fold_decl(&self, d: @Decl) -> Option<@Decl> {
218         let node = match d.node {
219             DeclLocal(ref l) => Some(DeclLocal(self.fold_local(*l))),
220             DeclItem(it) => {
221                 match self.fold_item(it) {
222                     Some(it_folded) => Some(DeclItem(it_folded)),
223                     None => None,
224                 }
225             }
226         };
227
228         node.map(|node| {
229             @Spanned {
230                 node: node,
231                 span: d.span,
232             }
233         })
234     }
235
236     fn fold_expr(&self, e: @Expr) -> @Expr {
237         noop_fold_expr(e, self)
238     }
239
240     fn fold_ty(&self, t: &Ty) -> Ty {
241         let node = match t.node {
242             ty_nil | ty_bot | ty_infer => t.node.clone(),
243             ty_box(ref mt) => ty_box(fold_mt(mt, self)),
244             ty_uniq(ref mt) => ty_uniq(fold_mt(mt, self)),
245             ty_vec(ref mt) => ty_vec(fold_mt(mt, self)),
246             ty_ptr(ref mt) => ty_ptr(fold_mt(mt, self)),
247             ty_rptr(region, ref mt) => ty_rptr(region, fold_mt(mt, self)),
248             ty_closure(ref f) => {
249                 ty_closure(@TyClosure {
250                     sigil: f.sigil,
251                     purity: f.purity,
252                     region: f.region,
253                     onceness: f.onceness,
254                     bounds: fold_opt_bounds(&f.bounds, self),
255                     decl: fold_fn_decl(&f.decl, self),
256                     lifetimes: f.lifetimes.map(|l| fold_lifetime(l, self)),
257                 })
258             }
259             ty_bare_fn(ref f) => {
260                 ty_bare_fn(@TyBareFn {
261                     lifetimes: f.lifetimes.map(|l| fold_lifetime(l, self)),
262                     purity: f.purity,
263                     abis: f.abis,
264                     decl: fold_fn_decl(&f.decl, self)
265                 })
266             }
267             ty_tup(ref tys) => ty_tup(tys.map(|ty| self.fold_ty(ty))),
268             ty_path(ref path, ref bounds, id) => {
269                 ty_path(self.fold_path(path),
270                         fold_opt_bounds(bounds, self),
271                         self.new_id(id))
272             }
273             ty_fixed_length_vec(ref mt, e) => {
274                 ty_fixed_length_vec(fold_mt(mt, self), self.fold_expr(e))
275             }
276             ty_mac(ref mac) => ty_mac(self.fold_mac(mac)),
277             ty_typeof(expr) => ty_typeof(self.fold_expr(expr)),
278         };
279         Ty {
280             id: self.new_id(t.id),
281             span: self.new_span(t.span),
282             node: node,
283         }
284     }
285
286     fn fold_mod(&self, m: &_mod) -> _mod {
287         noop_fold_mod(m, self)
288     }
289
290     fn fold_foreign_mod(&self, nm: &foreign_mod) -> foreign_mod {
291         ast::foreign_mod {
292             abis: nm.abis,
293             view_items: nm.view_items
294                           .iter()
295                           .map(|x| self.fold_view_item(x))
296                           .collect(),
297             items: nm.items
298                      .iter()
299                      .map(|x| self.fold_foreign_item(*x))
300                      .collect(),
301         }
302     }
303
304     fn fold_variant(&self, v: &variant) -> variant {
305         let kind;
306         match v.node.kind {
307             tuple_variant_kind(ref variant_args) => {
308                 kind = tuple_variant_kind(variant_args.map(|x|
309                     fold_variant_arg_(x, self)))
310             }
311             struct_variant_kind(ref struct_def) => {
312                 kind = struct_variant_kind(@ast::struct_def {
313                     fields: struct_def.fields.iter()
314                         .map(|f| self.fold_struct_field(*f)).collect(),
315                     ctor_id: struct_def.ctor_id.map(|c| self.new_id(c))
316                 })
317             }
318         }
319
320         let fold_attribute = |x| fold_attribute_(x, self);
321         let attrs = v.node.attrs.map(|x| fold_attribute(*x));
322
323         let de = match v.node.disr_expr {
324           Some(e) => Some(self.fold_expr(e)),
325           None => None
326         };
327         let node = ast::variant_ {
328             name: v.node.name,
329             attrs: attrs,
330             kind: kind,
331             id: self.new_id(v.node.id),
332             disr_expr: de,
333             vis: v.node.vis,
334         };
335         Spanned {
336             node: node,
337             span: self.new_span(v.span),
338         }
339     }
340
341     fn fold_ident(&self, i: Ident) -> Ident {
342         i
343     }
344
345     fn fold_path(&self, p: &Path) -> Path {
346         ast::Path {
347             span: self.new_span(p.span),
348             global: p.global,
349             segments: p.segments.map(|segment| ast::PathSegment {
350                 identifier: self.fold_ident(segment.identifier),
351                 lifetime: segment.lifetime,
352                 types: segment.types.map(|typ| self.fold_ty(typ)),
353             })
354         }
355     }
356
357     fn fold_local(&self, l: @Local) -> @Local {
358         @Local {
359             is_mutbl: l.is_mutbl,
360             ty: self.fold_ty(&l.ty),
361             pat: self.fold_pat(l.pat),
362             init: l.init.map(|e| self.fold_expr(e)),
363             id: self.new_id(l.id),
364             span: self.new_span(l.span),
365         }
366     }
367
368     fn fold_mac(&self, macro: &mac) -> mac {
369         Spanned {
370             node: match macro.node {
371                 mac_invoc_tt(ref p, ref tts, ctxt) => {
372                     mac_invoc_tt(self.fold_path(p),
373                                  fold_tts(*tts, self),
374                                  ctxt)
375                 }
376             },
377             span: self.new_span(macro.span)
378         }
379     }
380
381     fn map_exprs(&self, f: &fn(@Expr) -> @Expr, es: &[@Expr]) -> ~[@Expr] {
382         es.map(|x| f(*x))
383     }
384
385     fn new_id(&self, i: NodeId) -> NodeId {
386         i
387     }
388
389     fn new_span(&self, sp: Span) -> Span {
390         sp
391     }
392 }
393
394 /* some little folds that probably aren't useful to have in ast_fold itself*/
395
396 //used in noop_fold_item and noop_fold_crate and noop_fold_crate_directive
397 fn fold_meta_item_<T:ast_fold>(mi: @MetaItem, fld: &T) -> @MetaItem {
398     @Spanned {
399         node:
400             match mi.node {
401                 MetaWord(id) => MetaWord(id),
402                 MetaList(id, ref mis) => {
403                     let fold_meta_item = |x| fold_meta_item_(x, fld);
404                     MetaList(
405                         id,
406                         mis.map(|e| fold_meta_item(*e))
407                     )
408                 }
409                 MetaNameValue(id, s) => MetaNameValue(id, s)
410             },
411         span: fld.new_span(mi.span) }
412 }
413
414 //used in noop_fold_item and noop_fold_crate
415 fn fold_attribute_<T:ast_fold>(at: Attribute, fld: &T) -> Attribute {
416     Spanned {
417         span: fld.new_span(at.span),
418         node: ast::Attribute_ {
419             style: at.node.style,
420             value: fold_meta_item_(at.node.value, fld),
421             is_sugared_doc: at.node.is_sugared_doc
422         }
423     }
424 }
425
426 //used in noop_fold_foreign_item and noop_fold_fn_decl
427 fn fold_arg_<T:ast_fold>(a: &arg, fld: &T) -> arg {
428     ast::arg {
429         is_mutbl: a.is_mutbl,
430         ty: fld.fold_ty(&a.ty),
431         pat: fld.fold_pat(a.pat),
432         id: fld.new_id(a.id),
433     }
434 }
435
436 // build a new vector of tts by appling the ast_fold's fold_ident to
437 // all of the identifiers in the token trees.
438 pub fn fold_tts<T:ast_fold>(tts: &[token_tree], fld: &T) -> ~[token_tree] {
439     do tts.map |tt| {
440         match *tt {
441             tt_tok(span, ref tok) =>
442             tt_tok(span,maybe_fold_ident(tok,fld)),
443             tt_delim(ref tts) => tt_delim(@mut fold_tts(**tts, fld)),
444             tt_seq(span, ref pattern, ref sep, is_optional) =>
445             tt_seq(span,
446                    @mut fold_tts(**pattern, fld),
447                    sep.as_ref().map(|tok|maybe_fold_ident(tok,fld)),
448                    is_optional),
449             tt_nonterminal(sp,ref ident) =>
450             tt_nonterminal(sp,fld.fold_ident(*ident))
451         }
452     }
453 }
454
455 // apply ident folder if it's an ident, otherwise leave it alone
456 fn maybe_fold_ident<T:ast_fold>(t: &token::Token, fld: &T) -> token::Token {
457     match *t {
458         token::IDENT(id, followed_by_colons) => {
459             token::IDENT(fld.fold_ident(id), followed_by_colons)
460         }
461         _ => (*t).clone()
462     }
463 }
464
465 pub fn fold_fn_decl<T:ast_fold>(decl: &ast::fn_decl, fld: &T)
466                                 -> ast::fn_decl {
467     ast::fn_decl {
468         inputs: decl.inputs.map(|x| fold_arg_(x, fld)), // bad copy
469         output: fld.fold_ty(&decl.output),
470         cf: decl.cf,
471     }
472 }
473
474 fn fold_ty_param_bound<T:ast_fold>(tpb: &TyParamBound, fld: &T)
475                                    -> TyParamBound {
476     match *tpb {
477         TraitTyParamBound(ref ty) => TraitTyParamBound(fold_trait_ref(ty, fld)),
478         RegionTyParamBound => RegionTyParamBound
479     }
480 }
481
482 pub fn fold_ty_param<T:ast_fold>(tp: &TyParam, fld: &T) -> TyParam {
483     TyParam {
484         ident: tp.ident,
485         id: fld.new_id(tp.id),
486         bounds: tp.bounds.map(|x| fold_ty_param_bound(x, fld)),
487     }
488 }
489
490 pub fn fold_ty_params<T:ast_fold>(tps: &OptVec<TyParam>, fld: &T)
491                                   -> OptVec<TyParam> {
492     tps.map(|tp| fold_ty_param(tp, fld))
493 }
494
495 pub fn fold_lifetime<T:ast_fold>(l: &Lifetime, fld: &T) -> Lifetime {
496     Lifetime {
497         id: fld.new_id(l.id),
498         span: fld.new_span(l.span),
499         ident: l.ident
500     }
501 }
502
503 pub fn fold_lifetimes<T:ast_fold>(lts: &OptVec<Lifetime>, fld: &T)
504                                   -> OptVec<Lifetime> {
505     lts.map(|l| fold_lifetime(l, fld))
506 }
507
508 pub fn fold_generics<T:ast_fold>(generics: &Generics, fld: &T) -> Generics {
509     Generics {ty_params: fold_ty_params(&generics.ty_params, fld),
510               lifetimes: fold_lifetimes(&generics.lifetimes, fld)}
511 }
512
513 fn fold_struct_def<T:ast_fold>(struct_def: @ast::struct_def, fld: &T)
514                                -> @ast::struct_def {
515     @ast::struct_def {
516         fields: struct_def.fields.map(|f| fold_struct_field(*f, fld)),
517         ctor_id: struct_def.ctor_id.map(|cid| fld.new_id(cid)),
518     }
519 }
520
521 fn noop_fold_view_item(vi: &view_item_, fld: @ast_fold) -> view_item_ {
522     match *vi {
523         view_item_extern_mod(ident, name, ref meta_items, node_id) => {
524             view_item_extern_mod(ident,
525                                  name,
526                                  fld.fold_meta_items(*meta_items),
527                                  fld.new_id(node_id))
528         }
529         view_item_use(ref view_paths) => {
530             view_item_use(fld.fold_view_paths(*view_paths))
531         }
532     }
533 }
534
535 fn fold_trait_ref<T:ast_fold>(p: &trait_ref, fld: &T) -> trait_ref {
536     ast::trait_ref {
537         path: fld.fold_path(&p.path),
538         ref_id: fld.new_id(p.ref_id),
539     }
540 }
541
542 fn fold_struct_field<T:ast_fold>(f: @struct_field, fld: &T) -> @struct_field {
543     @Spanned {
544         node: ast::struct_field_ {
545             kind: f.node.kind,
546             id: fld.new_id(f.node.id),
547             ty: fld.fold_ty(&f.node.ty),
548             attrs: f.node.attrs.map(|a| fold_attribute_(*a, fld)),
549         },
550         span: fld.new_span(f.span),
551     }
552 }
553
554 fn fold_field_<T:ast_fold>(field: Field, folder: &T) -> Field {
555     ast::Field {
556         ident: folder.fold_ident(field.ident),
557         expr: folder.fold_expr(field.expr),
558         span: folder.new_span(field.span),
559     }
560 }
561
562 fn fold_mt<T:ast_fold>(mt: &mt, folder: &T) -> mt {
563     mt {
564         ty: ~folder.fold_ty(mt.ty),
565         mutbl: mt.mutbl,
566     }
567 }
568
569 fn fold_field<T:ast_fold>(f: TypeField, folder: &T) -> TypeField {
570     ast::TypeField {
571         ident: folder.fold_ident(f.ident),
572         mt: fold_mt(&f.mt, folder),
573         span: folder.new_span(f.span),
574     }
575 }
576
577 fn fold_opt_bounds<T:ast_fold>(b: &Option<OptVec<TyParamBound>>, folder: &T)
578                                -> Option<OptVec<TyParamBound>> {
579     do b.as_ref().map |bounds| {
580         do bounds.map |bound| {
581             fold_ty_param_bound(bound, folder)
582         }
583     }
584 }
585
586 fn fold_variant_arg_<T:ast_fold>(va: &variant_arg, folder: &T)
587                                  -> variant_arg {
588     ast::variant_arg {
589         ty: folder.fold_ty(&va.ty),
590         id: folder.new_id(va.id)
591     }
592 }
593
594 pub fn noop_fold_block<T:ast_fold>(b: &Block, folder: &T) -> Block {
595     let view_items = b.view_items.map(|x| folder.fold_view_item(x));
596     let mut stmts = ~[];
597     for stmt in b.stmts.iter() {
598         match folder.fold_stmt(*stmt) {
599             None => {}
600             Some(stmt) => stmts.push(stmt)
601         }
602     }
603     ast::Block {
604         view_items: view_items,
605         stmts: stmts,
606         expr: b.expr.map(|x| folder.fold_expr(x)),
607         id: folder.new_id(b.id),
608         rules: b.rules,
609         span: folder.new_span(b.span),
610     }
611 }
612
613 pub fn noop_fold_item_underscore<T:ast_fold>(i: &item_, folder: &T) -> item_ {
614     match *i {
615         item_static(ref t, m, e) => {
616             item_static(folder.fold_ty(t), m, folder.fold_expr(e))
617         }
618         item_fn(ref decl, purity, abi, ref generics, ref body) => {
619             item_fn(
620                 fold_fn_decl(decl, folder),
621                 purity,
622                 abi,
623                 fold_generics(generics, folder),
624                 folder.fold_block(body)
625             )
626         }
627         item_mod(ref m) => item_mod(folder.fold_mod(m)),
628         item_foreign_mod(ref nm) => {
629             item_foreign_mod(folder.fold_foreign_mod(nm))
630         }
631         item_ty(ref t, ref generics) => {
632             item_ty(folder.fold_ty(t),
633                     fold_generics(generics, folder))
634         }
635         item_enum(ref enum_definition, ref generics) => {
636             item_enum(
637                 ast::enum_def {
638                     variants: do enum_definition.variants.map |x| {
639                         folder.fold_variant(x)
640                     },
641                 },
642                 fold_generics(generics, folder))
643         }
644         item_struct(ref struct_def, ref generics) => {
645             let struct_def = fold_struct_def(*struct_def, folder);
646             item_struct(struct_def, fold_generics(generics, folder))
647         }
648         item_impl(ref generics, ref ifce, ref ty, ref methods) => {
649             item_impl(fold_generics(generics, folder),
650                       ifce.as_ref().map(|p| fold_trait_ref(p, folder)),
651                       folder.fold_ty(ty),
652                       methods.map(|x| folder.fold_method(*x))
653             )
654         }
655         item_trait(ref generics, ref traits, ref methods) => {
656             let methods = do methods.map |method| {
657                 match *method {
658                     required(ref m) => required(folder.fold_type_method(m)),
659                     provided(method) => provided(folder.fold_method(method))
660                 }
661             };
662             item_trait(fold_generics(generics, folder),
663                        traits.map(|p| fold_trait_ref(p, folder)),
664                        methods)
665         }
666         item_mac(ref m) => item_mac(folder.fold_mac(m)),
667     }
668 }
669
670 pub fn noop_fold_type_method<T:ast_fold>(m: &TypeMethod, fld: &T)
671                                          -> TypeMethod {
672     TypeMethod {
673         ident: fld.fold_ident(m.ident),
674         attrs: m.attrs.map(|a| fold_attribute_(*a, fld)),
675         purity: m.purity,
676         decl: fold_fn_decl(&m.decl, fld),
677         generics: fold_generics(&m.generics, fld),
678         explicit_self: m.explicit_self,
679         id: fld.new_id(m.id),
680         span: fld.new_span(m.span),
681     }
682 }
683
684 pub fn noop_fold_mod<T:ast_fold>(m: &_mod, folder: &T) -> _mod {
685     ast::_mod {
686         view_items: m.view_items
687                      .iter()
688                      .map(|x| folder.fold_view_item(x)).collect(),
689         items: m.items.iter().filter_map(|x| folder.fold_item(*x)).collect(),
690     }
691 }
692
693 pub fn noop_fold_crate<T:ast_fold>(c: Crate, folder: &T) -> Crate {
694     let fold_meta_item = |x| fold_meta_item_(x, folder);
695     let fold_attribute = |x| fold_attribute_(x, folder);
696
697     Crate {
698         module: folder.fold_mod(&c.module),
699         attrs: c.attrs.map(|x| fold_attribute(*x)),
700         config: c.config.map(|x| fold_meta_item(*x)),
701         span: folder.new_span(c.span),
702     }
703 }
704
705 pub fn noop_fold_item<T:ast_fold>(i: @ast::item, folder: &T)
706                                   -> Option<@ast::item> {
707     let fold_attribute = |x| fold_attribute_(x, folder);
708
709     Some(@ast::item {
710         ident: folder.fold_ident(i.ident),
711         attrs: i.attrs.map(|e| fold_attribute(*e)),
712         id: folder.new_id(i.id),
713         node: folder.fold_item_underscore(&i.node),
714         vis: i.vis,
715         span: folder.new_span(i.span)
716     })
717 }
718
719 pub fn noop_fold_expr<T:ast_fold>(e: @ast::Expr, folder: &T) -> @ast::Expr {
720     let fold_field = |x| fold_field_(x, folder);
721
722     let node = match e.node {
723         ExprVstore(e, v) => {
724             ExprVstore(folder.fold_expr(e), v)
725         }
726         ExprVec(ref exprs, mutt) => {
727             ExprVec(folder.map_exprs(|x| folder.fold_expr(x), *exprs), mutt)
728         }
729         ExprRepeat(expr, count, mutt) => {
730             ExprRepeat(folder.fold_expr(expr), folder.fold_expr(count), mutt)
731         }
732         ExprTup(ref elts) => ExprTup(elts.map(|x| folder.fold_expr(*x))),
733         ExprCall(f, ref args, blk) => {
734             ExprCall(folder.fold_expr(f),
735                      folder.map_exprs(|x| folder.fold_expr(x), *args),
736                      blk)
737         }
738         ExprMethodCall(callee_id, f, i, ref tps, ref args, blk) => {
739             ExprMethodCall(
740                 folder.new_id(callee_id),
741                 folder.fold_expr(f),
742                 folder.fold_ident(i),
743                 tps.map(|x| folder.fold_ty(x)),
744                 folder.map_exprs(|x| folder.fold_expr(x), *args),
745                 blk
746             )
747         }
748         ExprBinary(callee_id, binop, lhs, rhs) => {
749             ExprBinary(folder.new_id(callee_id),
750                        binop,
751                        folder.fold_expr(lhs),
752                        folder.fold_expr(rhs))
753         }
754         ExprUnary(callee_id, binop, ohs) => {
755             ExprUnary(folder.new_id(callee_id), binop, folder.fold_expr(ohs))
756         }
757         ExprDoBody(f) => ExprDoBody(folder.fold_expr(f)),
758         ExprLit(_) => e.node.clone(),
759         ExprCast(expr, ref ty) => {
760             ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
761         }
762         ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
763         ExprIf(cond, ref tr, fl) => {
764             ExprIf(folder.fold_expr(cond),
765                    folder.fold_block(tr),
766                    fl.map(|x| folder.fold_expr(x)))
767         }
768         ExprWhile(cond, ref body) => {
769             ExprWhile(folder.fold_expr(cond), folder.fold_block(body))
770         }
771         ExprForLoop(pat, iter, ref body, ref maybe_ident) => {
772             ExprForLoop(folder.fold_pat(pat),
773                         folder.fold_expr(iter),
774                         folder.fold_block(body),
775                         maybe_ident.map(|i| folder.fold_ident(i)))
776         }
777         ExprLoop(ref body, opt_ident) => {
778             ExprLoop(folder.fold_block(body),
779                      opt_ident.map(|x| folder.fold_ident(x)))
780         }
781         ExprMatch(expr, ref arms) => {
782             ExprMatch(folder.fold_expr(expr),
783                       arms.map(|x| folder.fold_arm(x)))
784         }
785         ExprFnBlock(ref decl, ref body) => {
786             ExprFnBlock(
787                 fold_fn_decl(decl, folder),
788                 folder.fold_block(body)
789             )
790         }
791         ExprBlock(ref blk) => ExprBlock(folder.fold_block(blk)),
792         ExprAssign(el, er) => {
793             ExprAssign(folder.fold_expr(el), folder.fold_expr(er))
794         }
795         ExprAssignOp(callee_id, op, el, er) => {
796             ExprAssignOp(folder.new_id(callee_id),
797                          op,
798                          folder.fold_expr(el),
799                          folder.fold_expr(er))
800         }
801         ExprField(el, id, ref tys) => {
802             ExprField(folder.fold_expr(el), folder.fold_ident(id),
803                       tys.map(|x| folder.fold_ty(x)))
804         }
805         ExprIndex(callee_id, el, er) => {
806             ExprIndex(folder.new_id(callee_id),
807                       folder.fold_expr(el),
808                       folder.fold_expr(er))
809         }
810         ExprPath(ref pth) => ExprPath(folder.fold_path(pth)),
811         ExprSelf => ExprSelf,
812         ExprLogLevel => ExprLogLevel,
813         ExprBreak(opt_ident) => ExprBreak(opt_ident),
814         ExprAgain(opt_ident) => ExprAgain(opt_ident),
815         ExprRet(ref e) => {
816             ExprRet(e.map(|x| folder.fold_expr(x)))
817         }
818         ExprInlineAsm(ref a) => {
819             ExprInlineAsm(inline_asm {
820                 inputs: a.inputs.map(|&(c, input)| (c, folder.fold_expr(input))),
821                 outputs: a.outputs.map(|&(c, out)| (c, folder.fold_expr(out))),
822                 .. (*a).clone()
823             })
824         }
825         ExprMac(ref mac) => ExprMac(folder.fold_mac(mac)),
826         ExprStruct(ref path, ref fields, maybe_expr) => {
827             ExprStruct(folder.fold_path(path),
828                        fields.map(|x| fold_field(*x)),
829                        maybe_expr.map(|x| folder.fold_expr(x)))
830         },
831         ExprParen(ex) => ExprParen(folder.fold_expr(ex))
832     };
833
834     @Expr {
835         id: folder.new_id(e.id),
836         node: node,
837         span: folder.new_span(e.span),
838     }
839 }
840
841 pub fn noop_fold_stmt<T:ast_fold>(s: &Stmt, folder: &T) -> Option<@Stmt> {
842     let node = match s.node {
843         StmtDecl(d, nid) => {
844             match folder.fold_decl(d) {
845                 Some(d) => Some(StmtDecl(d, folder.new_id(nid))),
846                 None => None,
847             }
848         }
849         StmtExpr(e, nid) => {
850             Some(StmtExpr(folder.fold_expr(e), folder.new_id(nid)))
851         }
852         StmtSemi(e, nid) => {
853             Some(StmtSemi(folder.fold_expr(e), folder.new_id(nid)))
854         }
855         StmtMac(ref mac, semi) => Some(StmtMac(folder.fold_mac(mac), semi))
856     };
857
858     node.map(|node| @Spanned {
859         node: node,
860         span: folder.new_span(s.span),
861     })
862 }
863
864 #[cfg(test)]
865 mod test {
866     use ast;
867     use util::parser_testing::{string_to_crate, matches_codepattern};
868     use parse::token;
869     use print::pprust;
870     use super::*;
871
872     // this version doesn't care about getting comments or docstrings in.
873     fn fake_print_crate(s: @pprust::ps, crate: &ast::Crate) {
874         pprust::print_mod(s, &crate.module, crate.attrs);
875     }
876
877     // change every identifier to "zz"
878     struct ToZzIdentFolder;
879
880     impl ast_fold for ToZzIdentFolder {
881         fn fold_ident(&self, _: ast::Ident) -> ast::Ident {
882             token::str_to_ident("zz")
883         }
884     }
885
886     // maybe add to expand.rs...
887     macro_rules! assert_pred (
888         ($pred:expr, $predname:expr, $a:expr , $b:expr) => (
889             {
890                 let pred_val = $pred;
891                 let a_val = $a;
892                 let b_val = $b;
893                 if !(pred_val(a_val,b_val)) {
894                     fail!("expected args satisfying {}, got {:?} and {:?}",
895                           $predname, a_val, b_val);
896                 }
897             }
898         )
899     )
900
901     // make sure idents get transformed everywhere
902     #[test] fn ident_transformation () {
903         let zz_fold = ToZzIdentFolder;
904         let ast = string_to_crate(@"#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}");
905         assert_pred!(matches_codepattern,
906                      "matches_codepattern",
907                      pprust::to_str(&zz_fold.fold_crate(ast),fake_print_crate,
908                                     token::get_ident_interner()),
909                      ~"#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}");
910     }
911
912     // even inside macro defs....
913     #[test] fn ident_transformation_in_defs () {
914         let zz_fold = ToZzIdentFolder;
915         let ast = string_to_crate(@"macro_rules! a {(b $c:expr $(d $e:token)f+
916 => (g $(d $d $e)+))} ");
917         assert_pred!(matches_codepattern,
918                      "matches_codepattern",
919                      pprust::to_str(&zz_fold.fold_crate(ast),fake_print_crate,
920                                     token::get_ident_interner()),
921                      ~"zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))");
922     }
923 }
924