]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/project-model/src/sysroot.rs
Rollup merge of #102059 - compiler-errors:issue-101984, r=jackh726
[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, CargoConfig, 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, 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)?;
75         Ok(res)
76     }
77
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)
82             .ok()
83             .and_then(|sysroot_dir| get_rustc_src(&sysroot_dir))
84     }
85
86     pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Result<Sysroot> {
87         let mut sysroot =
88             Sysroot { root: sysroot_dir, src_root: sysroot_src_dir, crates: Arena::default() };
89
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)]
93                 .into_iter()
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());
97
98             if let Some(root) = root {
99                 sysroot.crates.alloc(SysrootCrateData {
100                     name: name.into(),
101                     root,
102                     deps: Vec::new(),
103                 });
104             }
105         }
106
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)
111                 }
112             }
113         }
114
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);
118             }
119         }
120
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);
124             }
125         }
126
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)"
130             } else {
131                 ""
132             };
133             anyhow::bail!(
134                 "could not find libcore in sysroot path `{}`{}",
135                 sysroot.src_root.as_path().display(),
136                 var_note,
137             );
138         }
139
140         Ok(sysroot)
141     }
142
143     fn by_name(&self, name: &str) -> Option<SysrootCrate> {
144         let (id, _data) = self.crates.iter().find(|(_id, data)| data.name == name)?;
145         Some(id)
146     }
147 }
148
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)))
156 }
157
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());
169             return Ok(path);
170         }
171         tracing::debug!("RUST_SRC_PATH is set, but is invalid (no core: {:?}), ignoring", core);
172     }
173
174     get_rust_src(sysroot_path)
175         .or_else(|| {
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)
181         })
182         .ok_or_else(|| {
183             format_err!(
184                 "\
185 can't load standard library from sysroot
186 {}
187 (discovered via `rustc --print sysroot`)
188 try installing the Rust source the same way you installed rustc",
189                 sysroot_path.display(),
190             )
191         })
192 }
193
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() {
199         Some(rustc_src)
200     } else {
201         None
202     }
203 }
204
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() {
209         Some(rust_src)
210     } else {
211         None
212     }
213 }
214
215 const SYSROOT_CRATES: &str = "
216 alloc
217 core
218 panic_abort
219 panic_unwind
220 proc_macro
221 profiler_builtins
222 std
223 stdarch/crates/std_detect
224 term
225 test
226 unwind";
227
228 const STD_DEPS: &str = "
229 alloc
230 core
231 panic_abort
232 panic_unwind
233 profiler_builtins
234 std_detect
235 term
236 test
237 unwind";