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, 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) -> Result<Sysroot> {
71 tracing::debug!("Discovering sysroot for {}", dir.display());
72 let sysroot_dir = discover_sysroot_dir(dir)?;
73 let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir, dir)?;
74 let res = Sysroot::load(sysroot_dir, sysroot_src_dir)?;
78 pub fn discover_rustc(cargo_toml: &ManifestPath) -> 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).ok().and_then(|sysroot_dir| get_rustc_src(&sysroot_dir))
84 pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Result<Sysroot> {
86 Sysroot { root: sysroot_dir, src_root: sysroot_src_dir, crates: Arena::default() };
88 for path in SYSROOT_CRATES.trim().lines() {
89 let name = path.split('/').last().unwrap();
90 let root = [format!("{}/src/lib.rs", path), format!("lib{}/lib.rs", path)]
92 .map(|it| sysroot.src_root.join(it))
93 .filter_map(|it| ManifestPath::try_from(it).ok())
94 .find(|it| fs::metadata(it).is_ok());
96 if let Some(root) = root {
97 sysroot.crates.alloc(SysrootCrateData {
105 if let Some(std) = sysroot.by_name("std") {
106 for dep in STD_DEPS.trim().lines() {
107 if let Some(dep) = sysroot.by_name(dep) {
108 sysroot.crates[std].deps.push(dep)
113 if let Some(alloc) = sysroot.by_name("alloc") {
114 if let Some(core) = sysroot.by_name("core") {
115 sysroot.crates[alloc].deps.push(core);
119 if let Some(proc_macro) = sysroot.by_name("proc_macro") {
120 if let Some(std) = sysroot.by_name("std") {
121 sysroot.crates[proc_macro].deps.push(std);
125 if sysroot.by_name("core").is_none() {
126 let var_note = if env::var_os("RUST_SRC_PATH").is_some() {
127 " (`RUST_SRC_PATH` might be incorrect, try unsetting it)"
132 "could not find libcore in sysroot path `{}`{}",
133 sysroot.src_root.as_path().display(),
141 fn by_name(&self, name: &str) -> Option<SysrootCrate> {
142 let (id, _data) = self.crates.iter().find(|(_id, data)| data.name == name)?;
147 fn discover_sysroot_dir(current_dir: &AbsPath) -> Result<AbsPathBuf> {
148 let mut rustc = Command::new(toolchain::rustc());
149 rustc.current_dir(current_dir).args(&["--print", "sysroot"]);
150 tracing::debug!("Discovering sysroot by {:?}", rustc);
151 let stdout = utf8_stdout(rustc)?;
152 Ok(AbsPathBuf::assert(PathBuf::from(stdout)))
155 fn discover_sysroot_src_dir(
156 sysroot_path: &AbsPathBuf,
157 current_dir: &AbsPath,
158 ) -> Result<AbsPathBuf> {
159 if let Ok(path) = env::var("RUST_SRC_PATH") {
160 let path = AbsPathBuf::try_from(path.as_str())
161 .map_err(|path| format_err!("RUST_SRC_PATH must be absolute: {}", path.display()))?;
162 let core = path.join("core");
163 if fs::metadata(&core).is_ok() {
164 tracing::debug!("Discovered sysroot by RUST_SRC_PATH: {}", path.display());
167 tracing::debug!("RUST_SRC_PATH is set, but is invalid (no core: {:?}), ignoring", core);
170 get_rust_src(sysroot_path)
172 let mut rustup = Command::new(toolchain::rustup());
173 rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]);
174 utf8_stdout(rustup).ok()?;
175 get_rust_src(sysroot_path)
180 can't load standard library from sysroot
182 (discovered via `rustc --print sysroot`)
183 try installing the Rust source the same way you installed rustc",
184 sysroot_path.display(),
189 fn get_rustc_src(sysroot_path: &AbsPath) -> Option<ManifestPath> {
190 let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml");
191 let rustc_src = ManifestPath::try_from(rustc_src).ok()?;
192 tracing::debug!("Checking for rustc source code: {}", rustc_src.display());
193 if fs::metadata(&rustc_src).is_ok() {
200 fn get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> {
201 let rust_src = sysroot_path.join("lib/rustlib/src/rust/library");
202 tracing::debug!("Checking sysroot: {}", rust_src.display());
203 if fs::metadata(&rust_src).is_ok() {
210 const SYSROOT_CRATES: &str = "
218 stdarch/crates/std_detect
223 const STD_DEPS: &str = "