dtolnay / syn

Parser for Rust source code

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to handle `AssignOp` from syn v1 to v2?

dbsxdbsx opened this issue · comments

I am trying to move my code from syn v1 to syn v2, the original code is like this :

use quote::{quote, ToTokens};
use regex::{Captures, Regex};

use syn::{parse_str, Expr, FnArg, Receiver, Signature};

pub fn process_assignment_expr(re: &Regex, expr: &Expr, is_method_mut: bool) -> Expr {
    // 1. left side
    let left = match expr {
        syn::Expr::Assign(assign_expr) => &assign_expr.left,
        syn::Expr::AssignOp(assign_op_expr) => &assign_op_expr.left,
        _ => unreachable!(),
    };
    let left_str = quote!(#left).to_string();
    let new_left_str = re
        .replace_all(&left_str, |caps: &Captures| {
            format!("(*self._{}_mut())", &caps[1])
        })
        .to_string();

    // 2. right side
    let right = match expr {
        syn::Expr::Assign(assign_expr) => &assign_expr.right,
        syn::Expr::AssignOp(assign_op_expr) => &assign_op_expr.right,
        _ => unreachable!(),
    };
    let new_right_str = replace_self_field(right, is_method_mut, false);

    // 3. rebuild the final expression and return
    let new_expr_str = match expr {
        syn::Expr::Assign(_) => format!("{} = {}", new_left_str, new_right_str),
        syn::Expr::AssignOp(assign_op_expr) => format!(
            "{} {} {}",
            new_left_str,
            assign_op_expr.op.to_token_stream(),
            new_right_str
        ),
        _ => unreachable!(),
    };
    syn::parse_str(&new_expr_str).expect("Failed to parse new expr")
}

I know there is no syn::Expr::AssignOp in v2, but what to use then?

https://github.com/dtolnay/syn/tree/master/examples/dump-syntax has a program that you can use for inspecting syn's syntax tree for any Rust file. You can try running it on a file that contains an assignment to see what that's represented as.