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::{convert::TryFrom, env, 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;
15 #[derive(Default, Debug, Clone, Eq, PartialEq)]
17 crates: Arena<SysrootCrateData>,
20 pub(crate) type SysrootCrate = Idx<SysrootCrateData>;
22 #[derive(Debug, Clone, Eq, PartialEq)]
23 pub struct SysrootCrateData {
26 pub deps: Vec<SysrootCrate>,
29 impl ops::Index<SysrootCrate> for Sysroot {
30 type Output = SysrootCrateData;
31 fn index(&self, index: SysrootCrate) -> &SysrootCrateData {
37 pub fn public_deps(&self) -> impl Iterator<Item = (&'static str, SysrootCrate)> + '_ {
38 // core is added as a dependency before std in order to
39 // mimic rustcs dependency order
40 ["core", "alloc", "std"].iter().filter_map(move |&it| Some((it, self.by_name(it)?)))
43 pub fn proc_macro(&self) -> Option<SysrootCrate> {
44 self.by_name("proc_macro")
47 pub fn crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + ExactSizeIterator + 'a {
48 self.crates.iter().map(|(id, _data)| id)
51 pub fn discover(cargo_toml: &AbsPath) -> Result<Sysroot> {
52 log::debug!("Discovering sysroot for {}", cargo_toml.display());
53 let current_dir = cargo_toml.parent().ok_or_else(|| {
54 format_err!("Failed to find the parent directory for {}", cargo_toml.display())
56 let sysroot_dir = discover_sysroot_dir(current_dir)?;
57 let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir, current_dir)?;
58 let res = Sysroot::load(&sysroot_src_dir)?;
62 pub fn discover_rustc(cargo_toml: &AbsPath) -> Option<AbsPathBuf> {
63 log::debug!("Discovering rustc source for {}", cargo_toml.display());
64 let current_dir = cargo_toml.parent().unwrap();
65 discover_sysroot_dir(current_dir).ok().and_then(|sysroot_dir| get_rustc_src(&sysroot_dir))
68 pub fn load(sysroot_src_dir: &AbsPath) -> Result<Sysroot> {
69 let mut sysroot = Sysroot { crates: Arena::default() };
71 for name in SYSROOT_CRATES.trim().lines() {
72 let root = [format!("{}/src/lib.rs", name), format!("lib{}/lib.rs", name)]
74 .map(|it| sysroot_src_dir.join(it))
75 .find(|it| it.exists());
77 if let Some(root) = root {
78 sysroot.crates.alloc(SysrootCrateData {
86 if let Some(std) = sysroot.by_name("std") {
87 for dep in STD_DEPS.trim().lines() {
88 if let Some(dep) = sysroot.by_name(dep) {
89 sysroot.crates[std].deps.push(dep)
94 if let Some(alloc) = sysroot.by_name("alloc") {
95 if let Some(core) = sysroot.by_name("core") {
96 sysroot.crates[alloc].deps.push(core);
100 if sysroot.by_name("core").is_none() {
101 let var_note = if env::var_os("RUST_SRC_PATH").is_some() {
102 " (`RUST_SRC_PATH` might be incorrect, try unsetting it)"
107 "could not find libcore in sysroot path `{}`{}",
108 sysroot_src_dir.as_ref().display(),
116 fn by_name(&self, name: &str) -> Option<SysrootCrate> {
117 let (id, _data) = self.crates.iter().find(|(_id, data)| data.name == name)?;
122 fn discover_sysroot_dir(current_dir: &AbsPath) -> Result<AbsPathBuf> {
123 let mut rustc = Command::new(toolchain::rustc());
124 rustc.current_dir(current_dir).args(&["--print", "sysroot"]);
125 log::debug!("Discovering sysroot by {:?}", rustc);
126 let stdout = utf8_stdout(rustc)?;
127 Ok(AbsPathBuf::assert(PathBuf::from(stdout)))
130 fn discover_sysroot_src_dir(
131 sysroot_path: &AbsPathBuf,
132 current_dir: &AbsPath,
133 ) -> Result<AbsPathBuf> {
134 if let Ok(path) = env::var("RUST_SRC_PATH") {
135 let path = AbsPathBuf::try_from(path.as_str())
136 .map_err(|path| format_err!("RUST_SRC_PATH must be absolute: {}", path.display()))?;
137 let core = path.join("core");
139 log::debug!("Discovered sysroot by RUST_SRC_PATH: {}", path.display());
142 log::debug!("RUST_SRC_PATH is set, but is invalid (no core: {:?}), ignoring", core);
145 get_rust_src(&sysroot_path)
147 let mut rustup = Command::new(toolchain::rustup());
148 rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]);
149 utf8_stdout(rustup).ok()?;
150 get_rust_src(&sysroot_path)
155 can't load standard library from sysroot
157 (discovered via `rustc --print sysroot`)
158 try installing the Rust source the same way you installed rustc",
159 sysroot_path.display(),
164 fn get_rustc_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> {
165 let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml");
166 log::debug!("Checking for rustc source code: {}", rustc_src.display());
167 if rustc_src.exists() {
174 fn get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> {
175 // Try the new path first since the old one still exists.
176 let rust_src = sysroot_path.join("lib/rustlib/src/rust");
177 log::debug!("Checking sysroot (looking for `library` and `src` dirs): {}", rust_src.display());
178 ["library", "src"].iter().map(|it| rust_src.join(it)).find(|it| it.exists())
181 impl SysrootCrateData {
182 pub fn root_dir(&self) -> &AbsPath {
183 self.root.parent().unwrap()
187 const SYSROOT_CRATES: &str = "
201 const STD_DEPS: &str = "