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;
51mod unit;
52pub mod unit_dependencies;
53pub mod unit_graph;
54pub mod unused_deps;
55
56use crate::util::data_structures::{HashMap, HashSet};
57use std::borrow::Cow;
58use std::cell::OnceCell;
59use std::collections::BTreeMap;
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_terminal::report::{AnnotationKind, Group, Level, Renderer, Snippet};
72use itertools::Itertools;
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::CrateType;
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::unit_graph::UnitDep;
99
100use crate::core::compiler::future_incompat::FutureIncompatReport;
101use crate::core::compiler::locking::LockKey;
102use crate::core::compiler::timings::SectionTiming;
103pub use crate::core::compiler::unit::Unit;
104pub use crate::core::compiler::unit::UnitIndex;
105pub use crate::core::compiler::unit::UnitInterner;
106use crate::core::manifest::TargetSourcePath;
107use crate::core::profiles::{PanicStrategy, Profile, StripInner};
108use crate::core::{Feature, PackageId, Target};
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};
115
116use cargo_util::{ProcessBuilder, ProcessError, paths};
117use cargo_util_schemas::manifest::TomlDebugInfo;
118use cargo_util_schemas::manifest::TomlTrimPaths;
119use cargo_util_schemas::manifest::TomlTrimPathsValue;
120use cargo_util_terminal::Verbosity;
121use rustfix::diagnostics::Applicability;
122
123const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
124
125pub trait Executor: Send + Sync + 'static {
129 fn init(&self, _build_runner: &BuildRunner<'_, '_>, _unit: &Unit) {}
133
134 fn exec(
137 &self,
138 cmd: &ProcessBuilder,
139 id: PackageId,
140 target: &Target,
141 mode: CompileMode,
142 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
143 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
144 ) -> CargoResult<()>;
145
146 fn force_rebuild(&self, _unit: &Unit) -> bool {
149 false
150 }
151}
152
153#[derive(Copy, Clone)]
156pub struct DefaultExecutor;
157
158impl Executor for DefaultExecutor {
159 #[instrument(name = "rustc", skip_all, fields(package = id.name().as_str(), process = cmd.to_string()))]
160 fn exec(
161 &self,
162 cmd: &ProcessBuilder,
163 id: PackageId,
164 _target: &Target,
165 _mode: CompileMode,
166 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
167 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
168 ) -> CargoResult<()> {
169 cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
170 .map(drop)
171 }
172}
173
174#[tracing::instrument(skip(build_runner, jobs, exec))]
184fn compile<'gctx>(
185 build_runner: &mut BuildRunner<'_, 'gctx>,
186 jobs: &mut JobQueue<'gctx>,
187 unit: &Unit,
188 exec: &Arc<dyn Executor>,
189 force_rebuild: bool,
190) -> CargoResult<()> {
191 if !build_runner.compiled.insert(unit.clone()) {
192 return Ok(());
193 }
194
195 let lock = if build_runner.bcx.gctx.cli_unstable().fine_grain_locking {
196 Some(build_runner.lock_manager.lock_shared(build_runner, unit)?)
197 } else {
198 None
199 };
200
201 if !unit.skip_non_compile_time_dep {
205 fingerprint::prepare_init(build_runner, unit)?;
208
209 let job = if unit.mode.is_run_custom_build() {
210 custom_build::prepare(build_runner, unit)?
211 } else if unit.mode.is_doc_test() {
212 Job::new_fresh()
214 } else {
215 let force = exec.force_rebuild(unit) || force_rebuild;
216 let mut job = fingerprint::prepare_target(build_runner, unit, force)?;
217 job.before(if job.freshness().is_dirty() {
218 let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
219 rustdoc(build_runner, unit)?
220 } else {
221 rustc(build_runner, unit, exec)?
222 };
223 work.then(link_targets(build_runner, unit, false)?)
224 } else {
225 let output_options = OutputOptions::for_fresh(build_runner, unit);
226 let manifest = ManifestErrorContext::new(build_runner, unit);
227 let work = replay_output_cache(
228 unit.pkg.package_id(),
229 manifest,
230 &unit.target,
231 build_runner.files().message_cache_path(unit),
232 output_options,
233 );
234 work.then(link_targets(build_runner, unit, true)?)
236 });
237
238 if build_runner.bcx.gctx.cli_unstable().fine_grain_locking && job.freshness().is_dirty()
241 {
242 if let Some(lock) = lock {
243 build_runner.lock_manager.unlock(&lock)?;
250 job.before(prebuild_lock_exclusive(lock.clone()));
251 job.after(downgrade_lock_to_shared(lock));
252 }
253 }
254
255 job
256 };
257 jobs.enqueue(build_runner, unit, job)?;
258 }
259
260 let deps = Vec::from(build_runner.unit_deps(unit)); for dep in deps {
263 compile(build_runner, jobs, &dep.unit, exec, false)?;
264 }
265
266 Ok(())
267}
268
269fn make_failed_scrape_diagnostic(
272 build_runner: &BuildRunner<'_, '_>,
273 unit: &Unit,
274 top_line: impl Display,
275) -> String {
276 let manifest_path = unit.pkg.manifest_path();
277 let relative_manifest_path = manifest_path
278 .strip_prefix(build_runner.bcx.ws.root())
279 .unwrap_or(&manifest_path);
280
281 format!(
282 "\
283{top_line}
284 Try running with `--verbose` to see the error message.
285 If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
286 relative_manifest_path.display()
287 )
288}
289
290fn rustc(
292 build_runner: &mut BuildRunner<'_, '_>,
293 unit: &Unit,
294 exec: &Arc<dyn Executor>,
295) -> CargoResult<Work> {
296 let mut rustc = prepare_rustc(build_runner, unit)?;
297
298 let name = unit.pkg.name();
299
300 let outputs = build_runner.outputs(unit)?;
301 let root = build_runner.files().output_dir(unit);
302
303 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
305 let current_id = unit.pkg.package_id();
306 let manifest = ManifestErrorContext::new(build_runner, unit);
307 let build_scripts = build_runner.build_scripts.get(unit).cloned();
308
309 let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
312
313 let dep_info_name =
314 if let Some(c_extra_filename) = build_runner.files().metadata(unit).c_extra_filename() {
315 format!("{}-{}.d", unit.target.crate_name(), c_extra_filename)
316 } else {
317 format!("{}.d", unit.target.crate_name())
318 };
319 let rustc_dep_info_loc = root.join(dep_info_name);
320 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
321
322 let mut output_options = OutputOptions::for_dirty(build_runner, unit);
323 let package_id = unit.pkg.package_id();
324 let target = Target::clone(&unit.target);
325 let mode = unit.mode;
326
327 exec.init(build_runner, unit);
328 let exec = exec.clone();
329
330 let root_output = build_runner.files().host_dest().map(|v| v.to_path_buf());
331 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
332 let pkg_root = unit.pkg.root().to_path_buf();
333 let cwd = rustc
334 .get_cwd()
335 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
336 .to_path_buf();
337 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
338 let script_metadatas = build_runner.find_build_script_metadatas(unit);
339 let is_local = unit.is_local();
340 let artifact = unit.artifact;
341 let sbom_files = build_runner.sbom_output_files(unit)?;
342 let sbom = build_sbom(build_runner, unit)?;
343
344 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
345 && !matches!(
346 build_runner.bcx.gctx.shell().verbosity(),
347 Verbosity::Verbose
348 );
349 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
350 let target_desc = unit.target.description_named();
353 let mut for_scrape_units = build_runner
354 .bcx
355 .scrape_units_have_dep_on(unit)
356 .into_iter()
357 .map(|unit| unit.target.description_named())
358 .collect::<Vec<_>>();
359 for_scrape_units.sort();
360 let for_scrape_units = for_scrape_units.join(", ");
361 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}"))
362 });
363 if hide_diagnostics_for_scrape_unit {
364 output_options.show_diagnostics = false;
365 }
366 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
367 return Ok(Work::new(move |state| {
368 if artifact.is_true() {
372 paths::create_dir_all(&root)?;
373 }
374
375 if let Some(build_scripts) = build_scripts {
383 let script_outputs = build_script_outputs.lock().unwrap();
384 add_native_deps(
385 &mut rustc,
386 &script_outputs,
387 &build_scripts,
388 pass_l_flag,
389 &target,
390 current_id,
391 mode,
392 )?;
393 if let Some(ref root_output) = root_output {
394 add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, root_output)?;
395 }
396 add_custom_flags(&mut rustc, &script_outputs, script_metadatas)?;
397 }
398
399 for output in outputs.iter() {
400 if output.path.extension() == Some(OsStr::new("rmeta")) {
404 let dst = root.join(&output.path).with_extension("rlib");
405 if dst.exists() {
406 paths::remove_file(&dst)?;
407 }
408 }
409
410 if output.hardlink.is_some() && output.path.exists() {
415 _ = paths::remove_file(&output.path).map_err(|e| {
416 tracing::debug!(
417 "failed to delete previous output file `{:?}`: {e:?}",
418 output.path
419 );
420 });
421 }
422 }
423
424 state.running(&rustc);
425 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
426 for file in sbom_files {
427 tracing::debug!("writing sbom to {}", file.display());
428 let outfile = BufWriter::new(paths::create(&file)?);
429 serde_json::to_writer(outfile, &sbom)?;
430 }
431
432 let result = exec
433 .exec(
434 &rustc,
435 package_id,
436 &target,
437 mode,
438 &mut |line| on_stdout_line(state, line, package_id, &target),
439 &mut |line| {
440 on_stderr_line(
441 state,
442 line,
443 package_id,
444 &manifest,
445 &target,
446 &mut output_options,
447 )
448 },
449 )
450 .map_err(|e| {
451 if output_options.errors_seen == 0 {
452 e
457 } else {
458 verbose_if_simple_exit_code(e)
459 }
460 })
461 .with_context(|| {
462 let warnings = match output_options.warnings_seen {
464 0 => String::new(),
465 1 => "; 1 warning emitted".to_string(),
466 count => format!("; {} warnings emitted", count),
467 };
468 let errors = match output_options.errors_seen {
469 0 => String::new(),
470 1 => " due to 1 previous error".to_string(),
471 count => format!(" due to {} previous errors", count),
472 };
473 let name = descriptive_pkg_name(&name, &target, &mode);
474 format!("could not compile {name}{errors}{warnings}")
475 });
476
477 if let Err(e) = result {
478 if let Some(diagnostic) = failed_scrape_diagnostic {
479 state.warning(diagnostic);
480 }
481
482 return Err(e);
483 }
484
485 debug_assert_eq!(output_options.errors_seen, 0);
487
488 if rustc_dep_info_loc.exists() {
489 fingerprint::translate_dep_info(
490 &rustc_dep_info_loc,
491 &dep_info_loc,
492 &cwd,
493 &pkg_root,
494 &build_dir,
495 &rustc,
496 is_local,
498 &env_config,
499 )
500 .with_context(|| {
501 internal(format!(
502 "could not parse/generate dep info at: {}",
503 rustc_dep_info_loc.display()
504 ))
505 })?;
506 paths::set_file_time_no_err(dep_info_loc, timestamp);
509 }
510
511 if mode.is_check() {
525 for output in outputs.iter() {
526 paths::set_file_time_no_err(&output.path, timestamp);
527 }
528 }
529
530 Ok(())
531 }));
532
533 fn add_native_deps(
536 rustc: &mut ProcessBuilder,
537 build_script_outputs: &BuildScriptOutputs,
538 build_scripts: &BuildScripts,
539 pass_l_flag: bool,
540 target: &Target,
541 current_id: PackageId,
542 mode: CompileMode,
543 ) -> CargoResult<()> {
544 let mut library_paths = vec![];
545
546 for key in build_scripts.to_link.iter() {
547 let output = build_script_outputs.get(key.1).ok_or_else(|| {
548 internal(format!(
549 "couldn't find build script output for {}/{}",
550 key.0, key.1
551 ))
552 })?;
553 library_paths.extend(output.library_paths.iter());
554 }
555
556 library_paths.sort_by_key(|p| match p {
562 LibraryPath::CargoArtifact(_) => 0,
563 LibraryPath::External(_) => 1,
564 });
565
566 for path in library_paths.iter() {
567 rustc.arg("-L").arg(path.as_ref());
568 }
569
570 for key in build_scripts.to_link.iter() {
571 let output = build_script_outputs.get(key.1).ok_or_else(|| {
572 internal(format!(
573 "couldn't find build script output for {}/{}",
574 key.0, key.1
575 ))
576 })?;
577
578 if key.0 == current_id {
579 if pass_l_flag {
580 for name in output.library_links.iter() {
581 rustc.arg("-l").arg(name);
582 }
583 }
584 }
585
586 for (lt, arg) in &output.linker_args {
587 if lt.applies_to(target, mode)
593 && (key.0 == current_id || *lt == LinkArgTarget::Cdylib)
594 {
595 rustc.arg("-C").arg(format!("link-arg={}", arg));
596 }
597 }
598 }
599 Ok(())
600 }
601}
602
603fn verbose_if_simple_exit_code(err: Error) -> Error {
604 match err
607 .downcast_ref::<ProcessError>()
608 .as_ref()
609 .and_then(|perr| perr.code)
610 {
611 Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
612 _ => err,
613 }
614}
615
616fn prebuild_lock_exclusive(lock: LockKey) -> Work {
617 Work::new(move |state| {
618 state.lock_exclusive(&lock)?;
619 Ok(())
620 })
621}
622
623fn downgrade_lock_to_shared(lock: LockKey) -> Work {
624 Work::new(move |state| {
625 state.downgrade_to_shared(&lock)?;
626 Ok(())
627 })
628}
629
630fn link_targets(
633 build_runner: &mut BuildRunner<'_, '_>,
634 unit: &Unit,
635 fresh: bool,
636) -> CargoResult<Work> {
637 let bcx = build_runner.bcx;
638 let outputs = build_runner.outputs(unit)?;
639 let export_dir = build_runner.files().export_dir();
640 let package_id = unit.pkg.package_id();
641 let manifest_path = PathBuf::from(unit.pkg.manifest_path());
642 let profile = unit.profile.clone();
643 let unit_mode = unit.mode;
644 let features = unit.features.iter().map(|s| s.to_string()).collect();
645 let json_messages = bcx.build_config.emit_json();
646 let executable = build_runner.get_executable(unit)?;
647 let mut target = Target::clone(&unit.target);
648 if let TargetSourcePath::Metabuild = target.src_path() {
649 let path = unit
651 .pkg
652 .manifest()
653 .metabuild_path(build_runner.bcx.ws.build_dir());
654 target.set_src_path(TargetSourcePath::Path(path));
655 }
656
657 Ok(Work::new(move |state| {
658 let mut destinations = vec![];
663 for output in outputs.iter() {
664 let src = &output.path;
665 if !src.exists() {
668 continue;
669 }
670 let Some(dst) = output.hardlink.as_ref() else {
671 destinations.push(src.clone());
672 continue;
673 };
674 destinations.push(dst.clone());
675 paths::link_or_copy(src, dst)?;
676 if let Some(ref path) = output.export_path {
677 let export_dir = export_dir.as_ref().unwrap();
678 paths::create_dir_all(export_dir)?;
679
680 paths::link_or_copy(src, path)?;
681 }
682 }
683
684 if json_messages {
685 let debuginfo = match profile.debuginfo.into_inner() {
686 TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
687 TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
688 TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
689 TomlDebugInfo::LineDirectivesOnly => {
690 machine_message::ArtifactDebuginfo::Named("line-directives-only")
691 }
692 TomlDebugInfo::LineTablesOnly => {
693 machine_message::ArtifactDebuginfo::Named("line-tables-only")
694 }
695 };
696 let art_profile = machine_message::ArtifactProfile {
697 opt_level: profile.opt_level.as_str(),
698 debuginfo: Some(debuginfo),
699 debug_assertions: profile.debug_assertions,
700 overflow_checks: profile.overflow_checks,
701 test: unit_mode.is_any_test(),
702 };
703
704 let msg = machine_message::Artifact {
705 package_id: package_id.to_spec(),
706 manifest_path,
707 target: &target,
708 profile: art_profile,
709 features,
710 filenames: destinations,
711 executable,
712 fresh,
713 }
714 .to_json_string();
715 state.stdout(msg)?;
716 }
717 Ok(())
718 }))
719}
720
721fn add_plugin_deps(
725 rustc: &mut ProcessBuilder,
726 build_script_outputs: &BuildScriptOutputs,
727 build_scripts: &BuildScripts,
728 root_output: &Path,
729) -> CargoResult<()> {
730 let var = paths::dylib_path_envvar();
731 let search_path = rustc.get_env(var).unwrap_or_default();
732 let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
733 for (pkg_id, metadata) in &build_scripts.plugins {
734 let output = build_script_outputs
735 .get(*metadata)
736 .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
737 search_path.append(&mut filter_dynamic_search_path(
738 output.library_paths.iter().map(AsRef::as_ref),
739 root_output,
740 ));
741 }
742 let search_path = paths::join_paths(&search_path, var)?;
743 rustc.env(var, &search_path);
744 Ok(())
745}
746
747fn get_dynamic_search_path(path: &Path) -> &Path {
748 match path.to_str().and_then(|s| s.split_once("=")) {
749 Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => Path::new(path),
750 _ => path,
751 }
752}
753
754fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
760where
761 I: Iterator<Item = &'a PathBuf>,
762{
763 let mut search_path = vec![];
764 for dir in paths {
765 let dir = get_dynamic_search_path(dir);
766 if dir.starts_with(&root_output) {
767 search_path.push(dir.to_path_buf());
768 } else {
769 debug!(
770 "Not including path {} in runtime library search path because it is \
771 outside target root {}",
772 dir.display(),
773 root_output.display()
774 );
775 }
776 }
777 search_path
778}
779
780fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
787 let gctx = build_runner.bcx.gctx;
788 let is_primary = build_runner.is_primary_package(unit);
789 let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg);
790
791 let mut base = build_runner
792 .compilation
793 .rustc_process(unit, is_primary, is_workspace)?;
794 build_base_args(build_runner, &mut base, unit)?;
795 if unit.pkg.manifest().is_embedded() {
796 if !gctx.cli_unstable().script {
797 anyhow::bail!(
798 "parsing `{}` requires `-Zscript`",
799 unit.pkg.manifest_path().display()
800 );
801 }
802 base.arg("-Z").arg("crate-attr=feature(frontmatter)");
803 base.arg("-Z").arg("crate-attr=allow(unused_features)");
804 }
805
806 base.inherit_jobserver(&build_runner.jobserver);
807 build_deps_args(&mut base, build_runner, unit)?;
808 add_cap_lints(build_runner.bcx, unit, &mut base);
809 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
810 base.args(args);
811 }
812 base.args(&unit.rustflags);
813 if gctx.cli_unstable().binary_dep_depinfo {
814 base.arg("-Z").arg("binary-dep-depinfo");
815 }
816 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
817 base.arg("-Z").arg("checksum-hash-algorithm=blake3");
818 }
819 if gctx.shell().verbosity() == Verbosity::Verbose && unit.is_local() {
820 base.arg("--verbose");
821 }
822
823 if is_primary {
824 base.env("CARGO_PRIMARY_PACKAGE", "1");
825 let file_list = build_runner.sbom_output_files(unit)?;
826 if !file_list.is_empty() {
827 let file_list = std::env::join_paths(file_list)?;
828 base.env("CARGO_SBOM_PATH", file_list);
829 }
830 }
831
832 if unit.target.is_test() || unit.target.is_bench() {
833 let tmp = build_runner
834 .files()
835 .layout(unit.kind)
836 .build_dir()
837 .prepare_tmp()?;
838 base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
839 }
840
841 if build_runner.bcx.gctx.cli_unstable().cargo_lints {
842 base.arg("--force-warn=unused_crate_dependencies");
845 }
846
847 Ok(base)
848}
849
850fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
857 let bcx = build_runner.bcx;
858 let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
860 if unit.pkg.manifest().is_embedded() {
861 if !bcx.gctx.cli_unstable().script {
862 anyhow::bail!(
863 "parsing `{}` requires `-Zscript`",
864 unit.pkg.manifest_path().display()
865 );
866 }
867 rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
868 rustdoc.arg("-Z").arg("crate-attr=allow(unused_features)");
869 }
870 rustdoc.inherit_jobserver(&build_runner.jobserver);
871 let crate_name = unit.target.crate_name();
872 rustdoc.arg("--crate-name").arg(&crate_name);
873 add_path_args(bcx.ws, unit, &mut rustdoc);
874 add_cap_lints(bcx, unit, &mut rustdoc);
875
876 unit.kind.add_target_arg(&mut rustdoc);
877
878 let doc_dir = if build_runner.bcx.build_config.intent.wants_doc_json_output() {
879 build_runner.files().out_dir_new_layout(unit)
883 } else {
884 build_runner.files().output_dir(unit)
885 };
886
887 rustdoc.arg("-o").arg(&doc_dir);
888 rustdoc.args(&features_args(unit));
889 rustdoc.args(&check_cfg_args(unit));
890
891 add_error_format_and_color(build_runner, &mut rustdoc);
892 add_allow_features(build_runner, &mut rustdoc);
893
894 if build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo {
895 let mut arg = if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
898 OsString::from("--emit=html-non-static-files,dep-info=")
900 } else {
901 OsString::from("--emit=html-static-files,html-non-static-files,dep-info=")
903 };
904 arg.push(rustdoc_dep_info_loc(build_runner, unit));
905 rustdoc.arg(arg);
906
907 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
908 rustdoc.arg("-Z").arg("checksum-hash-algorithm=blake3");
909 }
910 } else if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
911 rustdoc.arg("--emit=html-non-static-files");
913 }
914
915 if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
916 rustdoc.arg("-Zunstable-options");
918 rustdoc.arg("--merge=none");
919 let mut arg = OsString::from("--parts-out-dir=");
920 arg.push(build_runner.files().out_dir_new_layout(unit));
922 rustdoc.arg(arg);
923 }
924
925 if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
926 trim_paths_args_rustdoc(&mut rustdoc, build_runner, unit, trim_paths)?;
927 }
928
929 rustdoc.args(unit.pkg.manifest().lint_rustflags());
930
931 let metadata = build_runner.metadata_for_doc_units[unit];
932 rustdoc
933 .arg("-C")
934 .arg(format!("metadata={}", metadata.c_metadata()));
935
936 if unit.mode.is_doc_scrape() {
937 debug_assert!(build_runner.bcx.scrape_units.contains(unit));
938
939 if unit.target.is_test() {
940 rustdoc.arg("--scrape-tests");
941 }
942
943 rustdoc.arg("-Zunstable-options");
944
945 rustdoc
946 .arg("--scrape-examples-output-path")
947 .arg(scrape_output_path(build_runner, unit)?);
948
949 for pkg in build_runner.bcx.packages.packages() {
951 let names = pkg
952 .targets()
953 .iter()
954 .map(|target| target.crate_name())
955 .collect::<HashSet<_>>();
956 for name in names {
957 rustdoc.arg("--scrape-examples-target-crate").arg(name);
958 }
959 }
960 }
961
962 if should_include_scrape_units(build_runner.bcx, unit) {
963 rustdoc.arg("-Zunstable-options");
964 }
965
966 build_deps_args(&mut rustdoc, build_runner, unit)?;
967 rustdoc::add_root_urls(build_runner, unit, &mut rustdoc)?;
968
969 rustdoc::add_output_format(build_runner, &mut rustdoc)?;
970
971 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
972 rustdoc.args(args);
973 }
974 rustdoc.args(&unit.rustdocflags);
975
976 if !crate_version_flag_already_present(&rustdoc) {
977 append_crate_version_flag(unit, &mut rustdoc);
978 }
979
980 Ok(rustdoc)
981}
982
983fn rustdoc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Work> {
985 let mut rustdoc = prepare_rustdoc(build_runner, unit)?;
986
987 let crate_name = unit.target.crate_name();
988 let is_json_output = build_runner.bcx.build_config.intent.wants_doc_json_output();
989 let doc_dir = build_runner.files().output_dir(unit);
990 paths::create_dir_all(&doc_dir)?;
994
995 let target_desc = unit.target.description_named();
996 let name = unit.pkg.name();
997 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
998 let package_id = unit.pkg.package_id();
999 let target = Target::clone(&unit.target);
1000 let manifest = ManifestErrorContext::new(build_runner, unit);
1001
1002 let rustdoc_dep_info_loc = rustdoc_dep_info_loc(build_runner, unit);
1003 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
1004 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
1005 let pkg_root = unit.pkg.root().to_path_buf();
1006 let cwd = rustdoc
1007 .get_cwd()
1008 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
1009 .to_path_buf();
1010 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
1011 let is_local = unit.is_local();
1012 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
1013 let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
1014
1015 let mut output_options = OutputOptions::for_dirty(build_runner, unit);
1016 let script_metadatas = build_runner.find_build_script_metadatas(unit);
1017 let scrape_outputs = if should_include_scrape_units(build_runner.bcx, unit) {
1018 Some(
1019 build_runner
1020 .bcx
1021 .scrape_units
1022 .iter()
1023 .map(|unit| {
1024 Ok((
1025 build_runner.files().metadata(unit).unit_id(),
1026 scrape_output_path(build_runner, unit)?,
1027 ))
1028 })
1029 .collect::<CargoResult<HashMap<_, _>>>()?,
1030 )
1031 } else {
1032 None
1033 };
1034
1035 let failed_scrape_units = Arc::clone(&build_runner.failed_scrape_units);
1036 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
1037 && !matches!(
1038 build_runner.bcx.gctx.shell().verbosity(),
1039 Verbosity::Verbose
1040 );
1041 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
1042 make_failed_scrape_diagnostic(
1043 build_runner,
1044 unit,
1045 format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
1046 )
1047 });
1048 if hide_diagnostics_for_scrape_unit {
1049 output_options.show_diagnostics = false;
1050 }
1051
1052 Ok(Work::new(move |state| {
1053 add_custom_flags(
1054 &mut rustdoc,
1055 &build_script_outputs.lock().unwrap(),
1056 script_metadatas,
1057 )?;
1058
1059 if let Some(scrape_outputs) = scrape_outputs {
1064 let failed_scrape_units = failed_scrape_units.lock().unwrap();
1065 for (metadata, output_path) in &scrape_outputs {
1066 if !failed_scrape_units.contains(metadata) {
1067 rustdoc.arg("--with-examples").arg(output_path);
1068 }
1069 }
1070 }
1071
1072 if !is_json_output {
1073 let crate_dir = doc_dir.join(&crate_name);
1074 if crate_dir.exists() {
1075 debug!("removing pre-existing doc directory {:?}", crate_dir);
1078 paths::remove_dir_all(&crate_dir)?;
1079 }
1080 };
1081 state.running(&rustdoc);
1082 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
1083
1084 let result = rustdoc
1085 .exec_with_streaming(
1086 &mut |line| on_stdout_line(state, line, package_id, &target),
1087 &mut |line| {
1088 on_stderr_line(
1089 state,
1090 line,
1091 package_id,
1092 &manifest,
1093 &target,
1094 &mut output_options,
1095 )
1096 },
1097 false,
1098 )
1099 .map_err(verbose_if_simple_exit_code)
1100 .with_context(|| format!("could not document `{}`", name));
1101
1102 if let Err(e) = result {
1103 if let Some(diagnostic) = failed_scrape_diagnostic {
1104 state.warning(diagnostic);
1105 }
1106
1107 return Err(e);
1108 }
1109
1110 if rustdoc_depinfo_enabled && rustdoc_dep_info_loc.exists() {
1111 fingerprint::translate_dep_info(
1112 &rustdoc_dep_info_loc,
1113 &dep_info_loc,
1114 &cwd,
1115 &pkg_root,
1116 &build_dir,
1117 &rustdoc,
1118 is_local,
1120 &env_config,
1121 )
1122 .with_context(|| {
1123 internal(format_args!(
1124 "could not parse/generate dep info at: {}",
1125 rustdoc_dep_info_loc.display()
1126 ))
1127 })?;
1128 paths::set_file_time_no_err(dep_info_loc, timestamp);
1131 }
1132
1133 Ok(())
1134 }))
1135}
1136
1137fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
1140 rustdoc.get_args().any(|flag| {
1141 flag.to_str()
1142 .map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
1143 })
1144}
1145
1146fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
1147 rustdoc
1148 .arg(RUSTDOC_CRATE_VERSION_FLAG)
1149 .arg(unit.pkg.version().to_string());
1150}
1151
1152enum CapLints {
1153 Allow,
1154 Warn,
1155}
1156
1157fn compute_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit) -> Option<CapLints> {
1158 if !unit.show_warnings(bcx.gctx) {
1161 Some(CapLints::Allow)
1162 } else if !unit.is_local() {
1165 Some(CapLints::Warn)
1166 } else {
1167 None
1168 }
1169}
1170
1171fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
1175 if let Some(cap_lints) = compute_cap_lints(bcx, unit) {
1176 match cap_lints {
1177 CapLints::Allow => {
1178 cmd.arg("--cap-lints").arg("allow");
1179 }
1180 CapLints::Warn => {
1181 cmd.arg("--cap-lints").arg("warn");
1182 }
1183 }
1184 }
1185}
1186
1187fn add_allow_features(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1191 if let Some(allow) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1192 use std::fmt::Write;
1193 let mut arg = String::from("-Zallow-features=");
1194 for f in allow {
1195 let _ = write!(&mut arg, "{f},");
1196 }
1197 cmd.arg(arg.trim_end_matches(','));
1198 }
1199}
1200
1201fn add_error_format_and_color(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1212 let enable_timings =
1213 build_runner.bcx.gctx.cli_unstable().section_timings && build_runner.bcx.logger.is_some();
1214 if enable_timings {
1215 cmd.arg("-Zunstable-options");
1216 }
1217
1218 cmd.arg("--error-format=json");
1219
1220 let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
1221 if build_runner.bcx.gctx.cli_unstable().cargo_lints {
1222 json.push_str(",unused-externs-silent");
1223 }
1224 if let MessageFormat::Short | MessageFormat::Json { short: true, .. } =
1225 build_runner.bcx.build_config.message_format
1226 {
1227 json.push_str(",diagnostic-short");
1228 } else if build_runner.bcx.gctx.shell().err_unicode()
1229 && build_runner.bcx.gctx.cli_unstable().rustc_unicode
1230 {
1231 json.push_str(",diagnostic-unicode");
1232 }
1233 if enable_timings {
1234 json.push_str(",timings");
1235 }
1236 cmd.arg(json);
1237
1238 let gctx = build_runner.bcx.gctx;
1239 if let Some(width) = gctx.shell().err_width().diagnostic_terminal_width() {
1240 cmd.arg(format!("--diagnostic-width={width}"));
1241 }
1242}
1243
1244fn build_base_args(
1246 build_runner: &BuildRunner<'_, '_>,
1247 cmd: &mut ProcessBuilder,
1248 unit: &Unit,
1249) -> CargoResult<()> {
1250 assert!(!unit.mode.is_run_custom_build());
1251
1252 let bcx = build_runner.bcx;
1253 let Profile {
1254 ref opt_level,
1255 codegen_backend,
1256 codegen_units,
1257 debuginfo,
1258 debug_assertions,
1259 split_debuginfo,
1260 overflow_checks,
1261 rpath,
1262 ref panic,
1263 incremental,
1264 strip,
1265 rustflags: profile_rustflags,
1266 trim_paths,
1267 hint_mostly_unused: profile_hint_mostly_unused,
1268 ..
1269 } = unit.profile.clone();
1270 let hints = unit.pkg.hints().cloned().unwrap_or_default();
1271 let test = unit.mode.is_any_test();
1272
1273 let warn = |msg: &str| {
1274 bcx.gctx.shell().warn(format!(
1275 "{}@{}: {msg}",
1276 unit.pkg.package_id().name(),
1277 unit.pkg.package_id().version()
1278 ))
1279 };
1280 let unit_capped_warn = |msg: &str| {
1281 if unit.show_warnings(bcx.gctx) {
1282 warn(msg)
1283 } else {
1284 Ok(())
1285 }
1286 };
1287
1288 cmd.arg("--crate-name").arg(&unit.target.crate_name());
1289
1290 let edition = unit.target.edition();
1291 edition.cmd_edition_arg(cmd);
1292
1293 add_path_args(bcx.ws, unit, cmd);
1294 add_error_format_and_color(build_runner, cmd);
1295 add_allow_features(build_runner, cmd);
1296
1297 let mut contains_dy_lib = false;
1298 if !test {
1299 for crate_type in &unit.target.rustc_crate_types() {
1300 cmd.arg("--crate-type").arg(crate_type.as_str());
1301 contains_dy_lib |= crate_type == &CrateType::Dylib;
1302 }
1303 }
1304
1305 if unit.mode.is_check() {
1306 cmd.arg("--emit=dep-info,metadata");
1307 } else if build_runner.bcx.gctx.cli_unstable().no_embed_metadata {
1308 if unit.benefits_from_no_embed_metadata() {
1318 cmd.arg("--emit=dep-info,metadata,link");
1319 cmd.args(&["-Z", "embed-metadata=no"]);
1320 } else {
1321 cmd.arg("--emit=dep-info,link");
1322 }
1323 } else {
1324 if !unit.requires_upstream_objects() {
1328 cmd.arg("--emit=dep-info,metadata,link");
1329 } else {
1330 cmd.arg("--emit=dep-info,link");
1331 }
1332 }
1333
1334 let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
1335 || (contains_dy_lib && !build_runner.is_primary_package(unit));
1336 if prefer_dynamic {
1337 cmd.arg("-C").arg("prefer-dynamic");
1338 }
1339
1340 if opt_level.as_str() != "0" {
1341 cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
1342 }
1343
1344 if *panic != PanicStrategy::Unwind {
1345 cmd.arg("-C").arg(format!("panic={}", panic));
1346 }
1347 if *panic == PanicStrategy::ImmediateAbort {
1348 cmd.arg("-Z").arg("unstable-options");
1349 }
1350
1351 cmd.args(<o_args(build_runner, unit));
1352
1353 if let Some(backend) = codegen_backend {
1354 cmd.arg("-Z").arg(&format!("codegen-backend={}", backend));
1355 }
1356
1357 if let Some(n) = codegen_units {
1358 cmd.arg("-C").arg(&format!("codegen-units={}", n));
1359 }
1360
1361 let debuginfo = debuginfo.into_inner();
1362 if debuginfo != TomlDebugInfo::None {
1364 cmd.arg("-C").arg(format!("debuginfo={debuginfo}"));
1365 if let Some(split) = split_debuginfo {
1372 if build_runner
1373 .bcx
1374 .target_data
1375 .info(unit.kind)
1376 .supports_debuginfo_split(split)
1377 {
1378 cmd.arg("-C").arg(format!("split-debuginfo={split}"));
1379 }
1380 }
1381 }
1382
1383 if let Some(trim_paths) = trim_paths {
1384 trim_paths_args(cmd, build_runner, unit, &trim_paths)?;
1385 }
1386
1387 match compute_cap_lints(bcx, unit) {
1388 None | Some(CapLints::Warn) => {
1389 cmd.args(unit.pkg.manifest().lint_rustflags());
1390 }
1391 Some(CapLints::Allow) => {}
1394 }
1395 cmd.args(&profile_rustflags);
1396
1397 if opt_level.as_str() != "0" {
1401 if debug_assertions {
1402 cmd.args(&["-C", "debug-assertions=on"]);
1403 if !overflow_checks {
1404 cmd.args(&["-C", "overflow-checks=off"]);
1405 }
1406 } else if overflow_checks {
1407 cmd.args(&["-C", "overflow-checks=on"]);
1408 }
1409 } else if !debug_assertions {
1410 cmd.args(&["-C", "debug-assertions=off"]);
1411 if overflow_checks {
1412 cmd.args(&["-C", "overflow-checks=on"]);
1413 }
1414 } else if !overflow_checks {
1415 cmd.args(&["-C", "overflow-checks=off"]);
1416 }
1417
1418 if test && unit.target.harness() {
1419 cmd.arg("--test");
1420
1421 if *panic == PanicStrategy::Abort || *panic == PanicStrategy::ImmediateAbort {
1429 cmd.arg("-Z").arg("panic-abort-tests");
1430 }
1431 } else if test {
1432 cmd.arg("--cfg").arg("test");
1433 }
1434
1435 cmd.args(&features_args(unit));
1436 cmd.args(&check_cfg_args(unit));
1437
1438 let meta = build_runner.files().metadata(unit);
1439 cmd.arg("-C")
1440 .arg(&format!("metadata={}", meta.c_metadata()));
1441 if let Some(c_extra_filename) = meta.c_extra_filename() {
1442 cmd.arg("-C")
1443 .arg(&format!("extra-filename=-{c_extra_filename}"));
1444 }
1445
1446 if rpath {
1447 cmd.arg("-C").arg("rpath");
1448 }
1449
1450 cmd.arg("--out-dir")
1451 .arg(&build_runner.files().output_dir(unit));
1452
1453 unit.kind.add_target_arg(cmd);
1454
1455 add_codegen_linker(cmd, build_runner, unit, bcx.gctx.target_applies_to_host()?);
1456
1457 if incremental {
1458 add_codegen_incremental(cmd, build_runner, unit)
1459 }
1460
1461 let pkg_hint_mostly_unused = match hints.mostly_unused {
1462 None => None,
1463 Some(toml::Value::Boolean(b)) => Some(b),
1464 Some(v) => {
1465 unit_capped_warn(&format!(
1466 "ignoring unsupported value type ({}) for 'hints.mostly-unused', which expects a boolean",
1467 v.type_str()
1468 ))?;
1469 None
1470 }
1471 };
1472 if profile_hint_mostly_unused
1473 .or(pkg_hint_mostly_unused)
1474 .unwrap_or(false)
1475 {
1476 if bcx.gctx.cli_unstable().profile_hint_mostly_unused {
1477 cmd.arg("-Zhint-mostly-unused");
1478 } else {
1479 if profile_hint_mostly_unused.is_some() {
1480 warn(
1482 "ignoring 'hint-mostly-unused' profile option, pass `-Zprofile-hint-mostly-unused` to enable it",
1483 )?;
1484 } else if pkg_hint_mostly_unused.is_some() {
1485 unit_capped_warn(
1486 "ignoring 'hints.mostly-unused', pass `-Zprofile-hint-mostly-unused` to enable it",
1487 )?;
1488 }
1489 }
1490 }
1491
1492 let strip = strip.into_inner();
1493 if strip != StripInner::None {
1494 cmd.arg("-C").arg(format!("strip={}", strip));
1495 }
1496
1497 if unit.is_std {
1498 cmd.arg("-Z")
1504 .arg("force-unstable-if-unmarked")
1505 .env("RUSTC_BOOTSTRAP", "1");
1506 }
1507
1508 if let Some(version) = unit.pkg.manifest().rust_version()
1509 && bcx.gctx.cli_unstable().hint_msrv
1510 {
1511 cmd.arg("-Z").arg(format!("hint-msrv={version}"));
1512 }
1513
1514 Ok(())
1515}
1516
1517fn features_args(unit: &Unit) -> Vec<OsString> {
1519 let mut args = Vec::with_capacity(unit.features.len() * 2);
1520
1521 for feat in &unit.features {
1522 args.push(OsString::from("--cfg"));
1523 args.push(OsString::from(format!("feature=\"{}\"", feat)));
1524 }
1525
1526 args
1527}
1528
1529fn trim_paths_args_rustdoc(
1531 cmd: &mut ProcessBuilder,
1532 build_runner: &BuildRunner<'_, '_>,
1533 unit: &Unit,
1534 trim_paths: &TomlTrimPaths,
1535) -> CargoResult<()> {
1536 match trim_paths {
1537 TomlTrimPaths::Values(values) if !values.contains(&TomlTrimPathsValue::Diagnostics) => {
1539 return Ok(());
1540 }
1541 _ => {}
1542 }
1543
1544 cmd.arg("-Zunstable-options");
1546
1547 for pair in trim_paths_remap(build_runner, unit) {
1548 let mut arg = OsString::from("--remap-path-prefix=");
1549 arg.push(pair);
1550 cmd.arg(arg);
1551 }
1552
1553 Ok(())
1554}
1555
1556fn trim_paths_args(
1562 cmd: &mut ProcessBuilder,
1563 build_runner: &BuildRunner<'_, '_>,
1564 unit: &Unit,
1565 trim_paths: &TomlTrimPaths,
1566) -> CargoResult<()> {
1567 if trim_paths.is_none() {
1568 return Ok(());
1569 }
1570
1571 cmd.arg(format!("--remap-path-scope={trim_paths}"));
1573
1574 for pair in trim_paths_remap(build_runner, unit) {
1575 let mut arg = OsString::from("--remap-path-prefix=");
1576 arg.push(pair);
1577 cmd.arg(arg);
1578 }
1579
1580 Ok(())
1581}
1582
1583pub(crate) fn trim_paths_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> [OsString; 3] {
1590 [
1591 package_remap(build_runner, unit),
1592 build_dir_remap(build_runner),
1593 sysroot_remap(build_runner, unit),
1594 ]
1595}
1596
1597fn sysroot_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1602 let mut remap = OsString::new();
1603 remap.push({
1604 let mut sysroot = build_runner.bcx.target_data.info(unit.kind).sysroot.clone();
1606 sysroot.push("lib");
1607 sysroot.push("rustlib");
1608 sysroot.push("src");
1609 sysroot.push("rust");
1610 sysroot
1611 });
1612 remap.push("=");
1613 remap.push("/rustc/");
1614 if let Some(commit_hash) = build_runner.bcx.rustc().commit_hash.as_ref() {
1615 remap.push(commit_hash);
1616 } else {
1617 remap.push(build_runner.bcx.rustc().version.to_string());
1618 }
1619 remap
1620}
1621
1622fn package_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1630 let pkg_root = unit.pkg.root();
1631 let ws_root = build_runner.bcx.ws.root();
1632 let mut remap = OsString::new();
1633 let source_id = unit.pkg.package_id().source_id();
1634 if source_id.is_git() {
1635 remap.push(
1636 build_runner
1637 .bcx
1638 .gctx
1639 .git_checkouts_path()
1640 .as_path_unlocked(),
1641 );
1642 remap.push("=");
1643 } else if source_id.is_registry() {
1644 remap.push(
1645 build_runner
1646 .bcx
1647 .gctx
1648 .registry_source_path()
1649 .as_path_unlocked(),
1650 );
1651 remap.push("=");
1652 } else if pkg_root.strip_prefix(ws_root).is_ok() {
1653 remap.push(ws_root);
1654 remap.push("=."); } else {
1656 remap.push(pkg_root);
1657 remap.push("=");
1658 remap.push(unit.pkg.name());
1659 remap.push("-");
1660 remap.push(unit.pkg.version().to_string());
1661 }
1662 remap
1663}
1664
1665fn build_dir_remap(build_runner: &BuildRunner<'_, '_>) -> OsString {
1678 let build_dir = build_runner.bcx.ws.build_dir();
1679 let mut remap = OsString::new();
1680 remap.push(build_dir.as_path_unlocked());
1681 remap.push("=/cargo/build-dir");
1682 remap
1683}
1684
1685fn check_cfg_args(unit: &Unit) -> Vec<OsString> {
1687 let gross_cap_estimation = unit.pkg.summary().features().len() * 7 + 25;
1705 let mut arg_feature = OsString::with_capacity(gross_cap_estimation);
1706
1707 arg_feature.push("cfg(feature, values(");
1708 for (i, feature) in unit.pkg.summary().features().keys().enumerate() {
1709 if i != 0 {
1710 arg_feature.push(", ");
1711 }
1712 arg_feature.push("\"");
1713 arg_feature.push(feature);
1714 arg_feature.push("\"");
1715 }
1716 arg_feature.push("))");
1717
1718 vec![
1727 OsString::from("--check-cfg"),
1728 OsString::from("cfg(docsrs,test)"),
1729 OsString::from("--check-cfg"),
1730 arg_feature,
1731 ]
1732}
1733
1734fn lto_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1736 let mut result = Vec::new();
1737 let mut push = |arg: &str| {
1738 result.push(OsString::from("-C"));
1739 result.push(OsString::from(arg));
1740 };
1741 match build_runner.lto[unit] {
1742 lto::Lto::Run(None) => push("lto"),
1743 lto::Lto::Run(Some(s)) => push(&format!("lto={}", s)),
1744 lto::Lto::Off => {
1745 push("lto=off");
1746 push("embed-bitcode=no");
1747 }
1748 lto::Lto::ObjectAndBitcode => {} lto::Lto::OnlyBitcode => push("linker-plugin-lto"),
1750 lto::Lto::OnlyObject => push("embed-bitcode=no"),
1751 }
1752 result
1753}
1754
1755fn build_deps_args(
1761 cmd: &mut ProcessBuilder,
1762 build_runner: &BuildRunner<'_, '_>,
1763 unit: &Unit,
1764) -> CargoResult<()> {
1765 let bcx = build_runner.bcx;
1766
1767 for arg in lib_search_paths(build_runner, unit)? {
1768 cmd.arg(arg);
1769 }
1770
1771 let deps = build_runner.unit_deps(unit);
1772
1773 if !deps
1777 .iter()
1778 .any(|dep| !dep.unit.mode.is_doc() && dep.unit.target.is_linkable())
1779 {
1780 if let Some(dep) = deps.iter().find(|dep| {
1781 !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true()
1782 }) {
1783 let dep_name = dep.unit.target.crate_name();
1784 let name = unit.target.crate_name();
1785 bcx.gctx.shell().print_report(&[
1786 Level::WARNING.secondary_title(format!("the package `{dep_name}` provides no linkable target"))
1787 .elements([
1788 Level::NOTE.message(format!("this might cause `{name}` to fail compilation")),
1789 Level::NOTE.message("this warning might turn into a hard error in the future"),
1790 Level::HELP.message(format!("consider adding 'dylib' or 'rlib' to key 'crate-type' in `{dep_name}`'s Cargo.toml"))
1791 ])
1792 ], false)?;
1793 }
1794 }
1795
1796 let mut unstable_opts = false;
1797
1798 let first_custom_build_dep = deps.iter().find(|dep| dep.unit.mode.is_run_custom_build());
1800 if let Some(dep) = first_custom_build_dep {
1801 let out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
1802 build_runner.files().out_dir_new_layout(&dep.unit)
1803 } else {
1804 build_runner.files().build_script_out_dir(&dep.unit)
1805 };
1806 cmd.env("OUT_DIR", &out_dir);
1807 }
1808
1809 let is_multiple_build_scripts_enabled = unit
1811 .pkg
1812 .manifest()
1813 .unstable_features()
1814 .require(Feature::multiple_build_scripts())
1815 .is_ok();
1816
1817 if is_multiple_build_scripts_enabled {
1818 for dep in deps {
1819 if dep.unit.mode.is_run_custom_build() {
1820 let out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
1821 build_runner.files().out_dir_new_layout(&dep.unit)
1822 } else {
1823 build_runner.files().build_script_out_dir(&dep.unit)
1824 };
1825 let target_name = dep.unit.target.name();
1826 let out_dir_prefix = target_name
1827 .strip_prefix("build-script-")
1828 .unwrap_or(target_name);
1829 let out_dir_name = format!("{out_dir_prefix}_OUT_DIR");
1830 cmd.env(&out_dir_name, &out_dir);
1831 }
1832 }
1833 }
1834 for arg in extern_args(build_runner, unit, &mut unstable_opts)? {
1835 cmd.arg(arg);
1836 }
1837
1838 for (var, env) in artifact::get_env(build_runner, unit, deps)? {
1839 cmd.env(&var, env);
1840 }
1841
1842 if unstable_opts {
1845 cmd.arg("-Z").arg("unstable-options");
1846 }
1847
1848 Ok(())
1849}
1850
1851fn add_dep_arg<'a, 'b: 'a>(
1852 map: &mut BTreeMap<&'a Unit, PathBuf>,
1853 build_runner: &'b BuildRunner<'b, '_>,
1854 unit: &'a Unit,
1855) {
1856 if map.contains_key(&unit) {
1857 return;
1858 }
1859 map.insert(&unit, build_runner.files().deps_dir(&unit));
1860
1861 for dep in build_runner.unit_deps(unit) {
1862 add_dep_arg(map, build_runner, &dep.unit);
1863 }
1864}
1865
1866fn add_custom_flags(
1870 cmd: &mut ProcessBuilder,
1871 build_script_outputs: &BuildScriptOutputs,
1872 metadata_vec: Option<Vec<UnitHash>>,
1873) -> CargoResult<()> {
1874 if let Some(metadata_vec) = metadata_vec {
1875 for metadata in metadata_vec {
1876 if let Some(output) = build_script_outputs.get(metadata) {
1877 for cfg in output.cfgs.iter() {
1878 cmd.arg("--cfg").arg(cfg);
1879 }
1880 for check_cfg in &output.check_cfgs {
1881 cmd.arg("--check-cfg").arg(check_cfg);
1882 }
1883 for (name, value) in output.env.iter() {
1884 cmd.env(name, value);
1885 }
1886 }
1887 }
1888 }
1889
1890 Ok(())
1891}
1892
1893pub fn lib_search_paths(
1895 build_runner: &BuildRunner<'_, '_>,
1896 unit: &Unit,
1897) -> CargoResult<Vec<OsString>> {
1898 let mut lib_search_paths = Vec::new();
1899 if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1900 let mut map = BTreeMap::new();
1901
1902 add_dep_arg(&mut map, build_runner, unit);
1904
1905 let paths = map.into_iter().map(|(_, path)| path).sorted_unstable();
1906
1907 for path in paths {
1908 let mut deps = OsString::from("dependency=");
1909 deps.push(path);
1910 lib_search_paths.extend(["-L".into(), deps]);
1911 }
1912 } else {
1913 let mut deps = OsString::from("dependency=");
1914 deps.push(build_runner.files().deps_dir(unit));
1915 lib_search_paths.extend(["-L".into(), deps]);
1916 }
1917
1918 if !unit.kind.is_host() {
1921 let mut deps = OsString::from("dependency=");
1922 deps.push(build_runner.files().host_deps(unit));
1923 lib_search_paths.extend(["-L".into(), deps]);
1924 }
1925
1926 Ok(lib_search_paths)
1927}
1928
1929fn is_public_dependency_enabled(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> bool {
1930 unit.pkg
1931 .manifest()
1932 .unstable_features()
1933 .require(Feature::public_dependency())
1934 .is_ok()
1935 || build_runner.bcx.gctx.cli_unstable().public_dependency
1936}
1937
1938pub fn extern_args(
1940 build_runner: &BuildRunner<'_, '_>,
1941 unit: &Unit,
1942 unstable_opts: &mut bool,
1943) -> CargoResult<Vec<OsString>> {
1944 let mut result = Vec::new();
1945 let deps = build_runner.unit_deps(unit);
1946
1947 let no_embed_metadata = build_runner.bcx.gctx.cli_unstable().no_embed_metadata;
1948 let public_dependency_enabled = is_public_dependency_enabled(build_runner, unit);
1949
1950 let mut link_to = |dep: &UnitDep,
1952 extern_crate_name: InternedString,
1953 noprelude: bool,
1954 nounused: bool|
1955 -> CargoResult<()> {
1956 let mut value = OsString::new();
1957 let mut opts = Vec::new();
1958 if !dep.public && unit.target.is_lib() && public_dependency_enabled {
1959 opts.push("priv");
1960 *unstable_opts = true;
1961 }
1962 if noprelude {
1963 opts.push("noprelude");
1964 *unstable_opts = true;
1965 }
1966 if nounused {
1967 opts.push("nounused");
1968 *unstable_opts = true;
1969 }
1970 if !opts.is_empty() {
1971 value.push(opts.join(","));
1972 value.push(":");
1973 }
1974 value.push(extern_crate_name.as_str());
1975 value.push("=");
1976
1977 let mut pass = |file| {
1978 let mut value = value.clone();
1979 value.push(file);
1980 result.push(OsString::from("--extern"));
1981 result.push(value);
1982 };
1983
1984 let outputs = build_runner.outputs(&dep.unit)?;
1985
1986 if build_runner.only_requires_rmeta(unit, &dep.unit) || dep.unit.mode.is_check() {
1987 let output = outputs
1989 .iter()
1990 .find(|output| output.flavor == FileFlavor::Rmeta)
1991 .expect("failed to find rmeta dep for pipelined dep");
1992 pass(&output.path);
1993 } else {
1994 for output in outputs.iter() {
1996 if output.flavor == FileFlavor::Linkable {
1997 pass(&output.path);
1998 }
1999 else if no_embed_metadata && output.flavor == FileFlavor::Rmeta {
2003 pass(&output.path);
2004 }
2005 }
2006 }
2007 Ok(())
2008 };
2009
2010 for dep in deps {
2011 if dep.unit.target.is_linkable() && !dep.unit.mode.is_doc() {
2012 link_to(dep, dep.extern_crate_name, dep.noprelude, dep.nounused)?;
2013 }
2014 }
2015 if unit.target.proc_macro() {
2016 result.push(OsString::from("--extern"));
2018 result.push(OsString::from("proc_macro"));
2019 }
2020
2021 Ok(result)
2022}
2023
2024fn add_codegen_linker(
2026 cmd: &mut ProcessBuilder,
2027 build_runner: &BuildRunner<'_, '_>,
2028 unit: &Unit,
2029 target_applies_to_host: bool,
2030) {
2031 let linker = if unit.target.for_host() && !target_applies_to_host {
2032 build_runner
2033 .compilation
2034 .host_linker()
2035 .map(|s| s.as_os_str())
2036 } else {
2037 build_runner
2038 .compilation
2039 .target_linker(unit.kind)
2040 .map(|s| s.as_os_str())
2041 };
2042
2043 if let Some(linker) = linker {
2044 let mut arg = OsString::from("linker=");
2045 arg.push(linker);
2046 cmd.arg("-C").arg(arg);
2047 }
2048}
2049
2050fn add_codegen_incremental(
2052 cmd: &mut ProcessBuilder,
2053 build_runner: &BuildRunner<'_, '_>,
2054 unit: &Unit,
2055) {
2056 let dir = build_runner.files().incremental_dir(&unit);
2057 let mut arg = OsString::from("incremental=");
2058 arg.push(dir.as_os_str());
2059 cmd.arg("-C").arg(arg);
2060}
2061
2062fn envify(s: &str) -> String {
2063 s.chars()
2064 .flat_map(|c| c.to_uppercase())
2065 .map(|c| if c == '-' { '_' } else { c })
2066 .collect()
2067}
2068
2069struct OutputOptions {
2072 format: MessageFormat,
2074 cache_cell: Option<(PathBuf, OnceCell<File>)>,
2079 show_diagnostics: bool,
2087 warnings_seen: usize,
2089 errors_seen: usize,
2091}
2092
2093impl OutputOptions {
2094 fn for_dirty(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2095 let path = build_runner.files().message_cache_path(unit);
2096 drop(fs::remove_file(&path));
2098 let cache_cell = Some((path, OnceCell::new()));
2099
2100 let show_diagnostics = true;
2101
2102 let format = build_runner.bcx.build_config.message_format;
2103
2104 OutputOptions {
2105 format,
2106 cache_cell,
2107 show_diagnostics,
2108 warnings_seen: 0,
2109 errors_seen: 0,
2110 }
2111 }
2112
2113 fn for_fresh(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2114 let cache_cell = None;
2115
2116 let show_diagnostics = unit.show_warnings(build_runner.bcx.gctx);
2119
2120 let format = build_runner.bcx.build_config.message_format;
2121
2122 OutputOptions {
2123 format,
2124 cache_cell,
2125 show_diagnostics,
2126 warnings_seen: 0,
2127 errors_seen: 0,
2128 }
2129 }
2130}
2131
2132struct ManifestErrorContext {
2138 path: PathBuf,
2140 spans: Option<Arc<toml::Spanned<toml::de::DeTable<'static>>>>,
2142 contents: Option<String>,
2144 rename_table: HashMap<InternedString, InternedString>,
2147 requested_kinds: Vec<CompileKind>,
2150 cfgs: Vec<Vec<Cfg>>,
2153 host_name: InternedString,
2154 cwd: PathBuf,
2156 term_width: usize,
2158}
2159
2160fn on_stdout_line(
2161 state: &JobState<'_, '_>,
2162 line: &str,
2163 _package_id: PackageId,
2164 _target: &Target,
2165) -> CargoResult<()> {
2166 state.stdout(line.to_string())?;
2167 Ok(())
2168}
2169
2170fn on_stderr_line(
2171 state: &JobState<'_, '_>,
2172 line: &str,
2173 package_id: PackageId,
2174 manifest: &ManifestErrorContext,
2175 target: &Target,
2176 options: &mut OutputOptions,
2177) -> CargoResult<()> {
2178 if on_stderr_line_inner(state, line, package_id, manifest, target, options)? {
2179 if let Some((path, cell)) = &mut options.cache_cell {
2181 let f = cell.try_borrow_mut_with(|| paths::create(path))?;
2183 debug_assert!(!line.contains('\n'));
2184 f.write_all(line.as_bytes())?;
2185 f.write_all(&[b'\n'])?;
2186 }
2187 }
2188 Ok(())
2189}
2190
2191fn on_stderr_line_inner(
2193 state: &JobState<'_, '_>,
2194 line: &str,
2195 package_id: PackageId,
2196 manifest: &ManifestErrorContext,
2197 target: &Target,
2198 options: &mut OutputOptions,
2199) -> CargoResult<bool> {
2200 if !line.starts_with('{') {
2206 state.stderr(line.to_string())?;
2207 return Ok(true);
2208 }
2209
2210 let mut compiler_message: Box<serde_json::value::RawValue> = match serde_json::from_str(line) {
2211 Ok(msg) => msg,
2212
2213 Err(e) => {
2217 debug!("failed to parse json: {:?}", e);
2218 state.stderr(line.to_string())?;
2219 return Ok(true);
2220 }
2221 };
2222
2223 let count_diagnostic = |level, options: &mut OutputOptions| {
2224 if level == "warning" {
2225 options.warnings_seen += 1;
2226 } else if level == "error" {
2227 options.errors_seen += 1;
2228 }
2229 };
2230
2231 if let Ok(report) = serde_json::from_str::<FutureIncompatReport>(compiler_message.get()) {
2232 for item in &report.future_incompat_report {
2233 count_diagnostic(&*item.diagnostic.level, options);
2234 }
2235 state.future_incompat_report(report.future_incompat_report);
2236 return Ok(true);
2237 }
2238
2239 let res = serde_json::from_str::<SectionTiming>(compiler_message.get());
2240 if let Ok(timing_record) = res {
2241 state.on_section_timing_emitted(timing_record);
2242 return Ok(false);
2243 }
2244
2245 let add_pub_in_priv_diagnostic = |diag: &mut String| -> bool {
2247 static PRIV_DEP_REGEX: LazyLock<Regex> =
2256 LazyLock::new(|| Regex::new("from private dependency '([A-Za-z0-9-_]+)'").unwrap());
2257 if let Some(crate_name) = PRIV_DEP_REGEX.captures(diag).and_then(|m| m.get(1))
2258 && let Some(ref contents) = manifest.contents
2259 && let Some(span) = manifest.find_crate_span(crate_name.as_str())
2260 {
2261 let rel_path = pathdiff::diff_paths(&manifest.path, &manifest.cwd)
2262 .unwrap_or_else(|| manifest.path.clone())
2263 .display()
2264 .to_string();
2265 let report = [Group::with_title(Level::NOTE.secondary_title(format!(
2266 "dependency `{}` declared here",
2267 crate_name.as_str()
2268 )))
2269 .element(
2270 Snippet::source(contents)
2271 .path(rel_path)
2272 .annotation(AnnotationKind::Context.span(span)),
2273 )];
2274
2275 let rendered = Renderer::styled()
2276 .term_width(manifest.term_width)
2277 .render(&report);
2278 diag.push_str(&rendered);
2279 diag.push('\n');
2280 return true;
2281 }
2282 false
2283 };
2284
2285 match options.format {
2288 MessageFormat::Human
2293 | MessageFormat::Short
2294 | MessageFormat::Json {
2295 render_diagnostics: true,
2296 ..
2297 } => {
2298 #[derive(serde::Deserialize)]
2299 struct CompilerMessage<'a> {
2300 rendered: String,
2304 #[serde(borrow)]
2305 message: Cow<'a, str>,
2306 #[serde(borrow)]
2307 level: Cow<'a, str>,
2308 children: Vec<PartialDiagnostic>,
2309 code: Option<DiagnosticCode>,
2310 }
2311
2312 #[derive(serde::Deserialize)]
2321 struct PartialDiagnostic {
2322 spans: Vec<PartialDiagnosticSpan>,
2323 }
2324
2325 #[derive(serde::Deserialize)]
2327 struct PartialDiagnosticSpan {
2328 suggestion_applicability: Option<Applicability>,
2329 }
2330
2331 #[derive(serde::Deserialize)]
2332 struct DiagnosticCode {
2333 code: String,
2334 }
2335
2336 if let Ok(mut msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2337 {
2338 if msg.message.starts_with("aborting due to")
2339 || msg.message.ends_with("warning emitted")
2340 || msg.message.ends_with("warnings emitted")
2341 {
2342 return Ok(true);
2344 }
2345 if msg.rendered.ends_with('\n') {
2347 msg.rendered.pop();
2348 }
2349 let mut rendered = msg.rendered;
2350 if options.show_diagnostics {
2351 let machine_applicable: bool = msg
2352 .children
2353 .iter()
2354 .map(|child| {
2355 child
2356 .spans
2357 .iter()
2358 .filter_map(|span| span.suggestion_applicability)
2359 .any(|app| app == Applicability::MachineApplicable)
2360 })
2361 .any(|b| b);
2362 count_diagnostic(&msg.level, options);
2363 if msg
2364 .code
2365 .as_ref()
2366 .is_some_and(|c| c.code == "exported_private_dependencies")
2367 && options.format != MessageFormat::Short
2368 {
2369 add_pub_in_priv_diagnostic(&mut rendered);
2370 }
2371 let lint = msg.code.is_some();
2372 state.emit_diag(&msg.level, rendered, lint, machine_applicable)?;
2373 }
2374 return Ok(true);
2375 }
2376 }
2377
2378 MessageFormat::Json { ansi, .. } => {
2379 #[derive(serde::Deserialize, serde::Serialize)]
2380 struct CompilerMessage<'a> {
2381 rendered: String,
2382 #[serde(flatten, borrow)]
2383 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2384 code: Option<DiagnosticCode<'a>>,
2385 }
2386
2387 #[derive(serde::Deserialize, serde::Serialize)]
2388 struct DiagnosticCode<'a> {
2389 code: String,
2390 #[serde(flatten, borrow)]
2391 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2392 }
2393
2394 if let Ok(mut error) =
2395 serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2396 {
2397 let modified_diag = if error
2398 .code
2399 .as_ref()
2400 .is_some_and(|c| c.code == "exported_private_dependencies")
2401 {
2402 add_pub_in_priv_diagnostic(&mut error.rendered)
2403 } else {
2404 false
2405 };
2406
2407 if !ansi {
2411 error.rendered = anstream::adapter::strip_str(&error.rendered).to_string();
2412 }
2413 if !ansi || modified_diag {
2414 let new_line = serde_json::to_string(&error)?;
2415 compiler_message = serde_json::value::RawValue::from_string(new_line)?;
2416 }
2417 }
2418 }
2419 }
2420
2421 #[derive(serde::Deserialize)]
2428 struct ArtifactNotification<'a> {
2429 #[serde(borrow)]
2430 artifact: Cow<'a, str>,
2431 }
2432
2433 if let Ok(artifact) = serde_json::from_str::<ArtifactNotification<'_>>(compiler_message.get()) {
2434 trace!("found directive from rustc: `{}`", artifact.artifact);
2435 if artifact.artifact.ends_with(".rmeta") {
2436 debug!("looks like metadata finished early!");
2437 state.rmeta_produced();
2438 }
2439 return Ok(false);
2440 }
2441
2442 #[derive(serde::Deserialize)]
2443 struct UnusedExterns {
2444 unused_extern_names: std::collections::BTreeSet<InternedString>,
2445 }
2446 if let Ok(uext) = serde_json::from_str::<UnusedExterns>(compiler_message.get()) {
2447 trace!(
2448 "obtained unused externs list from rustc: `{:?}`",
2449 uext.unused_extern_names
2450 );
2451 state.unused_externs(uext.unused_extern_names);
2452 return Ok(true);
2453 }
2454
2455 if !options.show_diagnostics {
2460 return Ok(true);
2461 }
2462
2463 #[derive(serde::Deserialize)]
2464 struct CompilerMessage<'a> {
2465 #[serde(borrow)]
2466 message: Cow<'a, str>,
2467 #[serde(borrow)]
2468 level: Cow<'a, str>,
2469 }
2470
2471 if let Ok(msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get()) {
2472 if msg.message.starts_with("aborting due to")
2473 || msg.message.ends_with("warning emitted")
2474 || msg.message.ends_with("warnings emitted")
2475 {
2476 return Ok(true);
2478 }
2479 count_diagnostic(&msg.level, options);
2480 }
2481
2482 let msg = machine_message::FromCompiler {
2483 package_id: package_id.to_spec(),
2484 manifest_path: &manifest.path,
2485 target,
2486 message: compiler_message,
2487 }
2488 .to_json_string();
2489
2490 state.stdout(msg)?;
2494 Ok(true)
2495}
2496
2497impl ManifestErrorContext {
2498 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> ManifestErrorContext {
2499 let mut duplicates = HashSet::default();
2500 let mut rename_table = HashMap::default();
2501
2502 for dep in build_runner.unit_deps(unit) {
2503 let unrenamed_id = dep.unit.pkg.package_id().name();
2504 if duplicates.contains(&unrenamed_id) {
2505 continue;
2506 }
2507 match rename_table.entry(unrenamed_id) {
2508 std::collections::hash_map::Entry::Occupied(occ) => {
2509 occ.remove_entry();
2510 duplicates.insert(unrenamed_id);
2511 }
2512 std::collections::hash_map::Entry::Vacant(vac) => {
2513 vac.insert(dep.extern_crate_name);
2514 }
2515 }
2516 }
2517
2518 let bcx = build_runner.bcx;
2519 ManifestErrorContext {
2520 path: unit.pkg.manifest_path().to_owned(),
2521 spans: unit.pkg.manifest().document_rc(),
2522 contents: unit.pkg.manifest().contents().map(String::from),
2523 requested_kinds: bcx.target_data.requested_kinds().to_owned(),
2524 host_name: bcx.rustc().host,
2525 rename_table,
2526 cwd: path_args(build_runner.bcx.ws, unit).1,
2527 cfgs: bcx
2528 .target_data
2529 .requested_kinds()
2530 .iter()
2531 .map(|k| bcx.target_data.cfg(*k).to_owned())
2532 .collect(),
2533 term_width: bcx
2534 .gctx
2535 .shell()
2536 .err_width()
2537 .diagnostic_terminal_width()
2538 .unwrap_or(cargo_util_terminal::report::renderer::DEFAULT_TERM_WIDTH),
2539 }
2540 }
2541
2542 fn requested_target_names(&self) -> impl Iterator<Item = &str> {
2543 self.requested_kinds.iter().map(|kind| match kind {
2544 CompileKind::Host => &self.host_name,
2545 CompileKind::Target(target) => target.short_name(),
2546 })
2547 }
2548
2549 fn find_crate_span(&self, unrenamed: &str) -> Option<Range<usize>> {
2563 let Some(ref spans) = self.spans else {
2564 return None;
2565 };
2566
2567 let orig_name = self.rename_table.get(unrenamed)?.as_str();
2568
2569 if let Some((k, v)) = get_key_value(&spans, &["dependencies", orig_name]) {
2570 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package")) {
2579 return Some(package.span());
2580 } else {
2581 return Some(k.span());
2582 }
2583 }
2584
2585 if let Some(target) = spans
2590 .deref()
2591 .as_ref()
2592 .get("target")
2593 .and_then(|t| t.as_ref().as_table())
2594 {
2595 for (platform, platform_table) in target.iter() {
2596 match platform.as_ref().parse::<Platform>() {
2597 Ok(Platform::Name(name)) => {
2598 if !self.requested_target_names().any(|n| n == name) {
2599 continue;
2600 }
2601 }
2602 Ok(Platform::Cfg(cfg_expr)) => {
2603 if !self.cfgs.iter().any(|cfgs| cfg_expr.matches(cfgs)) {
2604 continue;
2605 }
2606 }
2607 Err(_) => continue,
2608 }
2609
2610 let Some(platform_table) = platform_table.as_ref().as_table() else {
2611 continue;
2612 };
2613
2614 if let Some(deps) = platform_table
2615 .get("dependencies")
2616 .and_then(|d| d.as_ref().as_table())
2617 {
2618 if let Some((k, v)) = deps.get_key_value(orig_name) {
2619 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package"))
2620 {
2621 return Some(package.span());
2622 } else {
2623 return Some(k.span());
2624 }
2625 }
2626 }
2627 }
2628 }
2629 None
2630 }
2631}
2632
2633fn replay_output_cache(
2637 package_id: PackageId,
2638 manifest: ManifestErrorContext,
2639 target: &Target,
2640 path: PathBuf,
2641 mut output_options: OutputOptions,
2642) -> Work {
2643 let target = target.clone();
2644 Work::new(move |state| {
2645 if !path.exists() {
2646 return Ok(());
2648 }
2649 let file = paths::open(&path)?;
2653 let mut reader = std::io::BufReader::new(file);
2654 let mut line = String::new();
2655 loop {
2656 let length = reader.read_line(&mut line)?;
2657 if length == 0 {
2658 break;
2659 }
2660 let trimmed = line.trim_end_matches(&['\n', '\r'][..]);
2661 on_stderr_line(
2662 state,
2663 trimmed,
2664 package_id,
2665 &manifest,
2666 &target,
2667 &mut output_options,
2668 )?;
2669 line.clear();
2670 }
2671 Ok(())
2672 })
2673}
2674
2675fn descriptive_pkg_name(name: &str, target: &Target, mode: &CompileMode) -> String {
2678 let desc_name = target.description_named();
2679 let mode = if mode.is_rustc_test() && !(target.is_test() || target.is_bench()) {
2680 " test"
2681 } else if mode.is_doc_test() {
2682 " doctest"
2683 } else if mode.is_doc() {
2684 " doc"
2685 } else {
2686 ""
2687 };
2688 format!("`{name}` ({desc_name}{mode})")
2689}
2690
2691pub(crate) fn apply_env_config(
2693 gctx: &crate::GlobalContext,
2694 cmd: &mut ProcessBuilder,
2695) -> CargoResult<()> {
2696 for (key, value) in gctx.env_config()?.iter() {
2697 if cmd.get_envs().contains_key(key) {
2699 continue;
2700 }
2701 cmd.env(key, value);
2702 }
2703 Ok(())
2704}
2705
2706fn should_include_scrape_units(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
2708 unit.mode.is_doc() && bcx.scrape_units.len() > 0 && bcx.ws.unit_needs_doc_scrape(unit)
2709}
2710
2711fn scrape_output_path(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<PathBuf> {
2713 assert!(unit.mode.is_doc() || unit.mode.is_doc_scrape());
2714 build_runner
2715 .outputs(unit)
2716 .map(|outputs| outputs[0].path.clone())
2717}
2718
2719fn rustdoc_dep_info_loc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
2721 let mut loc = build_runner.files().fingerprint_file_path(unit, "");
2722 loc.set_extension("d");
2723 loc
2724}