]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/cargo_workspace.rs
Be more explicit about absolute paths at various places
[rust.git] / crates / ra_project_model / src / cargo_workspace.rs
1 //! FIXME: write short doc here
2
3 use std::{ffi::OsStr, ops, path::Path, process::Command};
4
5 use anyhow::{Context, Result};
6 use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
7 use paths::{AbsPath, AbsPathBuf};
8 use ra_arena::{Arena, Idx};
9 use ra_db::Edition;
10 use rustc_hash::FxHashMap;
11
12 /// `CargoWorkspace` represents the logical structure of, well, a Cargo
13 /// workspace. It pretty closely mirrors `cargo metadata` output.
14 ///
15 /// Note that internally, rust analyzer uses a different structure:
16 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
17 /// while this knows about `Packages` & `Targets`: purely cargo-related
18 /// concepts.
19 ///
20 /// We use absolute paths here, `cargo metadata` guarantees to always produce
21 /// abs paths.
22 #[derive(Debug, Clone)]
23 pub struct CargoWorkspace {
24     packages: Arena<PackageData>,
25     targets: Arena<TargetData>,
26     workspace_root: AbsPathBuf,
27 }
28
29 impl ops::Index<Package> for CargoWorkspace {
30     type Output = PackageData;
31     fn index(&self, index: Package) -> &PackageData {
32         &self.packages[index]
33     }
34 }
35
36 impl ops::Index<Target> for CargoWorkspace {
37     type Output = TargetData;
38     fn index(&self, index: Target) -> &TargetData {
39         &self.targets[index]
40     }
41 }
42
43 #[derive(Clone, Debug, PartialEq, Eq)]
44 pub struct CargoConfig {
45     /// Do not activate the `default` feature.
46     pub no_default_features: bool,
47
48     /// Activate all available features
49     pub all_features: bool,
50
51     /// List of features to activate.
52     /// This will be ignored if `cargo_all_features` is true.
53     pub features: Vec<String>,
54
55     /// Runs cargo check on launch to figure out the correct values of OUT_DIR
56     pub load_out_dirs_from_check: bool,
57
58     /// rustc target
59     pub target: Option<String>,
60 }
61
62 impl Default for CargoConfig {
63     fn default() -> Self {
64         CargoConfig {
65             no_default_features: false,
66             all_features: false,
67             features: Vec::new(),
68             load_out_dirs_from_check: false,
69             target: None,
70         }
71     }
72 }
73
74 pub type Package = Idx<PackageData>;
75
76 pub type Target = Idx<TargetData>;
77
78 #[derive(Debug, Clone)]
79 pub struct PackageData {
80     pub version: String,
81     pub name: String,
82     pub manifest: AbsPathBuf,
83     pub targets: Vec<Target>,
84     pub is_member: bool,
85     pub dependencies: Vec<PackageDependency>,
86     pub edition: Edition,
87     pub features: Vec<String>,
88     pub cfgs: Vec<String>,
89     pub out_dir: Option<AbsPathBuf>,
90     pub proc_macro_dylib_path: Option<AbsPathBuf>,
91 }
92
93 #[derive(Debug, Clone)]
94 pub struct PackageDependency {
95     pub pkg: Package,
96     pub name: String,
97 }
98
99 #[derive(Debug, Clone)]
100 pub struct TargetData {
101     pub package: Package,
102     pub name: String,
103     pub root: AbsPathBuf,
104     pub kind: TargetKind,
105     pub is_proc_macro: bool,
106 }
107
108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
109 pub enum TargetKind {
110     Bin,
111     /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
112     Lib,
113     Example,
114     Test,
115     Bench,
116     Other,
117 }
118
119 impl TargetKind {
120     fn new(kinds: &[String]) -> TargetKind {
121         for kind in kinds {
122             return match kind.as_str() {
123                 "bin" => TargetKind::Bin,
124                 "test" => TargetKind::Test,
125                 "bench" => TargetKind::Bench,
126                 "example" => TargetKind::Example,
127                 "proc-macro" => TargetKind::Lib,
128                 _ if kind.contains("lib") => TargetKind::Lib,
129                 _ => continue,
130             };
131         }
132         TargetKind::Other
133     }
134 }
135
136 impl PackageData {
137     pub fn root(&self) -> &AbsPath {
138         self.manifest.parent().unwrap()
139     }
140 }
141
142 impl CargoWorkspace {
143     pub fn from_cargo_metadata(
144         cargo_toml: &Path,
145         cargo_features: &CargoConfig,
146     ) -> Result<CargoWorkspace> {
147         let mut meta = MetadataCommand::new();
148         meta.cargo_path(ra_toolchain::cargo());
149         meta.manifest_path(cargo_toml);
150         if cargo_features.all_features {
151             meta.features(CargoOpt::AllFeatures);
152         } else if cargo_features.no_default_features {
153             // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
154             // https://github.com/oli-obk/cargo_metadata/issues/79
155             meta.features(CargoOpt::NoDefaultFeatures);
156         } else if !cargo_features.features.is_empty() {
157             meta.features(CargoOpt::SomeFeatures(cargo_features.features.clone()));
158         }
159         if let Some(parent) = cargo_toml.parent() {
160             meta.current_dir(parent);
161         }
162         if let Some(target) = cargo_features.target.as_ref() {
163             meta.other_options(vec![String::from("--filter-platform"), target.clone()]);
164         }
165         let meta = meta.exec().with_context(|| {
166             format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display())
167         })?;
168
169         let mut out_dir_by_id = FxHashMap::default();
170         let mut cfgs = FxHashMap::default();
171         let mut proc_macro_dylib_paths = FxHashMap::default();
172         if cargo_features.load_out_dirs_from_check {
173             let resources = load_extern_resources(cargo_toml, cargo_features)?;
174             out_dir_by_id = resources.out_dirs;
175             cfgs = resources.cfgs;
176             proc_macro_dylib_paths = resources.proc_dylib_paths;
177         }
178
179         let mut pkg_by_id = FxHashMap::default();
180         let mut packages = Arena::default();
181         let mut targets = Arena::default();
182
183         let ws_members = &meta.workspace_members;
184
185         for meta_pkg in meta.packages {
186             let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
187                 meta_pkg;
188             let is_member = ws_members.contains(&id);
189             let edition = edition
190                 .parse::<Edition>()
191                 .with_context(|| format!("Failed to parse edition {}", edition))?;
192             let pkg = packages.alloc(PackageData {
193                 name,
194                 version: version.to_string(),
195                 manifest: AbsPathBuf::assert(manifest_path),
196                 targets: Vec::new(),
197                 is_member,
198                 edition,
199                 dependencies: Vec::new(),
200                 features: Vec::new(),
201                 cfgs: cfgs.get(&id).cloned().unwrap_or_default(),
202                 out_dir: out_dir_by_id.get(&id).cloned(),
203                 proc_macro_dylib_path: proc_macro_dylib_paths.get(&id).cloned(),
204             });
205             let pkg_data = &mut packages[pkg];
206             pkg_by_id.insert(id, pkg);
207             for meta_tgt in meta_pkg.targets {
208                 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
209                 let tgt = targets.alloc(TargetData {
210                     package: pkg,
211                     name: meta_tgt.name,
212                     root: AbsPathBuf::assert(meta_tgt.src_path.clone()),
213                     kind: TargetKind::new(meta_tgt.kind.as_slice()),
214                     is_proc_macro,
215                 });
216                 pkg_data.targets.push(tgt);
217             }
218         }
219         let resolve = meta.resolve.expect("metadata executed with deps");
220         for node in resolve.nodes {
221             let source = match pkg_by_id.get(&node.id) {
222                 Some(&src) => src,
223                 // FIXME: replace this and a similar branch below with `.unwrap`, once
224                 // https://github.com/rust-lang/cargo/issues/7841
225                 // is fixed and hits stable (around 1.43-is probably?).
226                 None => {
227                     log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
228                     continue;
229                 }
230             };
231             for dep_node in node.deps {
232                 let pkg = match pkg_by_id.get(&dep_node.pkg) {
233                     Some(&pkg) => pkg,
234                     None => {
235                         log::error!(
236                             "Dep node id do not match in cargo metadata, ignoring {}",
237                             dep_node.pkg
238                         );
239                         continue;
240                     }
241                 };
242                 let dep = PackageDependency { name: dep_node.name, pkg };
243                 packages[source].dependencies.push(dep);
244             }
245             packages[source].features.extend(node.features);
246         }
247
248         let workspace_root = AbsPathBuf::assert(meta.workspace_root);
249         Ok(CargoWorkspace { packages, targets, workspace_root: 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: &AbsPath) -> 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, AbsPathBuf>,
283     proc_dylib_paths: FxHashMap<PackageId, AbsPathBuf>,
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                     let out_dir = AbsPathBuf::assert(out_dir);
312                     res.out_dirs.insert(package_id.clone(), out_dir);
313                     res.cfgs.insert(package_id, cfgs);
314                 }
315                 Message::CompilerArtifact(message) => {
316                     if message.target.kind.contains(&"proc-macro".to_string()) {
317                         let package_id = message.package_id;
318                         // Skip rmeta file
319                         if let Some(filename) = message.filenames.iter().find(|name| is_dylib(name))
320                         {
321                             let filename = AbsPathBuf::assert(filename.clone());
322                             res.proc_dylib_paths.insert(package_id, filename);
323                         }
324                     }
325                 }
326                 Message::CompilerMessage(_) => (),
327                 Message::Unknown => (),
328                 Message::BuildFinished(_) => {}
329                 Message::TextLine(_) => {}
330             }
331         }
332     }
333     Ok(res)
334 }
335
336 // FIXME: File a better way to know if it is a dylib
337 fn is_dylib(path: &Path) -> bool {
338     match path.extension().and_then(OsStr::to_str).map(|it| it.to_string().to_lowercase()) {
339         None => false,
340         Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
341     }
342 }