]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #9623
[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 fetch_metadata(
232         cargo_toml: &AbsPath,
233         config: &CargoConfig,
234         progress: &dyn Fn(String),
235     ) -> Result<cargo_metadata::Metadata> {
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: Fetching metadata is a slow process, as it might require
266         // calling crates.io. We should be reporting progress here, but it's
267         // unclear whether cargo itself supports it.
268         progress("metadata".to_string());
269
270         let meta = meta.exec().with_context(|| {
271             let cwd: Option<AbsPathBuf> =
272                 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
273
274             let workdir = cargo_toml
275                 .parent()
276                 .map(|p| p.to_path_buf())
277                 .or(cwd)
278                 .map(|dir| format!(" in `{}`", dir.display()))
279                 .unwrap_or_default();
280
281             format!(
282                 "Failed to run `cargo metadata --manifest-path {}`{}",
283                 cargo_toml.display(),
284                 workdir
285             )
286         })?;
287
288         Ok(meta)
289     }
290
291     pub fn new(
292         cargo_toml: &AbsPath,
293         config: &CargoConfig,
294         mut meta: cargo_metadata::Metadata,
295     ) -> CargoWorkspace {
296         let mut pkg_by_id = FxHashMap::default();
297         let mut packages = Arena::default();
298         let mut targets = Arena::default();
299
300         let ws_members = &meta.workspace_members;
301
302         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
303         for meta_pkg in &meta.packages {
304             let cargo_metadata::Package {
305                 id, edition, name, manifest_path, version, metadata, ..
306             } = meta_pkg;
307             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
308             let is_member = ws_members.contains(id);
309             let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
310                 log::error!("Failed to parse edition {}", err);
311                 Edition::CURRENT
312             });
313
314             let pkg = packages.alloc(PackageData {
315                 id: id.repr.clone(),
316                 name: name.clone(),
317                 version: version.to_string(),
318                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
319                 targets: Vec::new(),
320                 is_member,
321                 edition,
322                 dependencies: Vec::new(),
323                 features: meta_pkg.features.clone().into_iter().collect(),
324                 active_features: Vec::new(),
325                 metadata: meta.rust_analyzer.unwrap_or_default(),
326             });
327             let pkg_data = &mut packages[pkg];
328             pkg_by_id.insert(id, pkg);
329             for meta_tgt in &meta_pkg.targets {
330                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
331                 let tgt = targets.alloc(TargetData {
332                     package: pkg,
333                     name: meta_tgt.name.clone(),
334                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
335                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
336                     is_proc_macro,
337                 });
338                 pkg_data.targets.push(tgt);
339             }
340         }
341         let resolve = meta.resolve.expect("metadata executed with deps");
342         for mut node in resolve.nodes {
343             let source = match pkg_by_id.get(&node.id) {
344                 Some(&src) => src,
345                 // FIXME: replace this and a similar branch below with `.unwrap`, once
346                 // https://github.com/rust-lang/cargo/issues/7841
347                 // is fixed and hits stable (around 1.43-is probably?).
348                 None => {
349                     log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
350                     continue;
351                 }
352             };
353             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
354             for (dep_node, kind) in node
355                 .deps
356                 .iter()
357                 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
358             {
359                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
360                     Some(&pkg) => pkg,
361                     None => {
362                         log::error!(
363                             "Dep node id do not match in cargo metadata, ignoring {}",
364                             dep_node.pkg
365                         );
366                         continue;
367                     }
368                 };
369                 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
370                 packages[source].dependencies.push(dep);
371             }
372             packages[source].active_features.extend(node.features);
373         }
374
375         let workspace_root =
376             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
377         let build_data_config =
378             BuildDataConfig::new(cargo_toml.to_path_buf(), config.clone(), Arc::new(meta.packages));
379
380         CargoWorkspace { packages, targets, workspace_root, build_data_config }
381     }
382
383     pub fn from_cargo_metadata3(
384         cargo_toml: &AbsPath,
385         config: &CargoConfig,
386         progress: &dyn Fn(String),
387     ) -> Result<CargoWorkspace> {
388         let meta = CargoWorkspace::fetch_metadata(cargo_toml, config, progress)?;
389         Ok(CargoWorkspace::new(cargo_toml, config, meta))
390     }
391
392     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
393         self.packages.iter().map(|(id, _pkg)| id)
394     }
395
396     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
397         self.packages()
398             .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
399             .next()
400             .copied()
401     }
402
403     pub fn workspace_root(&self) -> &AbsPath {
404         &self.workspace_root
405     }
406
407     pub fn package_flag(&self, package: &PackageData) -> String {
408         if self.is_unique(&*package.name) {
409             package.name.clone()
410         } else {
411             format!("{}:{}", package.name, package.version)
412         }
413     }
414
415     pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
416         &self.build_data_config
417     }
418
419     fn is_unique(&self, name: &str) -> bool {
420         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
421     }
422 }
423
424 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
425     let mut rustc = Command::new(toolchain::rustc());
426     rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
427     log::debug!("Discovering host platform by {:?}", rustc);
428     match utf8_stdout(rustc) {
429         Ok(stdout) => {
430             let field = "host: ";
431             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
432             if let Some(target) = target {
433                 Some(target.to_string())
434             } else {
435                 // If we fail to resolve the host platform, it's not the end of the world.
436                 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
437                 None
438             }
439         }
440         Err(e) => {
441             log::warn!("Failed to discover host platform: {}", e);
442             None
443         }
444     }
445 }
446
447 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
448     let mut cargo_config = Command::new(toolchain::cargo());
449     cargo_config
450         .current_dir(cargo_toml.parent().unwrap())
451         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
452         .env("RUSTC_BOOTSTRAP", "1");
453     // if successful we receive `build.target = "target-triple"`
454     log::debug!("Discovering cargo config target by {:?}", cargo_config);
455     match utf8_stdout(cargo_config) {
456         Ok(stdout) => stdout
457             .strip_prefix("build.target = \"")
458             .and_then(|stdout| stdout.strip_suffix('"'))
459             .map(ToOwned::to_owned),
460         Err(_) => None,
461     }
462 }