Q: How to manipulate nodes+parent_nodes in AST & generate the tree back to JS code? #3254
Replies: 3 comments 18 replies
-
for the second question, I think you can use |
Beta Was this translation helpful? Give feedback.
-
struct MyVisitor;
impl swc_ecma_visit::VisitMut for MyVisitor {
fn visit_mut_call_expr(&mut self, expr: &mut CallExpr) {
expr.visit_mut_children_with(self);
match &mut expr.callee {
Callee::Expr(callee) => match &mut **callee { // callee is &mut Box<Expr>
Expr::Ident(Ident { sym, .. }) => {
if sym.to_string() == "Foo" {
*expr = CallExpr {
span: DUMMY_SP,
callee: swc_ecma_ast::Callee::Expr(callee.take()), // here we want a Box<Expr>, and callee will not use in other place, so we take() it, we got a Box<Expr>,and the origin memory of callee will be replace with dummy value
args: vec![CallExpr {
span: DUMMY_SP,
callee: private_ident!("WrapperFunc").as_callee(),
args: expr.args.take(),
type_args: Default::default(),
}
.as_arg()],
type_args: Default::default(),
}
}
}
_ => {}
},
_ => {}
}
}
}
#[cfg(test)]
mod tests{
test!(
::swc_ecma_parser::Syntax::default(),
|_| {
as_folder(MyVisitor)
},
my,
"let x = Foo(arg1, arg2, arg3)",
r#"let x = Foo(WrapperFunc(arg1, arg2, arg3))"#
);
} |
Beta Was this translation helpful? Give feedback.
-
I'm back with another question. Since there's still no AST Explorer and I have to figure out what every visit_mut_* type is related to what code expression (CallExp, VarDeclaration etc.), is there a way I can do something naive like this (psuedo):
The reason I am asking this is because I find the AST representation with the API much more complex than babel (e.g).
where I wish to manipulate it into this:
There are just so many types that I'm getting lost inside the API. I realize it might cost in performance loss as I run an extra if on every node. But I need some progress to be made for my POC. Thanks. |
Beta Was this translation helpful? Give feedback.
-
Hey. My project requires manipulating js files. In example, changing all "A()" function calls to "B(A())".
Currently I have a js+babel implementation that is doing the basic following:
Unfortunately, babel seems to be performance-bottlenecked on large files, thus I started experimenting with SWC-Rust.
I have made a small program as a POC. I managed to parse my js file, traverse it and manipulate (well, access) Identifier nodes by implementing the Fold trait. See code at the end of the post.
Now, I have 2 main questions:
Thanks!
main.js:
Cargo.toml:
Beta Was this translation helpful? Give feedback.
All reactions