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