1use std::{cell::RefCell, io, mem, process::Command};
10
11use base_db::Env;
12use cargo_metadata::{Message, PackageId, camino::Utf8Path};
13use cfg::CfgAtom;
14use itertools::Itertools;
15use la_arena::ArenaMap;
16use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
17use rustc_hash::{FxHashMap, FxHashSet};
18use serde::Deserialize as _;
19use stdx::never;
20use toolchain::Tool;
21use triomphe::Arc;
22
23use crate::{
24 CargoConfig, CargoFeatures, CargoWorkspace, InvocationStrategy, ManifestPath, Package, Sysroot,
25 TargetKind,
26 cargo_config_file::{LockfileCopy, LockfileUsage, make_lockfile_copy},
27 utf8_stdout,
28};
29
30#[derive(Debug, Default, Clone, PartialEq, Eq)]
32pub struct WorkspaceBuildScripts {
33 outputs: ArenaMap<Package, BuildScriptOutput>,
34 error: Option<String>,
35}
36
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub enum ProcMacroDylibPath {
39 Path(AbsPathBuf),
40 DylibNotFound,
41 NotProcMacro,
42 #[default]
43 NotBuilt,
44}
45
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
48pub(crate) struct BuildScriptOutput {
49 pub(crate) cfgs: Vec<CfgAtom>,
51 pub(crate) envs: Env,
56 pub(crate) out_dir: Option<AbsPathBuf>,
58 pub(crate) proc_macro_dylib_path: ProcMacroDylibPath,
60}
61
62impl BuildScriptOutput {
63 fn is_empty(&self) -> bool {
64 self.cfgs.is_empty()
65 && self.envs.is_empty()
66 && self.out_dir.is_none()
67 && matches!(
68 self.proc_macro_dylib_path,
69 ProcMacroDylibPath::NotBuilt | ProcMacroDylibPath::NotProcMacro
70 )
71 }
72}
73
74impl WorkspaceBuildScripts {
75 pub(crate) fn run_for_workspace(
77 config: &CargoConfig,
78 workspace: &CargoWorkspace,
79 progress: &dyn Fn(String),
80 sysroot: &Sysroot,
81 toolchain: Option<&semver::Version>,
82 ) -> io::Result<WorkspaceBuildScripts> {
83 let current_dir = workspace.workspace_root();
84
85 let allowed_features = workspace.workspace_features();
86 let (_guard, cmd) = Self::build_command(
87 config,
88 &allowed_features,
89 workspace.manifest_path(),
90 workspace.target_directory().as_ref(),
91 current_dir,
92 sysroot,
93 toolchain,
94 )?;
95 Self::run_per_ws(cmd, workspace, progress)
96 }
97
98 pub(crate) fn run_once(
101 config: &CargoConfig,
102 workspaces: &[&CargoWorkspace],
103 progress: &dyn Fn(String),
104 working_directory: &AbsPathBuf,
105 ) -> io::Result<Vec<WorkspaceBuildScripts>> {
106 assert_eq!(config.invocation_strategy, InvocationStrategy::Once);
107
108 let (_guard, cmd) = Self::build_command(
109 config,
110 &Default::default(),
111 &ManifestPath::try_from(working_directory.clone()).unwrap(),
113 working_directory.as_ref(),
114 working_directory,
115 &Sysroot::empty(),
116 None,
117 )?;
118 let mut by_id = FxHashMap::default();
122 let mut collisions = Vec::new();
125 let mut res: Vec<_> = workspaces
126 .iter()
127 .enumerate()
128 .map(|(idx, workspace)| {
129 let mut res = WorkspaceBuildScripts::default();
130 for package in workspace.packages() {
131 res.outputs.insert(package, BuildScriptOutput::default());
132 if by_id.contains_key(&workspace[package].id) {
133 collisions.push((&workspace[package].id, idx, package));
134 } else {
135 by_id.insert(workspace[package].id.clone(), (package, idx));
136 }
137 }
138 res
139 })
140 .collect();
141
142 let errors = Self::run_command(
143 cmd,
144 |package, cb| {
145 if let Some(&(package, workspace)) = by_id.get(package) {
146 cb(&workspaces[workspace][package].name, &mut res[workspace].outputs[package]);
147 } else {
148 tracing::error!("Received compiler message for unknown package: {}", package);
149 }
150 },
151 progress,
152 )?;
153 res.iter_mut().for_each(|it| it.error.clone_from(&errors));
154 collisions.into_iter().for_each(|(id, workspace, package)| {
155 if let Some(&(p, w)) = by_id.get(id) {
156 res[workspace].outputs[package] = res[w].outputs[p].clone();
157 }
158 });
159
160 if tracing::enabled!(tracing::Level::INFO) {
161 for (idx, workspace) in workspaces.iter().enumerate() {
162 for package in workspace.packages() {
163 let package_build_data: &mut BuildScriptOutput = &mut res[idx].outputs[package];
164 if !package_build_data.is_empty() {
165 tracing::info!("{}: {package_build_data:?}", workspace[package].manifest,);
166 }
167 }
168 }
169 }
170
171 Ok(res)
172 }
173
174 pub fn error(&self) -> Option<&str> {
175 self.error.as_deref()
176 }
177
178 pub(crate) fn get_output(&self, idx: Package) -> Option<&BuildScriptOutput> {
179 self.outputs.get(idx)
180 }
181
182 pub(crate) fn rustc_crates(
184 rustc: &CargoWorkspace,
185 current_dir: &AbsPath,
186 extra_env: &FxHashMap<String, Option<String>>,
187 sysroot: &Sysroot,
188 ) -> Self {
189 let mut bs = WorkspaceBuildScripts::default();
190 for p in rustc.packages() {
191 bs.outputs.insert(p, BuildScriptOutput::default());
192 }
193 let res = (|| {
194 let target_libdir = (|| {
195 let mut cargo_config = sysroot.tool(Tool::Cargo, current_dir, extra_env);
196 cargo_config
197 .args(["rustc", "-Z", "unstable-options", "--print", "target-libdir"])
198 .env("RUSTC_BOOTSTRAP", "1");
199 if let Ok(it) = utf8_stdout(&mut cargo_config) {
200 return Ok(it);
201 }
202 let mut cmd = sysroot.tool(Tool::Rustc, current_dir, extra_env);
203 cmd.args(["--print", "target-libdir"]);
204 utf8_stdout(&mut cmd)
205 })()?;
206
207 let target_libdir = AbsPathBuf::try_from(Utf8PathBuf::from(target_libdir))
208 .map_err(|_| anyhow::format_err!("target-libdir was not an absolute path"))?;
209 tracing::info!("Loading rustc proc-macro paths from {target_libdir}");
210
211 let proc_macro_dylibs: Vec<(String, AbsPathBuf)> = std::fs::read_dir(target_libdir)?
212 .filter_map(|entry| {
213 let dir_entry = entry.ok()?;
214 if std::fs::metadata(dir_entry.path()).ok()?.is_file() {
218 let path = dir_entry.path();
219 let extension = path.extension()?;
220 if extension == std::env::consts::DLL_EXTENSION {
221 let name = path
222 .file_stem()?
223 .to_str()?
224 .split_once('-')?
225 .0
226 .trim_start_matches("lib")
227 .to_owned();
228 let path = match Utf8PathBuf::from_path_buf(path) {
229 Ok(path) => path,
230 Err(path) => {
231 tracing::warn!(
232 "Proc-macro dylib path contains non-UTF8 characters: {:?}",
233 path.display()
234 );
235 return None;
236 }
237 };
238 return match AbsPathBuf::try_from(path) {
239 Ok(path) => Some((name, path)),
240 Err(path) => {
241 tracing::error!(
242 "proc-macro dylib path is not absolute: {:?}",
243 path
244 );
245 None
246 }
247 };
248 }
249 }
250 None
251 })
252 .collect();
253 for p in rustc.packages() {
254 let package = &rustc[p];
255 bs.outputs[p].proc_macro_dylib_path =
256 if package.targets.iter().any(|&it| {
257 matches!(rustc[it].kind, TargetKind::Lib { is_proc_macro: true })
258 }) {
259 match proc_macro_dylibs.iter().find(|(name, _)| *name == package.name) {
260 Some((_, path)) => ProcMacroDylibPath::Path(path.clone()),
261 _ => ProcMacroDylibPath::DylibNotFound,
262 }
263 } else {
264 ProcMacroDylibPath::NotProcMacro
265 }
266 }
267
268 if tracing::enabled!(tracing::Level::INFO) {
269 for package in rustc.packages() {
270 let package_build_data = &bs.outputs[package];
271 if !package_build_data.is_empty() {
272 tracing::info!("{}: {package_build_data:?}", rustc[package].manifest,);
273 }
274 }
275 }
276 Ok(())
277 })();
278 if let Err::<_, anyhow::Error>(e) = res {
279 bs.error = Some(e.to_string());
280 }
281 bs
282 }
283
284 fn run_per_ws(
285 cmd: Command,
286 workspace: &CargoWorkspace,
287 progress: &dyn Fn(String),
288 ) -> io::Result<WorkspaceBuildScripts> {
289 let mut res = WorkspaceBuildScripts::default();
290 let outputs = &mut res.outputs;
291 let mut by_id: FxHashMap<Arc<PackageId>, Package> = FxHashMap::default();
295 for package in workspace.packages() {
296 outputs.insert(package, BuildScriptOutput::default());
297 by_id.insert(workspace[package].id.clone(), package);
298 }
299
300 res.error = Self::run_command(
301 cmd,
302 |package, cb| {
303 if let Some(&package) = by_id.get(package) {
304 cb(&workspace[package].name, &mut outputs[package]);
305 } else {
306 never!(
307 "Received compiler message for unknown package: {}\n {}",
308 package,
309 by_id.keys().join(", ")
310 );
311 }
312 },
313 progress,
314 )?;
315
316 if tracing::enabled!(tracing::Level::INFO) {
317 for package in workspace.packages() {
318 let package_build_data = &outputs[package];
319 if !package_build_data.is_empty() {
320 tracing::info!("{}: {package_build_data:?}", workspace[package].manifest,);
321 }
322 }
323 }
324
325 Ok(res)
326 }
327
328 fn run_command(
329 cmd: Command,
330 mut with_output_for: impl FnMut(&PackageId, &mut dyn FnMut(&str, &mut BuildScriptOutput)),
334 progress: &dyn Fn(String),
335 ) -> io::Result<Option<String>> {
336 let errors = RefCell::new(String::new());
337 let push_err = |err: &str| {
338 let mut e = errors.borrow_mut();
339 e.push_str(err);
340 e.push('\n');
341 };
342
343 tracing::info!("Running build scripts: {:?}", cmd);
344 let output = stdx::process::spawn_with_streaming_output(
345 cmd,
346 &mut |line| {
347 let mut deserializer = serde_json::Deserializer::from_str(line);
350 deserializer.disable_recursion_limit();
351 let message = Message::deserialize(&mut deserializer)
352 .unwrap_or_else(|_| Message::TextLine(line.to_owned()));
353
354 match message {
355 Message::BuildScriptExecuted(mut message) => {
356 with_output_for(&message.package_id, &mut |name, data| {
357 progress(format!("build script {name} run"));
358 let cfgs = {
359 let mut acc = Vec::new();
360 for cfg in &message.cfgs {
361 match crate::parse_cfg(cfg) {
362 Ok(it) => acc.push(it),
363 Err(err) => {
364 push_err(&format!(
365 "invalid cfg from cargo-metadata: {err}"
366 ));
367 return;
368 }
369 };
370 }
371 acc
372 };
373 data.envs.extend(message.env.drain(..));
374 let out_dir = mem::take(&mut message.out_dir);
377 if !out_dir.as_str().is_empty() {
378 let out_dir = AbsPathBuf::assert(out_dir);
379 data.envs.insert("OUT_DIR", out_dir.as_str());
381 data.out_dir = Some(out_dir);
382 data.cfgs = cfgs;
383 }
384 });
385 }
386 Message::CompilerArtifact(message) => {
387 with_output_for(&message.package_id, &mut |name, data| {
388 if data.proc_macro_dylib_path == ProcMacroDylibPath::NotBuilt {
389 data.proc_macro_dylib_path = ProcMacroDylibPath::NotProcMacro;
390 }
391 if !matches!(data.proc_macro_dylib_path, ProcMacroDylibPath::Path(_))
392 && message
393 .target
394 .kind
395 .contains(&cargo_metadata::TargetKind::ProcMacro)
396 {
397 progress(format!("proc-macro {name} built"));
398 data.proc_macro_dylib_path =
399 match message.filenames.iter().find(|file| is_dylib(file)) {
400 Some(filename) => {
401 let filename = AbsPath::assert(filename);
402 ProcMacroDylibPath::Path(filename.to_owned())
403 }
404 None => ProcMacroDylibPath::DylibNotFound,
405 };
406 }
407 });
408 }
409 Message::CompilerMessage(message) => {
410 progress(format!("received compiler message for: {}", message.target.name));
411
412 if let Some(diag) = message.message.rendered.as_deref() {
413 push_err(diag);
414 }
415 }
416 Message::BuildFinished(_) => {}
417 Message::TextLine(_) => {}
418 _ => {}
419 }
420 },
421 &mut |line| {
422 push_err(line);
423 },
424 )?;
425
426 let errors = if !output.status.success() {
427 let errors = errors.into_inner();
428 Some(if errors.is_empty() { "cargo check failed".to_owned() } else { errors })
429 } else {
430 None
431 };
432 Ok(errors)
433 }
434
435 fn build_command(
436 config: &CargoConfig,
437 allowed_features: &FxHashSet<String>,
438 manifest_path: &ManifestPath,
439 target_dir: &Utf8Path,
440 current_dir: &AbsPath,
441 sysroot: &Sysroot,
442 toolchain: Option<&semver::Version>,
443 ) -> io::Result<(Option<LockfileCopy>, Command)> {
444 match config.run_build_script_command.as_deref() {
445 Some([program, args @ ..]) => {
446 let mut cmd = toolchain::command(program, current_dir, &config.extra_env);
447 cmd.args(args);
448 Ok((None, cmd))
449 }
450 _ => {
451 let mut requires_unstable_options = false;
452 let mut cmd = sysroot.tool(Tool::Cargo, current_dir, &config.extra_env);
453
454 cmd.args(["check", "--quiet", "--workspace", "--message-format=json"]);
455 cmd.args(&config.extra_args);
456 if let Some(config_path) = &config.config_path {
457 cmd.arg("--config").arg(config_path);
458 }
459
460 cmd.arg("--manifest-path");
461 cmd.arg(manifest_path);
462
463 if let Some(target_dir) = config.target_dir_config.target_dir(Some(target_dir)) {
464 cmd.arg("--target-dir");
465 cmd.arg(target_dir.as_ref());
466 }
467
468 toolchain::cargo_use_targets(toolchain, &mut cmd, config.target.as_slice());
469 let mut lockfile_copy = None;
470 if let Some(toolchain) = toolchain {
471 let lockfile_path =
472 <_ as AsRef<Utf8Path>>::as_ref(manifest_path).with_extension("lock");
473 lockfile_copy = make_lockfile_copy(toolchain, &lockfile_path);
474 if let Some(lockfile_copy) = &lockfile_copy {
475 requires_unstable_options = true;
476 match lockfile_copy.usage {
477 LockfileUsage::WithFlag => {
478 cmd.arg("--lockfile-path");
479 cmd.arg(lockfile_copy.path.as_str());
480 }
481 LockfileUsage::WithEnvVarUnstable => {
482 cmd.arg("-Zlockfile-path");
483 cmd.env(
484 "CARGO_RESOLVER_LOCKFILE_PATH",
485 lockfile_copy.path.as_os_str(),
486 );
487 }
488 LockfileUsage::WithEnvVar => {
489 cmd.env(
490 "CARGO_RESOLVER_LOCKFILE_PATH",
491 lockfile_copy.path.as_os_str(),
492 );
493 }
494 }
495 }
496 }
497 match &config.features {
498 CargoFeatures::All => {
499 cmd.arg("--all-features");
500 }
501 CargoFeatures::Selected { features, no_default_features } => {
502 if *no_default_features {
503 cmd.arg("--no-default-features");
504 }
505 if !features.is_empty() {
506 cmd.arg("--features");
507 cmd.arg(
508 features
509 .iter()
510 .filter(|&feat| allowed_features.contains(feat))
511 .join(","),
512 );
513 }
514 }
515 }
516
517 if manifest_path.is_rust_manifest() {
518 requires_unstable_options = true;
519 cmd.arg("-Zscript");
520 }
521
522 cmd.arg("--keep-going");
523
524 const COMP_TIME_DEPS_MIN_TOOLCHAIN_VERSION: semver::Version = semver::Version {
527 major: 1,
528 minor: 89,
529 patch: 0,
530 pre: semver::Prerelease::EMPTY,
531 build: semver::BuildMetadata::EMPTY,
532 };
533
534 let cargo_comp_time_deps_available =
535 toolchain.is_some_and(|v| *v >= COMP_TIME_DEPS_MIN_TOOLCHAIN_VERSION);
536
537 if cargo_comp_time_deps_available {
538 requires_unstable_options = true;
539 cmd.arg("--compile-time-deps");
540 cmd.arg("--all-targets");
543 } else {
544 if config.all_targets {
548 cmd.arg("--all-targets");
549 }
550
551 if config.wrap_rustc_in_build_scripts {
552 let myself = std::env::current_exe()?;
557 cmd.env("RUSTC_WRAPPER", myself);
558 cmd.env("RA_RUSTC_WRAPPER", "1");
559 }
560 }
561 if requires_unstable_options {
562 cmd.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
563 cmd.arg("-Zunstable-options");
564 }
565 Ok((lockfile_copy, cmd))
566 }
567 }
568 }
569}
570
571fn is_dylib(path: &Utf8Path) -> bool {
573 match path.extension().map(|e| e.to_ascii_lowercase()) {
574 None => false,
575 Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
576 }
577}