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