]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #9368
[rust.git] / crates / project_model / src / cargo_workspace.rs
1 //! See [`CargoWorkspace`].
2
3 use std::iter;
4 use std::path::PathBuf;
5 use std::{convert::TryInto, ops, process::Command, sync::Arc};
6
7 use anyhow::{Context, Result};
8 use base_db::Edition;
9 use cargo_metadata::{CargoOpt, MetadataCommand};
10 use la_arena::{Arena, Idx};
11 use paths::{AbsPath, AbsPathBuf};
12 use rustc_hash::FxHashMap;
13 use serde::Deserialize;
14 use serde_json::from_value;
15
16 use crate::CfgOverrides;
17 use crate::{build_data::BuildDataConfig, utf8_stdout};
18
19 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
20 /// workspace. It pretty closely mirrors `cargo metadata` output.
21 ///
22 /// Note that internally, rust analyzer uses a different structure:
23 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
24 /// while this knows about `Packages` & `Targets`: purely cargo-related
25 /// concepts.
26 ///
27 /// We use absolute paths here, `cargo metadata` guarantees to always produce
28 /// abs paths.
29 #[derive(Debug, Clone, Eq, PartialEq)]
30 pub struct CargoWorkspace {
31     packages: Arena<PackageData>,
32     targets: Arena<TargetData>,
33     workspace_root: AbsPathBuf,
34     build_data_config: BuildDataConfig,
35 }
36
37 impl ops::Index<Package> for CargoWorkspace {
38     type Output = PackageData;
39     fn index(&self, index: Package) -> &PackageData {
40         &self.packages[index]
41     }
42 }
43
44 impl ops::Index<Target> for CargoWorkspace {
45     type Output = TargetData;
46     fn index(&self, index: Target) -> &TargetData {
47         &self.targets[index]
48     }
49 }
50
51 /// Describes how to set the rustc source directory.
52 #[derive(Clone, Debug, PartialEq, Eq)]
53 pub enum RustcSource {
54     /// Explicit path for the rustc source directory.
55     Path(AbsPathBuf),
56     /// Try to automatically detect where the rustc source directory is.
57     Discover,
58 }
59
60 #[derive(Default, Clone, Debug, PartialEq, Eq)]
61 pub struct CargoConfig {
62     /// Do not activate the `default` feature.
63     pub no_default_features: bool,
64
65     /// Activate all available features
66     pub all_features: bool,
67
68     /// List of features to activate.
69     /// This will be ignored if `cargo_all_features` is true.
70     pub features: Vec<String>,
71
72     /// rustc target
73     pub target: Option<String>,
74
75     /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
76     /// when debugging isolated issues.
77     pub no_sysroot: bool,
78
79     /// rustc private crate source
80     pub rustc_source: Option<RustcSource>,
81
82     /// crates to disable `#[cfg(test)]` on
83     pub unset_test_crates: Vec<String>,
84 }
85
86 impl CargoConfig {
87     pub fn cfg_overrides(&self) -> CfgOverrides {
88         self.unset_test_crates
89             .iter()
90             .cloned()
91             .zip(iter::repeat_with(|| {
92                 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap()
93             }))
94             .collect()
95     }
96 }
97
98 pub type Package = Idx<PackageData>;
99
100 pub type Target = Idx<TargetData>;
101
102 /// Information associated with a cargo crate
103 #[derive(Debug, Clone, Eq, PartialEq)]
104 pub struct PackageData {
105     /// Version given in the `Cargo.toml`
106     pub version: String,
107     /// Name as given in the `Cargo.toml`
108     pub name: String,
109     /// Path containing the `Cargo.toml`
110     pub manifest: AbsPathBuf,
111     /// Targets provided by the crate (lib, bin, example, test, ...)
112     pub targets: Vec<Target>,
113     /// Is this package a member of the current workspace
114     pub is_member: bool,
115     /// List of packages this package depends on
116     pub dependencies: Vec<PackageDependency>,
117     /// Rust edition for this package
118     pub edition: Edition,
119     /// Features provided by the crate, mapped to the features required by that feature.
120     pub features: FxHashMap<String, Vec<String>>,
121     /// List of features enabled on this package
122     pub active_features: Vec<String>,
123     // String representation of package id
124     pub id: String,
125     // The contents of [package.metadata.rust-analyzer]
126     pub metadata: RustAnalyzerPackageMetaData,
127 }
128
129 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
130 pub struct RustAnalyzerPackageMetaData {
131     pub rustc_private: bool,
132 }
133
134 #[derive(Debug, Clone, Eq, PartialEq)]
135 pub struct PackageDependency {
136     pub pkg: Package,
137     pub name: String,
138     pub kind: DepKind,
139 }
140
141 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
142 pub enum DepKind {
143     /// Available to the library, binary, and dev targets in the package (but not the build script).
144     Normal,
145     /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
146     Dev,
147     /// Available only to the build script target.
148     Build,
149 }
150
151 impl DepKind {
152     fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
153         let mut dep_kinds = Vec::new();
154         if list.is_empty() {
155             dep_kinds.push(Self::Normal);
156         }
157         for info in list {
158             let kind = match info.kind {
159                 cargo_metadata::DependencyKind::Normal => Self::Normal,
160                 cargo_metadata::DependencyKind::Development => Self::Dev,
161                 cargo_metadata::DependencyKind::Build => Self::Build,
162                 cargo_metadata::DependencyKind::Unknown => continue,
163             };
164             dep_kinds.push(kind);
165         }
166         dep_kinds.sort_unstable();
167         dep_kinds.dedup();
168         dep_kinds.into_iter()
169     }
170 }
171
172 /// Information associated with a package's target
173 #[derive(Debug, Clone, Eq, PartialEq)]
174 pub struct TargetData {
175     /// Package that provided this target
176     pub package: Package,
177     /// Name as given in the `Cargo.toml` or generated from the file name
178     pub name: String,
179     /// Path to the main source file of the target
180     pub root: AbsPathBuf,
181     /// Kind of target
182     pub kind: TargetKind,
183     /// Is this target a proc-macro
184     pub is_proc_macro: bool,
185 }
186
187 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
188 pub enum TargetKind {
189     Bin,
190     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
191     Lib,
192     Example,
193     Test,
194     Bench,
195     BuildScript,
196     Other,
197 }
198
199 impl TargetKind {
200     fn new(kinds: &[String]) -> TargetKind {
201         for kind in kinds {
202             return match kind.as_str() {
203                 "bin" => TargetKind::Bin,
204                 "test" => TargetKind::Test,
205                 "bench" => TargetKind::Bench,
206                 "example" => TargetKind::Example,
207                 "custom-build" => TargetKind::BuildScript,
208                 "proc-macro" => TargetKind::Lib,
209                 _ if kind.contains("lib") => TargetKind::Lib,
210                 _ => continue,
211             };
212         }
213         TargetKind::Other
214     }
215 }
216
217 impl PackageData {
218     pub fn root(&self) -> &AbsPath {
219         self.manifest.parent().unwrap()
220     }
221 }
222
223 #[derive(Deserialize, Default)]
224 // Deserialise helper for the cargo metadata
225 struct PackageMetadata {
226     #[serde(rename = "rust-analyzer")]
227     rust_analyzer: Option<RustAnalyzerPackageMetaData>,
228 }
229
230 impl CargoWorkspace {
231     pub fn from_cargo_metadata(
232         cargo_toml: &AbsPath,
233         config: &CargoConfig,
234         progress: &dyn Fn(String),
235     ) -> Result<CargoWorkspace> {
236         let mut meta = MetadataCommand::new();
237         meta.cargo_path(toolchain::cargo());
238         meta.manifest_path(cargo_toml.to_path_buf());
239         if config.all_features {
240             meta.features(CargoOpt::AllFeatures);
241         } else {
242             if config.no_default_features {
243                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
244                 // https://github.com/oli-obk/cargo_metadata/issues/79
245                 meta.features(CargoOpt::NoDefaultFeatures);
246             }
247             if !config.features.is_empty() {
248                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
249             }
250         }
251         if let Some(parent) = cargo_toml.parent() {
252             meta.current_dir(parent.to_path_buf());
253         }
254         let target = if let Some(target) = &config.target {
255             Some(target.clone())
256         } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
257             stdout
258         } else {
259             rustc_discover_host_triple(cargo_toml)
260         };
261         if let Some(target) = target {
262             meta.other_options(vec![String::from("--filter-platform"), target]);
263         }
264
265         // FIXME: Currently MetadataCommand is not based on parse_stream,
266         // So we just report it as a whole
267         progress("metadata".to_string());
268         let mut meta = meta.exec().with_context(|| {
269             let cwd: Option<AbsPathBuf> =
270                 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
271
272             let workdir = cargo_toml
273                 .parent()
274                 .map(|p| p.to_path_buf())
275                 .or(cwd)
276                 .map(|dir| dir.to_string_lossy().to_string())
277                 .unwrap_or_else(|| "<failed to get path>".into());
278
279             format!(
280                 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
281                 cargo_toml.display(),
282                 workdir
283             )
284         })?;
285
286         let mut pkg_by_id = FxHashMap::default();
287         let mut packages = Arena::default();
288         let mut targets = Arena::default();
289
290         let ws_members = &meta.workspace_members;
291
292         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
293         for meta_pkg in &meta.packages {
294             let cargo_metadata::Package {
295                 id, edition, name, manifest_path, version, metadata, ..
296             } = meta_pkg;
297             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
298             let is_member = ws_members.contains(id);
299             let edition = edition
300                 .parse::<Edition>()
301                 .with_context(|| format!("Failed to parse edition {}", edition))?;
302
303             let pkg = packages.alloc(PackageData {
304                 id: id.repr.clone(),
305                 name: name.clone(),
306                 version: version.to_string(),
307                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
308                 targets: Vec::new(),
309                 is_member,
310                 edition,
311                 dependencies: Vec::new(),
312                 features: meta_pkg.features.clone().into_iter().collect(),
313                 active_features: Vec::new(),
314                 metadata: meta.rust_analyzer.unwrap_or_default(),
315             });
316             let pkg_data = &mut packages[pkg];
317             pkg_by_id.insert(id, pkg);
318             for meta_tgt in &meta_pkg.targets {
319                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
320                 let tgt = targets.alloc(TargetData {
321                     package: pkg,
322                     name: meta_tgt.name.clone(),
323                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
324                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
325                     is_proc_macro,
326                 });
327                 pkg_data.targets.push(tgt);
328             }
329         }
330         let resolve = meta.resolve.expect("metadata executed with deps");
331         for mut node in resolve.nodes {
332             let source = match pkg_by_id.get(&node.id) {
333                 Some(&src) => src,
334                 // FIXME: replace this and a similar branch below with `.unwrap`, once
335                 // https://github.com/rust-lang/cargo/issues/7841
336                 // is fixed and hits stable (around 1.43-is probably?).
337                 None => {
338                     log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
339                     continue;
340                 }
341             };
342             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
343             for (dep_node, kind) in node
344                 .deps
345                 .iter()
346                 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
347             {
348                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
349                     Some(&pkg) => pkg,
350                     None => {
351                         log::error!(
352                             "Dep node id do not match in cargo metadata, ignoring {}",
353                             dep_node.pkg
354                         );
355                         continue;
356                     }
357                 };
358                 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
359                 packages[source].dependencies.push(dep);
360             }
361             packages[source].active_features.extend(node.features);
362         }
363
364         let workspace_root =
365             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
366         let build_data_config =
367             BuildDataConfig::new(cargo_toml.to_path_buf(), config.clone(), Arc::new(meta.packages));
368
369         Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
370     }
371
372     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
373         self.packages.iter().map(|(id, _pkg)| id)
374     }
375
376     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
377         self.packages()
378             .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
379             .next()
380             .copied()
381     }
382
383     pub fn workspace_root(&self) -> &AbsPath {
384         &self.workspace_root
385     }
386
387     pub fn package_flag(&self, package: &PackageData) -> String {
388         if self.is_unique(&*package.name) {
389             package.name.clone()
390         } else {
391             format!("{}:{}", package.name, package.version)
392         }
393     }
394
395     pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
396         &self.build_data_config
397     }
398
399     fn is_unique(&self, name: &str) -> bool {
400         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
401     }
402 }
403
404 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
405     let mut rustc = Command::new(toolchain::rustc());
406     rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
407     log::debug!("Discovering host platform by {:?}", rustc);
408     match utf8_stdout(rustc) {
409         Ok(stdout) => {
410             let field = "host: ";
411             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
412             if let Some(target) = target {
413                 Some(target.to_string())
414             } else {
415                 // If we fail to resolve the host platform, it's not the end of the world.
416                 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
417                 None
418             }
419         }
420         Err(e) => {
421             log::warn!("Failed to discover host platform: {}", e);
422             None
423         }
424     }
425 }
426
427 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
428     let mut cargo_config = Command::new(toolchain::cargo());
429     cargo_config
430         .current_dir(cargo_toml.parent().unwrap())
431         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
432         .env("RUSTC_BOOTSTRAP", "1");
433     // if successful we receive `build.target = "target-triple"`
434     log::debug!("Discovering cargo config target by {:?}", cargo_config);
435     match utf8_stdout(cargo_config) {
436         Ok(stdout) => stdout
437             .strip_prefix("build.target = \"")
438             .and_then(|stdout| stdout.strip_suffix('"'))
439             .map(ToOwned::to_owned),
440         Err(_) => None,
441     }
442 }