]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
clippy::redundant_clone fixes
[rust.git] / crates / project_model / src / cargo_workspace.rs
1 //! See [`CargoWorkspace`].
2
3 use std::path::PathBuf;
4 use std::{convert::TryInto, ops, process::Command, sync::Arc};
5
6 use anyhow::{Context, Result};
7 use base_db::Edition;
8 use cargo_metadata::{CargoOpt, MetadataCommand};
9 use la_arena::{Arena, Idx};
10 use paths::{AbsPath, AbsPathBuf};
11 use rustc_hash::FxHashMap;
12 use serde::Deserialize;
13 use serde_json::from_value;
14
15 use crate::{build_data::BuildDataConfig, utf8_stdout};
16
17 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
18 /// workspace. It pretty closely mirrors `cargo metadata` output.
19 ///
20 /// Note that internally, rust analyzer uses a different structure:
21 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
22 /// while this knows about `Packages` & `Targets`: purely cargo-related
23 /// concepts.
24 ///
25 /// We use absolute paths here, `cargo metadata` guarantees to always produce
26 /// abs paths.
27 #[derive(Debug, Clone, Eq, PartialEq)]
28 pub struct CargoWorkspace {
29     packages: Arena<PackageData>,
30     targets: Arena<TargetData>,
31     workspace_root: AbsPathBuf,
32     build_data_config: BuildDataConfig,
33 }
34
35 impl ops::Index<Package> for CargoWorkspace {
36     type Output = PackageData;
37     fn index(&self, index: Package) -> &PackageData {
38         &self.packages[index]
39     }
40 }
41
42 impl ops::Index<Target> for CargoWorkspace {
43     type Output = TargetData;
44     fn index(&self, index: Target) -> &TargetData {
45         &self.targets[index]
46     }
47 }
48
49 /// Describes how to set the rustc source directory.
50 #[derive(Clone, Debug, PartialEq, Eq)]
51 pub enum RustcSource {
52     /// Explicit path for the rustc source directory.
53     Path(AbsPathBuf),
54     /// Try to automatically detect where the rustc source directory is.
55     Discover,
56 }
57
58 #[derive(Default, Clone, Debug, PartialEq, Eq)]
59 pub struct CargoConfig {
60     /// Do not activate the `default` feature.
61     pub no_default_features: bool,
62
63     /// Activate all available features
64     pub all_features: bool,
65
66     /// List of features to activate.
67     /// This will be ignored if `cargo_all_features` is true.
68     pub features: Vec<String>,
69
70     /// rustc target
71     pub target: Option<String>,
72
73     /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
74     /// when debugging isolated issues.
75     pub no_sysroot: bool,
76
77     /// rustc private crate source
78     pub rustc_source: Option<RustcSource>,
79 }
80
81 pub type Package = Idx<PackageData>;
82
83 pub type Target = Idx<TargetData>;
84
85 /// Information associated with a cargo crate
86 #[derive(Debug, Clone, Eq, PartialEq)]
87 pub struct PackageData {
88     /// Version given in the `Cargo.toml`
89     pub version: String,
90     /// Name as given in the `Cargo.toml`
91     pub name: String,
92     /// Path containing the `Cargo.toml`
93     pub manifest: AbsPathBuf,
94     /// Targets provided by the crate (lib, bin, example, test, ...)
95     pub targets: Vec<Target>,
96     /// Is this package a member of the current workspace
97     pub is_member: bool,
98     /// List of packages this package depends on
99     pub dependencies: Vec<PackageDependency>,
100     /// Rust edition for this package
101     pub edition: Edition,
102     /// Features provided by the crate, mapped to the features required by that feature.
103     pub features: FxHashMap<String, Vec<String>>,
104     /// List of features enabled on this package
105     pub active_features: Vec<String>,
106     // String representation of package id
107     pub id: String,
108     // The contents of [package.metadata.rust-analyzer]
109     pub metadata: RustAnalyzerPackageMetaData,
110 }
111
112 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
113 pub struct RustAnalyzerPackageMetaData {
114     pub rustc_private: bool,
115 }
116
117 #[derive(Debug, Clone, Eq, PartialEq)]
118 pub struct PackageDependency {
119     pub pkg: Package,
120     pub name: String,
121     pub kind: DepKind,
122 }
123
124 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
125 pub enum DepKind {
126     /// Available to the library, binary, and dev targets in the package (but not the build script).
127     Normal,
128     /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
129     Dev,
130     /// Available only to the build script target.
131     Build,
132 }
133
134 impl DepKind {
135     fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
136         let mut dep_kinds = Vec::new();
137         if list.is_empty() {
138             dep_kinds.push(Self::Normal);
139         }
140         for info in list {
141             let kind = match info.kind {
142                 cargo_metadata::DependencyKind::Normal => Self::Normal,
143                 cargo_metadata::DependencyKind::Development => Self::Dev,
144                 cargo_metadata::DependencyKind::Build => Self::Build,
145                 cargo_metadata::DependencyKind::Unknown => continue,
146             };
147             dep_kinds.push(kind);
148         }
149         dep_kinds.sort_unstable();
150         dep_kinds.dedup();
151         dep_kinds.into_iter()
152     }
153 }
154
155 /// Information associated with a package's target
156 #[derive(Debug, Clone, Eq, PartialEq)]
157 pub struct TargetData {
158     /// Package that provided this target
159     pub package: Package,
160     /// Name as given in the `Cargo.toml` or generated from the file name
161     pub name: String,
162     /// Path to the main source file of the target
163     pub root: AbsPathBuf,
164     /// Kind of target
165     pub kind: TargetKind,
166     /// Is this target a proc-macro
167     pub is_proc_macro: bool,
168 }
169
170 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
171 pub enum TargetKind {
172     Bin,
173     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
174     Lib,
175     Example,
176     Test,
177     Bench,
178     BuildScript,
179     Other,
180 }
181
182 impl TargetKind {
183     fn new(kinds: &[String]) -> TargetKind {
184         for kind in kinds {
185             return match kind.as_str() {
186                 "bin" => TargetKind::Bin,
187                 "test" => TargetKind::Test,
188                 "bench" => TargetKind::Bench,
189                 "example" => TargetKind::Example,
190                 "custom-build" => TargetKind::BuildScript,
191                 "proc-macro" => TargetKind::Lib,
192                 _ if kind.contains("lib") => TargetKind::Lib,
193                 _ => continue,
194             };
195         }
196         TargetKind::Other
197     }
198 }
199
200 impl PackageData {
201     pub fn root(&self) -> &AbsPath {
202         self.manifest.parent().unwrap()
203     }
204 }
205
206 #[derive(Deserialize, Default)]
207 // Deserialise helper for the cargo metadata
208 struct PackageMetadata {
209     #[serde(rename = "rust-analyzer")]
210     rust_analyzer: Option<RustAnalyzerPackageMetaData>,
211 }
212
213 impl CargoWorkspace {
214     pub fn from_cargo_metadata(
215         cargo_toml: &AbsPath,
216         config: &CargoConfig,
217         progress: &dyn Fn(String),
218     ) -> Result<CargoWorkspace> {
219         let mut meta = MetadataCommand::new();
220         meta.cargo_path(toolchain::cargo());
221         meta.manifest_path(cargo_toml.to_path_buf());
222         if config.all_features {
223             meta.features(CargoOpt::AllFeatures);
224         } else {
225             if config.no_default_features {
226                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
227                 // https://github.com/oli-obk/cargo_metadata/issues/79
228                 meta.features(CargoOpt::NoDefaultFeatures);
229             }
230             if !config.features.is_empty() {
231                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
232             }
233         }
234         if let Some(parent) = cargo_toml.parent() {
235             meta.current_dir(parent.to_path_buf());
236         }
237         let target = if let Some(target) = &config.target {
238             Some(target.clone())
239         } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
240             stdout
241         } else {
242             rustc_discover_host_triple(cargo_toml)
243         };
244         if let Some(target) = target {
245             meta.other_options(vec![String::from("--filter-platform"), target]);
246         }
247
248         // FIXME: Currently MetadataCommand is not based on parse_stream,
249         // So we just report it as a whole
250         progress("metadata".to_string());
251         let mut meta = meta.exec().with_context(|| {
252             let cwd: Option<AbsPathBuf> =
253                 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
254
255             let workdir = cargo_toml
256                 .parent()
257                 .map(|p| p.to_path_buf())
258                 .or(cwd)
259                 .map(|dir| dir.to_string_lossy().to_string())
260                 .unwrap_or_else(|| "<failed to get path>".into());
261
262             format!(
263                 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
264                 cargo_toml.display(),
265                 workdir
266             )
267         })?;
268
269         let mut pkg_by_id = FxHashMap::default();
270         let mut packages = Arena::default();
271         let mut targets = Arena::default();
272
273         let ws_members = &meta.workspace_members;
274
275         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
276         for meta_pkg in &meta.packages {
277             let cargo_metadata::Package {
278                 id, edition, name, manifest_path, version, metadata, ..
279             } = meta_pkg;
280             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
281             let is_member = ws_members.contains(&id);
282             let edition = edition
283                 .parse::<Edition>()
284                 .with_context(|| format!("Failed to parse edition {}", edition))?;
285
286             let pkg = packages.alloc(PackageData {
287                 id: id.repr.clone(),
288                 name: name.clone(),
289                 version: version.to_string(),
290                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
291                 targets: Vec::new(),
292                 is_member,
293                 edition,
294                 dependencies: Vec::new(),
295                 features: meta_pkg.features.clone().into_iter().collect(),
296                 active_features: Vec::new(),
297                 metadata: meta.rust_analyzer.unwrap_or_default(),
298             });
299             let pkg_data = &mut packages[pkg];
300             pkg_by_id.insert(id, pkg);
301             for meta_tgt in &meta_pkg.targets {
302                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
303                 let tgt = targets.alloc(TargetData {
304                     package: pkg,
305                     name: meta_tgt.name.clone(),
306                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
307                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
308                     is_proc_macro,
309                 });
310                 pkg_data.targets.push(tgt);
311             }
312         }
313         let resolve = meta.resolve.expect("metadata executed with deps");
314         for mut node in resolve.nodes {
315             let source = match pkg_by_id.get(&node.id) {
316                 Some(&src) => src,
317                 // FIXME: replace this and a similar branch below with `.unwrap`, once
318                 // https://github.com/rust-lang/cargo/issues/7841
319                 // is fixed and hits stable (around 1.43-is probably?).
320                 None => {
321                     log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
322                     continue;
323                 }
324             };
325             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
326             for (dep_node, kind) in node
327                 .deps
328                 .iter()
329                 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
330             {
331                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
332                     Some(&pkg) => pkg,
333                     None => {
334                         log::error!(
335                             "Dep node id do not match in cargo metadata, ignoring {}",
336                             dep_node.pkg
337                         );
338                         continue;
339                     }
340                 };
341                 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
342                 packages[source].dependencies.push(dep);
343             }
344             packages[source].active_features.extend(node.features);
345         }
346
347         let workspace_root =
348             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
349         let build_data_config =
350             BuildDataConfig::new(cargo_toml.to_path_buf(), config.clone(), Arc::new(meta.packages));
351
352         Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
353     }
354
355     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
356         self.packages.iter().map(|(id, _pkg)| id)
357     }
358
359     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
360         self.packages()
361             .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
362             .next()
363             .copied()
364     }
365
366     pub fn workspace_root(&self) -> &AbsPath {
367         &self.workspace_root
368     }
369
370     pub fn package_flag(&self, package: &PackageData) -> String {
371         if self.is_unique(&*package.name) {
372             package.name.clone()
373         } else {
374             format!("{}:{}", package.name, package.version)
375         }
376     }
377
378     pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
379         &self.build_data_config
380     }
381
382     fn is_unique(&self, name: &str) -> bool {
383         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
384     }
385 }
386
387 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
388     let mut rustc = Command::new(toolchain::rustc());
389     rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
390     log::debug!("Discovering host platform by {:?}", rustc);
391     match utf8_stdout(rustc) {
392         Ok(stdout) => {
393             let field = "host: ";
394             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
395             if let Some(target) = target {
396                 Some(target.to_string())
397             } else {
398                 // If we fail to resolve the host platform, it's not the end of the world.
399                 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
400                 None
401             }
402         }
403         Err(e) => {
404             log::warn!("Failed to discover host platform: {}", e);
405             None
406         }
407     }
408 }
409
410 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
411     let mut cargo_config = Command::new(toolchain::cargo());
412     cargo_config
413         .current_dir(cargo_toml.parent().unwrap())
414         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
415         .env("RUSTC_BOOTSTRAP", "1");
416     // if successful we receive `build.target = "target-triple"`
417     log::debug!("Discovering cargo config target by {:?}", cargo_config);
418     match utf8_stdout(cargo_config) {
419         Ok(stdout) => stdout
420             .strip_prefix("build.target = \"")
421             .and_then(|stdout| stdout.strip_suffix('"'))
422             .map(ToOwned::to_owned),
423         Err(_) => None,
424     }
425 }