How can I implement my own tool with the code in rustc?

Hi, I am interested in rustc, I am trying to use the data structure defined in rustc and then implement my own tool development, how can I do it? For example, I want to use the code related to AST in rustc, how should I introduce the related dependencies in cargo.toml? Or do I need to clone the rust project and then recompile and modify it?

1 Like

If you just want to use the compiler internals, you can just write extern crate to load whichever crates you want:

#![feature(rustc_private)]
extern crate rustc_ast;

// ...do stuff with rustc_ast.

Documentation for the individual crates is at https://doc.rust-lang.org/nightly/nightly-rustc/.

This only works with the nightly toolchain.

If you want something that actually drives the entire compilation process, you can look at the Clippy source for a real-world example. I thought there was a small example in the docs somewhere, but I'm unable to find it right now.

If you aren't aware, there is also the https://rustc-dev-guide.rust-lang.org/ which gives an overview of the compiler internals.

Thanks, I've got it figured out!

One more question, when I use #! [feature(rustc_private)], does it have an effect on my code if the version of rustc is updated? For example, I am using rustc 1.67.0-nightly, am I always using the internals corresponding to rustc 1.67.0 when I use extern crate rustc_ast and other crates?

It will use the compiler libraries of the compiler you use to compile your code. So if you compile with rustc 1.71.0-nightly (a2b1646c5 2023-05-25), you will get the compiler libraries for rustc 1.71.0-nightly (a2b1646c5 2023-05-25). As such I did recommend pinning the exact nightly version you use in rust-toolchain.toml. This also allows automatically installing all necessary rustup components. For example:

[toolchain]
channel = "nightly-2023-05-26"
components = ["rust-src", "rustc-dev", "llvm-tools"]
1 Like

Thanks!

I've done something similar about a year and a half ago, and somewhat regreted to base it on top of rustc, because rustc internals are very unstable. I totally don't blame them (that was my decision after all to base my work on top of something explicitely unstable), but I think that I should thave done the same on top of rust-analyser instead.

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