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