Rust AST and Type-Checking API

I want to parse the Rust code and get it's AST along with all the type information (fully-resolved). I need to traverse the AST to collect some data. What are options to achieve this ? Is rustc provides some API to the compiler or I can use Rust-Analyzer for this (and by use, I mean to be able to understand that gigantic beautiful piece of software and do something useful with my little brain!). Thanks

(warning: I'm not an expert here, but I've spent some time poking at the rust repo and compilers in general)

This is a simple question with a surprisingly tricky answer! The simplest option is probably to just use the language service rust-analyzer like an editor would, that will let you get some basic type info and file structure information.

The compiler itself though is implemented as a series of crates, you can probably build on those somewhat easily with cargo git dependencies.

To get a typed structure, the "Typed High-level Intermediate Representation" (THIR) looks like it should be the closest match, but I expect you'll need to do quite a bit of scaffolding to get there.

2 Likes

thanks @simonbuchan for the response. I also went through the rust-analyzer docs and it says if I want to use it as a library then HIR is probably a good place to start. Will continue with analyzer and see how far I can reach in using it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.