1pub mod artifact;
32mod build_config;
33pub(crate) mod build_context;
34pub(crate) mod build_runner;
35mod compilation;
36mod compile_kind;
37mod crate_type;
38mod custom_build;
39pub(crate) mod fingerprint;
40pub mod future_incompat;
41pub(crate) mod job_queue;
42pub(crate) mod layout;
43mod links;
44mod locking;
45mod lto;
46mod output_depinfo;
47mod output_sbom;
48pub mod rustdoc;
49pub mod standard_lib;
50pub mod timings;
51pub(crate) mod trim_paths;
52mod unit;
53pub mod unit_dependencies;
54pub mod unit_graph;
55pub mod unused_deps;
56
57use cargo_util::collections::{HashMap, HashSet};
58use std::borrow::Cow;
59use std::cell::OnceCell;
60use std::env;
61use std::ffi::{OsStr, OsString};
62use std::fmt::Display;
63use std::fs::{self, File};
64use std::io::{BufRead, BufWriter, Write};
65use std::ops::{Deref, Range};
66use std::path::{Path, PathBuf};
67use std::sync::{Arc, LazyLock};
68
69use anyhow::{Context as _, Error};
70use cargo_platform::{Cfg, Platform};
71use cargo_util_schemas::core::CrateType;
72use cargo_util_terminal::report::{AnnotationKind, Group, Level, Renderer, Snippet};
73use regex::Regex;
74use tracing::{debug, instrument, trace};
75
76pub use self::build_config::UserIntent;
77pub use self::build_config::{BuildConfig, CompileMode, MessageFormat};
78pub use self::build_context::BuildContext;
79pub use self::build_context::DepKindSet;
80pub use self::build_context::FileFlavor;
81pub use self::build_context::FileType;
82pub use self::build_context::RustcTargetData;
83pub use self::build_context::TargetInfo;
84pub use self::build_runner::{BuildRunner, Metadata, UnitHash};
85pub use self::compilation::{Compilation, Doctest, UnitOutput};
86pub use self::compile_kind::{CompileKind, CompileKindFallback, CompileTarget};
87pub use self::crate_type::CrateTypeExt;
88pub use self::custom_build::LinkArgTarget;
89pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts, LibraryPath};
90pub(crate) use self::fingerprint::DirtyReason;
91pub use self::fingerprint::RustdocFingerprint;
92pub use self::job_queue::Freshness;
93use self::job_queue::{Job, JobQueue, JobState, Work};
94pub(crate) use self::layout::Layout;
95pub use self::lto::Lto;
96use self::output_depinfo::output_depinfo;
97use self::output_sbom::build_sbom;
98use self::trim_paths::trim_paths_args;
99use self::trim_paths::trim_paths_args_rustdoc;
100use self::unit_graph::UnitDep;
101
102use crate::compiler::future_incompat::FutureIncompatReport;
103use crate::compiler::locking::LockKey;
104use crate::compiler::timings::SectionTiming;
105pub use crate::compiler::unit::Unit;
106pub use crate::compiler::unit::UnitIndex;
107pub use crate::compiler::unit::UnitInterner;
108use crate::context::FingerprintMethod;
109use crate::diagnostics::get_key_value;
110use crate::util::OnceExt;
111use crate::util::errors::{CargoResult, VerboseError};
112use crate::util::interning::InternedString;
113use crate::util::machine_message::{self, Message};
114use crate::util::{add_path_args, internal, path_args};
115use crate::workspace::Feature;
116use crate::workspace::PackageId;
117use crate::workspace::Target;
118use crate::workspace::TargetKind;
119use crate::workspace::manifest::TargetSourcePath;
120use crate::workspace::profiles::{PanicStrategy, Profile, StripInner};
121
122use cargo_util::{ExecStats, ProcessBuilder, ProcessError, paths};
123use cargo_util_schemas::manifest::TomlDebugInfo;
124use cargo_util_terminal::Verbosity;
125use rustfix::diagnostics::Applicability;
126
127const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
128
129pub trait Executor: Send + Sync + 'static {
133 fn init(&self, _build_runner: &BuildRunner<'_, '_>, _unit: &Unit) {}
137
138 fn exec(
144 &self,
145 cmd: &ProcessBuilder,
146 id: PackageId,
147 target: &Target,
148 mode: CompileMode,
149 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
150 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
151 capture_rusage: bool,
152 ) -> (ExecStats, CargoResult<()>);
153
154 fn force_rebuild(&self, _unit: &Unit) -> bool {
157 false
158 }
159}
160
161#[derive(Copy, Clone)]
164pub struct DefaultExecutor;
165
166impl Executor for DefaultExecutor {
167 #[instrument(name = "rustc", skip_all, fields(package = id.name().as_str(), process = cmd.to_string()))]
168 fn exec(
169 &self,
170 cmd: &ProcessBuilder,
171 id: PackageId,
172 _target: &Target,
173 _mode: CompileMode,
174 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
175 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
176 capture_rusage: bool,
177 ) -> (ExecStats, CargoResult<()>) {
178 let (stats, result) =
179 cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false, capture_rusage);
180 (stats, result.map(drop))
181 }
182}
183
184#[tracing::instrument(skip(build_runner, jobs, exec))]
194fn compile<'gctx>(
195 build_runner: &mut BuildRunner<'_, 'gctx>,
196 jobs: &mut JobQueue<'gctx>,
197 unit: &Unit,
198 exec: &Arc<dyn Executor>,
199 force_rebuild: bool,
200) -> CargoResult<()> {
201 if !build_runner.compiled.insert(unit.clone()) {
202 return Ok(());
203 }
204
205 let lock = if build_runner.bcx.gctx.cli_unstable().fine_grain_locking {
206 Some(build_runner.lock_manager.lock_shared(build_runner, unit)?)
207 } else {
208 None
209 };
210
211 match build_runner
212 .bcx
213 .gctx
214 .build_config()?
215 .fingerprint
216 .unwrap_or_default()
217 {
218 FingerprintMethod::Content => {
219 if !build_runner.bcx.gctx.cli_unstable().checksum_freshness {
220 build_runner.bcx.gctx.shell().warn(
221 r#"ignoring `build.fingerprint = "content"` without `-Zchecksum-freshness`"#,
222 )?;
223 }
224 }
225 FingerprintMethod::Mtime => {}
226 }
227
228 if !unit.skip_non_compile_time_dep {
232 fingerprint::prepare_init(build_runner, unit)?;
235
236 let job = if unit.mode.is_run_custom_build() {
237 custom_build::prepare(build_runner, unit)?
238 } else if unit.mode.is_doc_test() {
239 Job::new_fresh()
241 } else {
242 let force = exec.force_rebuild(unit) || force_rebuild;
243 let mut job = fingerprint::prepare_target(build_runner, unit, force)?;
244 job.before(if job.freshness().is_dirty() {
245 let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
246 rustdoc(build_runner, unit)?
247 } else {
248 rustc(build_runner, unit, exec)?
249 };
250 work.then(link_targets(build_runner, unit, false)?)
251 } else {
252 let output_options = OutputOptions::for_fresh(build_runner, unit);
253 let manifest = ManifestErrorContext::new(build_runner, unit);
254 let work = replay_output_cache(
255 unit.pkg.package_id(),
256 manifest,
257 &unit.target,
258 build_runner.files().message_cache_path(unit),
259 output_options,
260 );
261 work.then(link_targets(build_runner, unit, true)?)
263 });
264
265 if build_runner.bcx.gctx.cli_unstable().fine_grain_locking && job.freshness().is_dirty()
268 {
269 if let Some(lock) = lock {
270 build_runner.lock_manager.unlock(&lock)?;
277 job.before(prebuild_lock_exclusive(lock.clone()));
278 job.after(downgrade_lock_to_shared(lock));
279 }
280 }
281
282 job
283 };
284 jobs.enqueue(build_runner, unit, job)?;
285 }
286
287 let deps = Vec::from(build_runner.unit_deps(unit)); for dep in deps {
290 compile(build_runner, jobs, &dep.unit, exec, false)?;
291 }
292
293 Ok(())
294}
295
296fn make_failed_scrape_diagnostic(
299 build_runner: &BuildRunner<'_, '_>,
300 unit: &Unit,
301 top_line: impl Display,
302) -> String {
303 let manifest_path = unit.pkg.manifest_path();
304 let relative_manifest_path = manifest_path.trim_prefix(build_runner.bcx.ws.root());
305
306 format!(
307 "\
308{top_line}
309 Try running with `--verbose` to see the error message.
310 If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
311 relative_manifest_path.display()
312 )
313}
314
315#[tracing::instrument(skip_all)]
317fn rustc(
318 build_runner: &mut BuildRunner<'_, '_>,
319 unit: &Unit,
320 exec: &Arc<dyn Executor>,
321) -> CargoResult<Work> {
322 let mut rustc = prepare_rustc(build_runner, unit)?;
323
324 let name = unit.pkg.name();
325
326 let outputs = build_runner.outputs(unit)?;
327 let root = build_runner.files().output_dir(unit);
328
329 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
331 let current_id = unit.pkg.package_id();
332 let manifest = ManifestErrorContext::new(build_runner, unit);
333 let build_scripts = build_runner.build_scripts.get(unit).cloned();
334
335 let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
338
339 let dep_info_name =
340 if let Some(c_extra_filename) = build_runner.files().metadata(unit).c_extra_filename() {
341 format!("{}-{}.d", unit.target.crate_name(), c_extra_filename)
342 } else {
343 format!("{}.d", unit.target.crate_name())
344 };
345 let rustc_dep_info_loc = root.join(dep_info_name);
346 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
347
348 let mut output_options = OutputOptions::for_dirty(build_runner, unit);
349 let package_id = unit.pkg.package_id();
350 let target = Target::clone(&unit.target);
351 let mode = unit.mode;
352 let capture_rusage = build_runner.bcx.capture_rusage();
353
354 exec.init(build_runner, unit);
355 let exec = exec.clone();
356
357 let root_output = build_runner.files().host_dest().map(|v| v.to_path_buf());
358 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
359 let pkg_root = unit.pkg.root().to_path_buf();
360 let ws_root = build_runner.bcx.ws.root().to_path_buf();
361 let cwd = rustc
362 .get_cwd()
363 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
364 .to_path_buf();
365 let timestamp_file = build_runner.files().timestamp_file(unit);
366 let script_metadatas = build_runner.find_build_script_metadatas(unit);
367 let is_local = unit.is_local();
368 let artifact = unit.artifact;
369 let build_dir_new_layout = build_runner.bcx.gctx.cli_unstable().build_dir_new_layout;
370 let sbom_files = build_runner.sbom_output_files(unit)?;
371 let sbom = if !sbom_files.is_empty() {
372 Some(build_sbom(build_runner, unit)?)
373 } else {
374 None
375 };
376
377 let unremap_files = build_runner.unremap_output_files(unit)?;
378 let unremap_content = if unremap_files.is_empty() {
379 None
380 } else {
381 let mut buf = Vec::new();
382 trim_paths::write_unremap_file(&mut buf, build_runner, unit)?;
383 Some(buf)
384 };
385
386 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
387 && !matches!(
388 build_runner.bcx.gctx.shell().verbosity(),
389 Verbosity::Verbose
390 );
391 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
392 let target_desc = unit.target.description_named();
395 let mut for_scrape_units = build_runner
396 .bcx
397 .scrape_units_have_dep_on(unit)
398 .into_iter()
399 .map(|unit| unit.target.description_named())
400 .collect::<Vec<_>>();
401 for_scrape_units.sort();
402 let for_scrape_units = for_scrape_units.join(", ");
403 make_failed_scrape_diagnostic(build_runner, unit, format_args!("failed to check {target_desc} in package `{name}` as a prerequisite for scraping examples from: {for_scrape_units}"))
404 });
405 if hide_diagnostics_for_scrape_unit {
406 output_options.show_diagnostics = false;
407 }
408 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
409 return Ok(Work::new(move |state| {
410 if build_dir_new_layout {
411 if root.exists() {
414 paths::remove_dir_all(&root)?;
415 }
416 paths::create_dir_all(&root)?;
417 } else if artifact.is_true() {
418 paths::create_dir_all(&root)?;
422 }
423
424 if let Some(build_scripts) = build_scripts {
432 let script_outputs = build_script_outputs.lock().unwrap();
433 add_native_deps(
434 &mut rustc,
435 &script_outputs,
436 &build_scripts,
437 pass_l_flag,
438 &target,
439 current_id,
440 mode,
441 )?;
442 if let Some(ref root_output) = root_output {
443 add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, root_output)?;
444 }
445 add_custom_flags(&mut rustc, &script_outputs, script_metadatas)?;
446 }
447
448 if !build_dir_new_layout {
449 for output in outputs.iter() {
450 if output.path.extension() == Some(OsStr::new("rmeta")) {
454 let dst = root.join(&output.path).with_extension("rlib");
455 if dst.exists() {
456 paths::remove_file(&dst)?;
457 }
458 }
459
460 if output.hardlink.is_some() && output.path.exists() {
465 _ = paths::remove_file(&output.path).map_err(|e| {
466 tracing::debug!(
467 "failed to delete previous output file `{:?}`: {e:?}",
468 output.path
469 );
470 });
471 }
472 }
473 }
474
475 state.running(&rustc);
476 let timestamp = paths::set_invocation_time(×tamp_file)?;
477 if let Some(sbom) = sbom {
478 for file in sbom_files {
479 tracing::debug!("writing sbom to {}", file.display());
480 let outfile = BufWriter::new(paths::create(&file)?);
481 serde_json::to_writer(outfile, &sbom)?;
482 }
483 }
484
485 if let Some(content) = &unremap_content {
486 for file in &unremap_files {
487 tracing::debug!("writing unremap file to {}", file.display());
488 paths::write_atomic(file, content)?;
489 }
490 }
491
492 let (stats, result) = exec.exec(
493 &rustc,
494 package_id,
495 &target,
496 mode,
497 &mut |line| on_stdout_line(state, line, package_id, &target),
498 &mut |line| {
499 on_stderr_line(
500 state,
501 line,
502 package_id,
503 &manifest,
504 &target,
505 &mut output_options,
506 )
507 },
508 capture_rusage,
509 );
510 let result = result
511 .map_err(|e| {
512 if output_options.errors_seen == 0 {
513 e
518 } else {
519 verbose_if_simple_exit_code(e)
520 }
521 })
522 .with_context(|| {
523 let warnings = match output_options.warnings_seen {
525 0 => String::new(),
526 1 => "; 1 warning emitted".to_string(),
527 count => format!("; {} warnings emitted", count),
528 };
529 let errors = match output_options.errors_seen {
530 0 => String::new(),
531 1 => " due to 1 previous error".to_string(),
532 count => format!(" due to {} previous errors", count),
533 };
534 let name = descriptive_pkg_name(&name, &target, &mode);
535 format!("could not compile {name}{errors}{warnings}")
536 });
537
538 if let Some(peak_memory) = stats.peak_rss {
539 state.peak_memory(peak_memory);
540 }
541
542 if let Err(e) = result {
543 if let Some(diagnostic) = failed_scrape_diagnostic {
544 state.warning(diagnostic);
545 }
546
547 return Err(e);
548 }
549
550 debug_assert_eq!(output_options.errors_seen, 0);
552
553 if rustc_dep_info_loc.exists() {
554 fingerprint::translate_dep_info(
555 &rustc_dep_info_loc,
556 &dep_info_loc,
557 &cwd,
558 &pkg_root,
559 &build_dir,
560 &ws_root,
561 &rustc,
562 is_local,
564 &env_config,
565 )
566 .with_context(|| {
567 internal(format!(
568 "could not parse/generate dep info at: {}",
569 rustc_dep_info_loc.display()
570 ))
571 })?;
572 paths::set_file_time_no_err(dep_info_loc, timestamp);
575 }
576
577 Ok(())
578 }));
579
580 fn add_native_deps(
583 rustc: &mut ProcessBuilder,
584 build_script_outputs: &BuildScriptOutputs,
585 build_scripts: &BuildScripts,
586 pass_l_flag: bool,
587 target: &Target,
588 current_id: PackageId,
589 mode: CompileMode,
590 ) -> CargoResult<()> {
591 let mut library_paths = vec![];
592
593 for key in build_scripts.to_link.iter() {
594 let output = build_script_outputs.get(key.1).ok_or_else(|| {
595 internal(format!(
596 "couldn't find build script output for {}/{}",
597 key.0, key.1
598 ))
599 })?;
600 library_paths.extend(output.library_paths.iter());
601 }
602
603 library_paths.sort_by_key(|p| match p {
609 LibraryPath::CargoArtifact(_) => 0,
610 LibraryPath::External(_) => 1,
611 });
612
613 for path in library_paths.iter() {
614 rustc.arg("-L").arg(path.as_ref());
615 }
616
617 for key in build_scripts.to_link.iter() {
618 let output = build_script_outputs.get(key.1).ok_or_else(|| {
619 internal(format!(
620 "couldn't find build script output for {}/{}",
621 key.0, key.1
622 ))
623 })?;
624
625 if key.0 == current_id {
626 if pass_l_flag {
627 for name in output.library_links.iter() {
628 rustc.arg("-l").arg(name);
629 }
630 }
631 }
632
633 for (lt, arg) in &output.linker_args {
634 if lt.applies_to(target, mode)
640 && (key.0 == current_id || *lt == LinkArgTarget::Cdylib)
641 {
642 rustc.arg("-C").arg(format!("link-arg={}", arg));
643 }
644 }
645 }
646 Ok(())
647 }
648}
649
650fn verbose_if_simple_exit_code(err: Error) -> Error {
651 match err
654 .downcast_ref::<ProcessError>()
655 .as_ref()
656 .and_then(|perr| perr.code)
657 {
658 Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
659 _ => err,
660 }
661}
662
663fn prebuild_lock_exclusive(lock: LockKey) -> Work {
664 Work::new(move |state| {
665 state.lock_exclusive(&lock)?;
666 Ok(())
667 })
668}
669
670fn downgrade_lock_to_shared(lock: LockKey) -> Work {
671 Work::new(move |state| {
672 state.downgrade_to_shared(&lock)?;
673 Ok(())
674 })
675}
676
677fn link_targets(
680 build_runner: &mut BuildRunner<'_, '_>,
681 unit: &Unit,
682 fresh: bool,
683) -> CargoResult<Work> {
684 let bcx = build_runner.bcx;
685 let outputs = build_runner.outputs(unit)?;
686 let export_dir = build_runner.files().export_dir();
687 let package_id = unit.pkg.package_id();
688 let manifest_path = PathBuf::from(unit.pkg.manifest_path());
689 let profile = unit.profile.clone();
690 let unit_mode = unit.mode;
691 let features = unit.features.iter().map(|s| s.to_string()).collect();
692 let json_messages = bcx.build_config.emit_json();
693 let executable = build_runner.get_executable(unit)?;
694 let mut target = Target::clone(&unit.target);
695 if let TargetSourcePath::Metabuild = target.src_path() {
696 let path = unit
698 .pkg
699 .manifest()
700 .metabuild_path(build_runner.bcx.ws.build_dir());
701 target.set_src_path(TargetSourcePath::Path(path));
702 }
703
704 Ok(Work::new(move |state| {
705 let mut destinations = vec![];
710 for output in outputs.iter() {
711 let src = &output.path;
712 if !src.exists() {
715 continue;
716 }
717 let Some(dst) = output.hardlink.as_ref() else {
718 destinations.push(src.clone());
719 continue;
720 };
721 destinations.push(dst.clone());
722 paths::link_or_copy(src, dst)?;
723 if let Some(ref path) = output.export_path {
724 let export_dir = export_dir.as_ref().unwrap();
725 paths::create_dir_all(export_dir)?;
726
727 paths::link_or_copy(src, path)?;
728 }
729 }
730
731 if json_messages {
732 let debuginfo = match profile.debuginfo.into_inner() {
733 TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
734 TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
735 TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
736 TomlDebugInfo::LineDirectivesOnly => {
737 machine_message::ArtifactDebuginfo::Named("line-directives-only")
738 }
739 TomlDebugInfo::LineTablesOnly => {
740 machine_message::ArtifactDebuginfo::Named("line-tables-only")
741 }
742 };
743 let art_profile = machine_message::ArtifactProfile {
744 opt_level: profile.opt_level.as_str(),
745 debuginfo: Some(debuginfo),
746 debug_assertions: profile.debug_assertions,
747 overflow_checks: profile.overflow_checks,
748 test: unit_mode.is_any_test(),
749 };
750
751 let msg = machine_message::Artifact {
752 package_id: package_id.to_spec(),
753 manifest_path,
754 target: &target,
755 profile: art_profile,
756 features,
757 filenames: destinations,
758 executable,
759 fresh,
760 }
761 .to_json_string();
762 state.stdout(msg)?;
763 }
764 Ok(())
765 }))
766}
767
768fn add_plugin_deps(
772 rustc: &mut ProcessBuilder,
773 build_script_outputs: &BuildScriptOutputs,
774 build_scripts: &BuildScripts,
775 root_output: &Path,
776) -> CargoResult<()> {
777 let var = paths::dylib_path_envvar();
778 let search_path = rustc.get_env(var).unwrap_or_default();
779 let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
780 for (pkg_id, metadata) in &build_scripts.plugins {
781 let output = build_script_outputs
782 .get(*metadata)
783 .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
784 search_path.append(&mut filter_dynamic_search_path(
785 output.library_paths.iter().map(AsRef::as_ref),
786 root_output,
787 ));
788 }
789 let search_path = paths::join_paths(&search_path, var)?;
790 rustc.env(var, &search_path);
791 Ok(())
792}
793
794fn get_dynamic_search_path(path: &Path) -> &Path {
795 match path.to_str().and_then(|s| s.split_once("=")) {
796 Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => Path::new(path),
797 _ => path,
798 }
799}
800
801fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
807where
808 I: Iterator<Item = &'a PathBuf>,
809{
810 let mut search_path = vec![];
811 for dir in paths {
812 let dir = get_dynamic_search_path(dir);
813 if dir.starts_with(&root_output) {
814 search_path.push(dir.to_path_buf());
815 } else {
816 debug!(
817 "Not including path {} in runtime library search path because it is \
818 outside target root {}",
819 dir.display(),
820 root_output.display()
821 );
822 }
823 }
824 search_path
825}
826
827#[tracing::instrument(skip_all)]
834fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
835 let gctx = build_runner.bcx.gctx;
836 let is_primary = build_runner.is_primary_package(unit);
837 let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg);
838
839 let mut base = build_runner
840 .compilation
841 .rustc_process(unit, is_primary, is_workspace)?;
842 build_base_args(build_runner, &mut base, unit)?;
843 if unit.pkg.manifest().is_embedded() {
844 if !gctx.cli_unstable().script {
845 anyhow::bail!(
846 "parsing `{}` requires `-Zscript`",
847 unit.pkg.manifest_path().display()
848 );
849 }
850 base.arg("-Z").arg("crate-attr=feature(frontmatter)");
851 base.arg("-Z").arg("crate-attr=allow(unused_features)");
852 }
853
854 base.inherit_jobserver(&build_runner.jobserver);
855 build_deps_args(&mut base, build_runner, unit)?;
856 add_cap_lints(build_runner.bcx, unit, &mut base);
857 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
858 base.args(args);
859 }
860 base.args(&unit.rustflags);
861
862 if unit.target.is_lib() && unit.mode.is_rustc_test() {
865 base.arg("-Adead_code_pub_in_binary");
866 }
867 if gctx.cli_unstable().binary_dep_depinfo {
868 base.arg("-Z").arg("binary-dep-depinfo");
869 }
870 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
871 match build_runner
872 .bcx
873 .gctx
874 .build_config()?
875 .fingerprint
876 .unwrap_or_default()
877 {
878 FingerprintMethod::Content => {
879 base.arg("-Z").arg("checksum-hash-algorithm=blake3");
880 }
881 FingerprintMethod::Mtime => {}
882 }
883 }
884
885 if is_primary {
886 base.env("CARGO_PRIMARY_PACKAGE", "1");
887 let file_list = build_runner.sbom_output_files(unit)?;
888 if !file_list.is_empty() {
889 let file_list = std::env::join_paths(file_list)?;
890 base.env("CARGO_SBOM_PATH", file_list);
891 }
892 }
893
894 if unit.target.is_test() || unit.target.is_bench() {
895 let tmp = build_runner
896 .files()
897 .layout(unit.kind)
898 .build_dir()
899 .prepare_tmp()?;
900 base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
901 }
902
903 base.arg("--force-warn=unused_crate_dependencies");
906
907 Ok(base)
908}
909
910#[tracing::instrument(skip_all)]
917fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
918 let bcx = build_runner.bcx;
919 let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
921 let wants_json_output = build_runner.bcx.build_config.intent.wants_doc_json_output();
922 if unit.pkg.manifest().is_embedded() {
923 if !bcx.gctx.cli_unstable().script {
924 anyhow::bail!(
925 "parsing `{}` requires `-Zscript`",
926 unit.pkg.manifest_path().display()
927 );
928 }
929 rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
930 rustdoc.arg("-Z").arg("crate-attr=allow(unused_features)");
931 }
932 rustdoc.inherit_jobserver(&build_runner.jobserver);
933 let crate_name = unit.target.crate_name();
934 rustdoc.arg("--crate-name").arg(&crate_name);
935 add_path_args(bcx.ws, unit, &mut rustdoc);
936 add_cap_lints(bcx, unit, &mut rustdoc);
937
938 unit.kind.add_target_arg(&mut rustdoc);
939
940 let doc_dir = if wants_json_output {
941 build_runner.files().out_dir_new_layout(unit)
945 } else {
946 build_runner.files().output_dir(unit)
947 };
948
949 rustdoc.arg("-o").arg(&doc_dir);
950 rustdoc.args(&features_args(unit));
951 rustdoc.args(&check_cfg_args(unit));
952
953 add_error_format_and_color(build_runner, &mut rustdoc);
954 add_allow_features(build_runner, &mut rustdoc);
955
956 if build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo {
957 let mut arg = if wants_json_output {
960 OsString::from("--emit=dep-info=")
961 } else if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
962 OsString::from("--emit=html-non-static-files,dep-info=")
964 } else {
965 OsString::from("--emit=html-static-files,html-non-static-files,dep-info=")
967 };
968 arg.push(rustdoc_dep_info_loc(build_runner, unit));
969 rustdoc.arg(arg);
970
971 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
972 match build_runner
973 .bcx
974 .gctx
975 .build_config()?
976 .fingerprint
977 .unwrap_or_default()
978 {
979 FingerprintMethod::Content => {
980 rustdoc.arg("-Z").arg("checksum-hash-algorithm=blake3");
981 }
982 FingerprintMethod::Mtime => {}
983 }
984 }
985 } else if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info && !wants_json_output {
986 rustdoc.arg("--emit=html-non-static-files");
988 }
989
990 if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info && !wants_json_output {
991 rustdoc.arg("-Zunstable-options");
993 let mut arg = OsString::from("--write-doc-meta-dir=");
994 arg.push(build_runner.files().out_dir_new_layout(unit));
996 rustdoc.arg(arg);
997 }
998
999 trim_paths_args_rustdoc(&mut rustdoc, build_runner, unit, &unit.profile.trim_paths)?;
1000
1001 rustdoc.args(unit.pkg.manifest().lint_rustflags());
1002
1003 let metadata = build_runner.metadata_for_doc_units[unit];
1004 rustdoc
1005 .arg("-C")
1006 .arg(format!("metadata={}", metadata.c_metadata()));
1007
1008 if unit.mode.is_doc_scrape() {
1009 debug_assert!(build_runner.bcx.scrape_units.contains(unit));
1010
1011 if unit.target.is_test() {
1012 rustdoc.arg("--scrape-tests");
1013 }
1014
1015 rustdoc.arg("-Zunstable-options");
1016
1017 rustdoc
1018 .arg("--scrape-examples-output-path")
1019 .arg(scrape_output_path(build_runner, unit)?);
1020
1021 for pkg in build_runner.bcx.packages.packages() {
1023 let names = pkg
1024 .targets()
1025 .iter()
1026 .map(|target| target.crate_name())
1027 .collect::<HashSet<_>>();
1028 for name in names {
1029 rustdoc.arg("--scrape-examples-target-crate").arg(name);
1030 }
1031 }
1032 }
1033
1034 if should_include_scrape_units(build_runner.bcx, unit) {
1035 rustdoc.arg("-Zunstable-options");
1036 }
1037
1038 build_deps_args(&mut rustdoc, build_runner, unit)?;
1039 rustdoc::add_root_urls(build_runner, unit, &mut rustdoc)?;
1040
1041 rustdoc::add_output_format(build_runner, &mut rustdoc)?;
1042
1043 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
1044 rustdoc.args(args);
1045 }
1046 rustdoc.args(&unit.rustdocflags);
1047
1048 if !crate_version_flag_already_present(&rustdoc) {
1049 append_crate_version_flag(unit, &mut rustdoc);
1050 }
1051
1052 Ok(rustdoc)
1053}
1054
1055#[tracing::instrument(skip_all)]
1057fn rustdoc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Work> {
1058 let mut rustdoc = prepare_rustdoc(build_runner, unit)?;
1059
1060 let crate_name = unit.target.crate_name();
1061 let is_json_output = build_runner.bcx.build_config.intent.wants_doc_json_output();
1062 let doc_dir = build_runner.files().output_dir(unit);
1063 paths::create_dir_all(&doc_dir)?;
1067
1068 let target_desc = unit.target.description_named();
1069 let name = unit.pkg.name();
1070 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
1071 let package_id = unit.pkg.package_id();
1072 let target = Target::clone(&unit.target);
1073 let manifest = ManifestErrorContext::new(build_runner, unit);
1074
1075 let rustdoc_dep_info_loc = rustdoc_dep_info_loc(build_runner, unit);
1076 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
1077 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
1078 let pkg_root = unit.pkg.root().to_path_buf();
1079 let ws_root = build_runner.bcx.ws.root().to_path_buf();
1080 let cwd = rustdoc
1081 .get_cwd()
1082 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
1083 .to_path_buf();
1084 let timestamp_file = build_runner.files().timestamp_file(unit);
1085 let is_local = unit.is_local();
1086 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
1087 let capture_rusage = build_runner.bcx.capture_rusage();
1088 let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
1089
1090 let mut output_options = OutputOptions::for_dirty(build_runner, unit);
1091 let script_metadatas = build_runner.find_build_script_metadatas(unit);
1092 let scrape_outputs = if should_include_scrape_units(build_runner.bcx, unit) {
1093 Some(
1094 build_runner
1095 .bcx
1096 .scrape_units
1097 .iter()
1098 .map(|unit| {
1099 Ok((
1100 build_runner.files().metadata(unit).unit_id(),
1101 scrape_output_path(build_runner, unit)?,
1102 ))
1103 })
1104 .collect::<CargoResult<HashMap<_, _>>>()?,
1105 )
1106 } else {
1107 None
1108 };
1109
1110 let failed_scrape_units = Arc::clone(&build_runner.failed_scrape_units);
1111 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
1112 && !matches!(
1113 build_runner.bcx.gctx.shell().verbosity(),
1114 Verbosity::Verbose
1115 );
1116 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
1117 make_failed_scrape_diagnostic(
1118 build_runner,
1119 unit,
1120 format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
1121 )
1122 });
1123 if hide_diagnostics_for_scrape_unit {
1124 output_options.show_diagnostics = false;
1125 }
1126
1127 Ok(Work::new(move |state| {
1128 add_custom_flags(
1129 &mut rustdoc,
1130 &build_script_outputs.lock().unwrap(),
1131 script_metadatas,
1132 )?;
1133
1134 if let Some(scrape_outputs) = scrape_outputs {
1139 let failed_scrape_units = failed_scrape_units.lock().unwrap();
1140 for (metadata, output_path) in &scrape_outputs {
1141 if !failed_scrape_units.contains(metadata) {
1142 rustdoc.arg("--with-examples").arg(output_path);
1143 }
1144 }
1145 }
1146
1147 if !is_json_output {
1148 let crate_dir = doc_dir.join(&crate_name);
1149 if crate_dir.exists() {
1150 debug!("removing pre-existing doc directory {:?}", crate_dir);
1153 paths::remove_dir_all(&crate_dir)?;
1154 }
1155 };
1156 state.running(&rustdoc);
1157 let timestamp = paths::set_invocation_time(×tamp_file)?;
1158
1159 let (stats, result) = rustdoc.exec_with_streaming(
1160 &mut |line| on_stdout_line(state, line, package_id, &target),
1161 &mut |line| {
1162 on_stderr_line(
1163 state,
1164 line,
1165 package_id,
1166 &manifest,
1167 &target,
1168 &mut output_options,
1169 )
1170 },
1171 false,
1172 capture_rusage,
1173 );
1174 let result = result
1175 .map_err(verbose_if_simple_exit_code)
1176 .with_context(|| format!("could not document `{}`", name));
1177
1178 if let Some(peak_memory) = stats.peak_rss {
1179 state.peak_memory(peak_memory);
1180 }
1181
1182 if let Err(e) = result {
1183 if let Some(diagnostic) = failed_scrape_diagnostic {
1184 state.warning(diagnostic);
1185 }
1186
1187 return Err(e);
1188 }
1189 if rustdoc_depinfo_enabled && rustdoc_dep_info_loc.exists() {
1190 fingerprint::translate_dep_info(
1191 &rustdoc_dep_info_loc,
1192 &dep_info_loc,
1193 &cwd,
1194 &pkg_root,
1195 &build_dir,
1196 &ws_root,
1197 &rustdoc,
1198 is_local,
1200 &env_config,
1201 )
1202 .with_context(|| {
1203 internal(format_args!(
1204 "could not parse/generate dep info at: {}",
1205 rustdoc_dep_info_loc.display()
1206 ))
1207 })?;
1208 paths::set_file_time_no_err(dep_info_loc, timestamp);
1211 }
1212
1213 Ok(())
1214 }))
1215}
1216
1217fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
1220 rustdoc.get_args().any(|flag| {
1221 flag.to_str()
1222 .map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
1223 })
1224}
1225
1226fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
1227 rustdoc
1228 .arg(RUSTDOC_CRATE_VERSION_FLAG)
1229 .arg(unit.pkg.version().to_string());
1230}
1231
1232enum CapLints {
1233 Allow,
1234 Warn,
1235}
1236
1237fn compute_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit) -> Option<CapLints> {
1238 if !unit.show_warnings(bcx.gctx) {
1241 Some(CapLints::Allow)
1242 } else if !unit.is_local() {
1245 Some(CapLints::Warn)
1246 } else {
1247 None
1248 }
1249}
1250
1251fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
1255 if let Some(cap_lints) = compute_cap_lints(bcx, unit) {
1256 match cap_lints {
1257 CapLints::Allow => {
1258 cmd.arg("--cap-lints").arg("allow");
1259 }
1260 CapLints::Warn => {
1261 cmd.arg("--cap-lints").arg("warn");
1262 }
1263 }
1264 }
1265}
1266
1267fn add_allow_features(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1271 if let Some(allow) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1272 use std::fmt::Write;
1273 let mut arg = String::from("-Zallow-features=");
1274 for f in allow {
1275 let _ = write!(&mut arg, "{f},");
1276 }
1277 cmd.arg(arg.trim_end_matches(','));
1278 }
1279}
1280
1281fn add_error_format_and_color(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1292 let enable_timings =
1293 build_runner.bcx.gctx.cli_unstable().section_timings && build_runner.bcx.logger.is_some();
1294 if enable_timings {
1295 cmd.arg("-Zunstable-options");
1296 }
1297
1298 cmd.arg("--error-format=json");
1299
1300 let mut json = String::from(
1301 "--json=diagnostic-rendered-ansi,artifacts,future-incompat,unused-externs-silent",
1302 );
1303 if let MessageFormat::Short | MessageFormat::Json { short: true, .. } =
1304 build_runner.bcx.build_config.message_format
1305 {
1306 json.push_str(",diagnostic-short");
1307 } else if build_runner.bcx.gctx.shell().err_unicode()
1308 && build_runner.bcx.gctx.cli_unstable().rustc_unicode
1309 {
1310 json.push_str(",diagnostic-unicode");
1311 }
1312
1313 if !build_runner.bcx.gctx.shell().graphics()
1314 && build_runner.bcx.gctx.cli_unstable().term_graphics
1315 {
1316 json.push_str(",diagnostic-no-graphics");
1317 }
1318
1319 if enable_timings {
1320 json.push_str(",timings");
1321 }
1322 cmd.arg(json);
1323
1324 let gctx = build_runner.bcx.gctx;
1325 if let Some(width) = gctx.shell().err_width().diagnostic_terminal_width() {
1326 cmd.arg(format!("--diagnostic-width={width}"));
1327 }
1328}
1329
1330fn build_base_args(
1332 build_runner: &BuildRunner<'_, '_>,
1333 cmd: &mut ProcessBuilder,
1334 unit: &Unit,
1335) -> CargoResult<()> {
1336 assert!(!unit.mode.is_run_custom_build());
1337
1338 let bcx = build_runner.bcx;
1339 let Profile {
1340 ref opt_level,
1341 codegen_backend,
1342 codegen_units,
1343 debuginfo,
1344 debug_assertions,
1345 split_debuginfo,
1346 overflow_checks,
1347 rpath,
1348 ref panic,
1349 incremental,
1350 strip,
1351 rustflags: profile_rustflags,
1352 trim_paths,
1353 hint_mostly_unused: profile_hint_mostly_unused,
1354 ..
1355 } = unit.profile.clone();
1356 let hints = unit.pkg.hints().cloned().unwrap_or_default();
1357 let test = unit.mode.is_any_test();
1358
1359 cmd.arg("--crate-name").arg(&unit.target.crate_name());
1360
1361 let edition = unit.target.edition();
1362 edition.cmd_edition_arg(cmd);
1363
1364 add_path_args(bcx.ws, unit, cmd);
1365 add_error_format_and_color(build_runner, cmd);
1366 add_allow_features(build_runner, cmd);
1367
1368 let mut contains_dy_lib = false;
1369 if !test {
1370 for crate_type in &unit.target.rustc_crate_types() {
1371 cmd.arg("--crate-type").arg(crate_type.as_str());
1372 contains_dy_lib |= crate_type == &CrateType::Dylib;
1373 }
1374 }
1375
1376 if unit.mode.is_check() {
1377 cmd.arg("--emit=dep-info,metadata");
1378 } else if !build_runner
1379 .bcx
1380 .target_data
1381 .info(unit.kind)
1382 .should_embed_metadata()
1383 {
1384 if unit.benefits_from_no_embed_metadata() {
1394 cmd.arg("--emit=dep-info,metadata,link");
1395 cmd.args(&["-Z", "embed-metadata=no"]);
1396 } else {
1397 cmd.arg("--emit=dep-info,link");
1398 }
1399 } else {
1400 if !unit.requires_upstream_objects() {
1404 cmd.arg("--emit=dep-info,metadata,link");
1405 } else {
1406 cmd.arg("--emit=dep-info,link");
1407 }
1408 }
1409
1410 let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
1411 || (contains_dy_lib && !build_runner.is_primary_package(unit));
1412 if prefer_dynamic {
1413 cmd.arg("-C").arg("prefer-dynamic");
1414 }
1415
1416 if opt_level.as_str() != "0" {
1417 cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
1418 }
1419
1420 if *panic != PanicStrategy::Unwind {
1421 cmd.arg("-C").arg(format!("panic={}", panic));
1422 }
1423 if *panic == PanicStrategy::ImmediateAbort {
1424 cmd.arg("-Z").arg("unstable-options");
1425 }
1426
1427 cmd.args(<o_args(build_runner, unit));
1428
1429 if let Some(backend) = codegen_backend {
1430 cmd.arg("-Z").arg(&format!("codegen-backend={}", backend));
1431 }
1432
1433 if let Some(n) = codegen_units {
1434 cmd.arg("-C").arg(&format!("codegen-units={}", n));
1435 }
1436
1437 let debuginfo = debuginfo.into_inner();
1438 if debuginfo != TomlDebugInfo::None {
1440 cmd.arg("-C").arg(format!("debuginfo={debuginfo}"));
1441 if let Some(split) = split_debuginfo {
1448 if build_runner
1449 .bcx
1450 .target_data
1451 .info(unit.kind)
1452 .supports_debuginfo_split(split)
1453 {
1454 cmd.arg("-C").arg(format!("split-debuginfo={split}"));
1455 }
1456 }
1457 }
1458
1459 trim_paths_args(cmd, build_runner, unit, &trim_paths)?;
1460
1461 match compute_cap_lints(bcx, unit) {
1462 None | Some(CapLints::Warn) => {
1463 cmd.args(unit.pkg.manifest().lint_rustflags());
1464 }
1465 Some(CapLints::Allow) => {}
1468 }
1469 cmd.args(&profile_rustflags);
1470
1471 if opt_level.as_str() != "0" {
1475 if debug_assertions {
1476 cmd.args(&["-C", "debug-assertions=on"]);
1477 if !overflow_checks {
1478 cmd.args(&["-C", "overflow-checks=off"]);
1479 }
1480 } else if overflow_checks {
1481 cmd.args(&["-C", "overflow-checks=on"]);
1482 }
1483 } else if !debug_assertions {
1484 cmd.args(&["-C", "debug-assertions=off"]);
1485 if overflow_checks {
1486 cmd.args(&["-C", "overflow-checks=on"]);
1487 }
1488 } else if !overflow_checks {
1489 cmd.args(&["-C", "overflow-checks=off"]);
1490 }
1491
1492 if test && unit.target.harness() {
1493 cmd.arg("--test");
1494
1495 if *panic == PanicStrategy::Abort || *panic == PanicStrategy::ImmediateAbort {
1503 cmd.arg("-Z").arg("panic-abort-tests");
1504 }
1505 } else if test {
1506 cmd.arg("--cfg").arg("test");
1507 }
1508
1509 cmd.args(&features_args(unit));
1510 cmd.args(&check_cfg_args(unit));
1511
1512 let meta = build_runner.files().metadata(unit);
1513 cmd.arg("-C")
1514 .arg(&format!("metadata={}", meta.c_metadata()));
1515 if let Some(c_extra_filename) = meta.c_extra_filename() {
1516 cmd.arg("-C")
1517 .arg(&format!("extra-filename=-{c_extra_filename}"));
1518 }
1519
1520 if rpath {
1521 cmd.arg("-C").arg("rpath");
1522 }
1523
1524 cmd.arg("--out-dir")
1525 .arg(&build_runner.files().output_dir(unit));
1526
1527 unit.kind.add_target_arg(cmd);
1528
1529 add_codegen_linker(cmd, build_runner, unit, bcx.gctx.target_applies_to_host()?);
1530
1531 if incremental {
1532 add_codegen_incremental(cmd, build_runner, unit)
1533 }
1534
1535 let pkg_hint_mostly_unused = match hints.mostly_unused {
1536 Some(toml::Value::Boolean(b)) => Some(b),
1537 _ => None,
1540 };
1541 if profile_hint_mostly_unused
1542 .or(pkg_hint_mostly_unused)
1543 .unwrap_or(false)
1544 && bcx.gctx.cli_unstable().profile_hint_mostly_unused
1545 {
1546 cmd.arg("-Zhint-mostly-unused");
1547 }
1548
1549 let strip = strip.into_inner();
1550 if strip != StripInner::None {
1551 cmd.arg("-C").arg(format!("strip={}", strip));
1552 }
1553
1554 if unit.is_std {
1555 cmd.arg("-Z")
1561 .arg("force-unstable-if-unmarked")
1562 .env("RUSTC_BOOTSTRAP", "1");
1563 }
1564
1565 if let Some(version) = unit.pkg.manifest().rust_version()
1566 && bcx.gctx.cli_unstable().hint_msrv
1567 {
1568 cmd.arg("-Z").arg(format!("hint-msrv={version}"));
1569 }
1570
1571 Ok(())
1572}
1573
1574fn features_args(unit: &Unit) -> Vec<OsString> {
1576 let mut args = Vec::with_capacity(unit.features.len() * 2);
1577
1578 for feat in &unit.features {
1579 args.push(OsString::from("--cfg"));
1580 args.push(OsString::from(format!("feature=\"{}\"", feat)));
1581 }
1582
1583 args
1584}
1585
1586fn check_cfg_args(unit: &Unit) -> Vec<OsString> {
1588 let gross_cap_estimation = unit.pkg.summary().features().len() * 7 + 25;
1606 let mut arg_feature = OsString::with_capacity(gross_cap_estimation);
1607
1608 arg_feature.push("cfg(feature, values(");
1609 for (i, feature) in unit.pkg.summary().features().keys().enumerate() {
1610 if i != 0 {
1611 arg_feature.push(", ");
1612 }
1613 arg_feature.push("\"");
1614 arg_feature.push(feature);
1615 arg_feature.push("\"");
1616 }
1617 arg_feature.push("))");
1618
1619 vec![
1628 OsString::from("--check-cfg"),
1629 OsString::from("cfg(docsrs,test)"),
1630 OsString::from("--check-cfg"),
1631 arg_feature,
1632 ]
1633}
1634
1635fn lto_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1637 let mut result = Vec::new();
1638 let mut push = |arg: &str| {
1639 result.push(OsString::from("-C"));
1640 result.push(OsString::from(arg));
1641 };
1642 match build_runner.lto[unit] {
1643 lto::Lto::Run(None) => push("lto"),
1644 lto::Lto::Run(Some(s)) => push(&format!("lto={}", s)),
1645 lto::Lto::Off => {
1646 push("lto=off");
1647 push("embed-bitcode=no");
1648 }
1649 lto::Lto::ObjectAndBitcode => {} lto::Lto::OnlyBitcode => push("linker-plugin-lto"),
1651 lto::Lto::OnlyObject => push("embed-bitcode=no"),
1652 }
1653 result
1654}
1655
1656fn build_deps_args(
1662 cmd: &mut ProcessBuilder,
1663 build_runner: &BuildRunner<'_, '_>,
1664 unit: &Unit,
1665) -> CargoResult<()> {
1666 let bcx = build_runner.bcx;
1667
1668 for arg in lib_search_paths(build_runner, unit)? {
1669 cmd.arg(arg);
1670 }
1671
1672 let deps = build_runner.unit_deps(unit);
1673
1674 if !deps
1678 .iter()
1679 .any(|dep| !dep.unit.mode.is_doc() && dep.unit.target.is_linkable())
1680 {
1681 if let Some(dep) = deps.iter().find(|dep| {
1682 !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true()
1683 }) {
1684 let dep_name = dep.unit.target.crate_name();
1685 let name = unit.target.crate_name();
1686 bcx.gctx.shell().print_report(&[
1687 Level::WARNING.secondary_title(format!("the package `{dep_name}` provides no linkable target"))
1688 .elements([
1689 Level::NOTE.message(format!("this might cause `{name}` to fail compilation")),
1690 Level::NOTE.message("this warning might turn into a hard error in the future"),
1691 Level::HELP.message(format!("consider adding 'dylib' or 'rlib' to key 'crate-type' in `{dep_name}`'s Cargo.toml"))
1692 ])
1693 ], false)?;
1694 }
1695 }
1696
1697 let mut unstable_opts = false;
1698
1699 let first_custom_build_dep = deps.iter().find(|dep| dep.unit.mode.is_run_custom_build());
1701 if let Some(dep) = first_custom_build_dep {
1702 let out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
1703 build_runner.files().out_dir_new_layout(&dep.unit)
1704 } else {
1705 build_runner.files().build_script_out_dir(&dep.unit)
1706 };
1707 cmd.env("OUT_DIR", &out_dir);
1708 }
1709
1710 let is_multiple_build_scripts_enabled = unit
1712 .pkg
1713 .manifest()
1714 .unstable_features()
1715 .require(Feature::multiple_build_scripts())
1716 .is_ok();
1717
1718 if is_multiple_build_scripts_enabled {
1719 for dep in deps {
1720 if dep.unit.mode.is_run_custom_build() {
1721 let out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
1722 build_runner.files().out_dir_new_layout(&dep.unit)
1723 } else {
1724 build_runner.files().build_script_out_dir(&dep.unit)
1725 };
1726 let target_name = dep.unit.target.name();
1727 let out_dir_prefix = target_name.trim_prefix("build-script-");
1728 let out_dir_name = format!("{out_dir_prefix}_OUT_DIR");
1729 cmd.env(&out_dir_name, &out_dir);
1730 }
1731 }
1732 }
1733 for arg in extern_args(build_runner, unit, &mut unstable_opts)? {
1734 cmd.arg(arg);
1735 }
1736
1737 for (var, env) in artifact::get_env(build_runner, unit, deps)? {
1738 cmd.env(&var, env);
1739 }
1740
1741 if unstable_opts {
1744 cmd.arg("-Z").arg("unstable-options");
1745 }
1746
1747 Ok(())
1748}
1749
1750fn add_custom_flags(
1754 cmd: &mut ProcessBuilder,
1755 build_script_outputs: &BuildScriptOutputs,
1756 metadata_vec: Option<Vec<UnitHash>>,
1757) -> CargoResult<()> {
1758 if let Some(metadata_vec) = metadata_vec {
1759 for metadata in metadata_vec {
1760 if let Some(output) = build_script_outputs.get(metadata) {
1761 for cfg in output.cfgs.iter() {
1762 cmd.arg("--cfg").arg(cfg);
1763 }
1764 for check_cfg in &output.check_cfgs {
1765 cmd.arg("--check-cfg").arg(check_cfg);
1766 }
1767 for (name, value) in output.env.iter() {
1768 cmd.env(name, value);
1769 }
1770 }
1771 }
1772 }
1773
1774 Ok(())
1775}
1776
1777#[tracing::instrument(skip_all)]
1779pub fn lib_search_paths(
1780 build_runner: &BuildRunner<'_, '_>,
1781 unit: &Unit,
1782) -> CargoResult<Vec<OsString>> {
1783 let mut lib_search_paths = Vec::new();
1784 if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1785 let paths = dep_paths_for_args(unit, build_runner);
1787
1788 for path in paths {
1789 let mut deps = OsString::from("dependency=");
1790 deps.push(path);
1791 lib_search_paths.extend(["-L".into(), deps]);
1792 }
1793 } else {
1794 let mut deps = OsString::from("dependency=");
1795 deps.push(build_runner.files().deps_dir(unit));
1796 lib_search_paths.extend(["-L".into(), deps]);
1797 }
1798
1799 if !unit.kind.is_host() {
1802 let mut deps = OsString::from("dependency=");
1803 deps.push(build_runner.files().host_deps(unit));
1804 lib_search_paths.extend(["-L".into(), deps]);
1805 }
1806
1807 Ok(lib_search_paths)
1808}
1809
1810fn dep_paths_for_args(unit: &Unit, build_runner: &BuildRunner<'_, '_>) -> Vec<PathBuf> {
1824 let direct = build_runner.unit_deps(unit);
1825 if direct.is_empty() {
1826 return Vec::new();
1827 }
1828
1829 let is_proc_macro = |u: &Unit| match u.target.kind() {
1833 TargetKind::Lib(kinds) => kinds.contains(&CrateType::ProcMacro),
1834 _ => false,
1835 };
1836
1837 let mut indirect = HashSet::default();
1838 let mut visited = HashSet::default();
1839 let mut stack: Vec<&Unit> = direct
1840 .iter()
1841 .filter(|d| !d.unit.target.is_custom_build())
1842 .map(|d| &d.unit)
1843 .collect();
1844 while let Some(u) = stack.pop() {
1845 if !visited.insert(u.clone()) {
1846 continue;
1847 }
1848 if is_proc_macro(u) {
1849 continue;
1850 }
1851 for dep in build_runner.unit_deps(u) {
1852 let v = &dep.unit;
1853 if v.target.is_custom_build() {
1854 continue;
1855 }
1856 indirect.insert(v.clone());
1857 if is_proc_macro(v) {
1858 continue;
1859 }
1860 if !visited.contains(v) {
1861 stack.push(v);
1862 }
1863 }
1864 }
1865
1866 let mut paths: Vec<PathBuf> = indirect
1867 .into_iter()
1868 .map(|u| build_runner.files().deps_dir(&u))
1869 .collect();
1870
1871 paths.sort_unstable_by(|a, b| match (a.to_str(), b.to_str()) {
1880 (Some(a), Some(b)) => a.cmp(b),
1881 (Some(_), None) => std::cmp::Ordering::Less,
1882 (None, Some(_)) => std::cmp::Ordering::Greater,
1883 (None, None) => std::cmp::Ordering::Less,
1884 });
1885 paths.dedup_by(|a, b| matches!((a.to_str(), b.to_str()), (Some(x), Some(y)) if x == y));
1886
1887 paths
1888}
1889
1890fn is_public_dependency_enabled(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> bool {
1891 unit.pkg
1892 .manifest()
1893 .unstable_features()
1894 .require(Feature::public_dependency())
1895 .is_ok()
1896 || build_runner.bcx.gctx.cli_unstable().public_dependency
1897}
1898
1899pub fn extern_args(
1901 build_runner: &BuildRunner<'_, '_>,
1902 unit: &Unit,
1903 unstable_opts: &mut bool,
1904) -> CargoResult<Vec<OsString>> {
1905 let mut result = Vec::new();
1906 let deps = build_runner.unit_deps(unit);
1907
1908 let no_embed_metadata = !build_runner
1909 .bcx
1910 .target_data
1911 .info(unit.kind)
1912 .should_embed_metadata();
1913 let public_dependency_enabled = is_public_dependency_enabled(build_runner, unit);
1914
1915 let mut link_to = |dep: &UnitDep,
1917 extern_crate_name: InternedString,
1918 noprelude: bool,
1919 nounused: bool|
1920 -> CargoResult<()> {
1921 let mut value = OsString::new();
1922 let mut opts = Vec::new();
1923 if !dep.public && unit.target.is_lib() && public_dependency_enabled {
1924 opts.push("priv");
1925 *unstable_opts = true;
1926 }
1927 if noprelude {
1928 opts.push("noprelude");
1929 *unstable_opts = true;
1930 }
1931 if nounused {
1932 opts.push("nounused");
1933 *unstable_opts = true;
1934 }
1935 if !opts.is_empty() {
1936 value.push(opts.join(","));
1937 value.push(":");
1938 }
1939 value.push(extern_crate_name.as_str());
1940 value.push("=");
1941
1942 let mut pass = |file| {
1943 let mut value = value.clone();
1944 value.push(file);
1945 result.push(OsString::from("--extern"));
1946 result.push(value);
1947 };
1948
1949 let outputs = build_runner.outputs(&dep.unit)?;
1950
1951 if build_runner.only_requires_rmeta(unit, &dep.unit) || dep.unit.mode.is_check() {
1952 let output = outputs
1954 .iter()
1955 .find(|output| output.flavor == FileFlavor::Rmeta)
1956 .expect("failed to find rmeta dep for pipelined dep");
1957 pass(&output.path);
1958 } else {
1959 for output in outputs.iter() {
1961 if output.flavor == FileFlavor::Linkable {
1962 pass(&output.path);
1963 }
1964 else if no_embed_metadata && output.flavor == FileFlavor::Rmeta {
1968 pass(&output.path);
1969 }
1970 }
1971 }
1972 Ok(())
1973 };
1974
1975 for dep in deps {
1976 if dep.unit.target.is_linkable() && !dep.unit.mode.is_doc() {
1977 link_to(dep, dep.extern_crate_name, dep.noprelude, dep.nounused)?;
1978 }
1979 }
1980 if unit.target.proc_macro() {
1981 result.push(OsString::from("--extern"));
1983 result.push(OsString::from("proc_macro"));
1984 }
1985
1986 Ok(result)
1987}
1988
1989fn add_codegen_linker(
1991 cmd: &mut ProcessBuilder,
1992 build_runner: &BuildRunner<'_, '_>,
1993 unit: &Unit,
1994 target_applies_to_host: bool,
1995) {
1996 let linker = if unit.target.for_host() && !target_applies_to_host {
1997 build_runner
1998 .compilation
1999 .host_linker()
2000 .map(|s| s.as_os_str())
2001 } else {
2002 build_runner
2003 .compilation
2004 .target_linker(unit.kind)
2005 .map(|s| s.as_os_str())
2006 };
2007
2008 if let Some(linker) = linker {
2009 let mut arg = OsString::from("linker=");
2010 arg.push(linker);
2011 cmd.arg("-C").arg(arg);
2012 }
2013}
2014
2015fn add_codegen_incremental(
2017 cmd: &mut ProcessBuilder,
2018 build_runner: &BuildRunner<'_, '_>,
2019 unit: &Unit,
2020) {
2021 let dir = build_runner.files().incremental_dir(&unit);
2022 let mut arg = OsString::from("incremental=");
2023 arg.push(dir.as_os_str());
2024 cmd.arg("-C").arg(arg);
2025}
2026
2027fn envify(s: &str) -> String {
2028 s.chars()
2029 .flat_map(|c| c.to_uppercase())
2030 .map(|c| if c == '-' { '_' } else { c })
2031 .collect()
2032}
2033
2034struct OutputOptions {
2037 format: MessageFormat,
2039 cache_cell: Option<(PathBuf, OnceCell<File>)>,
2044 show_diagnostics: bool,
2052 warnings_seen: usize,
2054 errors_seen: usize,
2056}
2057
2058impl OutputOptions {
2059 fn for_dirty(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2060 let path = build_runner.files().message_cache_path(unit);
2061 drop(fs::remove_file(&path));
2063 let cache_cell = Some((path, OnceCell::new()));
2064
2065 let show_diagnostics = true;
2066
2067 let format = build_runner.bcx.build_config.message_format;
2068
2069 OutputOptions {
2070 format,
2071 cache_cell,
2072 show_diagnostics,
2073 warnings_seen: 0,
2074 errors_seen: 0,
2075 }
2076 }
2077
2078 fn for_fresh(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2079 let cache_cell = None;
2080
2081 let show_diagnostics = unit.show_warnings(build_runner.bcx.gctx);
2084
2085 let format = build_runner.bcx.build_config.message_format;
2086
2087 OutputOptions {
2088 format,
2089 cache_cell,
2090 show_diagnostics,
2091 warnings_seen: 0,
2092 errors_seen: 0,
2093 }
2094 }
2095}
2096
2097struct ManifestErrorContext {
2103 path: PathBuf,
2105 spans: Option<Arc<toml::Spanned<toml::de::DeTable<'static>>>>,
2107 contents: Option<String>,
2109 rename_table: HashMap<InternedString, InternedString>,
2112 requested_kinds: Vec<CompileKind>,
2115 cfgs: Vec<Vec<Cfg>>,
2118 host_name: InternedString,
2119 cwd: PathBuf,
2121 term_width: usize,
2123}
2124
2125fn on_stdout_line(
2126 state: &JobState<'_, '_>,
2127 line: &str,
2128 _package_id: PackageId,
2129 _target: &Target,
2130) -> CargoResult<()> {
2131 state.stdout(line.to_string())?;
2132 Ok(())
2133}
2134
2135fn on_stderr_line(
2136 state: &JobState<'_, '_>,
2137 line: &str,
2138 package_id: PackageId,
2139 manifest: &ManifestErrorContext,
2140 target: &Target,
2141 options: &mut OutputOptions,
2142) -> CargoResult<()> {
2143 if on_stderr_line_inner(state, line, package_id, manifest, target, options)? {
2144 if let Some((path, cell)) = &mut options.cache_cell {
2146 let f = cell.try_borrow_mut_with(|| paths::create(path))?;
2148 debug_assert!(!line.contains('\n'));
2149 f.write_all(line.as_bytes())?;
2150 f.write_all(&[b'\n'])?;
2151 }
2152 }
2153 Ok(())
2154}
2155
2156fn on_stderr_line_inner(
2158 state: &JobState<'_, '_>,
2159 line: &str,
2160 package_id: PackageId,
2161 manifest: &ManifestErrorContext,
2162 target: &Target,
2163 options: &mut OutputOptions,
2164) -> CargoResult<bool> {
2165 if !line.starts_with('{') {
2171 state.stderr(line.to_string())?;
2172 return Ok(true);
2173 }
2174
2175 let mut compiler_message: Box<serde_json::value::RawValue> = match serde_json::from_str(line) {
2176 Ok(msg) => msg,
2177
2178 Err(e) => {
2182 debug!("failed to parse json: {:?}", e);
2183 state.stderr(line.to_string())?;
2184 return Ok(true);
2185 }
2186 };
2187
2188 let count_diagnostic = |level, options: &mut OutputOptions| {
2189 if level == "warning" {
2190 options.warnings_seen += 1;
2191 } else if level == "error" {
2192 options.errors_seen += 1;
2193 }
2194 };
2195
2196 if let Ok(report) = serde_json::from_str::<FutureIncompatReport>(compiler_message.get()) {
2197 for item in &report.future_incompat_report {
2198 count_diagnostic(&*item.diagnostic.level, options);
2199 }
2200 state.future_incompat_report(report.future_incompat_report);
2201 return Ok(true);
2202 }
2203
2204 let res = serde_json::from_str::<SectionTiming>(compiler_message.get());
2205 if let Ok(timing_record) = res {
2206 state.on_section_timing_emitted(timing_record);
2207 return Ok(false);
2208 }
2209
2210 let add_pub_in_priv_diagnostic = |diag: &mut String| -> bool {
2212 static PRIV_DEP_REGEX: LazyLock<Regex> =
2221 LazyLock::new(|| Regex::new("from private dependency '([A-Za-z0-9-_]+)'").unwrap());
2222 if let Some(crate_name) = PRIV_DEP_REGEX.captures(diag).and_then(|m| m.get(1))
2223 && let Some(ref contents) = manifest.contents
2224 && let Some(span) = manifest.find_crate_span(crate_name.as_str())
2225 {
2226 let rel_path = pathdiff::diff_paths(&manifest.path, &manifest.cwd)
2227 .unwrap_or_else(|| manifest.path.clone())
2228 .display()
2229 .to_string();
2230 let report = [Group::with_title(Level::NOTE.secondary_title(format!(
2231 "dependency `{}` declared here",
2232 crate_name.as_str()
2233 )))
2234 .element(
2235 Snippet::source(contents)
2236 .path(rel_path)
2237 .annotation(AnnotationKind::Context.span(span)),
2238 )];
2239
2240 let rendered = Renderer::styled()
2241 .term_width(manifest.term_width)
2242 .render(&report);
2243 diag.push_str(&rendered);
2244 diag.push('\n');
2245 return true;
2246 }
2247 false
2248 };
2249
2250 match options.format {
2253 MessageFormat::Human
2258 | MessageFormat::Short
2259 | MessageFormat::Json {
2260 render_diagnostics: true,
2261 ..
2262 } => {
2263 #[derive(serde::Deserialize)]
2264 struct CompilerMessage<'a> {
2265 rendered: String,
2269 #[serde(borrow)]
2270 message: Cow<'a, str>,
2271 #[serde(borrow)]
2272 level: Cow<'a, str>,
2273 children: Vec<PartialDiagnostic>,
2274 code: Option<DiagnosticCode>,
2275 }
2276
2277 #[derive(serde::Deserialize)]
2286 struct PartialDiagnostic {
2287 spans: Vec<PartialDiagnosticSpan>,
2288 }
2289
2290 #[derive(serde::Deserialize)]
2292 struct PartialDiagnosticSpan {
2293 suggestion_applicability: Option<Applicability>,
2294 }
2295
2296 #[derive(serde::Deserialize)]
2297 struct DiagnosticCode {
2298 code: String,
2299 }
2300
2301 if let Ok(mut msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2302 {
2303 if msg.message.starts_with("aborting due to")
2304 || msg.message.ends_with("warning emitted")
2305 || msg.message.ends_with("warnings emitted")
2306 {
2307 return Ok(true);
2309 }
2310 if msg.rendered.ends_with('\n') {
2312 msg.rendered.pop();
2313 }
2314 let mut rendered = msg.rendered;
2315 if options.show_diagnostics {
2316 let machine_applicable: bool = msg
2317 .children
2318 .iter()
2319 .map(|child| {
2320 child
2321 .spans
2322 .iter()
2323 .filter_map(|span| span.suggestion_applicability)
2324 .any(|app| app == Applicability::MachineApplicable)
2325 })
2326 .any(|b| b);
2327 count_diagnostic(&msg.level, options);
2328 if msg
2329 .code
2330 .as_ref()
2331 .is_some_and(|c| c.code == "exported_private_dependencies")
2332 && options.format != MessageFormat::Short
2333 {
2334 add_pub_in_priv_diagnostic(&mut rendered);
2335 }
2336 let lint = msg.code.is_some();
2337 state.emit_diag(&msg.level, rendered, lint, machine_applicable)?;
2338 }
2339 return Ok(true);
2340 }
2341 }
2342
2343 MessageFormat::Json { ansi, .. } => {
2344 #[derive(serde::Deserialize, serde::Serialize)]
2345 struct CompilerMessage<'a> {
2346 rendered: String,
2347 #[serde(flatten, borrow)]
2348 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2349 code: Option<DiagnosticCode<'a>>,
2350 }
2351
2352 #[derive(serde::Deserialize, serde::Serialize)]
2353 struct DiagnosticCode<'a> {
2354 code: String,
2355 #[serde(flatten, borrow)]
2356 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2357 }
2358
2359 if let Ok(mut error) =
2360 serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2361 {
2362 let modified_diag = if error
2363 .code
2364 .as_ref()
2365 .is_some_and(|c| c.code == "exported_private_dependencies")
2366 {
2367 add_pub_in_priv_diagnostic(&mut error.rendered)
2368 } else {
2369 false
2370 };
2371
2372 if !ansi {
2376 error.rendered = anstream::adapter::strip_str(&error.rendered).to_string();
2377 }
2378 if !ansi || modified_diag {
2379 let new_line = serde_json::to_string(&error)?;
2380 compiler_message = serde_json::value::RawValue::from_string(new_line)?;
2381 }
2382 }
2383 }
2384 }
2385
2386 #[derive(serde::Deserialize)]
2393 struct ArtifactNotification<'a> {
2394 #[serde(borrow)]
2395 artifact: Cow<'a, str>,
2396 }
2397
2398 if let Ok(artifact) = serde_json::from_str::<ArtifactNotification<'_>>(compiler_message.get()) {
2399 trace!("found directive from rustc: `{}`", artifact.artifact);
2400 if artifact.artifact.ends_with(".rmeta") {
2401 debug!("looks like metadata finished early!");
2402 state.rmeta_produced();
2403 }
2404 return Ok(false);
2405 }
2406
2407 #[derive(serde::Deserialize)]
2408 struct UnusedExterns {
2409 unused_extern_names: std::collections::BTreeSet<InternedString>,
2410 }
2411 if let Ok(uext) = serde_json::from_str::<UnusedExterns>(compiler_message.get()) {
2412 trace!(
2413 "obtained unused externs list from rustc: `{:?}`",
2414 uext.unused_extern_names
2415 );
2416 state.unused_externs(uext.unused_extern_names);
2417 return Ok(true);
2418 }
2419
2420 if !options.show_diagnostics {
2425 return Ok(true);
2426 }
2427
2428 #[derive(serde::Deserialize)]
2429 struct CompilerMessage<'a> {
2430 #[serde(borrow)]
2431 message: Cow<'a, str>,
2432 #[serde(borrow)]
2433 level: Cow<'a, str>,
2434 }
2435
2436 if let Ok(msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get()) {
2437 if msg.message.starts_with("aborting due to")
2438 || msg.message.ends_with("warning emitted")
2439 || msg.message.ends_with("warnings emitted")
2440 {
2441 return Ok(true);
2443 }
2444 count_diagnostic(&msg.level, options);
2445 }
2446
2447 let msg = machine_message::FromCompiler {
2448 package_id: package_id.to_spec(),
2449 manifest_path: &manifest.path,
2450 target,
2451 message: compiler_message,
2452 }
2453 .to_json_string();
2454
2455 state.stdout(msg)?;
2459 Ok(true)
2460}
2461
2462impl ManifestErrorContext {
2463 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> ManifestErrorContext {
2464 let mut duplicates = HashSet::default();
2465 let mut rename_table = HashMap::default();
2466
2467 for dep in build_runner.unit_deps(unit) {
2468 let unrenamed_id = dep.unit.pkg.package_id().name();
2469 if duplicates.contains(&unrenamed_id) {
2470 continue;
2471 }
2472 match rename_table.entry(unrenamed_id) {
2473 std::collections::hash_map::Entry::Occupied(occ) => {
2474 occ.remove_entry();
2475 duplicates.insert(unrenamed_id);
2476 }
2477 std::collections::hash_map::Entry::Vacant(vac) => {
2478 vac.insert(dep.extern_crate_name);
2479 }
2480 }
2481 }
2482
2483 let bcx = build_runner.bcx;
2484 ManifestErrorContext {
2485 path: unit.pkg.manifest_path().to_owned(),
2486 spans: unit.pkg.manifest().document_rc(),
2487 contents: unit.pkg.manifest().contents().map(String::from),
2488 requested_kinds: bcx.target_data.requested_kinds().to_owned(),
2489 host_name: bcx.rustc().host,
2490 rename_table,
2491 cwd: path_args(build_runner.bcx.ws, unit).1,
2492 cfgs: bcx
2493 .target_data
2494 .requested_kinds()
2495 .iter()
2496 .map(|k| bcx.target_data.cfg(*k).to_owned())
2497 .collect(),
2498 term_width: bcx
2499 .gctx
2500 .shell()
2501 .err_width()
2502 .diagnostic_terminal_width()
2503 .unwrap_or(cargo_util_terminal::report::renderer::DEFAULT_TERM_WIDTH),
2504 }
2505 }
2506
2507 fn requested_target_names(&self) -> impl Iterator<Item = &str> {
2508 self.requested_kinds.iter().map(|kind| match kind {
2509 CompileKind::Host => &self.host_name,
2510 CompileKind::Target(target) => target.short_name(),
2511 })
2512 }
2513
2514 fn find_crate_span(&self, unrenamed: &str) -> Option<Range<usize>> {
2528 let Some(ref spans) = self.spans else {
2529 return None;
2530 };
2531
2532 let orig_name = self.rename_table.get(unrenamed)?.as_str();
2533
2534 if let Some((k, v)) = get_key_value(&spans, &["dependencies", orig_name]) {
2535 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package")) {
2544 return Some(package.span());
2545 } else {
2546 return Some(k.span());
2547 }
2548 }
2549
2550 if let Some(target) = spans
2555 .deref()
2556 .as_ref()
2557 .get("target")
2558 .and_then(|t| t.as_ref().as_table())
2559 {
2560 for (platform, platform_table) in target.iter() {
2561 match platform.as_ref().parse::<Platform>() {
2562 Ok(Platform::Name(name)) => {
2563 if !self.requested_target_names().any(|n| n == name) {
2564 continue;
2565 }
2566 }
2567 Ok(Platform::Cfg(cfg_expr)) => {
2568 if !self.cfgs.iter().any(|cfgs| cfg_expr.matches(cfgs)) {
2569 continue;
2570 }
2571 }
2572 Err(_) => continue,
2573 }
2574
2575 let Some(platform_table) = platform_table.as_ref().as_table() else {
2576 continue;
2577 };
2578
2579 if let Some(deps) = platform_table
2580 .get("dependencies")
2581 .and_then(|d| d.as_ref().as_table())
2582 {
2583 if let Some((k, v)) = deps.get_key_value(orig_name) {
2584 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package"))
2585 {
2586 return Some(package.span());
2587 } else {
2588 return Some(k.span());
2589 }
2590 }
2591 }
2592 }
2593 }
2594 None
2595 }
2596}
2597
2598fn replay_output_cache(
2602 package_id: PackageId,
2603 manifest: ManifestErrorContext,
2604 target: &Target,
2605 path: PathBuf,
2606 mut output_options: OutputOptions,
2607) -> Work {
2608 let target = target.clone();
2609 Work::new(move |state| {
2610 if !path.exists() {
2611 return Ok(());
2613 }
2614 let file = paths::open(&path)?;
2618 let mut reader = std::io::BufReader::new(file);
2619 let mut line = String::new();
2620 loop {
2621 let length = reader.read_line(&mut line)?;
2622 if length == 0 {
2623 break;
2624 }
2625 let trimmed = line.trim_end_matches(&['\n', '\r'][..]);
2626 on_stderr_line(
2627 state,
2628 trimmed,
2629 package_id,
2630 &manifest,
2631 &target,
2632 &mut output_options,
2633 )?;
2634 line.clear();
2635 }
2636 Ok(())
2637 })
2638}
2639
2640fn descriptive_pkg_name(name: &str, target: &Target, mode: &CompileMode) -> String {
2643 let desc_name = target.description_named();
2644 let mode = if mode.is_rustc_test() && !(target.is_test() || target.is_bench()) {
2645 " test"
2646 } else if mode.is_doc_test() {
2647 " doctest"
2648 } else if mode.is_doc() {
2649 " doc"
2650 } else {
2651 ""
2652 };
2653 format!("`{name}` ({desc_name}{mode})")
2654}
2655
2656pub(crate) fn apply_env_config(
2658 gctx: &crate::GlobalContext,
2659 cmd: &mut ProcessBuilder,
2660) -> CargoResult<()> {
2661 for (key, value) in gctx.env_config()?.iter() {
2662 if cmd.get_envs().contains_key(key) {
2664 continue;
2665 }
2666 cmd.env(key, value);
2667 }
2668 Ok(())
2669}
2670
2671fn should_include_scrape_units(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
2673 unit.mode.is_doc() && bcx.scrape_units.len() > 0 && bcx.ws.unit_needs_doc_scrape(unit)
2674}
2675
2676fn scrape_output_path(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<PathBuf> {
2678 assert!(unit.mode.is_doc() || unit.mode.is_doc_scrape());
2679 build_runner
2680 .outputs(unit)
2681 .map(|outputs| outputs[0].path.clone())
2682}
2683
2684fn rustdoc_dep_info_loc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
2686 let mut loc = build_runner.files().fingerprint_file_path(unit, "");
2687 loc.set_extension("d");
2688 loc
2689}