]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #10871
[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 }
214
215 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
216 pub enum TargetKind {
217     Bin,
218     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
219     Lib,
220     Example,
221     Test,
222     Bench,
223     BuildScript,
224     Other,
225 }
226
227 impl TargetKind {
228     fn new(kinds: &[String]) -> TargetKind {
229         for kind in kinds {
230             return match kind.as_str() {
231                 "bin" => TargetKind::Bin,
232                 "test" => TargetKind::Test,
233                 "bench" => TargetKind::Bench,
234                 "example" => TargetKind::Example,
235                 "custom-build" => TargetKind::BuildScript,
236                 "proc-macro" => TargetKind::Lib,
237                 _ if kind.contains("lib") => TargetKind::Lib,
238                 _ => continue,
239             };
240         }
241         TargetKind::Other
242     }
243 }
244
245 #[derive(Deserialize, Default)]
246 // Deserialise helper for the cargo metadata
247 struct PackageMetadata {
248     #[serde(rename = "rust-analyzer")]
249     rust_analyzer: Option<RustAnalyzerPackageMetaData>,
250 }
251
252 impl CargoWorkspace {
253     pub fn fetch_metadata(
254         cargo_toml: &ManifestPath,
255         current_dir: &AbsPath,
256         config: &CargoConfig,
257         progress: &dyn Fn(String),
258     ) -> Result<cargo_metadata::Metadata> {
259         let target = config
260             .target
261             .clone()
262             .or_else(|| cargo_config_build_target(cargo_toml))
263             .or_else(|| rustc_discover_host_triple(cargo_toml));
264
265         let mut meta = MetadataCommand::new();
266         meta.cargo_path(toolchain::cargo());
267         meta.manifest_path(cargo_toml.to_path_buf());
268         if config.all_features {
269             meta.features(CargoOpt::AllFeatures);
270         } else {
271             if config.no_default_features {
272                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
273                 // https://github.com/oli-obk/cargo_metadata/issues/79
274                 meta.features(CargoOpt::NoDefaultFeatures);
275             }
276             if !config.features.is_empty() {
277                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
278             }
279         }
280         meta.current_dir(current_dir.as_os_str());
281
282         if let Some(target) = target {
283             meta.other_options(vec![String::from("--filter-platform"), target]);
284         }
285
286         // FIXME: Fetching metadata is a slow process, as it might require
287         // calling crates.io. We should be reporting progress here, but it's
288         // unclear whether cargo itself supports it.
289         progress("metadata".to_string());
290
291         let meta =
292             meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?;
293
294         Ok(meta)
295     }
296
297     pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
298         let mut pkg_by_id = FxHashMap::default();
299         let mut packages = Arena::default();
300         let mut targets = Arena::default();
301
302         let ws_members = &meta.workspace_members;
303
304         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
305         for meta_pkg in &meta.packages {
306             let cargo_metadata::Package {
307                 id,
308                 edition,
309                 name,
310                 manifest_path,
311                 version,
312                 metadata,
313                 repository,
314                 ..
315             } = meta_pkg;
316             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
317             let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
318                 tracing::error!("Failed to parse edition {}", err);
319                 Edition::CURRENT
320             });
321             // We treat packages without source as "local" packages. That includes all members of
322             // the current workspace, as well as any path dependency outside the workspace.
323             let is_local = meta_pkg.source.is_none();
324             let is_member = ws_members.contains(id);
325
326             let pkg = packages.alloc(PackageData {
327                 id: id.repr.clone(),
328                 name: name.clone(),
329                 version: version.clone(),
330                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
331                 targets: Vec::new(),
332                 is_local,
333                 is_member,
334                 edition,
335                 repository: repository.clone(),
336                 dependencies: Vec::new(),
337                 features: meta_pkg.features.clone().into_iter().collect(),
338                 active_features: Vec::new(),
339                 metadata: meta.rust_analyzer.unwrap_or_default(),
340             });
341             let pkg_data = &mut packages[pkg];
342             pkg_by_id.insert(id, pkg);
343             for meta_tgt in &meta_pkg.targets {
344                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
345                 let tgt = targets.alloc(TargetData {
346                     package: pkg,
347                     name: meta_tgt.name.clone(),
348                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
349                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
350                     is_proc_macro,
351                 });
352                 pkg_data.targets.push(tgt);
353             }
354         }
355         let resolve = meta.resolve.expect("metadata executed with deps");
356         for mut node in resolve.nodes {
357             let source = match pkg_by_id.get(&node.id) {
358                 Some(&src) => src,
359                 // FIXME: replace this and a similar branch below with `.unwrap`, once
360                 // https://github.com/rust-lang/cargo/issues/7841
361                 // is fixed and hits stable (around 1.43-is probably?).
362                 None => {
363                     tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
364                     continue;
365                 }
366             };
367             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
368             for (dep_node, kind) in node
369                 .deps
370                 .iter()
371                 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
372             {
373                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
374                     Some(&pkg) => pkg,
375                     None => {
376                         tracing::error!(
377                             "Dep node id do not match in cargo metadata, ignoring {}",
378                             dep_node.pkg
379                         );
380                         continue;
381                     }
382                 };
383                 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
384                 packages[source].dependencies.push(dep);
385             }
386             packages[source].active_features.extend(node.features);
387         }
388
389         let workspace_root =
390             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
391
392         CargoWorkspace { packages, targets, workspace_root }
393     }
394
395     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
396         self.packages.iter().map(|(id, _pkg)| id)
397     }
398
399     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
400         self.packages()
401             .filter(|&pkg| self[pkg].is_member)
402             .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
403             .copied()
404     }
405
406     pub fn workspace_root(&self) -> &AbsPath {
407         &self.workspace_root
408     }
409
410     pub fn package_flag(&self, package: &PackageData) -> String {
411         if self.is_unique(&*package.name) {
412             package.name.clone()
413         } else {
414             format!("{}:{}", package.name, package.version)
415         }
416     }
417
418     pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
419         let mut found = false;
420         let parent_manifests = self
421             .packages()
422             .filter_map(|pkg| {
423                 if !found && &self[pkg].manifest == manifest_path {
424                     found = true
425                 }
426                 self[pkg].dependencies.iter().find_map(|dep| {
427                     if &self[dep.pkg].manifest == manifest_path {
428                         return Some(self[pkg].manifest.clone());
429                     }
430                     None
431                 })
432             })
433             .collect::<Vec<ManifestPath>>();
434
435         // some packages has this pkg as dep. return their manifests
436         if parent_manifests.len() > 0 {
437             return Some(parent_manifests);
438         }
439
440         // this pkg is inside this cargo workspace, fallback to workspace root
441         if found {
442             return Some(vec![
443                 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
444             ]);
445         }
446
447         // not in this workspace
448         None
449     }
450
451     fn is_unique(&self, name: &str) -> bool {
452         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
453     }
454 }
455
456 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
457     let mut rustc = Command::new(toolchain::rustc());
458     rustc.current_dir(cargo_toml.parent()).arg("-vV");
459     tracing::debug!("Discovering host platform by {:?}", rustc);
460     match utf8_stdout(rustc) {
461         Ok(stdout) => {
462             let field = "host: ";
463             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
464             if let Some(target) = target {
465                 Some(target.to_string())
466             } else {
467                 // If we fail to resolve the host platform, it's not the end of the world.
468                 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
469                 None
470             }
471         }
472         Err(e) => {
473             tracing::warn!("Failed to discover host platform: {}", e);
474             None
475         }
476     }
477 }
478
479 fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
480     let mut cargo_config = Command::new(toolchain::cargo());
481     cargo_config
482         .current_dir(cargo_toml.parent())
483         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
484         .env("RUSTC_BOOTSTRAP", "1");
485     // if successful we receive `build.target = "target-triple"`
486     tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
487     match utf8_stdout(cargo_config) {
488         Ok(stdout) => stdout
489             .strip_prefix("build.target = \"")
490             .and_then(|stdout| stdout.strip_suffix('"'))
491             .map(ToOwned::to_owned),
492         Err(_) => None,
493     }
494 }