3
votes

I'm trying to use 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 extra dependency in Cargo.toml file.

[dependencies]
log = "0.4.1"

cargo run emits 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 rustc crate for my program?


Update

I added 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`)
2
Isn't this asking for you to declare rustc in your Cargo.toml? - tadman
@tadman I'm not sure. How should I do that? Can you post an answer? I couldn't find a crate page for the rustc crate on crates.io. - eonil
I mean add it to Cargo.toml to pull down that dependency instead of using the private one that ships with Rust. Just add that line and try it! - tadman
@tadman It doesn't work. error: no matching package named `rustc` found (required by `rust-swift-serde-gen`)... So sad. - eonil
@tadman Okay. I'm gonna check it out. - eonil

2 Answers

9
votes

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!

0
votes

Method 1: use 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 rustc-auto-publish repo

crate rustc-ap-rustc_ast is same as rustc_ast in rust source code

racer, rust-analyzer use rustc-ap-rustc_* crates

here is some code from racer's Cargo.toml:

[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"