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