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