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