'How can I use a `rustc` crate?

I'm trying to use a rustc crate in my program.

#[macro_use]
extern crate rustc;
extern crate rustc_typeck;
extern crate syntax;
extern crate syntax_pos;

use rustc::hir;

fn main() {
    println!("Hello, World!");

}

I also added an extra dependency in the Cargo.toml file:

[dependencies]
log = "0.4.1"

cargo run emits a bunch of errors that it's private and nightly only:

error: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? (see issue #27812)
 --> src/main.rs:2:1
  |
2 | extern crate rustc;
  | ^^^^^^^^^^^^^^^^^^^

It seems Cargo want a stable crate from crates.io, but I don't know which crate I should use. There's no crate named rustc on crates.io.

Here's my Rust installation version.

  • rustc 1.23.0 (766bd11c8 2018-01-01)
  • cargo 0.24.0 (45043115c 2017-12-05)

I installed it using rustup.

How can I use a rustc crate for my program?


I tried to add rustc = "1.23.0" to Cargo.toml, but it still doesn't work with this error:

error: no matching package named `rustc` found (required by `rust-swift-serde-gen`)


Solution 1:[1]

rustc is indeed not published on crates.io.

Because the API for the rustc crate is not stable, you must switch to the nightly compiler and opt in by adding this line at the beginning of your crate root (main.rs or lib.rs):

#![feature(rustc_private)]

Naturally, since the API is not stable, every time you update your nightly compiler, things may break without warning!

Solution 2:[2]

Method 1: use the rustc-dev component

rustup component add rustc-dev

Then you can use:

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

Method 2: use rustc-ap-rustc_* crates

According to the rustc-auto-publish repository:

crate rustc-ap-rustc_ast is the same as rustc_ast in the Rust source code.

racer and rust-analyzer use rustc-ap-rustc_* crates.

Here is some code from racer's Cargo.toml file:

[dependencies.rustc_errors]
package = "rustc-ap-rustc_errors"
version = "712.0.0"

[dependencies.rustc_parse]
package = "rustc-ap-rustc_parse"
version = "712.0.0"

[dependencies.rustc_session]
package = "rustc-ap-rustc_session"
version = "712.0.0"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Francis Gagné
Solution 2 Peter Mortensen