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