]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #11481
[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::{ops, process::Command};
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::{utf8_stdout, ManifestPath};
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 }
35
36 impl ops::Index<Package> for CargoWorkspace {
37     type Output = PackageData;
38     fn index(&self, index: Package) -> &PackageData {
39         &self.packages[index]
40     }
41 }
42
43 impl ops::Index<Target> for CargoWorkspace {
44     type Output = TargetData;
45     fn index(&self, index: Target) -> &TargetData {
46         &self.targets[index]
47     }
48 }
49
50 /// Describes how to set the rustc source directory.
51 #[derive(Clone, Debug, PartialEq, Eq)]
52 pub enum RustcSource {
53     /// Explicit path for the rustc source directory.
54     Path(AbsPathBuf),
55     /// Try to automatically detect where the rustc source directory is.
56     Discover,
57 }
58
59 /// Crates to disable `#[cfg(test)]` on.
60 #[derive(Clone, Debug, PartialEq, Eq)]
61 pub enum UnsetTestCrates {
62     None,
63     Only(Vec<String>),
64     All,
65 }
66
67 impl Default for UnsetTestCrates {
68     fn default() -> Self {
69         Self::None
70     }
71 }
72
73 #[derive(Default, Clone, Debug, PartialEq, Eq)]
74 pub struct CargoConfig {
75     /// Do not activate the `default` feature.
76     pub no_default_features: bool,
77
78     /// Activate all available features
79     pub all_features: bool,
80
81     /// List of features to activate.
82     /// This will be ignored if `cargo_all_features` is true.
83     pub features: Vec<String>,
84
85     /// rustc target
86     pub target: Option<String>,
87
88     /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
89     /// when debugging isolated issues.
90     pub no_sysroot: bool,
91
92     /// rustc private crate source
93     pub rustc_source: Option<RustcSource>,
94
95     /// crates to disable `#[cfg(test)]` on
96     pub unset_test_crates: UnsetTestCrates,
97
98     pub wrap_rustc_in_build_scripts: bool,
99 }
100
101 impl CargoConfig {
102     pub fn cfg_overrides(&self) -> CfgOverrides {
103         match &self.unset_test_crates {
104             UnsetTestCrates::None => CfgOverrides::Selective(iter::empty().collect()),
105             UnsetTestCrates::Only(unset_test_crates) => CfgOverrides::Selective(
106                 unset_test_crates
107                     .iter()
108                     .cloned()
109                     .zip(iter::repeat_with(|| {
110                         cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())])
111                             .unwrap()
112                     }))
113                     .collect(),
114             ),
115             UnsetTestCrates::All => CfgOverrides::Wildcard(
116                 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap(),
117             ),
118         }
119     }
120 }
121
122 pub type Package = Idx<PackageData>;
123
124 pub type Target = Idx<TargetData>;
125
126 /// Information associated with a cargo crate
127 #[derive(Debug, Clone, Eq, PartialEq)]
128 pub struct PackageData {
129     /// Version given in the `Cargo.toml`
130     pub version: semver::Version,
131     /// Name as given in the `Cargo.toml`
132     pub name: String,
133     /// Repository as given in the `Cargo.toml`
134     pub repository: Option<String>,
135     /// Path containing the `Cargo.toml`
136     pub manifest: ManifestPath,
137     /// Targets provided by the crate (lib, bin, example, test, ...)
138     pub targets: Vec<Target>,
139     /// Does this package come from the local filesystem (and is editable)?
140     pub is_local: bool,
141     // Whether this package is a member of the workspace
142     pub is_member: bool,
143     /// List of packages this package depends on
144     pub dependencies: Vec<PackageDependency>,
145     /// Rust edition for this package
146     pub edition: Edition,
147     /// Features provided by the crate, mapped to the features required by that feature.
148     pub features: FxHashMap<String, Vec<String>>,
149     /// List of features enabled on this package
150     pub active_features: Vec<String>,
151     /// String representation of package id
152     pub id: String,
153     /// The contents of [package.metadata.rust-analyzer]
154     pub metadata: RustAnalyzerPackageMetaData,
155 }
156
157 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
158 pub struct RustAnalyzerPackageMetaData {
159     pub rustc_private: bool,
160 }
161
162 #[derive(Debug, Clone, Eq, PartialEq)]
163 pub struct PackageDependency {
164     pub pkg: Package,
165     pub name: String,
166     pub kind: DepKind,
167 }
168
169 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
170 pub enum DepKind {
171     /// Available to the library, binary, and dev targets in the package (but not the build script).
172     Normal,
173     /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
174     Dev,
175     /// Available only to the build script target.
176     Build,
177 }
178
179 impl DepKind {
180     fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
181         let mut dep_kinds = Vec::new();
182         if list.is_empty() {
183             dep_kinds.push(Self::Normal);
184         }
185         for info in list {
186             let kind = match info.kind {
187                 cargo_metadata::DependencyKind::Normal => Self::Normal,
188                 cargo_metadata::DependencyKind::Development => Self::Dev,
189                 cargo_metadata::DependencyKind::Build => Self::Build,
190                 cargo_metadata::DependencyKind::Unknown => continue,
191             };
192             dep_kinds.push(kind);
193         }
194         dep_kinds.sort_unstable();
195         dep_kinds.dedup();
196         dep_kinds.into_iter()
197     }
198 }
199
200 /// Information associated with a package's target
201 #[derive(Debug, Clone, Eq, PartialEq)]
202 pub struct TargetData {
203     /// Package that provided this target
204     pub package: Package,
205     /// Name as given in the `Cargo.toml` or generated from the file name
206     pub name: String,
207     /// Path to the main source file of the target
208     pub root: AbsPathBuf,
209     /// Kind of target
210     pub kind: TargetKind,
211     /// Is this target a proc-macro
212     pub is_proc_macro: bool,
213     /// Required features of the target without which it won't build
214     pub required_features: Vec<String>,
215 }
216
217 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
218 pub enum TargetKind {
219     Bin,
220     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
221     Lib,
222     Example,
223     Test,
224     Bench,
225     BuildScript,
226     Other,
227 }
228
229 impl TargetKind {
230     fn new(kinds: &[String]) -> TargetKind {
231         for kind in kinds {
232             return match kind.as_str() {
233                 "bin" => TargetKind::Bin,
234                 "test" => TargetKind::Test,
235                 "bench" => TargetKind::Bench,
236                 "example" => TargetKind::Example,
237                 "custom-build" => TargetKind::BuildScript,
238                 "proc-macro" => TargetKind::Lib,
239                 _ if kind.contains("lib") => TargetKind::Lib,
240                 _ => continue,
241             };
242         }
243         TargetKind::Other
244     }
245 }
246
247 #[derive(Deserialize, Default)]
248 // Deserialise helper for the cargo metadata
249 struct PackageMetadata {
250     #[serde(rename = "rust-analyzer")]
251     rust_analyzer: Option<RustAnalyzerPackageMetaData>,
252 }
253
254 impl CargoWorkspace {
255     pub fn fetch_metadata(
256         cargo_toml: &ManifestPath,
257         current_dir: &AbsPath,
258         config: &CargoConfig,
259         progress: &dyn Fn(String),
260     ) -> Result<cargo_metadata::Metadata> {
261         let target = config
262             .target
263             .clone()
264             .or_else(|| cargo_config_build_target(cargo_toml))
265             .or_else(|| rustc_discover_host_triple(cargo_toml));
266
267         let mut meta = MetadataCommand::new();
268         meta.cargo_path(toolchain::cargo());
269         meta.manifest_path(cargo_toml.to_path_buf());
270         if config.all_features {
271             meta.features(CargoOpt::AllFeatures);
272         } else {
273             if config.no_default_features {
274                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
275                 // https://github.com/oli-obk/cargo_metadata/issues/79
276                 meta.features(CargoOpt::NoDefaultFeatures);
277             }
278             if !config.features.is_empty() {
279                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
280             }
281         }
282         meta.current_dir(current_dir.as_os_str());
283
284         if let Some(target) = target {
285             meta.other_options(vec![String::from("--filter-platform"), target]);
286         }
287
288         // FIXME: Fetching metadata is a slow process, as it might require
289         // calling crates.io. We should be reporting progress here, but it's
290         // unclear whether cargo itself supports it.
291         progress("metadata".to_string());
292
293         let meta =
294             meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?;
295
296         Ok(meta)
297     }
298
299     pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
300         let mut pkg_by_id = FxHashMap::default();
301         let mut packages = Arena::default();
302         let mut targets = Arena::default();
303
304         let ws_members = &meta.workspace_members;
305
306         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
307         for meta_pkg in &meta.packages {
308             let cargo_metadata::Package {
309                 id,
310                 edition,
311                 name,
312                 manifest_path,
313                 version,
314                 metadata,
315                 repository,
316                 ..
317             } = meta_pkg;
318             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
319             let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
320                 tracing::error!("Failed to parse edition {}", err);
321                 Edition::CURRENT
322             });
323             // We treat packages without source as "local" packages. That includes all members of
324             // the current workspace, as well as any path dependency outside the workspace.
325             let is_local = meta_pkg.source.is_none();
326             let is_member = ws_members.contains(id);
327
328             let pkg = packages.alloc(PackageData {
329                 id: id.repr.clone(),
330                 name: name.clone(),
331                 version: version.clone(),
332                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
333                 targets: Vec::new(),
334                 is_local,
335                 is_member,
336                 edition,
337                 repository: repository.clone(),
338                 dependencies: Vec::new(),
339                 features: meta_pkg.features.clone().into_iter().collect(),
340                 active_features: Vec::new(),
341                 metadata: meta.rust_analyzer.unwrap_or_default(),
342             });
343             let pkg_data = &mut packages[pkg];
344             pkg_by_id.insert(id, pkg);
345             for meta_tgt in &meta_pkg.targets {
346                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
347                 let tgt = targets.alloc(TargetData {
348                     package: pkg,
349                     name: meta_tgt.name.clone(),
350                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
351                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
352                     is_proc_macro,
353                     required_features: meta_tgt.required_features.clone(),
354                 });
355                 pkg_data.targets.push(tgt);
356             }
357         }
358         let resolve = meta.resolve.expect("metadata executed with deps");
359         for mut node in resolve.nodes {
360             let source = match pkg_by_id.get(&node.id) {
361                 Some(&src) => src,
362                 // FIXME: replace this and a similar branch below with `.unwrap`, once
363                 // https://github.com/rust-lang/cargo/issues/7841
364                 // is fixed and hits stable (around 1.43-is probably?).
365                 None => {
366                     tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
367                     continue;
368                 }
369             };
370             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
371             for (dep_node, kind) in node
372                 .deps
373                 .iter()
374                 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
375             {
376                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
377                     Some(&pkg) => pkg,
378                     None => {
379                         tracing::error!(
380                             "Dep node id do not match in cargo metadata, ignoring {}",
381                             dep_node.pkg
382                         );
383                         continue;
384                     }
385                 };
386                 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
387                 packages[source].dependencies.push(dep);
388             }
389             packages[source].active_features.extend(node.features);
390         }
391
392         let workspace_root =
393             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
394
395         CargoWorkspace { packages, targets, workspace_root }
396     }
397
398     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
399         self.packages.iter().map(|(id, _pkg)| id)
400     }
401
402     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
403         self.packages()
404             .filter(|&pkg| self[pkg].is_member)
405             .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
406             .copied()
407     }
408
409     pub fn workspace_root(&self) -> &AbsPath {
410         &self.workspace_root
411     }
412
413     pub fn package_flag(&self, package: &PackageData) -> String {
414         if self.is_unique(&*package.name) {
415             package.name.clone()
416         } else {
417             format!("{}:{}", package.name, package.version)
418         }
419     }
420
421     pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
422         let mut found = false;
423         let parent_manifests = self
424             .packages()
425             .filter_map(|pkg| {
426                 if !found && &self[pkg].manifest == manifest_path {
427                     found = true
428                 }
429                 self[pkg].dependencies.iter().find_map(|dep| {
430                     if &self[dep.pkg].manifest == manifest_path {
431                         return Some(self[pkg].manifest.clone());
432                     }
433                     None
434                 })
435             })
436             .collect::<Vec<ManifestPath>>();
437
438         // some packages has this pkg as dep. return their manifests
439         if parent_manifests.len() > 0 {
440             return Some(parent_manifests);
441         }
442
443         // this pkg is inside this cargo workspace, fallback to workspace root
444         if found {
445             return Some(vec![
446                 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
447             ]);
448         }
449
450         // not in this workspace
451         None
452     }
453
454     fn is_unique(&self, name: &str) -> bool {
455         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
456     }
457 }
458
459 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
460     let mut rustc = Command::new(toolchain::rustc());
461     rustc.current_dir(cargo_toml.parent()).arg("-vV");
462     tracing::debug!("Discovering host platform by {:?}", rustc);
463     match utf8_stdout(rustc) {
464         Ok(stdout) => {
465             let field = "host: ";
466             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
467             if let Some(target) = target {
468                 Some(target.to_string())
469             } else {
470                 // If we fail to resolve the host platform, it's not the end of the world.
471                 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
472                 None
473             }
474         }
475         Err(e) => {
476             tracing::warn!("Failed to discover host platform: {}", e);
477             None
478         }
479     }
480 }
481
482 fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
483     let mut cargo_config = Command::new(toolchain::cargo());
484     cargo_config
485         .current_dir(cargo_toml.parent())
486         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
487         .env("RUSTC_BOOTSTRAP", "1");
488     // if successful we receive `build.target = "target-triple"`
489     tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
490     match utf8_stdout(cargo_config) {
491         Ok(stdout) => stdout
492             .strip_prefix("build.target = \"")
493             .and_then(|stdout| stdout.strip_suffix('"'))
494             .map(ToOwned::to_owned),
495         Err(_) => None,
496     }
497 }