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