1 //! FIXME: write short doc here
3 use std::path::PathBuf;
4 use std::{convert::TryInto, ops, process::Command, sync::Arc};
6 use anyhow::{Context, Result};
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;
15 use crate::build_data::BuildDataConfig;
16 use crate::utf8_stdout;
18 /// `CargoWorkspace` represents the logical structure of, well, a Cargo
19 /// workspace. It pretty closely mirrors `cargo metadata` output.
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
26 /// We use absolute paths here, `cargo metadata` guarantees to always produce
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,
36 impl ops::Index<Package> for CargoWorkspace {
37 type Output = PackageData;
38 fn index(&self, index: Package) -> &PackageData {
43 impl ops::Index<Target> for CargoWorkspace {
44 type Output = TargetData;
45 fn index(&self, index: Target) -> &TargetData {
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.
55 /// Try to automatically detect where the rustc source directory is.
59 #[derive(Default, Clone, Debug, PartialEq, Eq)]
60 pub struct CargoConfig {
61 /// Do not activate the `default` feature.
62 pub no_default_features: bool,
64 /// Activate all available features
65 pub all_features: bool,
67 /// List of features to activate.
68 /// This will be ignored if `cargo_all_features` is true.
69 pub features: Vec<String>,
72 pub target: Option<String>,
74 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
75 /// when debugging isolated issues.
78 /// rustc private crate source
79 pub rustc_source: Option<RustcSource>,
82 pub type Package = Idx<PackageData>;
84 pub type Target = Idx<TargetData>;
86 /// Information associated with a cargo crate
87 #[derive(Debug, Clone, Eq, PartialEq)]
88 pub struct PackageData {
89 /// Version given in the `Cargo.toml`
91 /// Name as given in the `Cargo.toml`
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
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
109 // The contents of [package.metadata.rust-analyzer]
110 pub metadata: RustAnalyzerPackageMetaData,
113 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
114 pub struct RustAnalyzerPackageMetaData {
115 pub rustc_private: Option<bool>,
118 #[derive(Debug, Clone, Eq, PartialEq)]
119 pub struct PackageDependency {
124 /// Information associated with a package's target
125 #[derive(Debug, Clone, Eq, PartialEq)]
126 pub struct TargetData {
127 /// Package that provided this target
128 pub package: Package,
129 /// Name as given in the `Cargo.toml` or generated from the file name
131 /// Path to the main source file of the target
132 pub root: AbsPathBuf,
134 pub kind: TargetKind,
135 /// Is this target a proc-macro
136 pub is_proc_macro: bool,
139 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
140 pub enum TargetKind {
142 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
151 fn new(kinds: &[String]) -> TargetKind {
153 return match kind.as_str() {
154 "bin" => TargetKind::Bin,
155 "test" => TargetKind::Test,
156 "bench" => TargetKind::Bench,
157 "example" => TargetKind::Example,
158 "proc-macro" => TargetKind::Lib,
159 _ if kind.contains("lib") => TargetKind::Lib,
168 pub fn root(&self) -> &AbsPath {
169 self.manifest.parent().unwrap()
173 #[derive(Deserialize, Default)]
174 // Deserialise helper for the cargo metadata
175 struct PackageMetadata {
176 #[serde(rename = "rust-analyzer")]
177 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
180 impl CargoWorkspace {
181 pub fn from_cargo_metadata(
182 cargo_toml: &AbsPath,
183 config: &CargoConfig,
184 progress: &dyn Fn(String),
185 ) -> Result<CargoWorkspace> {
186 let mut meta = MetadataCommand::new();
187 meta.cargo_path(toolchain::cargo());
188 meta.manifest_path(cargo_toml.to_path_buf());
189 if config.all_features {
190 meta.features(CargoOpt::AllFeatures);
192 if config.no_default_features {
193 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
194 // https://github.com/oli-obk/cargo_metadata/issues/79
195 meta.features(CargoOpt::NoDefaultFeatures);
197 if !config.features.is_empty() {
198 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
201 if let Some(parent) = cargo_toml.parent() {
202 meta.current_dir(parent.to_path_buf());
204 let target = if let Some(target) = config.target.as_ref() {
207 // cargo metadata defaults to giving information for _all_ targets.
208 // In the absence of a preference from the user, we use the host platform.
209 let mut rustc = Command::new(toolchain::rustc());
210 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
211 log::debug!("Discovering host platform by {:?}", rustc);
212 match utf8_stdout(rustc) {
214 let field = "host: ";
215 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
216 if let Some(target) = target {
217 Some(target.to_string())
219 // If we fail to resolve the host platform, it's not the end of the world.
220 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
225 log::warn!("Failed to discover host platform: {}", e);
230 if let Some(target) = target {
231 meta.other_options(vec![String::from("--filter-platform"), target]);
234 // FIXME: Currently MetadataCommand is not based on parse_stream,
235 // So we just report it as a whole
236 progress("metadata".to_string());
237 let mut meta = meta.exec().with_context(|| {
238 let cwd: Option<AbsPathBuf> =
239 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
241 let workdir = cargo_toml
243 .map(|p| p.to_path_buf())
245 .map(|dir| dir.to_string_lossy().to_string())
246 .unwrap_or_else(|| "<failed to get path>".into());
249 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
250 cargo_toml.display(),
255 let mut pkg_by_id = FxHashMap::default();
256 let mut packages = Arena::default();
257 let mut targets = Arena::default();
259 let ws_members = &meta.workspace_members;
261 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
262 for meta_pkg in &meta.packages {
263 let cargo_metadata::Package {
264 id, edition, name, manifest_path, version, metadata, ..
266 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
267 let is_member = ws_members.contains(&id);
268 let edition = edition
270 .with_context(|| format!("Failed to parse edition {}", edition))?;
272 let pkg = packages.alloc(PackageData {
275 version: version.to_string(),
276 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
280 dependencies: Vec::new(),
281 features: meta_pkg.features.clone().into_iter().collect(),
282 active_features: Vec::new(),
283 metadata: meta.rust_analyzer.unwrap_or_default(),
285 let pkg_data = &mut packages[pkg];
286 pkg_by_id.insert(id, pkg);
287 for meta_tgt in &meta_pkg.targets {
288 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
289 let tgt = targets.alloc(TargetData {
291 name: meta_tgt.name.clone(),
292 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
293 kind: TargetKind::new(meta_tgt.kind.as_slice()),
296 pkg_data.targets.push(tgt);
299 let resolve = meta.resolve.expect("metadata executed with deps");
300 for mut node in resolve.nodes {
301 let source = match pkg_by_id.get(&node.id) {
303 // FIXME: replace this and a similar branch below with `.unwrap`, once
304 // https://github.com/rust-lang/cargo/issues/7841
305 // is fixed and hits stable (around 1.43-is probably?).
307 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
311 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
312 for dep_node in node.deps {
313 let pkg = match pkg_by_id.get(&dep_node.pkg) {
317 "Dep node id do not match in cargo metadata, ignoring {}",
323 let dep = PackageDependency { name: dep_node.name, pkg };
324 packages[source].dependencies.push(dep);
326 packages[source].active_features.extend(node.features);
330 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
331 let build_data_config = BuildDataConfig::new(
332 cargo_toml.to_path_buf(),
334 Arc::new(meta.packages.clone()),
337 Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
340 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
341 self.packages.iter().map(|(id, _pkg)| id)
344 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
346 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
351 pub fn workspace_root(&self) -> &AbsPath {
355 pub fn package_flag(&self, package: &PackageData) -> String {
356 if self.is_unique(&*package.name) {
359 format!("{}:{}", package.name, package.version)
363 pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
364 &self.build_data_config
367 fn is_unique(&self, name: &str) -> bool {
368 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1