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