Analysing crates

Is there a canonical way to get the abstract syntax tree (AST) of a crate? And or the unstable feature that it uses.

I found the rustc_ast crate.

I left open how to name or find the crate.

I don't think there's an official way to do this, but you can use cargo expand to get the contents of your entire crate post-macro expansion, and from there the syn crate can be used to parse the text into an AST (syn is used by pretty much every proc-macro implementation for parsing Rust code into an AST).

I guess that I am not the first one asking for the AST. Using cargo expand sounds a bit hacky. There is no better/official solution?

I use the syn crate with proc-macros.

1 Like

Why is it hacky?

This way you get the full source code as the compiler sees it - if you didn't expand macros then you would either a) need to handle them on your own, or b) be unable to analyse the code that they generate.

As a happy side-effect, the mod foo; items are inlined so you will get the entire crate's code in a single string.

The syn crate can also be used outside of proc-macros. It's just a parser for Rust source code, after all.