]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/cargo_workspace.rs
4b7444039e7b9b448126b7e5f09f21f7659d18ac
[rust.git] / crates / ra_project_model / src / cargo_workspace.rs
1 //! FIXME: write short doc here
2
3 use std::{
4     ffi::OsStr,
5     ops,
6     path::{Path, PathBuf},
7     process::Command,
8 };
9
10 use anyhow::{Context, Result};
11 use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
12 use ra_arena::{Arena, Idx};
13 use ra_db::Edition;
14 use rustc_hash::FxHashMap;
15
16 /// `CargoWorkspace` represents the logical structure of, well, a Cargo
17 /// workspace. It pretty closely mirrors `cargo metadata` output.
18 ///
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
22 /// concepts.
23 #[derive(Debug, Clone)]
24 pub struct CargoWorkspace {
25     packages: Arena<PackageData>,
26     targets: Arena<TargetData>,
27     workspace_root: PathBuf,
28 }
29
30 impl ops::Index<Package> for CargoWorkspace {
31     type Output = PackageData;
32     fn index(&self, index: Package) -> &PackageData {
33         &self.packages[index]
34     }
35 }
36
37 impl ops::Index<Target> for CargoWorkspace {
38     type Output = TargetData;
39     fn index(&self, index: Target) -> &TargetData {
40         &self.targets[index]
41     }
42 }
43
44 #[derive(Clone, Debug, PartialEq, Eq)]
45 pub struct CargoConfig {
46     /// Do not activate the `default` feature.
47     pub no_default_features: bool,
48
49     /// Activate all available features
50     pub all_features: bool,
51
52     /// List of features to activate.
53     /// This will be ignored if `cargo_all_features` is true.
54     pub features: Vec<String>,
55
56     /// Runs cargo check on launch to figure out the correct values of OUT_DIR
57     pub load_out_dirs_from_check: bool,
58
59     /// rustc target
60     pub target: Option<String>,
61 }
62
63 impl Default for CargoConfig {
64     fn default() -> Self {
65         CargoConfig {
66             no_default_features: false,
67             all_features: false,
68             features: Vec::new(),
69             load_out_dirs_from_check: false,
70             target: None,
71         }
72     }
73 }
74
75 pub type Package = Idx<PackageData>;
76
77 pub type Target = Idx<TargetData>;
78
79 #[derive(Debug, Clone)]
80 pub struct PackageData {
81     pub version: String,
82     pub name: String,
83     pub manifest: PathBuf,
84     pub targets: Vec<Target>,
85     pub is_member: bool,
86     pub dependencies: Vec<PackageDependency>,
87     pub edition: Edition,
88     pub features: Vec<String>,
89     pub cfgs: Vec<String>,
90     pub out_dir: Option<PathBuf>,
91     pub proc_macro_dylib_path: Option<PathBuf>,
92 }
93
94 #[derive(Debug, Clone)]
95 pub struct PackageDependency {
96     pub pkg: Package,
97     pub name: String,
98 }
99
100 #[derive(Debug, Clone)]
101 pub struct TargetData {
102     pub package: Package,
103     pub name: String,
104     pub root: PathBuf,
105     pub kind: TargetKind,
106     pub is_proc_macro: bool,
107 }
108
109 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
110 pub enum TargetKind {
111     Bin,
112     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
113     Lib,
114     Example,
115     Test,
116     Bench,
117     Other,
118 }
119
120 impl TargetKind {
121     fn new(kinds: &[String]) -> TargetKind {
122         for kind in kinds {
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,
130                 _ => continue,
131             };
132         }
133         TargetKind::Other
134     }
135 }
136
137 impl PackageData {
138     pub fn root(&self) -> &Path {
139         self.manifest.parent().unwrap()
140     }
141 }
142
143 impl CargoWorkspace {
144     pub fn from_cargo_metadata(
145         cargo_toml: &Path,
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()));
159         }
160         if let Some(parent) = cargo_toml.parent() {
161             meta.current_dir(parent);
162         }
163         if let Some(target) = cargo_features.target.as_ref() {
164             meta.other_options(vec![String::from("--filter-platform"), target.clone()]);
165         }
166         let meta = meta.exec().with_context(|| {
167             format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display())
168         })?;
169
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;
178         }
179
180         let mut pkg_by_id = FxHashMap::default();
181         let mut packages = Arena::default();
182         let mut targets = Arena::default();
183
184         let ws_members = &meta.workspace_members;
185
186         for meta_pkg in meta.packages {
187             let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
188                 meta_pkg;
189             let is_member = ws_members.contains(&id);
190             let edition = edition
191                 .parse::<Edition>()
192                 .with_context(|| format!("Failed to parse edition {}", edition))?;
193             let pkg = packages.alloc(PackageData {
194                 name,
195                 version: version.to_string(),
196                 manifest: manifest_path,
197                 targets: Vec::new(),
198                 is_member,
199                 edition,
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(),
205             });
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 {
211                     package: pkg,
212                     name: meta_tgt.name,
213                     root: meta_tgt.src_path.clone(),
214                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
215                     is_proc_macro,
216                 });
217                 pkg_data.targets.push(tgt);
218             }
219         }
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) {
223                 Some(&src) => src,
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?).
227                 None => {
228                     log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
229                     continue;
230                 }
231             };
232             for dep_node in node.deps {
233                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
234                     Some(&pkg) => pkg,
235                     None => {
236                         log::error!(
237                             "Dep node id do not match in cargo metadata, ignoring {}",
238                             dep_node.pkg
239                         );
240                         continue;
241                     }
242                 };
243                 let dep = PackageDependency { name: dep_node.name, pkg };
244                 packages[source].dependencies.push(dep);
245             }
246             packages[source].features.extend(node.features);
247         }
248
249         Ok(CargoWorkspace { packages, targets, workspace_root: meta.workspace_root })
250     }
251
252     pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
253         self.packages.iter().map(|(id, _pkg)| id)
254     }
255
256     pub fn target_by_root(&self, root: &Path) -> Option<Target> {
257         self.packages()
258             .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| self[it].root == root))
259             .next()
260             .copied()
261     }
262
263     pub fn workspace_root(&self) -> &Path {
264         &self.workspace_root
265     }
266
267     pub fn package_flag(&self, package: &PackageData) -> String {
268         if self.is_unique(&*package.name) {
269             package.name.clone()
270         } else {
271             format!("{}:{}", package.name, package.version)
272         }
273     }
274
275     fn is_unique(&self, name: &str) -> bool {
276         self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
277     }
278 }
279
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>>,
285 }
286
287 pub fn load_extern_resources(
288     cargo_toml: &Path,
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");
299     } else {
300         cmd.args(&cargo_features.features);
301     }
302
303     let output = cmd.output()?;
304
305     let mut res = ExternResources::default();
306
307     for message in cargo_metadata::Message::parse_stream(output.stdout.as_slice()) {
308         if let Ok(message) = message {
309             match 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);
313                 }
314                 Message::CompilerArtifact(message) => {
315                     if message.target.kind.contains(&"proc-macro".to_string()) {
316                         let package_id = message.package_id;
317                         // Skip rmeta file
318                         if let Some(filename) = message.filenames.iter().find(|name| is_dylib(name))
319                         {
320                             res.proc_dylib_paths.insert(package_id, filename.clone());
321                         }
322                     }
323                 }
324                 Message::CompilerMessage(_) => (),
325                 Message::Unknown => (),
326                 Message::BuildFinished(_) => {}
327                 Message::TextLine(_) => {}
328             }
329         }
330     }
331     Ok(res)
332 }
333
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()) {
337         None => false,
338         Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
339     }
340 }