1 //! FIXME: write short doc here
10 use anyhow::{Context, Result};
11 use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
12 use ra_arena::{Arena, Idx};
14 use rustc_hash::FxHashMap;
16 /// `CargoWorkspace` represents the logical structure of, well, a Cargo
17 /// workspace. It pretty closely mirrors `cargo metadata` output.
19 /// Note that internally, rust analyzer uses a different structure:
20 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
21 /// while this knows about `Packages` & `Targets`: purely cargo-related
23 #[derive(Debug, Clone)]
24 pub struct CargoWorkspace {
25 packages: Arena<PackageData>,
26 targets: Arena<TargetData>,
27 workspace_root: PathBuf,
30 impl ops::Index<Package> for CargoWorkspace {
31 type Output = PackageData;
32 fn index(&self, index: Package) -> &PackageData {
37 impl ops::Index<Target> for CargoWorkspace {
38 type Output = TargetData;
39 fn index(&self, index: Target) -> &TargetData {
44 #[derive(Clone, Debug, PartialEq, Eq)]
45 pub struct CargoConfig {
46 /// Do not activate the `default` feature.
47 pub no_default_features: bool,
49 /// Activate all available features
50 pub all_features: bool,
52 /// List of features to activate.
53 /// This will be ignored if `cargo_all_features` is true.
54 pub features: Vec<String>,
56 /// Runs cargo check on launch to figure out the correct values of OUT_DIR
57 pub load_out_dirs_from_check: bool,
60 pub target: Option<String>,
63 impl Default for CargoConfig {
64 fn default() -> Self {
66 no_default_features: false,
69 load_out_dirs_from_check: false,
75 pub type Package = Idx<PackageData>;
77 pub type Target = Idx<TargetData>;
79 #[derive(Debug, Clone)]
80 pub struct PackageData {
83 pub manifest: PathBuf,
84 pub targets: Vec<Target>,
86 pub dependencies: Vec<PackageDependency>,
88 pub features: Vec<String>,
89 pub cfgs: Vec<String>,
90 pub out_dir: Option<PathBuf>,
91 pub proc_macro_dylib_path: Option<PathBuf>,
94 #[derive(Debug, Clone)]
95 pub struct PackageDependency {
100 #[derive(Debug, Clone)]
101 pub struct TargetData {
102 pub package: Package,
105 pub kind: TargetKind,
106 pub is_proc_macro: bool,
109 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
110 pub enum TargetKind {
112 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
121 fn new(kinds: &[String]) -> TargetKind {
123 return match kind.as_str() {
124 "bin" => TargetKind::Bin,
125 "test" => TargetKind::Test,
126 "bench" => TargetKind::Bench,
127 "example" => TargetKind::Example,
128 "proc-macro" => TargetKind::Lib,
129 _ if kind.contains("lib") => TargetKind::Lib,
138 pub fn root(&self) -> &Path {
139 self.manifest.parent().unwrap()
143 impl CargoWorkspace {
144 pub fn from_cargo_metadata(
146 cargo_features: &CargoConfig,
147 ) -> Result<CargoWorkspace> {
148 let mut meta = MetadataCommand::new();
149 meta.cargo_path(ra_toolchain::cargo());
150 meta.manifest_path(cargo_toml);
151 if cargo_features.all_features {
152 meta.features(CargoOpt::AllFeatures);
153 } else if cargo_features.no_default_features {
154 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
155 // https://github.com/oli-obk/cargo_metadata/issues/79
156 meta.features(CargoOpt::NoDefaultFeatures);
157 } else if !cargo_features.features.is_empty() {
158 meta.features(CargoOpt::SomeFeatures(cargo_features.features.clone()));
160 if let Some(parent) = cargo_toml.parent() {
161 meta.current_dir(parent);
163 if let Some(target) = cargo_features.target.as_ref() {
164 meta.other_options(vec![String::from("--filter-platform"), target.clone()]);
166 let meta = meta.exec().with_context(|| {
167 format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display())
170 let mut out_dir_by_id = FxHashMap::default();
171 let mut cfgs = FxHashMap::default();
172 let mut proc_macro_dylib_paths = FxHashMap::default();
173 if cargo_features.load_out_dirs_from_check {
174 let resources = load_extern_resources(cargo_toml, cargo_features)?;
175 out_dir_by_id = resources.out_dirs;
176 cfgs = resources.cfgs;
177 proc_macro_dylib_paths = resources.proc_dylib_paths;
180 let mut pkg_by_id = FxHashMap::default();
181 let mut packages = Arena::default();
182 let mut targets = Arena::default();
184 let ws_members = &meta.workspace_members;
186 for meta_pkg in meta.packages {
187 let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
189 let is_member = ws_members.contains(&id);
190 let edition = edition
192 .with_context(|| format!("Failed to parse edition {}", edition))?;
193 let pkg = packages.alloc(PackageData {
195 version: version.to_string(),
196 manifest: manifest_path,
200 dependencies: Vec::new(),
201 features: Vec::new(),
202 cfgs: cfgs.get(&id).cloned().unwrap_or_default(),
203 out_dir: out_dir_by_id.get(&id).cloned(),
204 proc_macro_dylib_path: proc_macro_dylib_paths.get(&id).cloned(),
206 let pkg_data = &mut packages[pkg];
207 pkg_by_id.insert(id, pkg);
208 for meta_tgt in meta_pkg.targets {
209 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
210 let tgt = targets.alloc(TargetData {
213 root: meta_tgt.src_path.clone(),
214 kind: TargetKind::new(meta_tgt.kind.as_slice()),
217 pkg_data.targets.push(tgt);
220 let resolve = meta.resolve.expect("metadata executed with deps");
221 for node in resolve.nodes {
222 let source = match pkg_by_id.get(&node.id) {
224 // FIXME: replace this and a similar branch below with `.unwrap`, once
225 // https://github.com/rust-lang/cargo/issues/7841
226 // is fixed and hits stable (around 1.43-is probably?).
228 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
232 for dep_node in node.deps {
233 let pkg = match pkg_by_id.get(&dep_node.pkg) {
237 "Dep node id do not match in cargo metadata, ignoring {}",
243 let dep = PackageDependency { name: dep_node.name, pkg };
244 packages[source].dependencies.push(dep);
246 packages[source].features.extend(node.features);
249 Ok(CargoWorkspace { packages, targets, workspace_root: meta.workspace_root })
252 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
253 self.packages.iter().map(|(id, _pkg)| id)
256 pub fn target_by_root(&self, root: &Path) -> Option<Target> {
258 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| self[it].root == root))
263 pub fn workspace_root(&self) -> &Path {
267 pub fn package_flag(&self, package: &PackageData) -> String {
268 if self.is_unique(&*package.name) {
271 format!("{}:{}", package.name, package.version)
275 fn is_unique(&self, name: &str) -> bool {
276 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
280 #[derive(Debug, Clone, Default)]
281 pub struct ExternResources {
282 out_dirs: FxHashMap<PackageId, PathBuf>,
283 proc_dylib_paths: FxHashMap<PackageId, PathBuf>,
284 cfgs: FxHashMap<PackageId, Vec<String>>,
287 pub fn load_extern_resources(
289 cargo_features: &CargoConfig,
290 ) -> Result<ExternResources> {
291 let mut cmd = Command::new(ra_toolchain::cargo());
292 cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml);
293 if cargo_features.all_features {
294 cmd.arg("--all-features");
295 } else if cargo_features.no_default_features {
296 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
297 // https://github.com/oli-obk/cargo_metadata/issues/79
298 cmd.arg("--no-default-features");
300 cmd.args(&cargo_features.features);
303 let output = cmd.output()?;
305 let mut res = ExternResources::default();
307 for message in cargo_metadata::Message::parse_stream(output.stdout.as_slice()) {
308 if let Ok(message) = message {
310 Message::BuildScriptExecuted(BuildScript { package_id, out_dir, cfgs, .. }) => {
311 res.out_dirs.insert(package_id.clone(), out_dir);
312 res.cfgs.insert(package_id, cfgs);
314 Message::CompilerArtifact(message) => {
315 if message.target.kind.contains(&"proc-macro".to_string()) {
316 let package_id = message.package_id;
318 if let Some(filename) = message.filenames.iter().find(|name| is_dylib(name))
320 res.proc_dylib_paths.insert(package_id, filename.clone());
324 Message::CompilerMessage(_) => (),
325 Message::Unknown => (),
326 Message::BuildFinished(_) => {}
327 Message::TextLine(_) => {}
334 // FIXME: File a better way to know if it is a dylib
335 fn is_dylib(path: &Path) -> bool {
336 match path.extension().and_then(OsStr::to_str).map(|it| it.to_string().to_lowercase()) {
338 Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),