aboutsummaryrefslogtreecommitdiff
path: root/crates/project_model/src/build_data.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/project_model/src/build_data.rs')
-rw-r--r--crates/project_model/src/build_data.rs274
1 files changed, 165 insertions, 109 deletions
diff --git a/crates/project_model/src/build_data.rs b/crates/project_model/src/build_data.rs
index f7050be4e..ab5cc8c49 100644
--- a/crates/project_model/src/build_data.rs
+++ b/crates/project_model/src/build_data.rs
@@ -13,12 +13,12 @@ use cargo_metadata::{BuildScript, Message};
13use itertools::Itertools; 13use itertools::Itertools;
14use paths::{AbsPath, AbsPathBuf}; 14use paths::{AbsPath, AbsPathBuf};
15use rustc_hash::FxHashMap; 15use rustc_hash::FxHashMap;
16use stdx::JodChild; 16use stdx::{format_to, JodChild};
17 17
18use crate::{cfg_flag::CfgFlag, CargoConfig}; 18use crate::{cfg_flag::CfgFlag, CargoConfig};
19 19
20#[derive(Debug, Clone, Default, PartialEq, Eq)] 20#[derive(Debug, Clone, Default, PartialEq, Eq)]
21pub(crate) struct BuildData { 21pub(crate) struct PackageBuildData {
22 /// List of config flags defined by this package's build script 22 /// List of config flags defined by this package's build script
23 pub(crate) cfgs: Vec<CfgFlag>, 23 pub(crate) cfgs: Vec<CfgFlag>,
24 /// List of cargo-related environment variables with their value 24 /// List of cargo-related environment variables with their value
@@ -32,6 +32,17 @@ pub(crate) struct BuildData {
32 pub(crate) proc_macro_dylib_path: Option<AbsPathBuf>, 32 pub(crate) proc_macro_dylib_path: Option<AbsPathBuf>,
33} 33}
34 34
35#[derive(Debug, Default, PartialEq, Eq, Clone)]
36pub(crate) struct WorkspaceBuildData {
37 per_package: FxHashMap<String, PackageBuildData>,
38 error: Option<String>,
39}
40
41#[derive(Debug, Default, PartialEq, Eq, Clone)]
42pub struct BuildDataResult {
43 per_workspace: FxHashMap<AbsPathBuf, WorkspaceBuildData>,
44}
45
35#[derive(Clone, Debug)] 46#[derive(Clone, Debug)]
36pub(crate) struct BuildDataConfig { 47pub(crate) struct BuildDataConfig {
37 cargo_toml: AbsPathBuf, 48 cargo_toml: AbsPathBuf,
@@ -47,19 +58,17 @@ impl PartialEq for BuildDataConfig {
47 58
48impl Eq for BuildDataConfig {} 59impl Eq for BuildDataConfig {}
49 60
50#[derive(Debug, Default)] 61#[derive(Debug)]
51pub struct BuildDataCollector { 62pub struct BuildDataCollector {
63 wrap_rustc: bool,
52 configs: FxHashMap<AbsPathBuf, BuildDataConfig>, 64 configs: FxHashMap<AbsPathBuf, BuildDataConfig>,
53} 65}
54 66
55#[derive(Debug, Default, PartialEq, Eq)]
56pub struct BuildDataResult {
57 data: FxHashMap<AbsPathBuf, BuildDataMap>,
58}
59
60pub(crate) type BuildDataMap = FxHashMap<String, BuildData>;
61
62impl BuildDataCollector { 67impl BuildDataCollector {
68 pub fn new(wrap_rustc: bool) -> Self {
69 Self { wrap_rustc, configs: FxHashMap::default() }
70 }
71
63 pub(crate) fn add_config(&mut self, workspace_root: &AbsPath, config: BuildDataConfig) { 72 pub(crate) fn add_config(&mut self, workspace_root: &AbsPath, config: BuildDataConfig) {
64 self.configs.insert(workspace_root.to_path_buf(), config); 73 self.configs.insert(workspace_root.to_path_buf(), config);
65 } 74 }
@@ -67,23 +76,41 @@ impl BuildDataCollector {
67 pub fn collect(&mut self, progress: &dyn Fn(String)) -> Result<BuildDataResult> { 76 pub fn collect(&mut self, progress: &dyn Fn(String)) -> Result<BuildDataResult> {
68 let mut res = BuildDataResult::default(); 77 let mut res = BuildDataResult::default();
69 for (path, config) in self.configs.iter() { 78 for (path, config) in self.configs.iter() {
70 res.data.insert( 79 let workspace_build_data = WorkspaceBuildData::collect(
71 path.clone(), 80 &config.cargo_toml,
72 collect_from_workspace( 81 &config.cargo_features,
73 &config.cargo_toml, 82 &config.packages,
74 &config.cargo_features, 83 self.wrap_rustc,
75 &config.packages, 84 progress,
76 progress, 85 )?;
77 )?, 86 res.per_workspace.insert(path.clone(), workspace_build_data);
78 );
79 } 87 }
80 Ok(res) 88 Ok(res)
81 } 89 }
82} 90}
83 91
92impl WorkspaceBuildData {
93 pub(crate) fn get(&self, package_id: &str) -> Option<&PackageBuildData> {
94 self.per_package.get(package_id)
95 }
96}
97
84impl BuildDataResult { 98impl BuildDataResult {
85 pub(crate) fn get(&self, root: &AbsPath) -> Option<&BuildDataMap> { 99 pub(crate) fn get(&self, workspace_root: &AbsPath) -> Option<&WorkspaceBuildData> {
86 self.data.get(&root.to_path_buf()) 100 self.per_workspace.get(workspace_root)
101 }
102 pub fn error(&self) -> Option<String> {
103 let mut buf = String::new();
104 for (_workspace_root, build_data) in &self.per_workspace {
105 if let Some(err) = &build_data.error {
106 format_to!(buf, "cargo check failed:\n{}", err);
107 }
108 }
109 if buf.is_empty() {
110 return None;
111 }
112
113 Some(buf)
87 } 114 }
88} 115}
89 116
@@ -97,108 +124,137 @@ impl BuildDataConfig {
97 } 124 }
98} 125}
99 126
100fn collect_from_workspace( 127impl WorkspaceBuildData {
101 cargo_toml: &AbsPath, 128 fn collect(
102 cargo_features: &CargoConfig, 129 cargo_toml: &AbsPath,
103 packages: &Vec<cargo_metadata::Package>, 130 cargo_features: &CargoConfig,
104 progress: &dyn Fn(String), 131 packages: &Vec<cargo_metadata::Package>,
105) -> Result<BuildDataMap> { 132 wrap_rustc: bool,
106 let mut cmd = Command::new(toolchain::cargo()); 133 progress: &dyn Fn(String),
107 cmd.args(&["check", "--workspace", "--message-format=json", "--manifest-path"]) 134 ) -> Result<WorkspaceBuildData> {
108 .arg(cargo_toml.as_ref()); 135 let mut cmd = Command::new(toolchain::cargo());
109 136
110 // --all-targets includes tests, benches and examples in addition to the 137 if wrap_rustc {
111 // default lib and bins. This is an independent concept from the --targets 138 // Setup RUSTC_WRAPPER to point to `rust-analyzer` binary itself. We use
112 // flag below. 139 // that to compile only proc macros and build scripts during the initial
113 cmd.arg("--all-targets"); 140 // `cargo check`.
114 141 let myself = std::env::current_exe()?;
115 if let Some(target) = &cargo_features.target { 142 cmd.env("RUSTC_WRAPPER", myself);
116 cmd.args(&["--target", target]); 143 cmd.env("RA_RUSTC_WRAPPER", "1");
117 } 144 }
145
146 cmd.args(&["check", "--workspace", "--message-format=json", "--manifest-path"])
147 .arg(cargo_toml.as_ref());
118 148
119 if cargo_features.all_features { 149 // --all-targets includes tests, benches and examples in addition to the
120 cmd.arg("--all-features"); 150 // default lib and bins. This is an independent concept from the --targets
121 } else { 151 // flag below.
122 if cargo_features.no_default_features { 152 cmd.arg("--all-targets");
123 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures` 153
124 // https://github.com/oli-obk/cargo_metadata/issues/79 154 if let Some(target) = &cargo_features.target {
125 cmd.arg("--no-default-features"); 155 cmd.args(&["--target", target]);
126 } 156 }
127 if !cargo_features.features.is_empty() { 157
128 cmd.arg("--features"); 158 if cargo_features.all_features {
129 cmd.arg(cargo_features.features.join(" ")); 159 cmd.arg("--all-features");
160 } else {
161 if cargo_features.no_default_features {
162 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
163 // https://github.com/oli-obk/cargo_metadata/issues/79
164 cmd.arg("--no-default-features");
165 }
166 if !cargo_features.features.is_empty() {
167 cmd.arg("--features");
168 cmd.arg(cargo_features.features.join(" "));
169 }
130 } 170 }
131 }
132 171
133 cmd.stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null()); 172 cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null());
134 173
135 let mut child = cmd.spawn().map(JodChild)?; 174 let mut child = cmd.spawn().map(JodChild)?;
136 let child_stdout = child.stdout.take().unwrap(); 175 let child_stdout = child.stdout.take().unwrap();
137 let stdout = BufReader::new(child_stdout); 176 let stdout = BufReader::new(child_stdout);
138 177
139 let mut res = BuildDataMap::default(); 178 let mut res = WorkspaceBuildData::default();
140 for message in cargo_metadata::Message::parse_stream(stdout).flatten() { 179 for message in cargo_metadata::Message::parse_stream(stdout).flatten() {
141 match message { 180 match message {
142 Message::BuildScriptExecuted(BuildScript { 181 Message::BuildScriptExecuted(BuildScript {
143 package_id, out_dir, cfgs, env, .. 182 package_id,
144 }) => { 183 out_dir,
145 let cfgs = { 184 cfgs,
146 let mut acc = Vec::new(); 185 env,
147 for cfg in cfgs { 186 ..
148 match cfg.parse::<CfgFlag>() { 187 }) => {
149 Ok(it) => acc.push(it), 188 let cfgs = {
150 Err(err) => { 189 let mut acc = Vec::new();
151 anyhow::bail!("invalid cfg from cargo-metadata: {}", err) 190 for cfg in cfgs {
152 } 191 match cfg.parse::<CfgFlag>() {
153 }; 192 Ok(it) => acc.push(it),
193 Err(err) => {
194 anyhow::bail!("invalid cfg from cargo-metadata: {}", err)
195 }
196 };
197 }
198 acc
199 };
200 let package_build_data =
201 res.per_package.entry(package_id.repr.clone()).or_default();
202 // cargo_metadata crate returns default (empty) path for
203 // older cargos, which is not absolute, so work around that.
204 if !out_dir.as_str().is_empty() {
205 let out_dir = AbsPathBuf::assert(PathBuf::from(out_dir.into_os_string()));
206 package_build_data.out_dir = Some(out_dir);
207 package_build_data.cfgs = cfgs;
154 } 208 }
155 acc
156 };
157 let res = res.entry(package_id.repr.clone()).or_default();
158 // cargo_metadata crate returns default (empty) path for
159 // older cargos, which is not absolute, so work around that.
160 if !out_dir.as_str().is_empty() {
161 let out_dir = AbsPathBuf::assert(PathBuf::from(out_dir.into_os_string()));
162 res.out_dir = Some(out_dir);
163 res.cfgs = cfgs;
164 }
165 209
166 res.envs = env; 210 package_build_data.envs = env;
167 } 211 }
168 Message::CompilerArtifact(message) => { 212 Message::CompilerArtifact(message) => {
169 progress(format!("metadata {}", message.target.name)); 213 progress(format!("metadata {}", message.target.name));
170 214
171 if message.target.kind.contains(&"proc-macro".to_string()) { 215 if message.target.kind.contains(&"proc-macro".to_string()) {
172 let package_id = message.package_id; 216 let package_id = message.package_id;
173 // Skip rmeta file 217 // Skip rmeta file
174 if let Some(filename) = message.filenames.iter().find(|name| is_dylib(name)) { 218 if let Some(filename) = message.filenames.iter().find(|name| is_dylib(name))
175 let filename = AbsPathBuf::assert(PathBuf::from(&filename)); 219 {
176 let res = res.entry(package_id.repr.clone()).or_default(); 220 let filename = AbsPathBuf::assert(PathBuf::from(&filename));
177 res.proc_macro_dylib_path = Some(filename); 221 let package_build_data =
222 res.per_package.entry(package_id.repr.clone()).or_default();
223 package_build_data.proc_macro_dylib_path = Some(filename);
224 }
178 } 225 }
179 } 226 }
227 Message::CompilerMessage(message) => {
228 progress(message.target.name.clone());
229 }
230 Message::BuildFinished(_) => {}
231 Message::TextLine(_) => {}
232 _ => {}
180 } 233 }
181 Message::CompilerMessage(message) => { 234 }
182 progress(message.target.name.clone()); 235
236 for package in packages {
237 let package_build_data = res.per_package.entry(package.id.repr.clone()).or_default();
238 inject_cargo_env(package, package_build_data);
239 if let Some(out_dir) = &package_build_data.out_dir {
240 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
241 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
242 package_build_data.envs.push(("OUT_DIR".to_string(), out_dir));
243 }
183 } 244 }
184 Message::BuildFinished(_) => {}
185 Message::TextLine(_) => {}
186 _ => {}
187 } 245 }
188 }
189 246
190 for package in packages { 247 let output = child.into_inner().wait_with_output()?;
191 let build_data = res.entry(package.id.repr.clone()).or_default(); 248 if !output.status.success() {
192 inject_cargo_env(package, build_data); 249 let mut stderr = String::from_utf8(output.stderr).unwrap_or_default();
193 if let Some(out_dir) = &build_data.out_dir { 250 if stderr.is_empty() {
194 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!() 251 stderr = "cargo check failed".to_string();
195 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
196 build_data.envs.push(("OUT_DIR".to_string(), out_dir));
197 } 252 }
253 res.error = Some(stderr)
198 } 254 }
199 }
200 255
201 Ok(res) 256 Ok(res)
257 }
202} 258}
203 259
204// FIXME: File a better way to know if it is a dylib 260// FIXME: File a better way to know if it is a dylib
@@ -212,7 +268,7 @@ fn is_dylib(path: &Utf8Path) -> bool {
212/// Recreates the compile-time environment variables that Cargo sets. 268/// Recreates the compile-time environment variables that Cargo sets.
213/// 269///
214/// Should be synced with <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates> 270/// Should be synced with <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
215fn inject_cargo_env(package: &cargo_metadata::Package, build_data: &mut BuildData) { 271fn inject_cargo_env(package: &cargo_metadata::Package, build_data: &mut PackageBuildData) {
216 let env = &mut build_data.envs; 272 let env = &mut build_data.envs;
217 273
218 // FIXME: Missing variables: 274 // FIXME: Missing variables: