]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/cargo_workspace.rs
Merge #8830
[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     pub kind: DepKind,
123 }
124
125 #[derive(Debug, Clone, Eq, PartialEq)]
126 pub enum DepKind {
127     /// Available to the library, binary, and dev targets in the package (but not the build script).
128     Normal,
129     /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
130     Dev,
131     /// Available only to the build script target.
132     Build,
133 }
134
135 impl DepKind {
136     fn new(list: &[cargo_metadata::DepKindInfo]) -> Self {
137         for info in list {
138             match info.kind {
139                 cargo_metadata::DependencyKind::Normal => return Self::Normal,
140                 cargo_metadata::DependencyKind::Development => return Self::Dev,
141                 cargo_metadata::DependencyKind::Build => return Self::Build,
142                 cargo_metadata::DependencyKind::Unknown => continue,
143             }
144         }
145
146         Self::Normal
147     }
148 }
149
150 /// Information associated with a package's target
151 #[derive(Debug, Clone, Eq, PartialEq)]
152 pub struct TargetData {
153     /// Package that provided this target
154     pub package: Package,
155     /// Name as given in the `Cargo.toml` or generated from the file name
156     pub name: String,
157     /// Path to the main source file of the target
158     pub root: AbsPathBuf,
159     /// Kind of target
160     pub kind: TargetKind,
161     /// Is this target a proc-macro
162     pub is_proc_macro: bool,
163 }
164
165 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
166 pub enum TargetKind {
167     Bin,
168     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
169     Lib,
170     Example,
171     Test,
172     Bench,
173     BuildScript,
174     Other,
175 }
176
177 impl TargetKind {
178     fn new(kinds: &[String]) -> TargetKind {
179         for kind in kinds {
180             return match kind.as_str() {
181                 "bin" => TargetKind::Bin,
182                 "test" => TargetKind::Test,
183                 "bench" => TargetKind::Bench,
184                 "example" => TargetKind::Example,
185                 "custom-build" => TargetKind::BuildScript,
186                 "proc-macro" => TargetKind::Lib,
187                 _ if kind.contains("lib") => TargetKind::Lib,
188                 _ => continue,
189             };
190         }
191         TargetKind::Other
192     }
193 }
194
195 impl PackageData {
196     pub fn root(&self) -> &AbsPath {
197         self.manifest.parent().unwrap()
198     }
199 }
200
201 #[derive(Deserialize, Default)]
202 // Deserialise helper for the cargo metadata
203 struct PackageMetadata {
204     #[serde(rename = "rust-analyzer")]
205     rust_analyzer: Option<RustAnalyzerPackageMetaData>,
206 }
207
208 impl CargoWorkspace {
209     pub fn from_cargo_metadata(
210         cargo_toml: &AbsPath,
211         config: &CargoConfig,
212         progress: &dyn Fn(String),
213     ) -> Result<CargoWorkspace> {
214         let mut meta = MetadataCommand::new();
215         meta.cargo_path(toolchain::cargo());
216         meta.manifest_path(cargo_toml.to_path_buf());
217         if config.all_features {
218             meta.features(CargoOpt::AllFeatures);
219         } else {
220             if config.no_default_features {
221                 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
222                 // https://github.com/oli-obk/cargo_metadata/issues/79
223                 meta.features(CargoOpt::NoDefaultFeatures);
224             }
225             if !config.features.is_empty() {
226                 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
227             }
228         }
229         if let Some(parent) = cargo_toml.parent() {
230             meta.current_dir(parent.to_path_buf());
231         }
232         let target = if let Some(target) = &config.target {
233             Some(target.clone())
234         } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
235             stdout
236         } else {
237             rustc_discover_host_triple(cargo_toml)
238         };
239         if let Some(target) = target {
240             meta.other_options(vec![String::from("--filter-platform"), target]);
241         }
242
243         // FIXME: Currently MetadataCommand is not based on parse_stream,
244         // So we just report it as a whole
245         progress("metadata".to_string());
246         let mut meta = meta.exec().with_context(|| {
247             let cwd: Option<AbsPathBuf> =
248                 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
249
250             let workdir = cargo_toml
251                 .parent()
252                 .map(|p| p.to_path_buf())
253                 .or(cwd)
254                 .map(|dir| dir.to_string_lossy().to_string())
255                 .unwrap_or_else(|| "<failed to get path>".into());
256
257             format!(
258                 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
259                 cargo_toml.display(),
260                 workdir
261             )
262         })?;
263
264         let mut pkg_by_id = FxHashMap::default();
265         let mut packages = Arena::default();
266         let mut targets = Arena::default();
267
268         let ws_members = &meta.workspace_members;
269
270         meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
271         for meta_pkg in &meta.packages {
272             let cargo_metadata::Package {
273                 id, edition, name, manifest_path, version, metadata, ..
274             } = meta_pkg;
275             let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
276             let is_member = ws_members.contains(&id);
277             let edition = edition
278                 .parse::<Edition>()
279                 .with_context(|| format!("Failed to parse edition {}", edition))?;
280
281             let pkg = packages.alloc(PackageData {
282                 id: id.repr.clone(),
283                 name: name.clone(),
284                 version: version.to_string(),
285                 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
286                 targets: Vec::new(),
287                 is_member,
288                 edition,
289                 dependencies: Vec::new(),
290                 features: meta_pkg.features.clone().into_iter().collect(),
291                 active_features: Vec::new(),
292                 metadata: meta.rust_analyzer.unwrap_or_default(),
293             });
294             let pkg_data = &mut packages[pkg];
295             pkg_by_id.insert(id, pkg);
296             for meta_tgt in &meta_pkg.targets {
297                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
298                 let tgt = targets.alloc(TargetData {
299                     package: pkg,
300                     name: meta_tgt.name.clone(),
301                     root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
302                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
303                     is_proc_macro,
304                 });
305                 pkg_data.targets.push(tgt);
306             }
307         }
308         let resolve = meta.resolve.expect("metadata executed with deps");
309         for mut node in resolve.nodes {
310             let source = match pkg_by_id.get(&node.id) {
311                 Some(&src) => src,
312                 // FIXME: replace this and a similar branch below with `.unwrap`, once
313                 // https://github.com/rust-lang/cargo/issues/7841
314                 // is fixed and hits stable (around 1.43-is probably?).
315                 None => {
316                     log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
317                     continue;
318                 }
319             };
320             node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
321             for dep_node in node.deps {
322                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
323                     Some(&pkg) => pkg,
324                     None => {
325                         log::error!(
326                             "Dep node id do not match in cargo metadata, ignoring {}",
327                             dep_node.pkg
328                         );
329                         continue;
330                     }
331                 };
332                 let dep = PackageDependency {
333                     name: dep_node.name,
334                     pkg,
335                     kind: DepKind::new(&dep_node.dep_kinds),
336                 };
337                 packages[source].dependencies.push(dep);
338             }
339             packages[source].active_features.extend(node.features);
340         }
341
342         let workspace_root =
343             AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
344         let build_data_config = BuildDataConfig::new(
345             cargo_toml.to_path_buf(),
346             config.clone(),
347             Arc::new(meta.packages.clone()),
348         );
349
350         Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
351     }
352
353     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
354         self.packages.iter().map(|(id, _pkg)| id)
355     }
356
357     pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
358         self.packages()
359             .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
360             .next()
361             .copied()
362     }
363
364     pub fn workspace_root(&self) -> &AbsPath {
365         &self.workspace_root
366     }
367
368     pub fn package_flag(&self, package: &PackageData) -> String {
369         if self.is_unique(&*package.name) {
370             package.name.clone()
371         } else {
372             format!("{}:{}", package.name, package.version)
373         }
374     }
375
376     pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
377         &self.build_data_config
378     }
379
380     fn is_unique(&self, name: &str) -> bool {
381         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
382     }
383 }
384
385 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
386     let mut rustc = Command::new(toolchain::rustc());
387     rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
388     log::debug!("Discovering host platform by {:?}", rustc);
389     match utf8_stdout(rustc) {
390         Ok(stdout) => {
391             let field = "host: ";
392             let target = stdout.lines().find_map(|l| l.strip_prefix(field));
393             if let Some(target) = target {
394                 Some(target.to_string())
395             } else {
396                 // If we fail to resolve the host platform, it's not the end of the world.
397                 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
398                 None
399             }
400         }
401         Err(e) => {
402             log::warn!("Failed to discover host platform: {}", e);
403             None
404         }
405     }
406 }
407
408 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
409     let mut cargo_config = Command::new(toolchain::cargo());
410     cargo_config
411         .current_dir(cargo_toml.parent().unwrap())
412         .args(&["-Z", "unstable-options", "config", "get", "build.target"])
413         .env("RUSTC_BOOTSTRAP", "1");
414     // if successful we receive `build.target = "target-triple"`
415     log::debug!("Discovering cargo config target by {:?}", cargo_config);
416     match utf8_stdout(cargo_config) {
417         Ok(stdout) => stdout
418             .strip_prefix("build.target = \"")
419             .and_then(|stdout| stdout.strip_suffix('"'))
420             .map(ToOwned::to_owned),
421         Err(_) => None,
422     }
423 }