]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/project-model/src/sysroot.rs
Rollup merge of #101190 - yjhn:patch-1, r=Mark-Simulacrum
[rust.git] / src / tools / rust-analyzer / crates / project-model / src / sysroot.rs
1 //! Loads "sysroot" crate.
2 //!
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.
6
7 use std::{env, fs, iter, ops, path::PathBuf, process::Command};
8
9 use anyhow::{format_err, Result};
10 use la_arena::{Arena, Idx};
11 use paths::{AbsPath, AbsPathBuf};
12
13 use crate::{utf8_stdout, ManifestPath};
14
15 #[derive(Debug, Clone, Eq, PartialEq)]
16 pub struct Sysroot {
17     root: AbsPathBuf,
18     src_root: AbsPathBuf,
19     crates: Arena<SysrootCrateData>,
20 }
21
22 pub(crate) type SysrootCrate = Idx<SysrootCrateData>;
23
24 #[derive(Debug, Clone, Eq, PartialEq)]
25 pub struct SysrootCrateData {
26     pub name: String,
27     pub root: ManifestPath,
28     pub deps: Vec<SysrootCrate>,
29 }
30
31 impl ops::Index<SysrootCrate> for Sysroot {
32     type Output = SysrootCrateData;
33     fn index(&self, index: SysrootCrate) -> &SysrootCrateData {
34         &self.crates[index]
35     }
36 }
37
38 impl Sysroot {
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 {
43         &self.root
44     }
45
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 {
49         &self.src_root
50     }
51
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"]
56             .into_iter()
57             .zip(iter::repeat(true))
58             .chain(iter::once(("test", false)))
59             .filter_map(move |(name, prelude)| Some((name, self.by_name(name)?, prelude)))
60     }
61
62     pub fn proc_macro(&self) -> Option<SysrootCrate> {
63         self.by_name("proc_macro")
64     }
65
66     pub fn crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + ExactSizeIterator + 'a {
67         self.crates.iter().map(|(id, _data)| id)
68     }
69
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)?;
75         Ok(res)
76     }
77
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))
82     }
83
84     pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Result<Sysroot> {
85         let mut sysroot =
86             Sysroot { root: sysroot_dir, src_root: sysroot_src_dir, crates: Arena::default() };
87
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)]
91                 .into_iter()
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());
95
96             if let Some(root) = root {
97                 sysroot.crates.alloc(SysrootCrateData {
98                     name: name.into(),
99                     root,
100                     deps: Vec::new(),
101                 });
102             }
103         }
104
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)
109                 }
110             }
111         }
112
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);
116             }
117         }
118
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);
122             }
123         }
124
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)"
128             } else {
129                 ""
130             };
131             anyhow::bail!(
132                 "could not find libcore in sysroot path `{}`{}",
133                 sysroot.src_root.as_path().display(),
134                 var_note,
135             );
136         }
137
138         Ok(sysroot)
139     }
140
141     fn by_name(&self, name: &str) -> Option<SysrootCrate> {
142         let (id, _data) = self.crates.iter().find(|(_id, data)| data.name == name)?;
143         Some(id)
144     }
145 }
146
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)))
153 }
154
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());
165             return Ok(path);
166         }
167         tracing::debug!("RUST_SRC_PATH is set, but is invalid (no core: {:?}), ignoring", core);
168     }
169
170     get_rust_src(sysroot_path)
171         .or_else(|| {
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)
176         })
177         .ok_or_else(|| {
178             format_err!(
179                 "\
180 can't load standard library from sysroot
181 {}
182 (discovered via `rustc --print sysroot`)
183 try installing the Rust source the same way you installed rustc",
184                 sysroot_path.display(),
185             )
186         })
187 }
188
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() {
194         Some(rustc_src)
195     } else {
196         None
197     }
198 }
199
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() {
204         Some(rust_src)
205     } else {
206         None
207     }
208 }
209
210 const SYSROOT_CRATES: &str = "
211 alloc
212 core
213 panic_abort
214 panic_unwind
215 proc_macro
216 profiler_builtins
217 std
218 stdarch/crates/std_detect
219 term
220 test
221 unwind";
222
223 const STD_DEPS: &str = "
224 alloc
225 core
226 panic_abort
227 panic_unwind
228 profiler_builtins
229 std_detect
230 term
231 test
232 unwind";