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