Converting Rust's AST back to code


I was wondering how could one convert Rust's AST back to code. My goal is to take Rust's AST, apply a bunch of transforms, and then convert the transformed AST back to code. I guess ideally I would take this transformed AST and go through the remaining layers of compilation (conversion to HIR, THIR, MIR, LLVM), but currently, I don't have a good way of doing this. Hence the current approach.

I can see that rustfmt does this, pretty much, from scratch. It seems to have a separate file for each AST type, e.g. - expr. However, I was wondering whether there is some "magic" function that can take the AST and give me some valid code that represents the AST. Tbh, I'm quite new to all this. So, any help would be great.


It sounds like you are trying to write a procedural macro. The syn crate contains AST data structures that convert how to convert themselves to a proc_macro2::TokenStream, which is already enough for a proc-macro to work. However, if you do indeed want the Rust code as a raw string, you can see that TokenStream implements Display so it has a to_string() method.