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