Parse to AST, update, emit new Rust code?

With TypeScript, there are tools built into its library for parsing and emitting TypeScript code. There are similar libraries built into Python (ast / 2to3), C++ (libclang), and others.

In Rust, I want to read Rust code in, modify the code, then output the newly modified code.

How do I do this?

I’m not sure if there is a stable way to do this. I know there have been a few efforts to right IDE-friendly stable Rust parsers, but I’m not sure if any of them is complete… here is one of them:

Another thing you could do is look at what rustfmt does. I think it uses the compiler’s unstable interface.

Maybe you could use the syn and quote crates? The intended use of these crates is for writing procedural macros that transform Rust ASTs. However, you should be able to use them in a standalone program. For example, for parsing Rust source code you could try to use parse_str function.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.