]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #10859
[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     /// Path containing the `Cargo.toml`
134     pub manifest: ManifestPath,
135     /// Targets provided by the crate (lib, bin, example, test, ...)
136     pub targets: Vec<Target>,
137     /// Does this package come from the local filesystem (and is editable)?
138     pub is_local: bool,
139     // Whether this package is a member of the workspace
140     pub is_member: bool,
141     /// List of packages this package depends on
142     pub dependencies: Vec<PackageDependency>,
143     /// Rust edition for this package
144     pub edition: Edition,
145     /// Features provided by the crate, mapped to the features required by that feature.
146     pub features: FxHashMap<String, Vec<String>>,
147     /// List of features enabled on this package
148     pub active_features: Vec<String>,
149     // String representation of package id
150     pub id: String,
151     // The contents of [package.metadata.rust-analyzer]
152     pub metadata: RustAnalyzerPackageMetaData,
153 }
154
155 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
156 pub struct RustAnalyzerPackageMetaData {
157     pub rustc_private: bool,
158 }
159
160 #[derive(Debug, Clone, Eq, PartialEq)]
161 pub struct PackageDependency {
162     pub pkg: Package,
163     pub name: String,
164     pub kind: DepKind,
165 }
166
167 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
168 pub enum DepKind {
169     /// Available to the library, binary, and dev targets in the package (but not the build script).
170     Normal,
171     /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
172     Dev,
173     /// Available only to the build script target.
174     Build,
175 }
176
177 impl DepKind {
178     fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
179         let mut dep_kinds = Vec::new();
180         if list.is_empty() {
181             dep_kinds.push(Self::Normal);
182         }
183         for info in list {
184             let kind = match info.kind {
185                 cargo_metadata::DependencyKind::Normal => Self::Normal,
186                 cargo_metadata::DependencyKind::Development => Self::Dev,
187                 cargo_metadata::DependencyKind::Build => Self::Build,
188                 cargo_metadata::DependencyKind::Unknown => continue,
189             };
190             dep_kinds.push(kind);
191         }
192         dep_kinds.sort_unstable();
193         dep_kinds.dedup();
194         dep_kinds.into_iter()
195     }
196 }
197
198 /// Information associated with a package's target
199 #[derive(Debug, Clone, Eq, PartialEq)]
200 pub struct TargetData {
201     /// Package that provided this target
202     pub package: Package,
203     /// Name as given in the `Cargo.toml` or generated from the file name
204     pub name: String,
205     /// Path to the main source file of the target
206     pub root: AbsPathBuf,
207     /// Kind of target
208     pub kind: TargetKind,
209     /// Is this target a proc-macro
210     pub is_proc_macro: bool,
211 }
212
213 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
214 pub enum TargetKind {
215     Bin,
216     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
217     Lib,
218     Example,
219     Test,
220     Bench,
221     BuildScript,
222     Other,
223 }
224
225 impl TargetKind {
226     fn new(kinds: &[String]) -> TargetKind {
227         for kind in kinds {
228             return match kind.as_str() {
229                 "bin" => TargetKind::Bin,
230                 "test" => TargetKind::Test,
231                 "bench" => TargetKind::Bench,
232                 "example" => TargetKind::Example,
233                 "custom-build" => TargetKind::BuildScript,
234                 "proc-macro" => TargetKind::Lib,
235                 _ if kind.contains("lib") => TargetKind::Lib,
236                 _ => continue,
237             };
238         }
239         TargetKind::Other
240     }
241 }
242
243 #[derive(Deserialize, Default)]
244 // Deserialise helper for the cargo metadata
245 struct PackageMetadata {
246     #[serde(rename = "rust-analyzer")]
247     rust_analyzer: Option<RustAnalyzerPackageMetaData>,
248 }
249
250 impl CargoWorkspace {
251     pub fn fetch_metadata(
252         cargo_toml: &ManifestPath,
253         current_dir: &AbsPath,
254         config: &CargoConfig,
255         progress: &dyn Fn(String),
256     ) -> Result<cargo_metadata::Metadata> {
257         let target = config
258             .target
259             .clone()
260             .or_else(|| cargo_config_build_target(cargo_toml))
261             .or_else(|| rustc_discover_host_triple(cargo_toml));
262
263         let mut meta = MetadataCommand::new();
264         meta.cargo_path(toolchain::cargo());
265         meta.manifest_path(cargo_toml.to_path_buf());
266         if config.all_features {
267             meta.features(CargoOpt::AllFeatures);
268         } else {
269             if config.no_default_features {
270                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
271                 // https://github.com/oli-obk/cargo_metadata/issues/79
272                 meta.features(CargoOpt::NoDefaultFeatures);
273             }
274             if !config.features.is_empty() {
275                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
276             }
277         }
278         meta.current_dir(current_dir.as_os_str());
279
280         if let Some(target) = target {
281             meta.other_options(vec![String::from("--filter-platform"), target]);
282         }
283
284         // FIXME: Fetching metadata is a slow process, as it might require
285         // calling crates.io. We should be reporting progress here, but it's
286         // unclear whether cargo itself supports it.
287         progress("metadata".to_string());
288
289         let meta =
290             meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?;
291
292         Ok(meta)
293     }
294
295     pub fn new(mut meta: cargo_metadata::Metadata) -> 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 edition = edition.parse::<Edition>().unwrap_or_else(|err| {
309                 tracing::error!("Failed to parse edition {}", err);
310                 Edition::CURRENT
311             });
312             // We treat packages without source as "local" packages. That includes all members of
313             // the current workspace, as well as any path dependency outside the workspace.
314             let is_local = meta_pkg.source.is_none();
315             let is_member = ws_members.contains(id);
316
317             let pkg = packages.alloc(PackageData {
318                 id: id.repr.clone(),
319                 name: name.clone(),
320                 version: version.clone(),
321                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
322                 targets: Vec::new(),
323                 is_local,
324                 is_member,
325                 edition,
326                 dependencies: Vec::new(),
327                 features: meta_pkg.features.clone().into_iter().collect(),
328                 active_features: Vec::new(),
329                 metadata: meta.rust_analyzer.unwrap_or_default(),
330             });
331             let pkg_data = &mut packages[pkg];
332             pkg_by_id.insert(id, pkg);
333             for meta_tgt in &meta_pkg.targets {
334                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
335                 let tgt = targets.alloc(TargetData {
336                     package: pkg,
337                     name: meta_tgt.name.clone(),
338                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
339                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
340                     is_proc_macro,
341                 });
342                 pkg_data.targets.push(tgt);
343             }
344         }
345         let resolve = meta.resolve.expect("metadata executed with deps");
346         for mut node in resolve.nodes {
347             let source = match pkg_by_id.get(&node.id) {
348                 Some(&src) => src,
349                 // FIXME: replace this and a similar branch below with `.unwrap`, once
350                 // https://github.com/rust-lang/cargo/issues/7841
351                 // is fixed and hits stable (around 1.43-is probably?).
352                 None => {
353                     tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
354                     continue;
355                 }
356             };
357             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
358             for (dep_node, kind) in node
359                 .deps
360                 .iter()
361                 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
362             {
363                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
364                     Some(&pkg) => pkg,
365                     None => {
366                         tracing::error!(
367                             "Dep node id do not match in cargo metadata, ignoring {}",
368                             dep_node.pkg
369                         );
370                         continue;
371                     }
372                 };
373                 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
374                 packages[source].dependencies.push(dep);
375             }
376             packages[source].active_features.extend(node.features);
377         }
378
379         let workspace_root =
380             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
381
382         CargoWorkspace { packages, targets, workspace_root }
383     }
384
385     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
386         self.packages.iter().map(|(id, _pkg)| id)
387     }
388
389     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
390         self.packages()
391             .filter(|&pkg| self[pkg].is_member)
392             .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
393             .copied()
394     }
395
396     pub fn workspace_root(&self) -> &AbsPath {
397         &self.workspace_root
398     }
399
400     pub fn package_flag(&self, package: &PackageData) -> String {
401         if self.is_unique(&*package.name) {
402             package.name.clone()
403         } else {
404             format!("{}:{}", package.name, package.version)
405         }
406     }
407
408     pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
409         let mut found = false;
410         let parent_manifests = self
411             .packages()
412             .filter_map(|pkg| {
413                 if !found && &self[pkg].manifest == manifest_path {
414                     found = true
415                 }
416                 self[pkg].dependencies.iter().find_map(|dep| {
417                     if &self[dep.pkg].manifest == manifest_path {
418                         return Some(self[pkg].manifest.clone());
419                     }
420                     None
421                 })
422             })
423             .collect::<Vec<ManifestPath>>();
424
425         // some packages has this pkg as dep. return their manifests
426         if parent_manifests.len() > 0 {
427             return Some(parent_manifests);
428         }
429
430         // this pkg is inside this cargo workspace, fallback to workspace root
431         if found {
432             return Some(vec![
433                 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
434             ]);
435         }
436
437         // not in this workspace
438         None
439     }
440
441     fn is_unique(&self, name: &str) -> bool {
442         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
443     }
444 }
445
446 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
447     let mut rustc = Command::new(toolchain::rustc());
448     rustc.current_dir(cargo_toml.parent()).arg("-vV");
449     tracing::debug!("Discovering host platform by {:?}", rustc);
450     match utf8_stdout(rustc) {
451         Ok(stdout) => {
452             let field = "host: ";
453             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
454             if let Some(target) = target {
455                 Some(target.to_string())
456             } else {
457                 // If we fail to resolve the host platform, it's not the end of the world.
458                 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
459                 None
460             }
461         }
462         Err(e) => {
463             tracing::warn!("Failed to discover host platform: {}", e);
464             None
465         }
466     }
467 }
468
469 fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
470     let mut cargo_config = Command::new(toolchain::cargo());
471     cargo_config
472         .current_dir(cargo_toml.parent())
473         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
474         .env("RUSTC_BOOTSTRAP", "1");
475     // if successful we receive `build.target = "target-triple"`
476     tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
477     match utf8_stdout(cargo_config) {
478         Ok(stdout) => stdout
479             .strip_prefix("build.target = \"")
480             .and_then(|stdout| stdout.strip_suffix('"'))
481             .map(ToOwned::to_owned),
482         Err(_) => None,
483     }
484 }