How does using rustc as a library work?

I'd like to write some software in Rust that does some heavy-duty analysis of arbitrary Rust source code. I could try re-implementing a Rust parser, but that seems like a lot of unnecessary work since rustc already exists and has a working parser. As such, I'd like to somehow link to it.

When I started looking into how to do that, however, I came across some information, but some of my questions are still unanswered. I found a relevant book that describes the internals of rustc, which is extremely useful, but not enough information, as it focuses on helping to make contributions to rustc. While I have nothing against making such contributions should I find missing feature(s) that I want, it also isn't what I'm trying to do — the software that I want to write is well beyond the scope of a compiler.

Specifically, I need to know how one consumes rustc externally. It seems like a lot of its code is "internal" (see this for an example), suggesting some "external" APIs that I may want to look into to see if they meet my needs, but I can't find anything about that other than the aforementioned inference. It seems like there are no crates available that are really just bits of rustc either. Am I supposed to pull rustc's source into my program, and make changes to integrate it? If so, what are the best practices for reducing maintenance overhead so I'm not constantly refactoring the same code in slightly different ways over and over again every time it updates? If not, what am I supposed to do? I've also seen inklings of some sort of JSON-outputting option from rustc, but I can't find any detailed documentation on how this works, but it may be sufficient for my needs.

There are absolutely no stability guarantees or anything of rustc as a library.

What is the standard way to parse Rust source code then? Is it a case of one of dealing with instability (in which case this post is about the best ways to do that) or writing one's own parser?

Use syn.

1 Like

You may also be interested in the Rust grammar WG, which is attempting to formalize Rust's grammar. rustc also has a plugin capability, though that is being deprecated long-term. If you do go the plugin route, perhaps because you need more rustc processing than simply parsing, do remember that there are no stability guarantees for plugins.

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