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;
54
55use std::borrow::Cow;
56use std::cell::OnceCell;
57use std::collections::{BTreeMap, HashMap, HashSet};
58use std::env;
59use std::ffi::{OsStr, OsString};
60use std::fmt::Display;
61use std::fs::{self, File};
62use std::io::{BufRead, BufWriter, Write};
63use std::ops::Range;
64use std::path::{Path, PathBuf};
65use std::sync::{Arc, LazyLock};
66
67use annotate_snippets::{AnnotationKind, Group, Level, Renderer, Snippet};
68use anyhow::{Context as _, Error};
69use cargo_platform::{Cfg, Platform};
70use itertools::Itertools;
71use regex::Regex;
72use tracing::{debug, instrument, trace};
73
74pub use self::build_config::UserIntent;
75pub use self::build_config::{BuildConfig, CompileMode, MessageFormat, TimingOutput};
76pub use self::build_context::BuildContext;
77pub use self::build_context::FileFlavor;
78pub use self::build_context::FileType;
79pub use self::build_context::RustcTargetData;
80pub use self::build_context::TargetInfo;
81pub use self::build_runner::{BuildRunner, Metadata, UnitHash};
82pub use self::compilation::{Compilation, Doctest, UnitOutput};
83pub use self::compile_kind::{CompileKind, CompileKindFallback, CompileTarget};
84pub use self::crate_type::CrateType;
85pub use self::custom_build::LinkArgTarget;
86pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts, LibraryPath};
87pub(crate) use self::fingerprint::DirtyReason;
88pub use self::fingerprint::RustdocFingerprint;
89pub use self::job_queue::Freshness;
90use self::job_queue::{Job, JobQueue, JobState, Work};
91pub(crate) use self::layout::Layout;
92pub use self::lto::Lto;
93use self::output_depinfo::output_depinfo;
94use self::output_sbom::build_sbom;
95use self::unit_graph::UnitDep;
96
97use crate::core::compiler::future_incompat::FutureIncompatReport;
98use crate::core::compiler::locking::LockKey;
99use crate::core::compiler::timings::SectionTiming;
100pub use crate::core::compiler::unit::{Unit, UnitInterner};
101use crate::core::manifest::TargetSourcePath;
102use crate::core::profiles::{PanicStrategy, Profile, StripInner};
103use crate::core::{Feature, PackageId, Target, Verbosity};
104use crate::lints::get_key_value;
105use crate::util::OnceExt;
106use crate::util::context::WarningHandling;
107use crate::util::errors::{CargoResult, VerboseError};
108use crate::util::interning::InternedString;
109use crate::util::machine_message::{self, Message};
110use crate::util::{add_path_args, internal, path_args};
111
112use cargo_util::{ProcessBuilder, ProcessError, paths};
113use cargo_util_schemas::manifest::TomlDebugInfo;
114use cargo_util_schemas::manifest::TomlTrimPaths;
115use cargo_util_schemas::manifest::TomlTrimPathsValue;
116use rustfix::diagnostics::Applicability;
117pub(crate) use timings::CompilationSection;
118
119const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
120
121pub trait Executor: Send + Sync + 'static {
125 fn init(&self, _build_runner: &BuildRunner<'_, '_>, _unit: &Unit) {}
129
130 fn exec(
133 &self,
134 cmd: &ProcessBuilder,
135 id: PackageId,
136 target: &Target,
137 mode: CompileMode,
138 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
139 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
140 ) -> CargoResult<()>;
141
142 fn force_rebuild(&self, _unit: &Unit) -> bool {
145 false
146 }
147}
148
149#[derive(Copy, Clone)]
152pub struct DefaultExecutor;
153
154impl Executor for DefaultExecutor {
155 #[instrument(name = "rustc", skip_all, fields(package = id.name().as_str(), process = cmd.to_string()))]
156 fn exec(
157 &self,
158 cmd: &ProcessBuilder,
159 id: PackageId,
160 _target: &Target,
161 _mode: CompileMode,
162 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
163 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
164 ) -> CargoResult<()> {
165 cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
166 .map(drop)
167 }
168}
169
170#[tracing::instrument(skip(build_runner, jobs, exec))]
180fn compile<'gctx>(
181 build_runner: &mut BuildRunner<'_, 'gctx>,
182 jobs: &mut JobQueue<'gctx>,
183 unit: &Unit,
184 exec: &Arc<dyn Executor>,
185 force_rebuild: bool,
186) -> CargoResult<()> {
187 let bcx = build_runner.bcx;
188 if !build_runner.compiled.insert(unit.clone()) {
189 return Ok(());
190 }
191
192 let lock = if build_runner.bcx.gctx.cli_unstable().fine_grain_locking {
193 Some(build_runner.lock_manager.lock_shared(build_runner, unit)?)
194 } else {
195 None
196 };
197
198 if !unit.skip_non_compile_time_dep {
202 fingerprint::prepare_init(build_runner, unit)?;
205
206 let job = if unit.mode.is_run_custom_build() {
207 custom_build::prepare(build_runner, unit)?
208 } else if unit.mode.is_doc_test() {
209 Job::new_fresh()
211 } else {
212 let force = exec.force_rebuild(unit) || force_rebuild;
213 let mut job = fingerprint::prepare_target(build_runner, unit, force)?;
214 job.before(if job.freshness().is_dirty() {
215 let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
216 rustdoc(build_runner, unit)?
217 } else {
218 rustc(build_runner, unit, exec)?
219 };
220 work.then(link_targets(build_runner, unit, false)?)
221 } else {
222 let show_diagnostics = unit.show_warnings(bcx.gctx)
225 && build_runner.bcx.gctx.warning_handling()? != WarningHandling::Allow;
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 build_runner.bcx.build_config.message_format,
233 show_diagnostics,
234 );
235 work.then(link_targets(build_runner, unit, true)?)
237 });
238
239 if build_runner.bcx.gctx.cli_unstable().fine_grain_locking && job.freshness().is_dirty()
242 {
243 if let Some(lock) = lock {
244 build_runner.lock_manager.unlock(&lock)?;
251 job.before(prebuild_lock_exclusive(lock.clone()));
252 job.after(downgrade_lock_to_shared(lock));
253 }
254 }
255
256 job
257 };
258 jobs.enqueue(build_runner, unit, job)?;
259 }
260
261 let deps = Vec::from(build_runner.unit_deps(unit)); for dep in deps {
264 compile(build_runner, jobs, &dep.unit, exec, false)?;
265 }
266
267 Ok(())
268}
269
270fn make_failed_scrape_diagnostic(
273 build_runner: &BuildRunner<'_, '_>,
274 unit: &Unit,
275 top_line: impl Display,
276) -> String {
277 let manifest_path = unit.pkg.manifest_path();
278 let relative_manifest_path = manifest_path
279 .strip_prefix(build_runner.bcx.ws.root())
280 .unwrap_or(&manifest_path);
281
282 format!(
283 "\
284{top_line}
285 Try running with `--verbose` to see the error message.
286 If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
287 relative_manifest_path.display()
288 )
289}
290
291fn rustc(
293 build_runner: &mut BuildRunner<'_, '_>,
294 unit: &Unit,
295 exec: &Arc<dyn Executor>,
296) -> CargoResult<Work> {
297 let mut rustc = prepare_rustc(build_runner, unit)?;
298
299 let name = unit.pkg.name();
300
301 let outputs = build_runner.outputs(unit)?;
302 let root = build_runner.files().out_dir(unit);
303
304 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
306 let current_id = unit.pkg.package_id();
307 let manifest = ManifestErrorContext::new(build_runner, unit);
308 let build_scripts = build_runner.build_scripts.get(unit).cloned();
309
310 let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
313
314 let dep_info_name =
315 if let Some(c_extra_filename) = build_runner.files().metadata(unit).c_extra_filename() {
316 format!("{}-{}.d", unit.target.crate_name(), c_extra_filename)
317 } else {
318 format!("{}.d", unit.target.crate_name())
319 };
320 let rustc_dep_info_loc = root.join(dep_info_name);
321 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
322
323 let mut output_options = OutputOptions::new(build_runner, unit);
324 let package_id = unit.pkg.package_id();
325 let target = Target::clone(&unit.target);
326 let mode = unit.mode;
327
328 exec.init(build_runner, unit);
329 let exec = exec.clone();
330
331 let root_output = build_runner.files().host_dest().map(|v| v.to_path_buf());
332 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
333 let pkg_root = unit.pkg.root().to_path_buf();
334 let cwd = rustc
335 .get_cwd()
336 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
337 .to_path_buf();
338 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
339 let script_metadatas = build_runner.find_build_script_metadatas(unit);
340 let is_local = unit.is_local();
341 let artifact = unit.artifact;
342 let sbom_files = build_runner.sbom_output_files(unit)?;
343 let sbom = build_sbom(build_runner, unit)?;
344
345 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
346 && !matches!(
347 build_runner.bcx.gctx.shell().verbosity(),
348 Verbosity::Verbose
349 );
350 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
351 let target_desc = unit.target.description_named();
354 let mut for_scrape_units = build_runner
355 .bcx
356 .scrape_units_have_dep_on(unit)
357 .into_iter()
358 .map(|unit| unit.target.description_named())
359 .collect::<Vec<_>>();
360 for_scrape_units.sort();
361 let for_scrape_units = for_scrape_units.join(", ");
362 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}"))
363 });
364 if hide_diagnostics_for_scrape_unit {
365 output_options.show_diagnostics = false;
366 }
367 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
368 return Ok(Work::new(move |state| {
369 if artifact.is_true() {
373 paths::create_dir_all(&root)?;
374 }
375
376 if let Some(build_scripts) = build_scripts {
384 let script_outputs = build_script_outputs.lock().unwrap();
385 add_native_deps(
386 &mut rustc,
387 &script_outputs,
388 &build_scripts,
389 pass_l_flag,
390 &target,
391 current_id,
392 mode,
393 )?;
394 if let Some(ref root_output) = root_output {
395 add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, root_output)?;
396 }
397 add_custom_flags(&mut rustc, &script_outputs, script_metadatas)?;
398 }
399
400 for output in outputs.iter() {
401 if output.path.extension() == Some(OsStr::new("rmeta")) {
405 let dst = root.join(&output.path).with_extension("rlib");
406 if dst.exists() {
407 paths::remove_file(&dst)?;
408 }
409 }
410
411 if output.hardlink.is_some() && output.path.exists() {
416 _ = paths::remove_file(&output.path).map_err(|e| {
417 tracing::debug!(
418 "failed to delete previous output file `{:?}`: {e:?}",
419 output.path
420 );
421 });
422 }
423 }
424
425 state.running(&rustc);
426 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
427 for file in sbom_files {
428 tracing::debug!("writing sbom to {}", file.display());
429 let outfile = BufWriter::new(paths::create(&file)?);
430 serde_json::to_writer(outfile, &sbom)?;
431 }
432
433 let result = exec
434 .exec(
435 &rustc,
436 package_id,
437 &target,
438 mode,
439 &mut |line| on_stdout_line(state, line, package_id, &target),
440 &mut |line| {
441 on_stderr_line(
442 state,
443 line,
444 package_id,
445 &manifest,
446 &target,
447 &mut output_options,
448 )
449 },
450 )
451 .map_err(|e| {
452 if output_options.errors_seen == 0 {
453 e
458 } else {
459 verbose_if_simple_exit_code(e)
460 }
461 })
462 .with_context(|| {
463 let warnings = match output_options.warnings_seen {
465 0 => String::new(),
466 1 => "; 1 warning emitted".to_string(),
467 count => format!("; {} warnings emitted", count),
468 };
469 let errors = match output_options.errors_seen {
470 0 => String::new(),
471 1 => " due to 1 previous error".to_string(),
472 count => format!(" due to {} previous errors", count),
473 };
474 let name = descriptive_pkg_name(&name, &target, &mode);
475 format!("could not compile {name}{errors}{warnings}")
476 });
477
478 if let Err(e) = result {
479 if let Some(diagnostic) = failed_scrape_diagnostic {
480 state.warning(diagnostic);
481 }
482
483 return Err(e);
484 }
485
486 debug_assert_eq!(output_options.errors_seen, 0);
488
489 if rustc_dep_info_loc.exists() {
490 fingerprint::translate_dep_info(
491 &rustc_dep_info_loc,
492 &dep_info_loc,
493 &cwd,
494 &pkg_root,
495 &build_dir,
496 &rustc,
497 is_local,
499 &env_config,
500 )
501 .with_context(|| {
502 internal(format!(
503 "could not parse/generate dep info at: {}",
504 rustc_dep_info_loc.display()
505 ))
506 })?;
507 paths::set_file_time_no_err(dep_info_loc, timestamp);
510 }
511
512 if mode.is_check() {
526 for output in outputs.iter() {
527 paths::set_file_time_no_err(&output.path, timestamp);
528 }
529 }
530
531 Ok(())
532 }));
533
534 fn add_native_deps(
537 rustc: &mut ProcessBuilder,
538 build_script_outputs: &BuildScriptOutputs,
539 build_scripts: &BuildScripts,
540 pass_l_flag: bool,
541 target: &Target,
542 current_id: PackageId,
543 mode: CompileMode,
544 ) -> CargoResult<()> {
545 let mut library_paths = vec![];
546
547 for key in build_scripts.to_link.iter() {
548 let output = build_script_outputs.get(key.1).ok_or_else(|| {
549 internal(format!(
550 "couldn't find build script output for {}/{}",
551 key.0, key.1
552 ))
553 })?;
554 library_paths.extend(output.library_paths.iter());
555 }
556
557 library_paths.sort_by_key(|p| match p {
563 LibraryPath::CargoArtifact(_) => 0,
564 LibraryPath::External(_) => 1,
565 });
566
567 for path in library_paths.iter() {
568 rustc.arg("-L").arg(path.as_ref());
569 }
570
571 for key in build_scripts.to_link.iter() {
572 let output = build_script_outputs.get(key.1).ok_or_else(|| {
573 internal(format!(
574 "couldn't find build script output for {}/{}",
575 key.0, key.1
576 ))
577 })?;
578
579 if key.0 == current_id {
580 if pass_l_flag {
581 for name in output.library_links.iter() {
582 rustc.arg("-l").arg(name);
583 }
584 }
585 }
586
587 for (lt, arg) in &output.linker_args {
588 if lt.applies_to(target, mode)
594 && (key.0 == current_id || *lt == LinkArgTarget::Cdylib)
595 {
596 rustc.arg("-C").arg(format!("link-arg={}", arg));
597 }
598 }
599 }
600 Ok(())
601 }
602}
603
604fn verbose_if_simple_exit_code(err: Error) -> Error {
605 match err
608 .downcast_ref::<ProcessError>()
609 .as_ref()
610 .and_then(|perr| perr.code)
611 {
612 Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
613 _ => err,
614 }
615}
616
617fn prebuild_lock_exclusive(lock: LockKey) -> Work {
618 Work::new(move |state| {
619 state.lock_exclusive(&lock)?;
620 Ok(())
621 })
622}
623
624fn downgrade_lock_to_shared(lock: LockKey) -> Work {
625 Work::new(move |state| {
626 state.downgrade_to_shared(&lock)?;
627 Ok(())
628 })
629}
630
631fn link_targets(
634 build_runner: &mut BuildRunner<'_, '_>,
635 unit: &Unit,
636 fresh: bool,
637) -> CargoResult<Work> {
638 let bcx = build_runner.bcx;
639 let outputs = build_runner.outputs(unit)?;
640 let export_dir = build_runner.files().export_dir();
641 let package_id = unit.pkg.package_id();
642 let manifest_path = PathBuf::from(unit.pkg.manifest_path());
643 let profile = unit.profile.clone();
644 let unit_mode = unit.mode;
645 let features = unit.features.iter().map(|s| s.to_string()).collect();
646 let json_messages = bcx.build_config.emit_json();
647 let executable = build_runner.get_executable(unit)?;
648 let mut target = Target::clone(&unit.target);
649 if let TargetSourcePath::Metabuild = target.src_path() {
650 let path = unit
652 .pkg
653 .manifest()
654 .metabuild_path(build_runner.bcx.ws.build_dir());
655 target.set_src_path(TargetSourcePath::Path(path));
656 }
657
658 Ok(Work::new(move |state| {
659 let mut destinations = vec![];
664 for output in outputs.iter() {
665 let src = &output.path;
666 if !src.exists() {
669 continue;
670 }
671 let Some(dst) = output.hardlink.as_ref() else {
672 destinations.push(src.clone());
673 continue;
674 };
675 destinations.push(dst.clone());
676 paths::link_or_copy(src, dst)?;
677 if let Some(ref path) = output.export_path {
678 let export_dir = export_dir.as_ref().unwrap();
679 paths::create_dir_all(export_dir)?;
680
681 paths::link_or_copy(src, path)?;
682 }
683 }
684
685 if json_messages {
686 let debuginfo = match profile.debuginfo.into_inner() {
687 TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
688 TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
689 TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
690 TomlDebugInfo::LineDirectivesOnly => {
691 machine_message::ArtifactDebuginfo::Named("line-directives-only")
692 }
693 TomlDebugInfo::LineTablesOnly => {
694 machine_message::ArtifactDebuginfo::Named("line-tables-only")
695 }
696 };
697 let art_profile = machine_message::ArtifactProfile {
698 opt_level: profile.opt_level.as_str(),
699 debuginfo: Some(debuginfo),
700 debug_assertions: profile.debug_assertions,
701 overflow_checks: profile.overflow_checks,
702 test: unit_mode.is_any_test(),
703 };
704
705 let msg = machine_message::Artifact {
706 package_id: package_id.to_spec(),
707 manifest_path,
708 target: &target,
709 profile: art_profile,
710 features,
711 filenames: destinations,
712 executable,
713 fresh,
714 }
715 .to_json_string();
716 state.stdout(msg)?;
717 }
718 Ok(())
719 }))
720}
721
722fn add_plugin_deps(
726 rustc: &mut ProcessBuilder,
727 build_script_outputs: &BuildScriptOutputs,
728 build_scripts: &BuildScripts,
729 root_output: &Path,
730) -> CargoResult<()> {
731 let var = paths::dylib_path_envvar();
732 let search_path = rustc.get_env(var).unwrap_or_default();
733 let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
734 for (pkg_id, metadata) in &build_scripts.plugins {
735 let output = build_script_outputs
736 .get(*metadata)
737 .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
738 search_path.append(&mut filter_dynamic_search_path(
739 output.library_paths.iter().map(AsRef::as_ref),
740 root_output,
741 ));
742 }
743 let search_path = paths::join_paths(&search_path, var)?;
744 rustc.env(var, &search_path);
745 Ok(())
746}
747
748fn get_dynamic_search_path(path: &Path) -> &Path {
749 match path.to_str().and_then(|s| s.split_once("=")) {
750 Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => Path::new(path),
751 _ => path,
752 }
753}
754
755fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
761where
762 I: Iterator<Item = &'a PathBuf>,
763{
764 let mut search_path = vec![];
765 for dir in paths {
766 let dir = get_dynamic_search_path(dir);
767 if dir.starts_with(&root_output) {
768 search_path.push(dir.to_path_buf());
769 } else {
770 debug!(
771 "Not including path {} in runtime library search path because it is \
772 outside target root {}",
773 dir.display(),
774 root_output.display()
775 );
776 }
777 }
778 search_path
779}
780
781fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
788 let gctx = build_runner.bcx.gctx;
789 let is_primary = build_runner.is_primary_package(unit);
790 let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg);
791
792 let mut base = build_runner
793 .compilation
794 .rustc_process(unit, is_primary, is_workspace)?;
795 build_base_args(build_runner, &mut base, unit)?;
796 if unit.pkg.manifest().is_embedded() {
797 if !gctx.cli_unstable().script {
798 anyhow::bail!(
799 "parsing `{}` requires `-Zscript`",
800 unit.pkg.manifest_path().display()
801 );
802 }
803 base.arg("-Z").arg("crate-attr=feature(frontmatter)");
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
820 if is_primary {
821 base.env("CARGO_PRIMARY_PACKAGE", "1");
822 let file_list = build_runner.sbom_output_files(unit)?;
823 if !file_list.is_empty() {
824 let file_list = std::env::join_paths(file_list)?;
825 base.env("CARGO_SBOM_PATH", file_list);
826 }
827 }
828
829 if unit.target.is_test() || unit.target.is_bench() {
830 let tmp = build_runner
831 .files()
832 .layout(unit.kind)
833 .build_dir()
834 .prepare_tmp()?;
835 base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
836 }
837
838 Ok(base)
839}
840
841fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
848 let bcx = build_runner.bcx;
849 let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
851 if unit.pkg.manifest().is_embedded() {
852 if !bcx.gctx.cli_unstable().script {
853 anyhow::bail!(
854 "parsing `{}` requires `-Zscript`",
855 unit.pkg.manifest_path().display()
856 );
857 }
858 rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
859 }
860 rustdoc.inherit_jobserver(&build_runner.jobserver);
861 let crate_name = unit.target.crate_name();
862 rustdoc.arg("--crate-name").arg(&crate_name);
863 add_path_args(bcx.ws, unit, &mut rustdoc);
864 add_cap_lints(bcx, unit, &mut rustdoc);
865
866 if let CompileKind::Target(target) = unit.kind {
867 rustdoc.arg("--target").arg(target.rustc_target());
868 }
869 let doc_dir = build_runner.files().out_dir(unit);
870 rustdoc.arg("-o").arg(&doc_dir);
871 rustdoc.args(&features_args(unit));
872 rustdoc.args(&check_cfg_args(unit));
873
874 add_error_format_and_color(build_runner, &mut rustdoc);
875 add_allow_features(build_runner, &mut rustdoc);
876
877 if build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo {
878 let mut arg = if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
881 OsString::from("--emit=invocation-specific,dep-info=")
883 } else {
884 OsString::from("--emit=toolchain-shared-resources,invocation-specific,dep-info=")
886 };
887 arg.push(rustdoc_dep_info_loc(build_runner, unit));
888 rustdoc.arg(arg);
889
890 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
891 rustdoc.arg("-Z").arg("checksum-hash-algorithm=blake3");
892 }
893
894 rustdoc.arg("-Zunstable-options");
895 } else if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
896 rustdoc.arg("--emit=invocation-specific");
898 rustdoc.arg("-Zunstable-options");
899 }
900
901 if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
902 rustdoc.arg("--merge=none");
904 let mut arg = OsString::from("--parts-out-dir=");
905 arg.push(build_runner.files().deps_dir_new_layout(unit));
907 rustdoc.arg(arg);
908 }
909
910 if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
911 trim_paths_args_rustdoc(&mut rustdoc, build_runner, unit, trim_paths)?;
912 }
913
914 rustdoc.args(unit.pkg.manifest().lint_rustflags());
915
916 let metadata = build_runner.metadata_for_doc_units[unit];
917 rustdoc
918 .arg("-C")
919 .arg(format!("metadata={}", metadata.c_metadata()));
920
921 if unit.mode.is_doc_scrape() {
922 debug_assert!(build_runner.bcx.scrape_units.contains(unit));
923
924 if unit.target.is_test() {
925 rustdoc.arg("--scrape-tests");
926 }
927
928 rustdoc.arg("-Zunstable-options");
929
930 rustdoc
931 .arg("--scrape-examples-output-path")
932 .arg(scrape_output_path(build_runner, unit)?);
933
934 for pkg in build_runner.bcx.packages.packages() {
936 let names = pkg
937 .targets()
938 .iter()
939 .map(|target| target.crate_name())
940 .collect::<HashSet<_>>();
941 for name in names {
942 rustdoc.arg("--scrape-examples-target-crate").arg(name);
943 }
944 }
945 }
946
947 if should_include_scrape_units(build_runner.bcx, unit) {
948 rustdoc.arg("-Zunstable-options");
949 }
950
951 build_deps_args(&mut rustdoc, build_runner, unit)?;
952 rustdoc::add_root_urls(build_runner, unit, &mut rustdoc)?;
953
954 rustdoc::add_output_format(build_runner, &mut rustdoc)?;
955
956 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
957 rustdoc.args(args);
958 }
959 rustdoc.args(&unit.rustdocflags);
960
961 if !crate_version_flag_already_present(&rustdoc) {
962 append_crate_version_flag(unit, &mut rustdoc);
963 }
964
965 Ok(rustdoc)
966}
967
968fn rustdoc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Work> {
970 let mut rustdoc = prepare_rustdoc(build_runner, unit)?;
971
972 let crate_name = unit.target.crate_name();
973 let doc_dir = build_runner.files().out_dir(unit);
974 paths::create_dir_all(&doc_dir)?;
978
979 let target_desc = unit.target.description_named();
980 let name = unit.pkg.name();
981 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
982 let package_id = unit.pkg.package_id();
983 let target = Target::clone(&unit.target);
984 let manifest = ManifestErrorContext::new(build_runner, unit);
985
986 let rustdoc_dep_info_loc = rustdoc_dep_info_loc(build_runner, unit);
987 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
988 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
989 let pkg_root = unit.pkg.root().to_path_buf();
990 let cwd = rustdoc
991 .get_cwd()
992 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
993 .to_path_buf();
994 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
995 let is_local = unit.is_local();
996 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
997 let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
998
999 let mut output_options = OutputOptions::new(build_runner, unit);
1000 let script_metadatas = build_runner.find_build_script_metadatas(unit);
1001 let scrape_outputs = if should_include_scrape_units(build_runner.bcx, unit) {
1002 Some(
1003 build_runner
1004 .bcx
1005 .scrape_units
1006 .iter()
1007 .map(|unit| {
1008 Ok((
1009 build_runner.files().metadata(unit).unit_id(),
1010 scrape_output_path(build_runner, unit)?,
1011 ))
1012 })
1013 .collect::<CargoResult<HashMap<_, _>>>()?,
1014 )
1015 } else {
1016 None
1017 };
1018
1019 let failed_scrape_units = Arc::clone(&build_runner.failed_scrape_units);
1020 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
1021 && !matches!(
1022 build_runner.bcx.gctx.shell().verbosity(),
1023 Verbosity::Verbose
1024 );
1025 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
1026 make_failed_scrape_diagnostic(
1027 build_runner,
1028 unit,
1029 format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
1030 )
1031 });
1032 if hide_diagnostics_for_scrape_unit {
1033 output_options.show_diagnostics = false;
1034 }
1035
1036 Ok(Work::new(move |state| {
1037 add_custom_flags(
1038 &mut rustdoc,
1039 &build_script_outputs.lock().unwrap(),
1040 script_metadatas,
1041 )?;
1042
1043 if let Some(scrape_outputs) = scrape_outputs {
1048 let failed_scrape_units = failed_scrape_units.lock().unwrap();
1049 for (metadata, output_path) in &scrape_outputs {
1050 if !failed_scrape_units.contains(metadata) {
1051 rustdoc.arg("--with-examples").arg(output_path);
1052 }
1053 }
1054 }
1055
1056 let crate_dir = doc_dir.join(&crate_name);
1057 if crate_dir.exists() {
1058 debug!("removing pre-existing doc directory {:?}", crate_dir);
1061 paths::remove_dir_all(crate_dir)?;
1062 }
1063 state.running(&rustdoc);
1064 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
1065
1066 let result = rustdoc
1067 .exec_with_streaming(
1068 &mut |line| on_stdout_line(state, line, package_id, &target),
1069 &mut |line| {
1070 on_stderr_line(
1071 state,
1072 line,
1073 package_id,
1074 &manifest,
1075 &target,
1076 &mut output_options,
1077 )
1078 },
1079 false,
1080 )
1081 .map_err(verbose_if_simple_exit_code)
1082 .with_context(|| format!("could not document `{}`", name));
1083
1084 if let Err(e) = result {
1085 if let Some(diagnostic) = failed_scrape_diagnostic {
1086 state.warning(diagnostic);
1087 }
1088
1089 return Err(e);
1090 }
1091
1092 if rustdoc_depinfo_enabled && rustdoc_dep_info_loc.exists() {
1093 fingerprint::translate_dep_info(
1094 &rustdoc_dep_info_loc,
1095 &dep_info_loc,
1096 &cwd,
1097 &pkg_root,
1098 &build_dir,
1099 &rustdoc,
1100 is_local,
1102 &env_config,
1103 )
1104 .with_context(|| {
1105 internal(format_args!(
1106 "could not parse/generate dep info at: {}",
1107 rustdoc_dep_info_loc.display()
1108 ))
1109 })?;
1110 paths::set_file_time_no_err(dep_info_loc, timestamp);
1113 }
1114
1115 Ok(())
1116 }))
1117}
1118
1119fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
1122 rustdoc.get_args().any(|flag| {
1123 flag.to_str()
1124 .map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
1125 })
1126}
1127
1128fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
1129 rustdoc
1130 .arg(RUSTDOC_CRATE_VERSION_FLAG)
1131 .arg(unit.pkg.version().to_string());
1132}
1133
1134fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
1138 if !unit.show_warnings(bcx.gctx) {
1141 cmd.arg("--cap-lints").arg("allow");
1142
1143 } else if !unit.is_local() {
1146 cmd.arg("--cap-lints").arg("warn");
1147 }
1148}
1149
1150fn add_allow_features(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1154 if let Some(allow) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1155 use std::fmt::Write;
1156 let mut arg = String::from("-Zallow-features=");
1157 for f in allow {
1158 let _ = write!(&mut arg, "{f},");
1159 }
1160 cmd.arg(arg.trim_end_matches(','));
1161 }
1162}
1163
1164fn add_error_format_and_color(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1175 let enable_timings = build_runner.bcx.gctx.cli_unstable().section_timings
1176 && (!build_runner.bcx.build_config.timing_outputs.is_empty()
1177 || build_runner.bcx.logger.is_some());
1178 if enable_timings {
1179 cmd.arg("-Zunstable-options");
1180 }
1181
1182 cmd.arg("--error-format=json");
1183 let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
1184
1185 if let MessageFormat::Short | MessageFormat::Json { short: true, .. } =
1186 build_runner.bcx.build_config.message_format
1187 {
1188 json.push_str(",diagnostic-short");
1189 } else if build_runner.bcx.gctx.shell().err_unicode()
1190 && build_runner.bcx.gctx.cli_unstable().rustc_unicode
1191 {
1192 json.push_str(",diagnostic-unicode");
1193 }
1194
1195 if enable_timings {
1196 json.push_str(",timings");
1197 }
1198
1199 cmd.arg(json);
1200
1201 let gctx = build_runner.bcx.gctx;
1202 if let Some(width) = gctx.shell().err_width().diagnostic_terminal_width() {
1203 cmd.arg(format!("--diagnostic-width={width}"));
1204 }
1205}
1206
1207fn build_base_args(
1209 build_runner: &BuildRunner<'_, '_>,
1210 cmd: &mut ProcessBuilder,
1211 unit: &Unit,
1212) -> CargoResult<()> {
1213 assert!(!unit.mode.is_run_custom_build());
1214
1215 let bcx = build_runner.bcx;
1216 let Profile {
1217 ref opt_level,
1218 codegen_backend,
1219 codegen_units,
1220 debuginfo,
1221 debug_assertions,
1222 split_debuginfo,
1223 overflow_checks,
1224 rpath,
1225 ref panic,
1226 incremental,
1227 strip,
1228 rustflags: profile_rustflags,
1229 trim_paths,
1230 hint_mostly_unused: profile_hint_mostly_unused,
1231 ..
1232 } = unit.profile.clone();
1233 let hints = unit.pkg.hints().cloned().unwrap_or_default();
1234 let test = unit.mode.is_any_test();
1235
1236 let warn = |msg: &str| {
1237 bcx.gctx.shell().warn(format!(
1238 "{}@{}: {msg}",
1239 unit.pkg.package_id().name(),
1240 unit.pkg.package_id().version()
1241 ))
1242 };
1243 let unit_capped_warn = |msg: &str| {
1244 if unit.show_warnings(bcx.gctx) {
1245 warn(msg)
1246 } else {
1247 Ok(())
1248 }
1249 };
1250
1251 cmd.arg("--crate-name").arg(&unit.target.crate_name());
1252
1253 let edition = unit.target.edition();
1254 edition.cmd_edition_arg(cmd);
1255
1256 add_path_args(bcx.ws, unit, cmd);
1257 add_error_format_and_color(build_runner, cmd);
1258 add_allow_features(build_runner, cmd);
1259
1260 let mut contains_dy_lib = false;
1261 if !test {
1262 for crate_type in &unit.target.rustc_crate_types() {
1263 cmd.arg("--crate-type").arg(crate_type.as_str());
1264 contains_dy_lib |= crate_type == &CrateType::Dylib;
1265 }
1266 }
1267
1268 if unit.mode.is_check() {
1269 cmd.arg("--emit=dep-info,metadata");
1270 } else if build_runner.bcx.gctx.cli_unstable().no_embed_metadata {
1271 if unit.benefits_from_no_embed_metadata() {
1281 cmd.arg("--emit=dep-info,metadata,link");
1282 cmd.args(&["-Z", "embed-metadata=no"]);
1283 } else {
1284 cmd.arg("--emit=dep-info,link");
1285 }
1286 } else {
1287 if !unit.requires_upstream_objects() {
1291 cmd.arg("--emit=dep-info,metadata,link");
1292 } else {
1293 cmd.arg("--emit=dep-info,link");
1294 }
1295 }
1296
1297 let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
1298 || (contains_dy_lib && !build_runner.is_primary_package(unit));
1299 if prefer_dynamic {
1300 cmd.arg("-C").arg("prefer-dynamic");
1301 }
1302
1303 if opt_level.as_str() != "0" {
1304 cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
1305 }
1306
1307 if *panic != PanicStrategy::Unwind {
1308 cmd.arg("-C").arg(format!("panic={}", panic));
1309 }
1310 if *panic == PanicStrategy::ImmediateAbort {
1311 cmd.arg("-Z").arg("unstable-options");
1312 }
1313
1314 cmd.args(<o_args(build_runner, unit));
1315
1316 if let Some(backend) = codegen_backend {
1317 cmd.arg("-Z").arg(&format!("codegen-backend={}", backend));
1318 }
1319
1320 if let Some(n) = codegen_units {
1321 cmd.arg("-C").arg(&format!("codegen-units={}", n));
1322 }
1323
1324 let debuginfo = debuginfo.into_inner();
1325 if debuginfo != TomlDebugInfo::None {
1327 cmd.arg("-C").arg(format!("debuginfo={debuginfo}"));
1328 if let Some(split) = split_debuginfo {
1335 if build_runner
1336 .bcx
1337 .target_data
1338 .info(unit.kind)
1339 .supports_debuginfo_split(split)
1340 {
1341 cmd.arg("-C").arg(format!("split-debuginfo={split}"));
1342 }
1343 }
1344 }
1345
1346 if let Some(trim_paths) = trim_paths {
1347 trim_paths_args(cmd, build_runner, unit, &trim_paths)?;
1348 }
1349
1350 cmd.args(unit.pkg.manifest().lint_rustflags());
1351 cmd.args(&profile_rustflags);
1352
1353 if opt_level.as_str() != "0" {
1357 if debug_assertions {
1358 cmd.args(&["-C", "debug-assertions=on"]);
1359 if !overflow_checks {
1360 cmd.args(&["-C", "overflow-checks=off"]);
1361 }
1362 } else if overflow_checks {
1363 cmd.args(&["-C", "overflow-checks=on"]);
1364 }
1365 } else if !debug_assertions {
1366 cmd.args(&["-C", "debug-assertions=off"]);
1367 if overflow_checks {
1368 cmd.args(&["-C", "overflow-checks=on"]);
1369 }
1370 } else if !overflow_checks {
1371 cmd.args(&["-C", "overflow-checks=off"]);
1372 }
1373
1374 if test && unit.target.harness() {
1375 cmd.arg("--test");
1376
1377 if *panic == PanicStrategy::Abort || *panic == PanicStrategy::ImmediateAbort {
1385 cmd.arg("-Z").arg("panic-abort-tests");
1386 }
1387 } else if test {
1388 cmd.arg("--cfg").arg("test");
1389 }
1390
1391 cmd.args(&features_args(unit));
1392 cmd.args(&check_cfg_args(unit));
1393
1394 let meta = build_runner.files().metadata(unit);
1395 cmd.arg("-C")
1396 .arg(&format!("metadata={}", meta.c_metadata()));
1397 if let Some(c_extra_filename) = meta.c_extra_filename() {
1398 cmd.arg("-C")
1399 .arg(&format!("extra-filename=-{c_extra_filename}"));
1400 }
1401
1402 if rpath {
1403 cmd.arg("-C").arg("rpath");
1404 }
1405
1406 cmd.arg("--out-dir")
1407 .arg(&build_runner.files().out_dir(unit));
1408
1409 fn opt(cmd: &mut ProcessBuilder, key: &str, prefix: &str, val: Option<&OsStr>) {
1410 if let Some(val) = val {
1411 let mut joined = OsString::from(prefix);
1412 joined.push(val);
1413 cmd.arg(key).arg(joined);
1414 }
1415 }
1416
1417 if let CompileKind::Target(n) = unit.kind {
1418 cmd.arg("--target").arg(n.rustc_target());
1419 }
1420
1421 opt(
1422 cmd,
1423 "-C",
1424 "linker=",
1425 build_runner
1426 .compilation
1427 .target_linker(unit.kind)
1428 .as_ref()
1429 .map(|s| s.as_ref()),
1430 );
1431 if incremental {
1432 let dir = build_runner.files().incremental_dir(&unit);
1433 opt(cmd, "-C", "incremental=", Some(dir.as_os_str()));
1434 }
1435
1436 let pkg_hint_mostly_unused = match hints.mostly_unused {
1437 None => None,
1438 Some(toml::Value::Boolean(b)) => Some(b),
1439 Some(v) => {
1440 unit_capped_warn(&format!(
1441 "ignoring unsupported value type ({}) for 'hints.mostly-unused', which expects a boolean",
1442 v.type_str()
1443 ))?;
1444 None
1445 }
1446 };
1447 if profile_hint_mostly_unused
1448 .or(pkg_hint_mostly_unused)
1449 .unwrap_or(false)
1450 {
1451 if bcx.gctx.cli_unstable().profile_hint_mostly_unused {
1452 cmd.arg("-Zhint-mostly-unused");
1453 } else {
1454 if profile_hint_mostly_unused.is_some() {
1455 warn(
1457 "ignoring 'hint-mostly-unused' profile option, pass `-Zprofile-hint-mostly-unused` to enable it",
1458 )?;
1459 } else if pkg_hint_mostly_unused.is_some() {
1460 unit_capped_warn(
1461 "ignoring 'hints.mostly-unused', pass `-Zprofile-hint-mostly-unused` to enable it",
1462 )?;
1463 }
1464 }
1465 }
1466
1467 let strip = strip.into_inner();
1468 if strip != StripInner::None {
1469 cmd.arg("-C").arg(format!("strip={}", strip));
1470 }
1471
1472 if unit.is_std {
1473 cmd.arg("-Z")
1479 .arg("force-unstable-if-unmarked")
1480 .env("RUSTC_BOOTSTRAP", "1");
1481 }
1482
1483 if unit.target.is_test() || unit.target.is_bench() {
1485 for bin_target in unit
1486 .pkg
1487 .manifest()
1488 .targets()
1489 .iter()
1490 .filter(|target| target.is_bin())
1491 {
1492 let exe_path = build_runner
1496 .files()
1497 .bin_link_for_target(bin_target, unit.kind, build_runner.bcx)?
1498 .map(|path| path.as_os_str().to_os_string())
1499 .unwrap_or_else(|| OsString::from(format!("placeholder:{}", bin_target.name())));
1500
1501 let name = bin_target
1502 .binary_filename()
1503 .unwrap_or(bin_target.name().to_string());
1504 let key = format!("CARGO_BIN_EXE_{}", name);
1505 cmd.env(&key, exe_path);
1506 }
1507 }
1508 Ok(())
1509}
1510
1511fn features_args(unit: &Unit) -> Vec<OsString> {
1513 let mut args = Vec::with_capacity(unit.features.len() * 2);
1514
1515 for feat in &unit.features {
1516 args.push(OsString::from("--cfg"));
1517 args.push(OsString::from(format!("feature=\"{}\"", feat)));
1518 }
1519
1520 args
1521}
1522
1523fn trim_paths_args_rustdoc(
1525 cmd: &mut ProcessBuilder,
1526 build_runner: &BuildRunner<'_, '_>,
1527 unit: &Unit,
1528 trim_paths: &TomlTrimPaths,
1529) -> CargoResult<()> {
1530 match trim_paths {
1531 TomlTrimPaths::Values(values) if !values.contains(&TomlTrimPathsValue::Diagnostics) => {
1533 return Ok(());
1534 }
1535 _ => {}
1536 }
1537
1538 cmd.arg("-Zunstable-options");
1540
1541 cmd.arg(package_remap(build_runner, unit));
1544 cmd.arg(build_dir_remap(build_runner));
1545 cmd.arg(sysroot_remap(build_runner, unit));
1546
1547 Ok(())
1548}
1549
1550fn trim_paths_args(
1556 cmd: &mut ProcessBuilder,
1557 build_runner: &BuildRunner<'_, '_>,
1558 unit: &Unit,
1559 trim_paths: &TomlTrimPaths,
1560) -> CargoResult<()> {
1561 if trim_paths.is_none() {
1562 return Ok(());
1563 }
1564
1565 cmd.arg("-Zunstable-options");
1567 cmd.arg(format!("-Zremap-path-scope={trim_paths}"));
1568
1569 cmd.arg(package_remap(build_runner, unit));
1572 cmd.arg(build_dir_remap(build_runner));
1573 cmd.arg(sysroot_remap(build_runner, unit));
1574
1575 Ok(())
1576}
1577
1578fn sysroot_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1583 let mut remap = OsString::from("--remap-path-prefix=");
1584 remap.push({
1585 let mut sysroot = build_runner.bcx.target_data.info(unit.kind).sysroot.clone();
1587 sysroot.push("lib");
1588 sysroot.push("rustlib");
1589 sysroot.push("src");
1590 sysroot.push("rust");
1591 sysroot
1592 });
1593 remap.push("=");
1594 remap.push("/rustc/");
1595 if let Some(commit_hash) = build_runner.bcx.rustc().commit_hash.as_ref() {
1596 remap.push(commit_hash);
1597 } else {
1598 remap.push(build_runner.bcx.rustc().version.to_string());
1599 }
1600 remap
1601}
1602
1603fn package_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1611 let pkg_root = unit.pkg.root();
1612 let ws_root = build_runner.bcx.ws.root();
1613 let mut remap = OsString::from("--remap-path-prefix=");
1614 let source_id = unit.pkg.package_id().source_id();
1615 if source_id.is_git() {
1616 remap.push(
1617 build_runner
1618 .bcx
1619 .gctx
1620 .git_checkouts_path()
1621 .as_path_unlocked(),
1622 );
1623 remap.push("=");
1624 } else if source_id.is_registry() {
1625 remap.push(
1626 build_runner
1627 .bcx
1628 .gctx
1629 .registry_source_path()
1630 .as_path_unlocked(),
1631 );
1632 remap.push("=");
1633 } else if pkg_root.strip_prefix(ws_root).is_ok() {
1634 remap.push(ws_root);
1635 remap.push("=."); } else {
1637 remap.push(pkg_root);
1638 remap.push("=");
1639 remap.push(unit.pkg.name());
1640 remap.push("-");
1641 remap.push(unit.pkg.version().to_string());
1642 }
1643 remap
1644}
1645
1646fn build_dir_remap(build_runner: &BuildRunner<'_, '_>) -> OsString {
1659 let build_dir = build_runner.bcx.ws.build_dir();
1660 let mut remap = OsString::from("--remap-path-prefix=");
1661 remap.push(build_dir.as_path_unlocked());
1662 remap.push("=/cargo/build-dir");
1663 remap
1664}
1665
1666fn check_cfg_args(unit: &Unit) -> Vec<OsString> {
1668 let gross_cap_estimation = unit.pkg.summary().features().len() * 7 + 25;
1686 let mut arg_feature = OsString::with_capacity(gross_cap_estimation);
1687
1688 arg_feature.push("cfg(feature, values(");
1689 for (i, feature) in unit.pkg.summary().features().keys().enumerate() {
1690 if i != 0 {
1691 arg_feature.push(", ");
1692 }
1693 arg_feature.push("\"");
1694 arg_feature.push(feature);
1695 arg_feature.push("\"");
1696 }
1697 arg_feature.push("))");
1698
1699 vec![
1708 OsString::from("--check-cfg"),
1709 OsString::from("cfg(docsrs,test)"),
1710 OsString::from("--check-cfg"),
1711 arg_feature,
1712 ]
1713}
1714
1715fn lto_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1717 let mut result = Vec::new();
1718 let mut push = |arg: &str| {
1719 result.push(OsString::from("-C"));
1720 result.push(OsString::from(arg));
1721 };
1722 match build_runner.lto[unit] {
1723 lto::Lto::Run(None) => push("lto"),
1724 lto::Lto::Run(Some(s)) => push(&format!("lto={}", s)),
1725 lto::Lto::Off => {
1726 push("lto=off");
1727 push("embed-bitcode=no");
1728 }
1729 lto::Lto::ObjectAndBitcode => {} lto::Lto::OnlyBitcode => push("linker-plugin-lto"),
1731 lto::Lto::OnlyObject => push("embed-bitcode=no"),
1732 }
1733 result
1734}
1735
1736fn build_deps_args(
1742 cmd: &mut ProcessBuilder,
1743 build_runner: &BuildRunner<'_, '_>,
1744 unit: &Unit,
1745) -> CargoResult<()> {
1746 let bcx = build_runner.bcx;
1747
1748 for arg in lib_search_paths(build_runner, unit)? {
1749 cmd.arg(arg);
1750 }
1751
1752 let deps = build_runner.unit_deps(unit);
1753
1754 if !deps
1758 .iter()
1759 .any(|dep| !dep.unit.mode.is_doc() && dep.unit.target.is_linkable())
1760 {
1761 if let Some(dep) = deps.iter().find(|dep| {
1762 !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true()
1763 }) {
1764 let dep_name = dep.unit.target.crate_name();
1765 let name = unit.target.crate_name();
1766 bcx.gctx.shell().print_report(&[
1767 Level::WARNING.secondary_title(format!("the package `{dep_name}` provides no linkable target"))
1768 .elements([
1769 Level::NOTE.message(format!("this might cause `{name}` to fail compilation")),
1770 Level::NOTE.message("this warning might turn into a hard error in the future"),
1771 Level::HELP.message(format!("consider adding 'dylib' or 'rlib' to key 'crate-type' in `{dep_name}`'s Cargo.toml"))
1772 ])
1773 ], false)?;
1774 }
1775 }
1776
1777 let mut unstable_opts = false;
1778
1779 let first_custom_build_dep = deps.iter().find(|dep| dep.unit.mode.is_run_custom_build());
1781 if let Some(dep) = first_custom_build_dep {
1782 let out_dir = &build_runner.files().build_script_out_dir(&dep.unit);
1783 cmd.env("OUT_DIR", &out_dir);
1784 }
1785
1786 let is_multiple_build_scripts_enabled = unit
1788 .pkg
1789 .manifest()
1790 .unstable_features()
1791 .require(Feature::multiple_build_scripts())
1792 .is_ok();
1793
1794 if is_multiple_build_scripts_enabled {
1795 for dep in deps {
1796 if dep.unit.mode.is_run_custom_build() {
1797 let out_dir = &build_runner.files().build_script_out_dir(&dep.unit);
1798 let target_name = dep.unit.target.name();
1799 let out_dir_prefix = target_name
1800 .strip_prefix("build-script-")
1801 .unwrap_or(target_name);
1802 let out_dir_name = format!("{out_dir_prefix}_OUT_DIR");
1803 cmd.env(&out_dir_name, &out_dir);
1804 }
1805 }
1806 }
1807 for arg in extern_args(build_runner, unit, &mut unstable_opts)? {
1808 cmd.arg(arg);
1809 }
1810
1811 for (var, env) in artifact::get_env(build_runner, deps)? {
1812 cmd.env(&var, env);
1813 }
1814
1815 if unstable_opts {
1818 cmd.arg("-Z").arg("unstable-options");
1819 }
1820
1821 Ok(())
1822}
1823
1824fn add_dep_arg<'a, 'b: 'a>(
1825 map: &mut BTreeMap<&'a Unit, PathBuf>,
1826 build_runner: &'b BuildRunner<'b, '_>,
1827 unit: &'a Unit,
1828) {
1829 if map.contains_key(&unit) {
1830 return;
1831 }
1832 map.insert(&unit, build_runner.files().deps_dir(&unit));
1833
1834 for dep in build_runner.unit_deps(unit) {
1835 add_dep_arg(map, build_runner, &dep.unit);
1836 }
1837}
1838
1839fn add_custom_flags(
1843 cmd: &mut ProcessBuilder,
1844 build_script_outputs: &BuildScriptOutputs,
1845 metadata_vec: Option<Vec<UnitHash>>,
1846) -> CargoResult<()> {
1847 if let Some(metadata_vec) = metadata_vec {
1848 for metadata in metadata_vec {
1849 if let Some(output) = build_script_outputs.get(metadata) {
1850 for cfg in output.cfgs.iter() {
1851 cmd.arg("--cfg").arg(cfg);
1852 }
1853 for check_cfg in &output.check_cfgs {
1854 cmd.arg("--check-cfg").arg(check_cfg);
1855 }
1856 for (name, value) in output.env.iter() {
1857 cmd.env(name, value);
1858 }
1859 }
1860 }
1861 }
1862
1863 Ok(())
1864}
1865
1866pub fn lib_search_paths(
1868 build_runner: &BuildRunner<'_, '_>,
1869 unit: &Unit,
1870) -> CargoResult<Vec<OsString>> {
1871 let mut lib_search_paths = Vec::new();
1872 if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1873 let mut map = BTreeMap::new();
1874
1875 add_dep_arg(&mut map, build_runner, unit);
1877
1878 let paths = map.into_iter().map(|(_, path)| path).sorted_unstable();
1879
1880 for path in paths {
1881 let mut deps = OsString::from("dependency=");
1882 deps.push(path);
1883 lib_search_paths.extend(["-L".into(), deps]);
1884 }
1885 } else {
1886 let mut deps = OsString::from("dependency=");
1887 deps.push(build_runner.files().deps_dir(unit));
1888 lib_search_paths.extend(["-L".into(), deps]);
1889 }
1890
1891 if !unit.kind.is_host() {
1894 let mut deps = OsString::from("dependency=");
1895 deps.push(build_runner.files().host_deps(unit));
1896 lib_search_paths.extend(["-L".into(), deps]);
1897 }
1898
1899 Ok(lib_search_paths)
1900}
1901
1902pub fn extern_args(
1904 build_runner: &BuildRunner<'_, '_>,
1905 unit: &Unit,
1906 unstable_opts: &mut bool,
1907) -> CargoResult<Vec<OsString>> {
1908 let mut result = Vec::new();
1909 let deps = build_runner.unit_deps(unit);
1910
1911 let no_embed_metadata = build_runner.bcx.gctx.cli_unstable().no_embed_metadata;
1912
1913 let mut link_to =
1915 |dep: &UnitDep, extern_crate_name: InternedString, noprelude: bool| -> CargoResult<()> {
1916 let mut value = OsString::new();
1917 let mut opts = Vec::new();
1918 let is_public_dependency_enabled = unit
1919 .pkg
1920 .manifest()
1921 .unstable_features()
1922 .require(Feature::public_dependency())
1923 .is_ok()
1924 || build_runner.bcx.gctx.cli_unstable().public_dependency;
1925 if !dep.public && unit.target.is_lib() && is_public_dependency_enabled {
1926 opts.push("priv");
1927 *unstable_opts = true;
1928 }
1929 if noprelude {
1930 opts.push("noprelude");
1931 *unstable_opts = true;
1932 }
1933 if !opts.is_empty() {
1934 value.push(opts.join(","));
1935 value.push(":");
1936 }
1937 value.push(extern_crate_name.as_str());
1938 value.push("=");
1939
1940 let mut pass = |file| {
1941 let mut value = value.clone();
1942 value.push(file);
1943 result.push(OsString::from("--extern"));
1944 result.push(value);
1945 };
1946
1947 let outputs = build_runner.outputs(&dep.unit)?;
1948
1949 if build_runner.only_requires_rmeta(unit, &dep.unit) || dep.unit.mode.is_check() {
1950 let output = outputs
1952 .iter()
1953 .find(|output| output.flavor == FileFlavor::Rmeta)
1954 .expect("failed to find rmeta dep for pipelined dep");
1955 pass(&output.path);
1956 } else {
1957 for output in outputs.iter() {
1959 if output.flavor == FileFlavor::Linkable {
1960 pass(&output.path);
1961 }
1962 else if no_embed_metadata && output.flavor == FileFlavor::Rmeta {
1966 pass(&output.path);
1967 }
1968 }
1969 }
1970 Ok(())
1971 };
1972
1973 for dep in deps {
1974 if dep.unit.target.is_linkable() && !dep.unit.mode.is_doc() {
1975 link_to(dep, dep.extern_crate_name, dep.noprelude)?;
1976 }
1977 }
1978 if unit.target.proc_macro() {
1979 result.push(OsString::from("--extern"));
1981 result.push(OsString::from("proc_macro"));
1982 }
1983
1984 Ok(result)
1985}
1986
1987fn envify(s: &str) -> String {
1988 s.chars()
1989 .flat_map(|c| c.to_uppercase())
1990 .map(|c| if c == '-' { '_' } else { c })
1991 .collect()
1992}
1993
1994struct OutputOptions {
1997 format: MessageFormat,
1999 cache_cell: Option<(PathBuf, OnceCell<File>)>,
2004 show_diagnostics: bool,
2012 warnings_seen: usize,
2014 errors_seen: usize,
2016}
2017
2018impl OutputOptions {
2019 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2020 let path = build_runner.files().message_cache_path(unit);
2021 drop(fs::remove_file(&path));
2023 let cache_cell = Some((path, OnceCell::new()));
2024 let show_diagnostics =
2025 build_runner.bcx.gctx.warning_handling().unwrap_or_default() != WarningHandling::Allow;
2026 OutputOptions {
2027 format: build_runner.bcx.build_config.message_format,
2028 cache_cell,
2029 show_diagnostics,
2030 warnings_seen: 0,
2031 errors_seen: 0,
2032 }
2033 }
2034}
2035
2036struct ManifestErrorContext {
2042 path: PathBuf,
2044 spans: toml::Spanned<toml::de::DeTable<'static>>,
2046 contents: String,
2048 rename_table: HashMap<InternedString, InternedString>,
2051 requested_kinds: Vec<CompileKind>,
2054 cfgs: Vec<Vec<Cfg>>,
2057 host_name: InternedString,
2058 cwd: PathBuf,
2060 term_width: usize,
2062}
2063
2064fn on_stdout_line(
2065 state: &JobState<'_, '_>,
2066 line: &str,
2067 _package_id: PackageId,
2068 _target: &Target,
2069) -> CargoResult<()> {
2070 state.stdout(line.to_string())?;
2071 Ok(())
2072}
2073
2074fn on_stderr_line(
2075 state: &JobState<'_, '_>,
2076 line: &str,
2077 package_id: PackageId,
2078 manifest: &ManifestErrorContext,
2079 target: &Target,
2080 options: &mut OutputOptions,
2081) -> CargoResult<()> {
2082 if on_stderr_line_inner(state, line, package_id, manifest, target, options)? {
2083 if let Some((path, cell)) = &mut options.cache_cell {
2085 let f = cell.try_borrow_mut_with(|| paths::create(path))?;
2087 debug_assert!(!line.contains('\n'));
2088 f.write_all(line.as_bytes())?;
2089 f.write_all(&[b'\n'])?;
2090 }
2091 }
2092 Ok(())
2093}
2094
2095fn on_stderr_line_inner(
2097 state: &JobState<'_, '_>,
2098 line: &str,
2099 package_id: PackageId,
2100 manifest: &ManifestErrorContext,
2101 target: &Target,
2102 options: &mut OutputOptions,
2103) -> CargoResult<bool> {
2104 if !line.starts_with('{') {
2110 state.stderr(line.to_string())?;
2111 return Ok(true);
2112 }
2113
2114 let mut compiler_message: Box<serde_json::value::RawValue> = match serde_json::from_str(line) {
2115 Ok(msg) => msg,
2116
2117 Err(e) => {
2121 debug!("failed to parse json: {:?}", e);
2122 state.stderr(line.to_string())?;
2123 return Ok(true);
2124 }
2125 };
2126
2127 let count_diagnostic = |level, options: &mut OutputOptions| {
2128 if level == "warning" {
2129 options.warnings_seen += 1;
2130 } else if level == "error" {
2131 options.errors_seen += 1;
2132 }
2133 };
2134
2135 if let Ok(report) = serde_json::from_str::<FutureIncompatReport>(compiler_message.get()) {
2136 for item in &report.future_incompat_report {
2137 count_diagnostic(&*item.diagnostic.level, options);
2138 }
2139 state.future_incompat_report(report.future_incompat_report);
2140 return Ok(true);
2141 }
2142
2143 let res = serde_json::from_str::<SectionTiming>(compiler_message.get());
2144 if let Ok(timing_record) = res {
2145 state.on_section_timing_emitted(timing_record);
2146 return Ok(false);
2147 }
2148
2149 let add_pub_in_priv_diagnostic = |diag: &mut String| -> bool {
2151 static PRIV_DEP_REGEX: LazyLock<Regex> =
2160 LazyLock::new(|| Regex::new("from private dependency '([A-Za-z0-9-_]+)'").unwrap());
2161 if let Some(crate_name) = PRIV_DEP_REGEX.captures(diag).and_then(|m| m.get(1))
2162 && let Some(span) = manifest.find_crate_span(crate_name.as_str())
2163 {
2164 let rel_path = pathdiff::diff_paths(&manifest.path, &manifest.cwd)
2165 .unwrap_or_else(|| manifest.path.clone())
2166 .display()
2167 .to_string();
2168 let report = [Group::with_title(Level::NOTE.secondary_title(format!(
2169 "dependency `{}` declared here",
2170 crate_name.as_str()
2171 )))
2172 .element(
2173 Snippet::source(&manifest.contents)
2174 .path(rel_path)
2175 .annotation(AnnotationKind::Context.span(span)),
2176 )];
2177
2178 let rendered = Renderer::styled()
2179 .term_width(manifest.term_width)
2180 .render(&report);
2181 diag.push_str(&rendered);
2182 diag.push('\n');
2183 return true;
2184 }
2185 false
2186 };
2187
2188 match options.format {
2191 MessageFormat::Human
2196 | MessageFormat::Short
2197 | MessageFormat::Json {
2198 render_diagnostics: true,
2199 ..
2200 } => {
2201 #[derive(serde::Deserialize)]
2202 struct CompilerMessage<'a> {
2203 rendered: String,
2207 #[serde(borrow)]
2208 message: Cow<'a, str>,
2209 #[serde(borrow)]
2210 level: Cow<'a, str>,
2211 children: Vec<PartialDiagnostic>,
2212 code: Option<DiagnosticCode>,
2213 }
2214
2215 #[derive(serde::Deserialize)]
2224 struct PartialDiagnostic {
2225 spans: Vec<PartialDiagnosticSpan>,
2226 }
2227
2228 #[derive(serde::Deserialize)]
2230 struct PartialDiagnosticSpan {
2231 suggestion_applicability: Option<Applicability>,
2232 }
2233
2234 #[derive(serde::Deserialize)]
2235 struct DiagnosticCode {
2236 code: String,
2237 }
2238
2239 if let Ok(mut msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2240 {
2241 if msg.message.starts_with("aborting due to")
2242 || msg.message.ends_with("warning emitted")
2243 || msg.message.ends_with("warnings emitted")
2244 {
2245 return Ok(true);
2247 }
2248 if msg.rendered.ends_with('\n') {
2250 msg.rendered.pop();
2251 }
2252 let mut rendered = msg.rendered;
2253 if options.show_diagnostics {
2254 let machine_applicable: bool = msg
2255 .children
2256 .iter()
2257 .map(|child| {
2258 child
2259 .spans
2260 .iter()
2261 .filter_map(|span| span.suggestion_applicability)
2262 .any(|app| app == Applicability::MachineApplicable)
2263 })
2264 .any(|b| b);
2265 count_diagnostic(&msg.level, options);
2266 if msg
2267 .code
2268 .as_ref()
2269 .is_some_and(|c| c.code == "exported_private_dependencies")
2270 && options.format != MessageFormat::Short
2271 {
2272 add_pub_in_priv_diagnostic(&mut rendered);
2273 }
2274 let lint = msg.code.is_some();
2275 state.emit_diag(&msg.level, rendered, lint, machine_applicable)?;
2276 }
2277 return Ok(true);
2278 }
2279 }
2280
2281 MessageFormat::Json { ansi, .. } => {
2282 #[derive(serde::Deserialize, serde::Serialize)]
2283 struct CompilerMessage<'a> {
2284 rendered: String,
2285 #[serde(flatten, borrow)]
2286 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2287 code: Option<DiagnosticCode<'a>>,
2288 }
2289
2290 #[derive(serde::Deserialize, serde::Serialize)]
2291 struct DiagnosticCode<'a> {
2292 code: String,
2293 #[serde(flatten, borrow)]
2294 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2295 }
2296
2297 if let Ok(mut error) =
2298 serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2299 {
2300 let modified_diag = if error
2301 .code
2302 .as_ref()
2303 .is_some_and(|c| c.code == "exported_private_dependencies")
2304 {
2305 add_pub_in_priv_diagnostic(&mut error.rendered)
2306 } else {
2307 false
2308 };
2309
2310 if !ansi {
2314 error.rendered = anstream::adapter::strip_str(&error.rendered).to_string();
2315 }
2316 if !ansi || modified_diag {
2317 let new_line = serde_json::to_string(&error)?;
2318 compiler_message = serde_json::value::RawValue::from_string(new_line)?;
2319 }
2320 }
2321 }
2322 }
2323
2324 #[derive(serde::Deserialize)]
2331 struct ArtifactNotification<'a> {
2332 #[serde(borrow)]
2333 artifact: Cow<'a, str>,
2334 }
2335
2336 if let Ok(artifact) = serde_json::from_str::<ArtifactNotification<'_>>(compiler_message.get()) {
2337 trace!("found directive from rustc: `{}`", artifact.artifact);
2338 if artifact.artifact.ends_with(".rmeta") {
2339 debug!("looks like metadata finished early!");
2340 state.rmeta_produced();
2341 }
2342 return Ok(false);
2343 }
2344
2345 if !options.show_diagnostics {
2350 return Ok(true);
2351 }
2352
2353 #[derive(serde::Deserialize)]
2354 struct CompilerMessage<'a> {
2355 #[serde(borrow)]
2356 message: Cow<'a, str>,
2357 #[serde(borrow)]
2358 level: Cow<'a, str>,
2359 }
2360
2361 if let Ok(msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get()) {
2362 if msg.message.starts_with("aborting due to")
2363 || msg.message.ends_with("warning emitted")
2364 || msg.message.ends_with("warnings emitted")
2365 {
2366 return Ok(true);
2368 }
2369 count_diagnostic(&msg.level, options);
2370 }
2371
2372 let msg = machine_message::FromCompiler {
2373 package_id: package_id.to_spec(),
2374 manifest_path: &manifest.path,
2375 target,
2376 message: compiler_message,
2377 }
2378 .to_json_string();
2379
2380 state.stdout(msg)?;
2384 Ok(true)
2385}
2386
2387impl ManifestErrorContext {
2388 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> ManifestErrorContext {
2389 let mut duplicates = HashSet::new();
2390 let mut rename_table = HashMap::new();
2391
2392 for dep in build_runner.unit_deps(unit) {
2393 let unrenamed_id = dep.unit.pkg.package_id().name();
2394 if duplicates.contains(&unrenamed_id) {
2395 continue;
2396 }
2397 match rename_table.entry(unrenamed_id) {
2398 std::collections::hash_map::Entry::Occupied(occ) => {
2399 occ.remove_entry();
2400 duplicates.insert(unrenamed_id);
2401 }
2402 std::collections::hash_map::Entry::Vacant(vac) => {
2403 vac.insert(dep.extern_crate_name);
2404 }
2405 }
2406 }
2407
2408 let bcx = build_runner.bcx;
2409 ManifestErrorContext {
2410 path: unit.pkg.manifest_path().to_owned(),
2411 spans: unit.pkg.manifest().document().clone(),
2412 contents: unit.pkg.manifest().contents().to_owned(),
2413 requested_kinds: bcx.target_data.requested_kinds().to_owned(),
2414 host_name: bcx.rustc().host,
2415 rename_table,
2416 cwd: path_args(build_runner.bcx.ws, unit).1,
2417 cfgs: bcx
2418 .target_data
2419 .requested_kinds()
2420 .iter()
2421 .map(|k| bcx.target_data.cfg(*k).to_owned())
2422 .collect(),
2423 term_width: bcx
2424 .gctx
2425 .shell()
2426 .err_width()
2427 .diagnostic_terminal_width()
2428 .unwrap_or(annotate_snippets::renderer::DEFAULT_TERM_WIDTH),
2429 }
2430 }
2431
2432 fn requested_target_names(&self) -> impl Iterator<Item = &str> {
2433 self.requested_kinds.iter().map(|kind| match kind {
2434 CompileKind::Host => &self.host_name,
2435 CompileKind::Target(target) => target.short_name(),
2436 })
2437 }
2438
2439 fn find_crate_span(&self, unrenamed: &str) -> Option<Range<usize>> {
2453 let orig_name = self.rename_table.get(unrenamed)?.as_str();
2454
2455 if let Some((k, v)) = get_key_value(&self.spans, &["dependencies", orig_name]) {
2456 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package")) {
2465 return Some(package.span());
2466 } else {
2467 return Some(k.span());
2468 }
2469 }
2470
2471 if let Some(target) = self
2476 .spans
2477 .as_ref()
2478 .get("target")
2479 .and_then(|t| t.as_ref().as_table())
2480 {
2481 for (platform, platform_table) in target.iter() {
2482 match platform.as_ref().parse::<Platform>() {
2483 Ok(Platform::Name(name)) => {
2484 if !self.requested_target_names().any(|n| n == name) {
2485 continue;
2486 }
2487 }
2488 Ok(Platform::Cfg(cfg_expr)) => {
2489 if !self.cfgs.iter().any(|cfgs| cfg_expr.matches(cfgs)) {
2490 continue;
2491 }
2492 }
2493 Err(_) => continue,
2494 }
2495
2496 let Some(platform_table) = platform_table.as_ref().as_table() else {
2497 continue;
2498 };
2499
2500 if let Some(deps) = platform_table
2501 .get("dependencies")
2502 .and_then(|d| d.as_ref().as_table())
2503 {
2504 if let Some((k, v)) = deps.get_key_value(orig_name) {
2505 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package"))
2506 {
2507 return Some(package.span());
2508 } else {
2509 return Some(k.span());
2510 }
2511 }
2512 }
2513 }
2514 }
2515 None
2516 }
2517}
2518
2519fn replay_output_cache(
2523 package_id: PackageId,
2524 manifest: ManifestErrorContext,
2525 target: &Target,
2526 path: PathBuf,
2527 format: MessageFormat,
2528 show_diagnostics: bool,
2529) -> Work {
2530 let target = target.clone();
2531 let mut options = OutputOptions {
2532 format,
2533 cache_cell: None,
2534 show_diagnostics,
2535 warnings_seen: 0,
2536 errors_seen: 0,
2537 };
2538 Work::new(move |state| {
2539 if !path.exists() {
2540 return Ok(());
2542 }
2543 let file = paths::open(&path)?;
2547 let mut reader = std::io::BufReader::new(file);
2548 let mut line = String::new();
2549 loop {
2550 let length = reader.read_line(&mut line)?;
2551 if length == 0 {
2552 break;
2553 }
2554 let trimmed = line.trim_end_matches(&['\n', '\r'][..]);
2555 on_stderr_line(state, trimmed, package_id, &manifest, &target, &mut options)?;
2556 line.clear();
2557 }
2558 Ok(())
2559 })
2560}
2561
2562fn descriptive_pkg_name(name: &str, target: &Target, mode: &CompileMode) -> String {
2565 let desc_name = target.description_named();
2566 let mode = if mode.is_rustc_test() && !(target.is_test() || target.is_bench()) {
2567 " test"
2568 } else if mode.is_doc_test() {
2569 " doctest"
2570 } else if mode.is_doc() {
2571 " doc"
2572 } else {
2573 ""
2574 };
2575 format!("`{name}` ({desc_name}{mode})")
2576}
2577
2578pub(crate) fn apply_env_config(
2580 gctx: &crate::GlobalContext,
2581 cmd: &mut ProcessBuilder,
2582) -> CargoResult<()> {
2583 for (key, value) in gctx.env_config()?.iter() {
2584 if cmd.get_envs().contains_key(key) {
2586 continue;
2587 }
2588 cmd.env(key, value);
2589 }
2590 Ok(())
2591}
2592
2593fn should_include_scrape_units(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
2595 unit.mode.is_doc() && bcx.scrape_units.len() > 0 && bcx.ws.unit_needs_doc_scrape(unit)
2596}
2597
2598fn scrape_output_path(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<PathBuf> {
2600 assert!(unit.mode.is_doc() || unit.mode.is_doc_scrape());
2601 build_runner
2602 .outputs(unit)
2603 .map(|outputs| outputs[0].path.clone())
2604}
2605
2606fn rustdoc_dep_info_loc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
2608 let mut loc = build_runner.files().fingerprint_file_path(unit, "");
2609 loc.set_extension("d");
2610 loc
2611}