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