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