1 //! Loads "sysroot" crate.
3 //! One confusing point here is that normally sysroot is a bunch of `.rlib`s,
4 //! but we can't process `.rlib` and need source code instead. The source code
5 //! is typically installed with `rustup component add rust-src` command.
7 use std::{env, fs, iter, ops, path::PathBuf, process::Command};
9 use anyhow::{format_err, Result};
10 use la_arena::{Arena, Idx};
11 use paths::{AbsPath, AbsPathBuf};
13 use crate::{utf8_stdout, CargoConfig, ManifestPath};
15 #[derive(Debug, Clone, Eq, PartialEq)]
19 crates: Arena<SysrootCrateData>,
22 pub(crate) type SysrootCrate = Idx<SysrootCrateData>;
24 #[derive(Debug, Clone, Eq, PartialEq)]
25 pub struct SysrootCrateData {
27 pub root: ManifestPath,
28 pub deps: Vec<SysrootCrate>,
31 impl ops::Index<SysrootCrate> for Sysroot {
32 type Output = SysrootCrateData;
33 fn index(&self, index: SysrootCrate) -> &SysrootCrateData {
39 /// Returns sysroot "root" directory, where `bin/`, `etc/`, `lib/`, `libexec/`
40 /// subfolder live, like:
41 /// `$HOME/.rustup/toolchains/nightly-2022-07-23-x86_64-unknown-linux-gnu`
42 pub fn root(&self) -> &AbsPath {
46 /// Returns the sysroot "source" directory, where stdlib sources are located, like:
47 /// `$HOME/.rustup/toolchains/nightly-2022-07-23-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library`
48 pub fn src_root(&self) -> &AbsPath {
52 pub fn public_deps(&self) -> impl Iterator<Item = (&'static str, SysrootCrate, bool)> + '_ {
53 // core is added as a dependency before std in order to
54 // mimic rustcs dependency order
55 ["core", "alloc", "std"]
57 .zip(iter::repeat(true))
58 .chain(iter::once(("test", false)))
59 .filter_map(move |(name, prelude)| Some((name, self.by_name(name)?, prelude)))
62 pub fn proc_macro(&self) -> Option<SysrootCrate> {
63 self.by_name("proc_macro")
66 pub fn crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + ExactSizeIterator + 'a {
67 self.crates.iter().map(|(id, _data)| id)
70 pub fn discover(dir: &AbsPath, config: &CargoConfig) -> Result<Sysroot> {
71 tracing::debug!("Discovering sysroot for {}", dir.display());
72 let sysroot_dir = discover_sysroot_dir(dir, config)?;
73 let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir, dir, config)?;
74 let res = Sysroot::load(sysroot_dir, sysroot_src_dir)?;
78 pub fn discover_rustc(cargo_toml: &ManifestPath, config: &CargoConfig) -> Option<ManifestPath> {
79 tracing::debug!("Discovering rustc source for {}", cargo_toml.display());
80 let current_dir = cargo_toml.parent();
81 discover_sysroot_dir(current_dir, config)
83 .and_then(|sysroot_dir| get_rustc_src(&sysroot_dir))
86 pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Result<Sysroot> {
88 Sysroot { root: sysroot_dir, src_root: sysroot_src_dir, crates: Arena::default() };
90 for path in SYSROOT_CRATES.trim().lines() {
91 let name = path.split('/').last().unwrap();
92 let root = [format!("{}/src/lib.rs", path), format!("lib{}/lib.rs", path)]
94 .map(|it| sysroot.src_root.join(it))
95 .filter_map(|it| ManifestPath::try_from(it).ok())
96 .find(|it| fs::metadata(it).is_ok());
98 if let Some(root) = root {
99 sysroot.crates.alloc(SysrootCrateData {
107 if let Some(std) = sysroot.by_name("std") {
108 for dep in STD_DEPS.trim().lines() {
109 if let Some(dep) = sysroot.by_name(dep) {
110 sysroot.crates[std].deps.push(dep)
115 if let Some(alloc) = sysroot.by_name("alloc") {
116 if let Some(core) = sysroot.by_name("core") {
117 sysroot.crates[alloc].deps.push(core);
121 if let Some(proc_macro) = sysroot.by_name("proc_macro") {
122 if let Some(std) = sysroot.by_name("std") {
123 sysroot.crates[proc_macro].deps.push(std);
127 if sysroot.by_name("core").is_none() {
128 let var_note = if env::var_os("RUST_SRC_PATH").is_some() {
129 " (`RUST_SRC_PATH` might be incorrect, try unsetting it)"
134 "could not find libcore in sysroot path `{}`{}",
135 sysroot.src_root.as_path().display(),
143 fn by_name(&self, name: &str) -> Option<SysrootCrate> {
144 let (id, _data) = self.crates.iter().find(|(_id, data)| data.name == name)?;
149 fn discover_sysroot_dir(current_dir: &AbsPath, config: &CargoConfig) -> Result<AbsPathBuf> {
150 let mut rustc = Command::new(toolchain::rustc());
151 rustc.envs(&config.extra_env);
152 rustc.current_dir(current_dir).args(&["--print", "sysroot"]);
153 tracing::debug!("Discovering sysroot by {:?}", rustc);
154 let stdout = utf8_stdout(rustc)?;
155 Ok(AbsPathBuf::assert(PathBuf::from(stdout)))
158 fn discover_sysroot_src_dir(
159 sysroot_path: &AbsPathBuf,
160 current_dir: &AbsPath,
161 config: &CargoConfig,
162 ) -> Result<AbsPathBuf> {
163 if let Ok(path) = env::var("RUST_SRC_PATH") {
164 let path = AbsPathBuf::try_from(path.as_str())
165 .map_err(|path| format_err!("RUST_SRC_PATH must be absolute: {}", path.display()))?;
166 let core = path.join("core");
167 if fs::metadata(&core).is_ok() {
168 tracing::debug!("Discovered sysroot by RUST_SRC_PATH: {}", path.display());
171 tracing::debug!("RUST_SRC_PATH is set, but is invalid (no core: {:?}), ignoring", core);
174 get_rust_src(sysroot_path)
176 let mut rustup = Command::new(toolchain::rustup());
177 rustup.envs(&config.extra_env);
178 rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]);
179 utf8_stdout(rustup).ok()?;
180 get_rust_src(sysroot_path)
185 can't load standard library from sysroot
187 (discovered via `rustc --print sysroot`)
188 try installing the Rust source the same way you installed rustc",
189 sysroot_path.display(),
194 fn get_rustc_src(sysroot_path: &AbsPath) -> Option<ManifestPath> {
195 let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml");
196 let rustc_src = ManifestPath::try_from(rustc_src).ok()?;
197 tracing::debug!("Checking for rustc source code: {}", rustc_src.display());
198 if fs::metadata(&rustc_src).is_ok() {
205 fn get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> {
206 let rust_src = sysroot_path.join("lib/rustlib/src/rust/library");
207 tracing::debug!("Checking sysroot: {}", rust_src.display());
208 if fs::metadata(&rust_src).is_ok() {
215 const SYSROOT_CRATES: &str = "
223 stdarch/crates/std_detect
228 const STD_DEPS: &str = "