Module syn::fold

source · []
Expand description

Syntax tree traversal to transform the nodes of an owned syntax tree.

Each method of the Fold trait is a hook that can be overridden to customize the behavior when transforming the corresponding type of node. By default, every method recursively visits the substructure of the input by invoking the right visitor method of each of its fields.

pub trait Fold {
    /* ... */

    fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary {
        fold_expr_binary(self, node)
    }

    /* ... */
}

pub fn fold_expr_binary<V>(v: &mut V, node: ExprBinary) -> ExprBinary
where
    V: Fold + ?Sized,
{
    ExprBinary {
        attrs: node
            .attrs
            .into_iter()
            .map(|attr| v.fold_attribute(attr))
            .collect(),
        left: Box::new(v.fold_expr(*node.left)),
        op: v.fold_bin_op(node.op),
        right: Box::new(v.fold_expr(*node.right)),
    }
}

/* ... */

This module is available only if Syn is built with the "fold" feature.


Example

This fold inserts parentheses to fully parenthesizes any expression.

// [dependencies]
// quote = "1.0"
// syn = { version = "1.0", features = ["fold", "full"] }

use quote::quote;
use syn::fold::{fold_expr, Fold};
use syn::{token, Expr, ExprParen};

struct ParenthesizeEveryExpr;

impl Fold for ParenthesizeEveryExpr {
    fn fold_expr(&mut self, expr: Expr) -> Expr {
        Expr::Paren(ExprParen {
            attrs: Vec::new(),
            expr: Box::new(fold_expr(self, expr)),
            paren_token: token::Paren::default(),
        })
    }
}

fn main() {
    let code = quote! { a() + b(1) * c.d };
    let expr: Expr = syn::parse2(code).unwrap();
    let parenthesized = ParenthesizeEveryExpr.fold_expr(expr);
    println!("{}", quote!(#parenthesized));

    // Output: (((a)()) + (((b)((1))) * ((c).d)))
}

Traits

Syntax tree traversal to transform the nodes of an owned syntax tree.

Functions