# Converting Rust's AST back to code

**URL:** <https://internals.rust-lang.org/t/converting-rusts-ast-back-to-code/14353>\
**Category:** compiler\
**Created:** [March 27, 2021, 7:36pm UTC](https://internals.rust-lang.org/t/converting-rusts-ast-back-to-code/14353 "2021-03-27T19:36:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![prgzz](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/prgzz/32/7920_2.png) [@prgzz](https://internals.rust-lang.org/u/prgzz)\
**Post date:** [March 27, 2021, 7:36pm UTC](https://internals.rust-lang.org/t/converting-rusts-ast-back-to-code/14353/1 "2021-03-27T19:36:53Z")

</div>

Hi,

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](https://github.com/rust-lang/rustfmt) does this, pretty much, from scratch. It seems to have a separate file for each AST type, e.g. - [expr](https://github.com/rust-lang/rustfmt/blob/master/src/formatting/expr.rs). 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.

Thanks!

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [March 27, 2021, 8:28pm UTC](https://internals.rust-lang.org/t/converting-rusts-ast-back-to-code/14353/2 "2021-03-27T20:28:47Z")

</div>

It sounds like you are trying to write a [procedural macro](https://doc.rust-lang.org/reference/procedural-macros.html). The [syn](https://docs.rs/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.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [June 25, 2021, 8:29pm UTC](https://internals.rust-lang.org/t/converting-rusts-ast-back-to-code/14353/3 "2021-06-25T20:29:00Z")

</div>

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