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