]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #7353
[rust.git] / crates / project_model / src / cargo_workspace.rs
1 //! FIXME: write short doc here
2
3 use std::{convert::TryInto, ops, process::Command};
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::{BuildData, BuildDataMap};
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 }
31
32 impl ops::Index<Package> for CargoWorkspace {
33     type Output = PackageData;
34     fn index(&self, index: Package) -> &PackageData {
35         &self.packages[index]
36     }
37 }
38
39 impl ops::Index<Target> for CargoWorkspace {
40     type Output = TargetData;
41     fn index(&self, index: Target) -> &TargetData {
42         &self.targets[index]
43     }
44 }
45
46 #[derive(Default, Clone, Debug, PartialEq, Eq)]
47 pub struct CargoConfig {
48     /// Do not activate the `default` feature.
49     pub no_default_features: bool,
50
51     /// Activate all available features
52     pub all_features: bool,
53
54     /// List of features to activate.
55     /// This will be ignored if `cargo_all_features` is true.
56     pub features: Vec<String>,
57
58     /// Runs cargo check on launch to figure out the correct values of OUT_DIR
59     pub load_out_dirs_from_check: bool,
60
61     /// rustc target
62     pub target: Option<String>,
63
64     /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
65     /// when debugging isolated issues.
66     pub no_sysroot: bool,
67
68     /// rustc private crate source
69     pub rustc_source: Option<AbsPathBuf>,
70 }
71
72 pub type Package = Idx<PackageData>;
73
74 pub type Target = Idx<TargetData>;
75
76 /// Information associated with a cargo crate
77 #[derive(Debug, Clone, Eq, PartialEq)]
78 pub struct PackageData {
79     /// Version given in the `Cargo.toml`
80     pub version: String,
81     /// Name as given in the `Cargo.toml`
82     pub name: String,
83     /// Path containing the `Cargo.toml`
84     pub manifest: AbsPathBuf,
85     /// Targets provided by the crate (lib, bin, example, test, ...)
86     pub targets: Vec<Target>,
87     /// Is this package a member of the current workspace
88     pub is_member: bool,
89     /// List of packages this package depends on
90     pub dependencies: Vec<PackageDependency>,
91     /// Rust edition for this package
92     pub edition: Edition,
93     /// Features provided by the crate, mapped to the features required by that feature.
94     pub features: FxHashMap<String, Vec<String>>,
95     /// List of features enabled on this package
96     pub active_features: Vec<String>,
97     /// Build script related data for this package
98     pub build_data: BuildData,
99 }
100
101 #[derive(Debug, Clone, Eq, PartialEq)]
102 pub struct PackageDependency {
103     pub pkg: Package,
104     pub name: String,
105 }
106
107 /// Information associated with a package's target
108 #[derive(Debug, Clone, Eq, PartialEq)]
109 pub struct TargetData {
110     /// Package that provided this target
111     pub package: Package,
112     /// Name as given in the `Cargo.toml` or generated from the file name
113     pub name: String,
114     /// Path to the main source file of the target
115     pub root: AbsPathBuf,
116     /// Kind of target
117     pub kind: TargetKind,
118     /// Is this target a proc-macro
119     pub is_proc_macro: bool,
120 }
121
122 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
123 pub enum TargetKind {
124     Bin,
125     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
126     Lib,
127     Example,
128     Test,
129     Bench,
130     Other,
131 }
132
133 impl TargetKind {
134     fn new(kinds: &[String]) -> TargetKind {
135         for kind in kinds {
136             return match kind.as_str() {
137                 "bin" => TargetKind::Bin,
138                 "test" => TargetKind::Test,
139                 "bench" => TargetKind::Bench,
140                 "example" => TargetKind::Example,
141                 "proc-macro" => TargetKind::Lib,
142                 _ if kind.contains("lib") => TargetKind::Lib,
143                 _ => continue,
144             };
145         }
146         TargetKind::Other
147     }
148 }
149
150 impl PackageData {
151     pub fn root(&self) -> &AbsPath {
152         self.manifest.parent().unwrap()
153     }
154 }
155
156 impl CargoWorkspace {
157     pub fn from_cargo_metadata(
158         cargo_toml: &AbsPath,
159         config: &CargoConfig,
160         progress: &dyn Fn(String),
161     ) -> Result<CargoWorkspace> {
162         let mut meta = MetadataCommand::new();
163         meta.cargo_path(toolchain::cargo());
164         meta.manifest_path(cargo_toml.to_path_buf());
165         if config.all_features {
166             meta.features(CargoOpt::AllFeatures);
167         } else {
168             if config.no_default_features {
169                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
170                 // https://github.com/oli-obk/cargo_metadata/issues/79
171                 meta.features(CargoOpt::NoDefaultFeatures);
172             }
173             if !config.features.is_empty() {
174                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
175             }
176         }
177         if let Some(parent) = cargo_toml.parent() {
178             meta.current_dir(parent.to_path_buf());
179         }
180         let target = if let Some(target) = config.target.as_ref() {
181             Some(target.clone())
182         } else {
183             // cargo metadata defaults to giving information for _all_ targets.
184             // In the absence of a preference from the user, we use the host platform.
185             let mut rustc = Command::new(toolchain::rustc());
186             rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
187             log::debug!("Discovering host platform by {:?}", rustc);
188             match utf8_stdout(rustc) {
189                 Ok(stdout) => {
190                     let field = "host: ";
191                     let target = stdout.lines().find_map(|l| l.strip_prefix(field));
192                     if let Some(target) = target {
193                         Some(target.to_string())
194                     } else {
195                         // If we fail to resolve the host platform, it's not the end of the world.
196                         log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
197                         None
198                     }
199                 }
200                 Err(e) => {
201                     log::warn!("Failed to discover host platform: {}", e);
202                     None
203                 }
204             }
205         };
206         if let Some(target) = target {
207             meta.other_options(vec![String::from("--filter-platform"), target]);
208         }
209
210         // FIXME: Currently MetadataCommand is not based on parse_stream,
211         // So we just report it as a whole
212         progress("metadata".to_string());
213         let mut meta = meta.exec().with_context(|| {
214             let cwd: Option<AbsPathBuf> =
215                 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
216
217             let workdir = cargo_toml
218                 .parent()
219                 .map(|p| p.to_path_buf())
220                 .or(cwd)
221                 .map(|dir| dir.to_string_lossy().to_string())
222                 .unwrap_or_else(|| "<failed to get path>".into());
223
224             format!(
225                 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
226                 cargo_toml.display(),
227                 workdir
228             )
229         })?;
230
231         let resources = if config.load_out_dirs_from_check {
232             BuildDataMap::new(cargo_toml, config, &meta.packages, progress)?
233         } else {
234             BuildDataMap::with_cargo_env(&meta.packages)
235         };
236
237         let mut pkg_by_id = FxHashMap::default();
238         let mut packages = Arena::default();
239         let mut targets = Arena::default();
240
241         let ws_members = &meta.workspace_members;
242
243         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
244         for meta_pkg in meta.packages {
245             let id = meta_pkg.id.clone();
246             let build_data = resources.get(&id).cloned().unwrap_or_default();
247
248             let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
249                 meta_pkg;
250             let is_member = ws_members.contains(&id);
251             let edition = edition
252                 .parse::<Edition>()
253                 .with_context(|| format!("Failed to parse edition {}", edition))?;
254             let pkg = packages.alloc(PackageData {
255                 name,
256                 version: version.to_string(),
257                 manifest: AbsPathBuf::assert(manifest_path),
258                 targets: Vec::new(),
259                 is_member,
260                 edition,
261                 dependencies: Vec::new(),
262                 features: meta_pkg.features.into_iter().collect(),
263                 active_features: Vec::new(),
264                 build_data,
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,
273                     root: AbsPathBuf::assert(meta_tgt.src_path.clone()),
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 = AbsPathBuf::assert(meta.workspace_root);
311         Ok(CargoWorkspace { packages, targets, workspace_root: workspace_root })
312     }
313
314     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
315         self.packages.iter().map(|(id, _pkg)| id)
316     }
317
318     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
319         self.packages()
320             .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
321             .next()
322             .copied()
323     }
324
325     pub fn workspace_root(&self) -> &AbsPath {
326         &self.workspace_root
327     }
328
329     pub fn package_flag(&self, package: &PackageData) -> String {
330         if self.is_unique(&*package.name) {
331             package.name.clone()
332         } else {
333             format!("{}:{}", package.name, package.version)
334         }
335     }
336
337     fn is_unique(&self, name: &str) -> bool {
338         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
339     }
340 }