1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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.
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
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.
24 use codemap::{respan, Span, Spanned};
26 use owned_slice::OwnedSlice;
27 use util::small_vector::SmallVector;
30 use std::gc::{Gc, GC};
33 // Any additions to this trait should happen in form
34 // of a call to a public `noop_*` function that only calls
35 // out to the folder again, not other `noop_*` functions.
37 // This is a necessary API workaround to the problem of not
38 // being able to call out to the super default method
39 // in an overridden default method.
41 fn fold_crate(&mut self, c: Crate) -> Crate {
42 noop_fold_crate(c, self)
45 fn fold_meta_items(&mut self, meta_items: &[Gc<MetaItem>]) -> Vec<Gc<MetaItem>> {
46 noop_fold_meta_items(meta_items, self)
49 fn fold_meta_item(&mut self, meta_item: &MetaItem) -> MetaItem {
50 noop_fold_meta_item(meta_item, self)
53 fn fold_view_path(&mut self, view_path: Gc<ViewPath>) -> Gc<ViewPath> {
54 noop_fold_view_path(view_path, self)
57 fn fold_view_item(&mut self, vi: &ViewItem) -> ViewItem {
58 noop_fold_view_item(vi, self)
61 fn fold_foreign_item(&mut self, ni: Gc<ForeignItem>) -> Gc<ForeignItem> {
62 noop_fold_foreign_item(&*ni, self)
65 fn fold_item(&mut self, i: Gc<Item>) -> SmallVector<Gc<Item>> {
66 noop_fold_item(&*i, self)
69 fn fold_item_simple(&mut self, i: &Item) -> Item {
70 noop_fold_item_simple(i, self)
73 fn fold_struct_field(&mut self, sf: &StructField) -> StructField {
74 noop_fold_struct_field(sf, self)
77 fn fold_item_underscore(&mut self, i: &Item_) -> Item_ {
78 noop_fold_item_underscore(i, self)
81 fn fold_fn_decl(&mut self, d: &FnDecl) -> P<FnDecl> {
82 noop_fold_fn_decl(d, self)
85 fn fold_type_method(&mut self, m: &TypeMethod) -> TypeMethod {
86 noop_fold_type_method(m, self)
89 fn fold_method(&mut self, m: Gc<Method>) -> SmallVector<Gc<Method>> {
90 noop_fold_method(&*m, self)
93 fn fold_block(&mut self, b: P<Block>) -> P<Block> {
94 noop_fold_block(b, self)
97 fn fold_stmt(&mut self, s: &Stmt) -> SmallVector<Gc<Stmt>> {
98 noop_fold_stmt(s, self)
101 fn fold_arm(&mut self, a: &Arm) -> Arm {
102 noop_fold_arm(a, self)
105 fn fold_pat(&mut self, p: Gc<Pat>) -> Gc<Pat> {
106 noop_fold_pat(p, self)
109 fn fold_decl(&mut self, d: Gc<Decl>) -> SmallVector<Gc<Decl>> {
110 noop_fold_decl(d, self)
113 fn fold_expr(&mut self, e: Gc<Expr>) -> Gc<Expr> {
114 noop_fold_expr(e, self)
117 fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> {
118 noop_fold_ty(t, self)
121 fn fold_mod(&mut self, m: &Mod) -> Mod {
122 noop_fold_mod(m, self)
125 fn fold_foreign_mod(&mut self, nm: &ForeignMod) -> ForeignMod {
126 noop_fold_foreign_mod(nm, self)
129 fn fold_variant(&mut self, v: &Variant) -> P<Variant> {
130 noop_fold_variant(v, self)
133 fn fold_ident(&mut self, i: Ident) -> Ident {
134 noop_fold_ident(i, self)
137 fn fold_path(&mut self, p: &Path) -> Path {
138 noop_fold_path(p, self)
141 fn fold_local(&mut self, l: Gc<Local>) -> Gc<Local> {
142 noop_fold_local(l, self)
145 fn fold_mac(&mut self, _macro: &Mac) -> Mac {
146 fail!("fold_mac disabled by default");
147 // NB: see note about macros above.
148 // if you really want a folder that
149 // works on macros, use this
150 // definition in your trait impl:
151 // fold::noop_fold_mac(_macro, self)
154 fn fold_explicit_self(&mut self, es: &ExplicitSelf) -> ExplicitSelf {
155 noop_fold_explicit_self(es, self)
158 fn fold_explicit_self_underscore(&mut self, es: &ExplicitSelf_) -> ExplicitSelf_ {
159 noop_fold_explicit_self_underscore(es, self)
162 fn fold_lifetime(&mut self, l: &Lifetime) -> Lifetime {
163 noop_fold_lifetime(l, self)
166 fn fold_attribute(&mut self, at: Attribute) -> Attribute {
167 noop_fold_attribute(at, self)
170 fn fold_arg(&mut self, a: &Arg) -> Arg {
171 noop_fold_arg(a, self)
174 fn fold_generics(&mut self, generics: &Generics) -> Generics {
175 noop_fold_generics(generics, self)
178 fn fold_trait_ref(&mut self, p: &TraitRef) -> TraitRef {
179 noop_fold_trait_ref(p, self)
182 fn fold_struct_def(&mut self, struct_def: Gc<StructDef>) -> Gc<StructDef> {
183 noop_fold_struct_def(struct_def, self)
186 fn fold_lifetimes(&mut self, lts: &[Lifetime]) -> Vec<Lifetime> {
187 noop_fold_lifetimes(lts, self)
190 fn fold_ty_param(&mut self, tp: &TyParam) -> TyParam {
191 noop_fold_ty_param(tp, self)
194 fn fold_ty_params(&mut self, tps: &[TyParam]) -> OwnedSlice<TyParam> {
195 noop_fold_ty_params(tps, self)
198 fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
199 noop_fold_tt(tt, self)
202 fn fold_tts(&mut self, tts: &[TokenTree]) -> Vec<TokenTree> {
203 noop_fold_tts(tts, self)
206 fn fold_token(&mut self, t: &token::Token) -> token::Token {
207 noop_fold_token(t, self)
210 fn fold_interpolated(&mut self, nt : &token::Nonterminal) -> token::Nonterminal {
211 noop_fold_interpolated(nt, self)
214 fn fold_opt_lifetime(&mut self, o_lt: &Option<Lifetime>) -> Option<Lifetime> {
215 noop_fold_opt_lifetime(o_lt, self)
218 fn fold_variant_arg(&mut self, va: &VariantArg) -> VariantArg {
219 noop_fold_variant_arg(va, self)
222 fn fold_ty_param_bound(&mut self, tpb: &TyParamBound) -> TyParamBound {
223 noop_fold_ty_param_bound(tpb, self)
226 fn fold_opt_bounds(&mut self, b: &Option<OwnedSlice<TyParamBound>>)
227 -> Option<OwnedSlice<TyParamBound>> {
228 noop_fold_opt_bounds(b, self)
231 fn fold_mt(&mut self, mt: &MutTy) -> MutTy {
232 noop_fold_mt(mt, self)
235 fn fold_field(&mut self, field: Field) -> Field {
236 noop_fold_field(field, self)
241 fn map_exprs(&self, f: |Gc<Expr>| -> Gc<Expr>,
242 es: &[Gc<Expr>]) -> Vec<Gc<Expr>> {
243 es.iter().map(|x| f(*x)).collect()
246 fn new_id(&mut self, i: NodeId) -> NodeId {
250 fn new_span(&mut self, sp: Span) -> Span {
255 pub fn noop_fold_meta_items<T: Folder>(meta_items: &[Gc<MetaItem>], fld: &mut T)
256 -> Vec<Gc<MetaItem>> {
257 meta_items.iter().map(|x| box (GC) fld.fold_meta_item(&**x)).collect()
260 pub fn noop_fold_view_path<T: Folder>(view_path: Gc<ViewPath>, fld: &mut T) -> Gc<ViewPath> {
261 let inner_view_path = match view_path.node {
262 ViewPathSimple(ref ident, ref path, node_id) => {
263 let id = fld.new_id(node_id);
264 ViewPathSimple(ident.clone(),
268 ViewPathGlob(ref path, node_id) => {
269 let id = fld.new_id(node_id);
270 ViewPathGlob(fld.fold_path(path), id)
272 ViewPathList(ref path, ref path_list_idents, node_id) => {
273 let id = fld.new_id(node_id);
274 ViewPathList(fld.fold_path(path),
275 path_list_idents.iter().map(|path_list_ident| {
277 node: match path_list_ident.node {
278 PathListIdent { id, name } =>
283 PathListMod { id } =>
284 PathListMod { id: fld.new_id(id) }
286 span: fld.new_span(path_list_ident.span)
293 node: inner_view_path,
294 span: fld.new_span(view_path.span),
298 pub fn noop_fold_arm<T: Folder>(a: &Arm, fld: &mut T) -> Arm {
300 attrs: a.attrs.iter().map(|x| fld.fold_attribute(*x)).collect(),
301 pats: a.pats.iter().map(|x| fld.fold_pat(*x)).collect(),
302 guard: a.guard.map(|x| fld.fold_expr(x)),
303 body: fld.fold_expr(a.body),
307 pub fn noop_fold_decl<T: Folder>(d: Gc<Decl>, fld: &mut T) -> SmallVector<Gc<Decl>> {
308 let node = match d.node {
309 DeclLocal(ref l) => SmallVector::one(DeclLocal(fld.fold_local(*l))),
311 fld.fold_item(it).move_iter().map(|i| DeclItem(i)).collect()
315 node.move_iter().map(|node| {
318 span: fld.new_span(d.span),
323 pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
324 let id = fld.new_id(t.id);
325 let node = match t.node {
326 TyNil | TyBot | TyInfer => t.node.clone(),
327 TyBox(ty) => TyBox(fld.fold_ty(ty)),
328 TyUniq(ty) => TyUniq(fld.fold_ty(ty)),
329 TyVec(ty) => TyVec(fld.fold_ty(ty)),
330 TyPtr(ref mt) => TyPtr(fld.fold_mt(mt)),
331 TyRptr(ref region, ref mt) => {
332 TyRptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt))
334 TyClosure(ref f, ref region) => {
335 TyClosure(box(GC) ClosureTy {
336 fn_style: f.fn_style,
337 onceness: f.onceness,
338 bounds: fld.fold_opt_bounds(&f.bounds),
339 decl: fld.fold_fn_decl(&*f.decl),
340 lifetimes: f.lifetimes.iter().map(|l| fld.fold_lifetime(l)).collect(),
341 }, fld.fold_opt_lifetime(region))
344 TyProc(box(GC) ClosureTy {
345 fn_style: f.fn_style,
346 onceness: f.onceness,
347 bounds: fld.fold_opt_bounds(&f.bounds),
348 decl: fld.fold_fn_decl(&*f.decl),
349 lifetimes: f.lifetimes.iter().map(|l| fld.fold_lifetime(l)).collect(),
353 TyBareFn(box(GC) BareFnTy {
354 lifetimes: f.lifetimes.iter().map(|l| fld.fold_lifetime(l)).collect(),
355 fn_style: f.fn_style,
357 decl: fld.fold_fn_decl(&*f.decl)
360 TyUnboxedFn(ref f) => {
361 TyUnboxedFn(box(GC) UnboxedFnTy {
362 decl: fld.fold_fn_decl(&*f.decl),
365 TyTup(ref tys) => TyTup(tys.iter().map(|&ty| fld.fold_ty(ty)).collect()),
366 TyParen(ref ty) => TyParen(fld.fold_ty(*ty)),
367 TyPath(ref path, ref bounds, id) => {
368 let id = fld.new_id(id);
369 TyPath(fld.fold_path(path),
370 fld.fold_opt_bounds(bounds),
373 TyFixedLengthVec(ty, e) => {
374 TyFixedLengthVec(fld.fold_ty(ty), fld.fold_expr(e))
376 TyTypeof(expr) => TyTypeof(fld.fold_expr(expr)),
380 span: fld.new_span(t.span),
385 pub fn noop_fold_foreign_mod<T: Folder>(nm: &ForeignMod, fld: &mut T) -> ForeignMod {
388 view_items: nm.view_items
390 .map(|x| fld.fold_view_item(x))
394 .map(|x| fld.fold_foreign_item(*x))
399 pub fn noop_fold_variant<T: Folder>(v: &Variant, fld: &mut T) -> P<Variant> {
400 let id = fld.new_id(v.node.id);
403 TupleVariantKind(ref variant_args) => {
404 kind = TupleVariantKind(variant_args.iter().map(|x|
405 fld.fold_variant_arg(x)).collect())
407 StructVariantKind(ref struct_def) => {
408 kind = StructVariantKind(box(GC) ast::StructDef {
409 fields: struct_def.fields.iter()
410 .map(|f| fld.fold_struct_field(f)).collect(),
411 ctor_id: struct_def.ctor_id.map(|c| fld.new_id(c)),
412 super_struct: match struct_def.super_struct {
413 Some(t) => Some(fld.fold_ty(t)),
416 is_virtual: struct_def.is_virtual,
421 let attrs = v.node.attrs.iter().map(|x| fld.fold_attribute(*x)).collect();
423 let de = match v.node.disr_expr {
424 Some(e) => Some(fld.fold_expr(e)),
427 let node = ast::Variant_ {
437 span: fld.new_span(v.span),
441 pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident {
445 pub fn noop_fold_path<T: Folder>(p: &Path, fld: &mut T) -> Path {
447 span: fld.new_span(p.span),
449 segments: p.segments.iter().map(|segment| ast::PathSegment {
450 identifier: fld.fold_ident(segment.identifier),
451 lifetimes: segment.lifetimes.iter().map(|l| fld.fold_lifetime(l)).collect(),
452 types: segment.types.iter().map(|&typ| fld.fold_ty(typ)).collect(),
457 pub fn noop_fold_local<T: Folder>(l: Gc<Local>, fld: &mut T) -> Gc<Local> {
458 let id = fld.new_id(l.id); // Needs to be first, for ast_map.
461 ty: fld.fold_ty(l.ty),
462 pat: fld.fold_pat(l.pat),
463 init: l.init.map(|e| fld.fold_expr(e)),
464 span: fld.new_span(l.span),
469 pub fn noop_fold_attribute<T: Folder>(at: Attribute, fld: &mut T) -> Attribute {
471 span: fld.new_span(at.span),
472 node: ast::Attribute_ {
474 style: at.node.style,
475 value: box (GC) fld.fold_meta_item(&*at.node.value),
476 is_sugared_doc: at.node.is_sugared_doc
481 pub fn noop_fold_explicit_self_underscore<T: Folder>(es: &ExplicitSelf_, fld: &mut T)
484 SelfStatic | SelfValue(_) => *es,
485 SelfRegion(ref lifetime, m, id) => {
486 SelfRegion(fld.fold_opt_lifetime(lifetime), m, id)
488 SelfExplicit(ref typ, id) => SelfExplicit(fld.fold_ty(*typ), id),
492 pub fn noop_fold_explicit_self<T: Folder>(es: &ExplicitSelf, fld: &mut T) -> ExplicitSelf {
494 span: fld.new_span(es.span),
495 node: fld.fold_explicit_self_underscore(&es.node)
500 pub fn noop_fold_mac<T: Folder>(macro: &Mac, fld: &mut T) -> Mac {
502 node: match macro.node {
503 MacInvocTT(ref p, ref tts, ctxt) => {
504 MacInvocTT(fld.fold_path(p),
505 fld.fold_tts(tts.as_slice()),
509 span: fld.new_span(macro.span)
513 pub fn noop_fold_meta_item<T: Folder>(mi: &MetaItem, fld: &mut T) -> MetaItem {
517 MetaWord(ref id) => MetaWord((*id).clone()),
518 MetaList(ref id, ref mis) => {
519 MetaList((*id).clone(),
521 .map(|e| box (GC) fld.fold_meta_item(&**e)).collect())
523 MetaNameValue(ref id, ref s) => {
524 MetaNameValue((*id).clone(), (*s).clone())
527 span: fld.new_span(mi.span) }
530 pub fn noop_fold_arg<T: Folder>(a: &Arg, fld: &mut T) -> Arg {
531 let id = fld.new_id(a.id); // Needs to be first, for ast_map.
534 ty: fld.fold_ty(a.ty),
535 pat: fld.fold_pat(a.pat),
539 pub fn noop_fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree {
541 TTTok(span, ref tok) =>
542 TTTok(span, fld.fold_token(tok)),
543 TTDelim(ref tts) => TTDelim(Rc::new(fld.fold_tts(tts.as_slice()))),
544 TTSeq(span, ref pattern, ref sep, is_optional) =>
546 Rc::new(fld.fold_tts(pattern.as_slice())),
547 sep.as_ref().map(|tok| fld.fold_token(tok)),
549 TTNonterminal(sp,ref ident) =>
550 TTNonterminal(sp,fld.fold_ident(*ident))
554 pub fn noop_fold_tts<T: Folder>(tts: &[TokenTree], fld: &mut T) -> Vec<TokenTree> {
555 tts.iter().map(|tt| fld.fold_tt(tt)).collect()
558 // apply ident folder if it's an ident, apply other folds to interpolated nodes
559 pub fn noop_fold_token<T: Folder>(t: &token::Token, fld: &mut T) -> token::Token {
561 token::IDENT(id, followed_by_colons) => {
562 token::IDENT(fld.fold_ident(id), followed_by_colons)
564 token::LIFETIME(id) => token::LIFETIME(fld.fold_ident(id)),
565 token::INTERPOLATED(ref nt) => token::INTERPOLATED(fld.fold_interpolated(nt)),
570 /// apply folder to elements of interpolated nodes
572 // NB: this can occur only when applying a fold to partially expanded code, where
573 // parsed pieces have gotten implanted ito *other* macro invocations. This is relevant
574 // for macro hygiene, but possibly not elsewhere.
576 // One problem here occurs because the types for fold_item, fold_stmt, etc. allow the
577 // folder to return *multiple* items; this is a problem for the nodes here, because
578 // they insist on having exactly one piece. One solution would be to mangle the fold
579 // trait to include one-to-many and one-to-one versions of these entry points, but that
580 // would probably confuse a lot of people and help very few. Instead, I'm just going
581 // to put in dynamic checks. I think the performance impact of this will be pretty much
582 // nonexistent. The danger is that someone will apply a fold to a partially expanded
583 // node, and will be confused by the fact that their "fold_item" or "fold_stmt" isn't
584 // getting called on NtItem or NtStmt nodes. Hopefully they'll wind up reading this
585 // comment, and doing something appropriate.
587 // BTW, design choice: I considered just changing the type of, e.g., NtItem to contain
588 // multiple items, but decided against it when I looked at parse_item_or_view_item and
589 // tried to figure out what I would do with multiple items there....
590 pub fn noop_fold_interpolated<T: Folder>(nt : &token::Nonterminal, fld: &mut T)
591 -> token::Nonterminal {
593 token::NtItem(item) =>
594 token::NtItem(fld.fold_item(item)
595 // this is probably okay, because the only folds likely
596 // to peek inside interpolated nodes will be renamings/markings,
597 // which map single items to single items
598 .expect_one("expected fold to produce exactly one item")),
599 token::NtBlock(block) => token::NtBlock(fld.fold_block(block)),
600 token::NtStmt(stmt) =>
601 token::NtStmt(fld.fold_stmt(&*stmt)
602 // this is probably okay, because the only folds likely
603 // to peek inside interpolated nodes will be renamings/markings,
604 // which map single items to single items
605 .expect_one("expected fold to produce exactly one statement")),
606 token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)),
607 token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)),
608 token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)),
609 token::NtIdent(ref id, is_mod_name) =>
610 token::NtIdent(box fld.fold_ident(**id),is_mod_name),
611 token::NtMeta(meta_item) => token::NtMeta(box (GC) fld.fold_meta_item(&*meta_item)),
612 token::NtPath(ref path) => token::NtPath(box fld.fold_path(&**path)),
613 token::NtTT(tt) => token::NtTT(box (GC) fld.fold_tt(&*tt)),
614 // it looks to me like we can leave out the matchers: token::NtMatchers(matchers)
619 pub fn noop_fold_fn_decl<T: Folder>(decl: &FnDecl, fld: &mut T) -> P<FnDecl> {
621 inputs: decl.inputs.iter().map(|x| fld.fold_arg(x)).collect(), // bad copy
622 output: fld.fold_ty(decl.output),
624 variadic: decl.variadic
628 pub fn noop_fold_ty_param_bound<T: Folder>(tpb: &TyParamBound, fld: &mut T)
631 TraitTyParamBound(ref ty) => TraitTyParamBound(fld.fold_trait_ref(ty)),
632 StaticRegionTyParamBound => StaticRegionTyParamBound,
633 UnboxedFnTyParamBound(ref unboxed_function_type) => {
634 UnboxedFnTyParamBound(UnboxedFnTy {
635 decl: fld.fold_fn_decl(&*unboxed_function_type.decl),
638 OtherRegionTyParamBound(s) => OtherRegionTyParamBound(s)
642 pub fn noop_fold_ty_param<T: Folder>(tp: &TyParam, fld: &mut T) -> TyParam {
643 let id = fld.new_id(tp.id);
647 bounds: tp.bounds.map(|x| fld.fold_ty_param_bound(x)),
648 unbound: tp.unbound.as_ref().map(|x| fld.fold_ty_param_bound(x)),
649 default: tp.default.map(|x| fld.fold_ty(x)),
654 pub fn noop_fold_ty_params<T: Folder>(tps: &[TyParam], fld: &mut T)
655 -> OwnedSlice<TyParam> {
656 tps.iter().map(|tp| fld.fold_ty_param(tp)).collect()
659 pub fn noop_fold_lifetime<T: Folder>(l: &Lifetime, fld: &mut T) -> Lifetime {
660 let id = fld.new_id(l.id);
663 span: fld.new_span(l.span),
668 pub fn noop_fold_lifetimes<T: Folder>(lts: &[Lifetime], fld: &mut T) -> Vec<Lifetime> {
669 lts.iter().map(|l| fld.fold_lifetime(l)).collect()
672 pub fn noop_fold_opt_lifetime<T: Folder>(o_lt: &Option<Lifetime>, fld: &mut T)
673 -> Option<Lifetime> {
674 o_lt.as_ref().map(|lt| fld.fold_lifetime(lt))
677 pub fn noop_fold_generics<T: Folder>(generics: &Generics, fld: &mut T) -> Generics {
678 Generics {ty_params: fld.fold_ty_params(generics.ty_params.as_slice()),
679 lifetimes: fld.fold_lifetimes(generics.lifetimes.as_slice())}
682 pub fn noop_fold_struct_def<T: Folder>(struct_def: Gc<StructDef>,
683 fld: &mut T) -> Gc<StructDef> {
684 box(GC) ast::StructDef {
685 fields: struct_def.fields.iter().map(|f| fld.fold_struct_field(f)).collect(),
686 ctor_id: struct_def.ctor_id.map(|cid| fld.new_id(cid)),
687 super_struct: match struct_def.super_struct {
688 Some(t) => Some(fld.fold_ty(t)),
691 is_virtual: struct_def.is_virtual,
695 pub fn noop_fold_trait_ref<T: Folder>(p: &TraitRef, fld: &mut T) -> TraitRef {
696 let id = fld.new_id(p.ref_id);
698 path: fld.fold_path(&p.path),
703 pub fn noop_fold_struct_field<T: Folder>(f: &StructField, fld: &mut T) -> StructField {
704 let id = fld.new_id(f.node.id);
706 node: ast::StructField_ {
709 ty: fld.fold_ty(f.node.ty),
710 attrs: f.node.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(),
712 span: fld.new_span(f.span),
716 pub fn noop_fold_field<T: Folder>(field: Field, folder: &mut T) -> Field {
718 ident: respan(field.ident.span, folder.fold_ident(field.ident.node)),
719 expr: folder.fold_expr(field.expr),
720 span: folder.new_span(field.span),
724 pub fn noop_fold_mt<T: Folder>(mt: &MutTy, folder: &mut T) -> MutTy {
726 ty: folder.fold_ty(mt.ty),
731 pub fn noop_fold_opt_bounds<T: Folder>(b: &Option<OwnedSlice<TyParamBound>>, folder: &mut T)
732 -> Option<OwnedSlice<TyParamBound>> {
733 b.as_ref().map(|bounds| {
735 folder.fold_ty_param_bound(bound)
740 pub fn noop_fold_variant_arg<T: Folder>(va: &VariantArg, folder: &mut T) -> VariantArg {
741 let id = folder.new_id(va.id);
743 ty: folder.fold_ty(va.ty),
748 pub fn noop_fold_view_item<T: Folder>(vi: &ViewItem, folder: &mut T)
750 let inner_view_item = match vi.node {
751 ViewItemExternCrate(ref ident, ref string, node_id) => {
752 ViewItemExternCrate(ident.clone(),
754 folder.new_id(node_id))
756 ViewItemUse(ref view_path) => {
757 ViewItemUse(folder.fold_view_path(*view_path))
761 node: inner_view_item,
762 attrs: vi.attrs.iter().map(|a| folder.fold_attribute(*a)).collect(),
764 span: folder.new_span(vi.span),
768 pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> {
769 let id = folder.new_id(b.id); // Needs to be first, for ast_map.
770 let view_items = b.view_items.iter().map(|x| folder.fold_view_item(x)).collect();
771 let stmts = b.stmts.iter().flat_map(|s| folder.fold_stmt(&**s).move_iter()).collect();
774 view_items: view_items,
776 expr: b.expr.map(|x| folder.fold_expr(x)),
778 span: folder.new_span(b.span),
782 pub fn noop_fold_item_underscore<T: Folder>(i: &Item_, folder: &mut T) -> Item_ {
784 ItemStatic(t, m, e) => {
785 ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e))
787 ItemFn(decl, fn_style, abi, ref generics, body) => {
789 folder.fold_fn_decl(&*decl),
792 folder.fold_generics(generics),
793 folder.fold_block(body)
796 ItemMod(ref m) => ItemMod(folder.fold_mod(m)),
797 ItemForeignMod(ref nm) => ItemForeignMod(folder.fold_foreign_mod(nm)),
798 ItemTy(t, ref generics) => {
799 ItemTy(folder.fold_ty(t), folder.fold_generics(generics))
801 ItemEnum(ref enum_definition, ref generics) => {
804 variants: enum_definition.variants.iter().map(|&x| {
805 folder.fold_variant(&*x)
808 folder.fold_generics(generics))
810 ItemStruct(ref struct_def, ref generics) => {
811 let struct_def = folder.fold_struct_def(*struct_def);
812 ItemStruct(struct_def, folder.fold_generics(generics))
814 ItemImpl(ref generics, ref ifce, ty, ref methods) => {
815 ItemImpl(folder.fold_generics(generics),
816 ifce.as_ref().map(|p| folder.fold_trait_ref(p)),
818 methods.iter().flat_map(|x| folder.fold_method(*x).move_iter()).collect()
821 ItemTrait(ref generics, ref unbound, ref traits, ref methods) => {
822 let methods = methods.iter().flat_map(|method| {
823 let r = match *method {
825 SmallVector::one(Required(folder.fold_type_method(m))).move_iter(),
826 Provided(method) => {
827 // the awkward collect/iter idiom here is because
828 // even though an iter and a map satisfy the same trait bound,
829 // they're not actually the same type, so the method arms
831 let methods : SmallVector<ast::TraitMethod> =
832 folder.fold_method(method).move_iter()
833 .map(|m| Provided(m)).collect();
839 ItemTrait(folder.fold_generics(generics),
841 traits.iter().map(|p| folder.fold_trait_ref(p)).collect(),
844 ItemMac(ref m) => ItemMac(folder.fold_mac(m)),
848 pub fn noop_fold_type_method<T: Folder>(m: &TypeMethod, fld: &mut T) -> TypeMethod {
849 let id = fld.new_id(m.id); // Needs to be first, for ast_map.
852 ident: fld.fold_ident(m.ident),
853 attrs: m.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(),
854 fn_style: m.fn_style,
856 decl: fld.fold_fn_decl(&*m.decl),
857 generics: fld.fold_generics(&m.generics),
858 explicit_self: fld.fold_explicit_self(&m.explicit_self),
859 span: fld.new_span(m.span),
864 pub fn noop_fold_mod<T: Folder>(m: &Mod, folder: &mut T) -> Mod {
866 inner: folder.new_span(m.inner),
867 view_items: m.view_items
869 .map(|x| folder.fold_view_item(x)).collect(),
870 items: m.items.iter().flat_map(|x| folder.fold_item(*x).move_iter()).collect(),
874 pub fn noop_fold_crate<T: Folder>(c: Crate, folder: &mut T) -> Crate {
876 module: folder.fold_mod(&c.module),
877 attrs: c.attrs.iter().map(|x| folder.fold_attribute(*x)).collect(),
878 config: c.config.iter().map(|x| box (GC) folder.fold_meta_item(&**x)).collect(),
879 span: folder.new_span(c.span),
880 exported_macros: c.exported_macros
884 // fold one item into possibly many items
885 pub fn noop_fold_item<T: Folder>(i: &Item,
886 folder: &mut T) -> SmallVector<Gc<Item>> {
887 SmallVector::one(box(GC) folder.fold_item_simple(i))
891 // fold one item into exactly one item
892 pub fn noop_fold_item_simple<T: Folder>(i: &Item, folder: &mut T) -> Item {
893 let id = folder.new_id(i.id); // Needs to be first, for ast_map.
894 let node = folder.fold_item_underscore(&i.node);
895 let ident = match node {
896 // The node may have changed, recompute the "pretty" impl name.
897 ItemImpl(_, ref maybe_trait, ty, _) => {
898 ast_util::impl_pretty_name(maybe_trait, &*ty)
905 ident: folder.fold_ident(ident),
906 attrs: i.attrs.iter().map(|e| folder.fold_attribute(*e)).collect(),
909 span: folder.new_span(i.span)
913 pub fn noop_fold_foreign_item<T: Folder>(ni: &ForeignItem,
914 folder: &mut T) -> Gc<ForeignItem> {
915 let id = folder.new_id(ni.id); // Needs to be first, for ast_map.
916 box(GC) ForeignItem {
918 ident: folder.fold_ident(ni.ident),
919 attrs: ni.attrs.iter().map(|x| folder.fold_attribute(*x)).collect(),
920 node: match ni.node {
921 ForeignItemFn(ref fdec, ref generics) => {
922 ForeignItemFn(P(FnDecl {
923 inputs: fdec.inputs.iter().map(|a| folder.fold_arg(a)).collect(),
924 output: folder.fold_ty(fdec.output),
926 variadic: fdec.variadic
927 }), folder.fold_generics(generics))
929 ForeignItemStatic(t, m) => {
930 ForeignItemStatic(folder.fold_ty(t), m)
933 span: folder.new_span(ni.span),
938 // Default fold over a method.
939 // Invariant: produces exactly one method.
940 pub fn noop_fold_method<T: Folder>(m: &Method, folder: &mut T) -> SmallVector<Gc<Method>> {
941 let id = folder.new_id(m.id); // Needs to be first, for ast_map.
942 SmallVector::one(box(GC) Method {
943 attrs: m.attrs.iter().map(|a| folder.fold_attribute(*a)).collect(),
945 span: folder.new_span(m.span),
955 MethDecl(folder.fold_ident(ident),
956 folder.fold_generics(generics),
958 folder.fold_explicit_self(explicit_self),
960 folder.fold_fn_decl(&*decl),
961 folder.fold_block(body),
964 MethMac(ref mac) => MethMac(folder.fold_mac(mac)),
969 pub fn noop_fold_pat<T: Folder>(p: Gc<Pat>, folder: &mut T) -> Gc<Pat> {
970 let id = folder.new_id(p.id);
971 let node = match p.node {
973 PatWildMulti => PatWildMulti,
974 PatIdent(binding_mode, ref pth1, ref sub) => {
975 PatIdent(binding_mode,
976 Spanned{span: folder.new_span(pth1.span),
977 node: folder.fold_ident(pth1.node)},
978 sub.map(|x| folder.fold_pat(x)))
980 PatLit(e) => PatLit(folder.fold_expr(e)),
981 PatEnum(ref pth, ref pats) => {
982 PatEnum(folder.fold_path(pth),
983 pats.as_ref().map(|pats| pats.iter().map(|x| folder.fold_pat(*x)).collect()))
985 PatStruct(ref pth, ref fields, etc) => {
986 let pth_ = folder.fold_path(pth);
987 let fs = fields.iter().map(|f| {
990 pat: folder.fold_pat(f.pat)
993 PatStruct(pth_, fs, etc)
995 PatTup(ref elts) => PatTup(elts.iter().map(|x| folder.fold_pat(*x)).collect()),
996 PatBox(inner) => PatBox(folder.fold_pat(inner)),
997 PatRegion(inner) => PatRegion(folder.fold_pat(inner)),
998 PatRange(e1, e2) => {
999 PatRange(folder.fold_expr(e1), folder.fold_expr(e2))
1001 PatVec(ref before, ref slice, ref after) => {
1002 PatVec(before.iter().map(|x| folder.fold_pat(*x)).collect(),
1003 slice.map(|x| folder.fold_pat(x)),
1004 after.iter().map(|x| folder.fold_pat(*x)).collect())
1006 PatMac(ref mac) => PatMac(folder.fold_mac(mac)),
1011 span: folder.new_span(p.span),
1016 pub fn noop_fold_expr<T: Folder>(e: Gc<Expr>, folder: &mut T) -> Gc<Expr> {
1017 let id = folder.new_id(e.id);
1018 let node = match e.node {
1019 ExprVstore(e, v) => {
1020 ExprVstore(folder.fold_expr(e), v)
1023 ExprBox(folder.fold_expr(p), folder.fold_expr(e))
1025 ExprVec(ref exprs) => {
1026 ExprVec(exprs.iter().map(|&x| folder.fold_expr(x)).collect())
1028 ExprRepeat(expr, count) => {
1029 ExprRepeat(folder.fold_expr(expr), folder.fold_expr(count))
1031 ExprTup(ref elts) => ExprTup(elts.iter().map(|x| folder.fold_expr(*x)).collect()),
1032 ExprCall(f, ref args) => {
1033 ExprCall(folder.fold_expr(f),
1034 args.iter().map(|&x| folder.fold_expr(x)).collect())
1036 ExprMethodCall(i, ref tps, ref args) => {
1038 respan(i.span, folder.fold_ident(i.node)),
1039 tps.iter().map(|&x| folder.fold_ty(x)).collect(),
1040 args.iter().map(|&x| folder.fold_expr(x)).collect())
1042 ExprBinary(binop, lhs, rhs) => {
1044 folder.fold_expr(lhs),
1045 folder.fold_expr(rhs))
1047 ExprUnary(binop, ohs) => {
1048 ExprUnary(binop, folder.fold_expr(ohs))
1050 ExprLit(_) => e.node.clone(),
1051 ExprCast(expr, ty) => {
1052 ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
1054 ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
1055 ExprIf(cond, tr, fl) => {
1056 ExprIf(folder.fold_expr(cond),
1057 folder.fold_block(tr),
1058 fl.map(|x| folder.fold_expr(x)))
1060 ExprWhile(cond, body) => {
1061 ExprWhile(folder.fold_expr(cond), folder.fold_block(body))
1063 ExprForLoop(pat, iter, body, ref maybe_ident) => {
1064 ExprForLoop(folder.fold_pat(pat),
1065 folder.fold_expr(iter),
1066 folder.fold_block(body),
1067 maybe_ident.map(|i| folder.fold_ident(i)))
1069 ExprLoop(body, opt_ident) => {
1070 ExprLoop(folder.fold_block(body),
1071 opt_ident.map(|x| folder.fold_ident(x)))
1073 ExprMatch(expr, ref arms) => {
1074 ExprMatch(folder.fold_expr(expr),
1075 arms.iter().map(|x| folder.fold_arm(x)).collect())
1077 ExprFnBlock(ref decl, ref body) => {
1078 ExprFnBlock(folder.fold_fn_decl(&**decl),
1079 folder.fold_block(body.clone()))
1081 ExprProc(ref decl, ref body) => {
1082 ExprProc(folder.fold_fn_decl(&**decl),
1083 folder.fold_block(body.clone()))
1085 ExprUnboxedFn(ref decl, ref body) => {
1086 ExprUnboxedFn(folder.fold_fn_decl(&**decl),
1087 folder.fold_block(*body))
1089 ExprBlock(ref blk) => ExprBlock(folder.fold_block(*blk)),
1090 ExprAssign(el, er) => {
1091 ExprAssign(folder.fold_expr(el), folder.fold_expr(er))
1093 ExprAssignOp(op, el, er) => {
1095 folder.fold_expr(el),
1096 folder.fold_expr(er))
1098 ExprField(el, id, ref tys) => {
1099 ExprField(folder.fold_expr(el),
1100 respan(id.span, folder.fold_ident(id.node)),
1101 tys.iter().map(|&x| folder.fold_ty(x)).collect())
1103 ExprIndex(el, er) => {
1104 ExprIndex(folder.fold_expr(el), folder.fold_expr(er))
1106 ExprPath(ref pth) => ExprPath(folder.fold_path(pth)),
1107 ExprBreak(opt_ident) => ExprBreak(opt_ident.map(|x| folder.fold_ident(x))),
1108 ExprAgain(opt_ident) => ExprAgain(opt_ident.map(|x| folder.fold_ident(x))),
1110 ExprRet(e.map(|x| folder.fold_expr(x)))
1112 ExprInlineAsm(ref a) => {
1113 ExprInlineAsm(InlineAsm {
1114 inputs: a.inputs.iter().map(|&(ref c, input)| {
1115 ((*c).clone(), folder.fold_expr(input))
1117 outputs: a.outputs.iter().map(|&(ref c, out)| {
1118 ((*c).clone(), folder.fold_expr(out))
1123 ExprMac(ref mac) => ExprMac(folder.fold_mac(mac)),
1124 ExprStruct(ref path, ref fields, maybe_expr) => {
1125 ExprStruct(folder.fold_path(path),
1126 fields.iter().map(|x| folder.fold_field(*x)).collect(),
1127 maybe_expr.map(|x| folder.fold_expr(x)))
1129 ExprParen(ex) => ExprParen(folder.fold_expr(ex))
1135 span: folder.new_span(e.span),
1139 pub fn noop_fold_stmt<T: Folder>(s: &Stmt,
1140 folder: &mut T) -> SmallVector<Gc<Stmt>> {
1141 let nodes = match s.node {
1142 StmtDecl(d, id) => {
1143 let id = folder.new_id(id);
1144 folder.fold_decl(d).move_iter()
1145 .map(|d| StmtDecl(d, id))
1148 StmtExpr(e, id) => {
1149 let id = folder.new_id(id);
1150 SmallVector::one(StmtExpr(folder.fold_expr(e), id))
1152 StmtSemi(e, id) => {
1153 let id = folder.new_id(id);
1154 SmallVector::one(StmtSemi(folder.fold_expr(e), id))
1156 StmtMac(ref mac, semi) => SmallVector::one(StmtMac(folder.fold_mac(mac), semi))
1159 nodes.move_iter().map(|node| box(GC) Spanned {
1161 span: folder.new_span(s.span),
1169 use util::parser_testing::{string_to_crate, matches_codepattern};
1175 // this version doesn't care about getting comments or docstrings in.
1176 fn fake_print_crate(s: &mut pprust::State,
1177 krate: &ast::Crate) -> io::IoResult<()> {
1178 s.print_mod(&krate.module, krate.attrs.as_slice())
1181 // change every identifier to "zz"
1182 struct ToZzIdentFolder;
1184 impl Folder for ToZzIdentFolder {
1185 fn fold_ident(&mut self, _: ast::Ident) -> ast::Ident {
1186 token::str_to_ident("zz")
1188 fn fold_mac(&mut self, macro: &ast::Mac) -> ast::Mac {
1189 fold::noop_fold_mac(macro, self)
1193 // maybe add to expand.rs...
1194 macro_rules! assert_pred (
1195 ($pred:expr, $predname:expr, $a:expr , $b:expr) => (
1197 let pred_val = $pred;
1200 if !(pred_val(a_val.as_slice(),b_val.as_slice())) {
1201 fail!("expected args satisfying {}, got {:?} and {:?}",
1202 $predname, a_val, b_val);
1208 // make sure idents get transformed everywhere
1209 #[test] fn ident_transformation () {
1210 let mut zz_fold = ToZzIdentFolder;
1211 let ast = string_to_crate(
1212 "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
1213 let folded_crate = zz_fold.fold_crate(ast);
1215 matches_codepattern,
1216 "matches_codepattern",
1217 pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
1218 "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string());
1221 // even inside macro defs....
1222 #[test] fn ident_transformation_in_defs () {
1223 let mut zz_fold = ToZzIdentFolder;
1224 let ast = string_to_crate(
1225 "macro_rules! a {(b $c:expr $(d $e:token)f+ => \
1226 (g $(d $d $e)+))} ".to_string());
1227 let folded_crate = zz_fold.fold_crate(ast);
1229 matches_codepattern,
1230 "matches_codepattern",
1231 pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
1232 "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))".to_string());