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