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;
54mod unused_deps;
55
56use std::borrow::Cow;
57use std::cell::OnceCell;
58use std::collections::{BTreeMap, HashMap, HashSet};
59use std::env;
60use std::ffi::{OsStr, OsString};
61use std::fmt::Display;
62use std::fs::{self, File};
63use std::io::{BufRead, BufWriter, Write};
64use std::ops::Range;
65use std::path::{Path, PathBuf};
66use std::sync::{Arc, LazyLock};
67
68use anyhow::{Context as _, Error};
69use cargo_platform::{Cfg, Platform};
70use cargo_util_terminal::report::{AnnotationKind, Group, Level, Renderer, Snippet};
71use itertools::Itertools;
72use regex::Regex;
73use tracing::{debug, instrument, trace};
74
75pub use self::build_config::UserIntent;
76pub use self::build_config::{BuildConfig, CompileMode, MessageFormat};
77pub use self::build_context::BuildContext;
78pub use self::build_context::DepKindSet;
79pub use self::build_context::FileFlavor;
80pub use self::build_context::FileType;
81pub use self::build_context::RustcTargetData;
82pub use self::build_context::TargetInfo;
83pub use self::build_runner::{BuildRunner, Metadata, UnitHash};
84pub use self::compilation::{Compilation, Doctest, UnitOutput};
85pub use self::compile_kind::{CompileKind, CompileKindFallback, CompileTarget};
86pub use self::crate_type::CrateType;
87pub use self::custom_build::LinkArgTarget;
88pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts, LibraryPath};
89pub(crate) use self::fingerprint::DirtyReason;
90pub use self::fingerprint::RustdocFingerprint;
91pub use self::job_queue::Freshness;
92use self::job_queue::{Job, JobQueue, JobState, Work};
93pub(crate) use self::layout::Layout;
94pub use self::lto::Lto;
95use self::output_depinfo::output_depinfo;
96use self::output_sbom::build_sbom;
97use self::unit_graph::UnitDep;
98
99use crate::core::compiler::future_incompat::FutureIncompatReport;
100use crate::core::compiler::locking::LockKey;
101use crate::core::compiler::timings::SectionTiming;
102pub use crate::core::compiler::unit::Unit;
103pub use crate::core::compiler::unit::UnitIndex;
104pub use crate::core::compiler::unit::UnitInterner;
105use crate::core::manifest::TargetSourcePath;
106use crate::core::profiles::{FramePointers, PanicStrategy, Profile, StripInner};
107use crate::core::{Feature, PackageId, Target};
108use crate::lints::get_key_value;
109use crate::util::OnceExt;
110use crate::util::errors::{CargoResult, VerboseError};
111use crate::util::interning::InternedString;
112use crate::util::machine_message::{self, Message};
113use crate::util::{add_path_args, internal, path_args};
114
115use cargo_util::{ProcessBuilder, ProcessError, paths};
116use cargo_util_schemas::manifest::TomlDebugInfo;
117use cargo_util_schemas::manifest::TomlTrimPaths;
118use cargo_util_schemas::manifest::TomlTrimPathsValue;
119use cargo_util_terminal::Verbosity;
120use rustfix::diagnostics::Applicability;
121
122const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
123
124pub trait Executor: Send + Sync + 'static {
128 fn init(&self, _build_runner: &BuildRunner<'_, '_>, _unit: &Unit) {}
132
133 fn exec(
136 &self,
137 cmd: &ProcessBuilder,
138 id: PackageId,
139 target: &Target,
140 mode: CompileMode,
141 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
142 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
143 ) -> CargoResult<()>;
144
145 fn force_rebuild(&self, _unit: &Unit) -> bool {
148 false
149 }
150}
151
152#[derive(Copy, Clone)]
155pub struct DefaultExecutor;
156
157impl Executor for DefaultExecutor {
158 #[instrument(name = "rustc", skip_all, fields(package = id.name().as_str(), process = cmd.to_string()))]
159 fn exec(
160 &self,
161 cmd: &ProcessBuilder,
162 id: PackageId,
163 _target: &Target,
164 _mode: CompileMode,
165 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
166 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
167 ) -> CargoResult<()> {
168 cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
169 .map(drop)
170 }
171}
172
173#[tracing::instrument(skip(build_runner, jobs, exec))]
183fn compile<'gctx>(
184 build_runner: &mut BuildRunner<'_, 'gctx>,
185 jobs: &mut JobQueue<'gctx>,
186 unit: &Unit,
187 exec: &Arc<dyn Executor>,
188 force_rebuild: bool,
189) -> CargoResult<()> {
190 if !build_runner.compiled.insert(unit.clone()) {
191 return Ok(());
192 }
193
194 let lock = if build_runner.bcx.gctx.cli_unstable().fine_grain_locking {
195 Some(build_runner.lock_manager.lock_shared(build_runner, unit)?)
196 } else {
197 None
198 };
199
200 if !unit.skip_non_compile_time_dep {
204 fingerprint::prepare_init(build_runner, unit)?;
207
208 let job = if unit.mode.is_run_custom_build() {
209 custom_build::prepare(build_runner, unit)?
210 } else if unit.mode.is_doc_test() {
211 Job::new_fresh()
213 } else {
214 let force = exec.force_rebuild(unit) || force_rebuild;
215 let mut job = fingerprint::prepare_target(build_runner, unit, force)?;
216 job.before(if job.freshness().is_dirty() {
217 let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
218 rustdoc(build_runner, unit)?
219 } else {
220 rustc(build_runner, unit, exec)?
221 };
222 work.then(link_targets(build_runner, unit, false)?)
223 } else {
224 let output_options = OutputOptions::for_fresh(build_runner, unit);
225 let manifest = ManifestErrorContext::new(build_runner, unit);
226 let work = replay_output_cache(
227 unit.pkg.package_id(),
228 manifest,
229 &unit.target,
230 build_runner.files().message_cache_path(unit),
231 output_options,
232 );
233 work.then(link_targets(build_runner, unit, true)?)
235 });
236
237 if build_runner.bcx.gctx.cli_unstable().fine_grain_locking && job.freshness().is_dirty()
240 {
241 if let Some(lock) = lock {
242 build_runner.lock_manager.unlock(&lock)?;
249 job.before(prebuild_lock_exclusive(lock.clone()));
250 job.after(downgrade_lock_to_shared(lock));
251 }
252 }
253
254 job
255 };
256 jobs.enqueue(build_runner, unit, job)?;
257 }
258
259 let deps = Vec::from(build_runner.unit_deps(unit)); for dep in deps {
262 compile(build_runner, jobs, &dep.unit, exec, false)?;
263 }
264
265 Ok(())
266}
267
268fn make_failed_scrape_diagnostic(
271 build_runner: &BuildRunner<'_, '_>,
272 unit: &Unit,
273 top_line: impl Display,
274) -> String {
275 let manifest_path = unit.pkg.manifest_path();
276 let relative_manifest_path = manifest_path
277 .strip_prefix(build_runner.bcx.ws.root())
278 .unwrap_or(&manifest_path);
279
280 format!(
281 "\
282{top_line}
283 Try running with `--verbose` to see the error message.
284 If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
285 relative_manifest_path.display()
286 )
287}
288
289fn rustc(
291 build_runner: &mut BuildRunner<'_, '_>,
292 unit: &Unit,
293 exec: &Arc<dyn Executor>,
294) -> CargoResult<Work> {
295 let mut rustc = prepare_rustc(build_runner, unit)?;
296
297 let name = unit.pkg.name();
298
299 let outputs = build_runner.outputs(unit)?;
300 let root = build_runner.files().output_dir(unit);
301
302 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
304 let current_id = unit.pkg.package_id();
305 let manifest = ManifestErrorContext::new(build_runner, unit);
306 let build_scripts = build_runner.build_scripts.get(unit).cloned();
307
308 let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
311
312 let dep_info_name =
313 if let Some(c_extra_filename) = build_runner.files().metadata(unit).c_extra_filename() {
314 format!("{}-{}.d", unit.target.crate_name(), c_extra_filename)
315 } else {
316 format!("{}.d", unit.target.crate_name())
317 };
318 let rustc_dep_info_loc = root.join(dep_info_name);
319 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
320
321 let mut output_options = OutputOptions::for_dirty(build_runner, unit);
322 let package_id = unit.pkg.package_id();
323 let target = Target::clone(&unit.target);
324 let mode = unit.mode;
325
326 exec.init(build_runner, unit);
327 let exec = exec.clone();
328
329 let root_output = build_runner.files().host_dest().map(|v| v.to_path_buf());
330 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
331 let pkg_root = unit.pkg.root().to_path_buf();
332 let cwd = rustc
333 .get_cwd()
334 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
335 .to_path_buf();
336 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
337 let script_metadatas = build_runner.find_build_script_metadatas(unit);
338 let is_local = unit.is_local();
339 let artifact = unit.artifact;
340 let sbom_files = build_runner.sbom_output_files(unit)?;
341 let sbom = build_sbom(build_runner, unit)?;
342
343 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
344 && !matches!(
345 build_runner.bcx.gctx.shell().verbosity(),
346 Verbosity::Verbose
347 );
348 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
349 let target_desc = unit.target.description_named();
352 let mut for_scrape_units = build_runner
353 .bcx
354 .scrape_units_have_dep_on(unit)
355 .into_iter()
356 .map(|unit| unit.target.description_named())
357 .collect::<Vec<_>>();
358 for_scrape_units.sort();
359 let for_scrape_units = for_scrape_units.join(", ");
360 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}"))
361 });
362 if hide_diagnostics_for_scrape_unit {
363 output_options.show_diagnostics = false;
364 }
365 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
366 return Ok(Work::new(move |state| {
367 if artifact.is_true() {
371 paths::create_dir_all(&root)?;
372 }
373
374 if let Some(build_scripts) = build_scripts {
382 let script_outputs = build_script_outputs.lock().unwrap();
383 add_native_deps(
384 &mut rustc,
385 &script_outputs,
386 &build_scripts,
387 pass_l_flag,
388 &target,
389 current_id,
390 mode,
391 )?;
392 if let Some(ref root_output) = root_output {
393 add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, root_output)?;
394 }
395 add_custom_flags(&mut rustc, &script_outputs, script_metadatas)?;
396 }
397
398 for output in outputs.iter() {
399 if output.path.extension() == Some(OsStr::new("rmeta")) {
403 let dst = root.join(&output.path).with_extension("rlib");
404 if dst.exists() {
405 paths::remove_file(&dst)?;
406 }
407 }
408
409 if output.hardlink.is_some() && output.path.exists() {
414 _ = paths::remove_file(&output.path).map_err(|e| {
415 tracing::debug!(
416 "failed to delete previous output file `{:?}`: {e:?}",
417 output.path
418 );
419 });
420 }
421 }
422
423 state.running(&rustc);
424 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
425 for file in sbom_files {
426 tracing::debug!("writing sbom to {}", file.display());
427 let outfile = BufWriter::new(paths::create(&file)?);
428 serde_json::to_writer(outfile, &sbom)?;
429 }
430
431 let result = exec
432 .exec(
433 &rustc,
434 package_id,
435 &target,
436 mode,
437 &mut |line| on_stdout_line(state, line, package_id, &target),
438 &mut |line| {
439 on_stderr_line(
440 state,
441 line,
442 package_id,
443 &manifest,
444 &target,
445 &mut output_options,
446 )
447 },
448 )
449 .map_err(|e| {
450 if output_options.errors_seen == 0 {
451 e
456 } else {
457 verbose_if_simple_exit_code(e)
458 }
459 })
460 .with_context(|| {
461 let warnings = match output_options.warnings_seen {
463 0 => String::new(),
464 1 => "; 1 warning emitted".to_string(),
465 count => format!("; {} warnings emitted", count),
466 };
467 let errors = match output_options.errors_seen {
468 0 => String::new(),
469 1 => " due to 1 previous error".to_string(),
470 count => format!(" due to {} previous errors", count),
471 };
472 let name = descriptive_pkg_name(&name, &target, &mode);
473 format!("could not compile {name}{errors}{warnings}")
474 });
475
476 if let Err(e) = result {
477 if let Some(diagnostic) = failed_scrape_diagnostic {
478 state.warning(diagnostic);
479 }
480
481 return Err(e);
482 }
483
484 debug_assert_eq!(output_options.errors_seen, 0);
486
487 if rustc_dep_info_loc.exists() {
488 fingerprint::translate_dep_info(
489 &rustc_dep_info_loc,
490 &dep_info_loc,
491 &cwd,
492 &pkg_root,
493 &build_dir,
494 &rustc,
495 is_local,
497 &env_config,
498 )
499 .with_context(|| {
500 internal(format!(
501 "could not parse/generate dep info at: {}",
502 rustc_dep_info_loc.display()
503 ))
504 })?;
505 paths::set_file_time_no_err(dep_info_loc, timestamp);
508 }
509
510 if mode.is_check() {
524 for output in outputs.iter() {
525 paths::set_file_time_no_err(&output.path, timestamp);
526 }
527 }
528
529 Ok(())
530 }));
531
532 fn add_native_deps(
535 rustc: &mut ProcessBuilder,
536 build_script_outputs: &BuildScriptOutputs,
537 build_scripts: &BuildScripts,
538 pass_l_flag: bool,
539 target: &Target,
540 current_id: PackageId,
541 mode: CompileMode,
542 ) -> CargoResult<()> {
543 let mut library_paths = vec![];
544
545 for key in build_scripts.to_link.iter() {
546 let output = build_script_outputs.get(key.1).ok_or_else(|| {
547 internal(format!(
548 "couldn't find build script output for {}/{}",
549 key.0, key.1
550 ))
551 })?;
552 library_paths.extend(output.library_paths.iter());
553 }
554
555 library_paths.sort_by_key(|p| match p {
561 LibraryPath::CargoArtifact(_) => 0,
562 LibraryPath::External(_) => 1,
563 });
564
565 for path in library_paths.iter() {
566 rustc.arg("-L").arg(path.as_ref());
567 }
568
569 for key in build_scripts.to_link.iter() {
570 let output = build_script_outputs.get(key.1).ok_or_else(|| {
571 internal(format!(
572 "couldn't find build script output for {}/{}",
573 key.0, key.1
574 ))
575 })?;
576
577 if key.0 == current_id {
578 if pass_l_flag {
579 for name in output.library_links.iter() {
580 rustc.arg("-l").arg(name);
581 }
582 }
583 }
584
585 for (lt, arg) in &output.linker_args {
586 if lt.applies_to(target, mode)
592 && (key.0 == current_id || *lt == LinkArgTarget::Cdylib)
593 {
594 rustc.arg("-C").arg(format!("link-arg={}", arg));
595 }
596 }
597 }
598 Ok(())
599 }
600}
601
602fn verbose_if_simple_exit_code(err: Error) -> Error {
603 match err
606 .downcast_ref::<ProcessError>()
607 .as_ref()
608 .and_then(|perr| perr.code)
609 {
610 Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
611 _ => err,
612 }
613}
614
615fn prebuild_lock_exclusive(lock: LockKey) -> Work {
616 Work::new(move |state| {
617 state.lock_exclusive(&lock)?;
618 Ok(())
619 })
620}
621
622fn downgrade_lock_to_shared(lock: LockKey) -> Work {
623 Work::new(move |state| {
624 state.downgrade_to_shared(&lock)?;
625 Ok(())
626 })
627}
628
629fn link_targets(
632 build_runner: &mut BuildRunner<'_, '_>,
633 unit: &Unit,
634 fresh: bool,
635) -> CargoResult<Work> {
636 let bcx = build_runner.bcx;
637 let outputs = build_runner.outputs(unit)?;
638 let export_dir = build_runner.files().export_dir();
639 let package_id = unit.pkg.package_id();
640 let manifest_path = PathBuf::from(unit.pkg.manifest_path());
641 let profile = unit.profile.clone();
642 let unit_mode = unit.mode;
643 let features = unit.features.iter().map(|s| s.to_string()).collect();
644 let json_messages = bcx.build_config.emit_json();
645 let executable = build_runner.get_executable(unit)?;
646 let mut target = Target::clone(&unit.target);
647 if let TargetSourcePath::Metabuild = target.src_path() {
648 let path = unit
650 .pkg
651 .manifest()
652 .metabuild_path(build_runner.bcx.ws.build_dir());
653 target.set_src_path(TargetSourcePath::Path(path));
654 }
655
656 Ok(Work::new(move |state| {
657 let mut destinations = vec![];
662 for output in outputs.iter() {
663 let src = &output.path;
664 if !src.exists() {
667 continue;
668 }
669 let Some(dst) = output.hardlink.as_ref() else {
670 destinations.push(src.clone());
671 continue;
672 };
673 destinations.push(dst.clone());
674 paths::link_or_copy(src, dst)?;
675 if let Some(ref path) = output.export_path {
676 let export_dir = export_dir.as_ref().unwrap();
677 paths::create_dir_all(export_dir)?;
678
679 paths::link_or_copy(src, path)?;
680 }
681 }
682
683 if json_messages {
684 let debuginfo = match profile.debuginfo.into_inner() {
685 TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
686 TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
687 TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
688 TomlDebugInfo::LineDirectivesOnly => {
689 machine_message::ArtifactDebuginfo::Named("line-directives-only")
690 }
691 TomlDebugInfo::LineTablesOnly => {
692 machine_message::ArtifactDebuginfo::Named("line-tables-only")
693 }
694 };
695 let art_profile = machine_message::ArtifactProfile {
696 opt_level: profile.opt_level.as_str(),
697 debuginfo: Some(debuginfo),
698 debug_assertions: profile.debug_assertions,
699 overflow_checks: profile.overflow_checks,
700 test: unit_mode.is_any_test(),
701 };
702
703 let msg = machine_message::Artifact {
704 package_id: package_id.to_spec(),
705 manifest_path,
706 target: &target,
707 profile: art_profile,
708 features,
709 filenames: destinations,
710 executable,
711 fresh,
712 }
713 .to_json_string();
714 state.stdout(msg)?;
715 }
716 Ok(())
717 }))
718}
719
720fn add_plugin_deps(
724 rustc: &mut ProcessBuilder,
725 build_script_outputs: &BuildScriptOutputs,
726 build_scripts: &BuildScripts,
727 root_output: &Path,
728) -> CargoResult<()> {
729 let var = paths::dylib_path_envvar();
730 let search_path = rustc.get_env(var).unwrap_or_default();
731 let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
732 for (pkg_id, metadata) in &build_scripts.plugins {
733 let output = build_script_outputs
734 .get(*metadata)
735 .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
736 search_path.append(&mut filter_dynamic_search_path(
737 output.library_paths.iter().map(AsRef::as_ref),
738 root_output,
739 ));
740 }
741 let search_path = paths::join_paths(&search_path, var)?;
742 rustc.env(var, &search_path);
743 Ok(())
744}
745
746fn get_dynamic_search_path(path: &Path) -> &Path {
747 match path.to_str().and_then(|s| s.split_once("=")) {
748 Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => Path::new(path),
749 _ => path,
750 }
751}
752
753fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
759where
760 I: Iterator<Item = &'a PathBuf>,
761{
762 let mut search_path = vec![];
763 for dir in paths {
764 let dir = get_dynamic_search_path(dir);
765 if dir.starts_with(&root_output) {
766 search_path.push(dir.to_path_buf());
767 } else {
768 debug!(
769 "Not including path {} in runtime library search path because it is \
770 outside target root {}",
771 dir.display(),
772 root_output.display()
773 );
774 }
775 }
776 search_path
777}
778
779fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
786 let gctx = build_runner.bcx.gctx;
787 let is_primary = build_runner.is_primary_package(unit);
788 let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg);
789
790 let mut base = build_runner
791 .compilation
792 .rustc_process(unit, is_primary, is_workspace)?;
793 build_base_args(build_runner, &mut base, unit)?;
794 if unit.pkg.manifest().is_embedded() {
795 if !gctx.cli_unstable().script {
796 anyhow::bail!(
797 "parsing `{}` requires `-Zscript`",
798 unit.pkg.manifest_path().display()
799 );
800 }
801 base.arg("-Z").arg("crate-attr=feature(frontmatter)");
802 base.arg("-Z").arg("crate-attr=allow(unused_features)");
803 }
804
805 base.inherit_jobserver(&build_runner.jobserver);
806 build_deps_args(&mut base, build_runner, unit)?;
807 add_cap_lints(build_runner.bcx, unit, &mut base);
808 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
809 base.args(args);
810 }
811 base.args(&unit.rustflags);
812 if gctx.cli_unstable().binary_dep_depinfo {
813 base.arg("-Z").arg("binary-dep-depinfo");
814 }
815 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
816 base.arg("-Z").arg("checksum-hash-algorithm=blake3");
817 }
818
819 if is_primary {
820 base.env("CARGO_PRIMARY_PACKAGE", "1");
821 let file_list = build_runner.sbom_output_files(unit)?;
822 if !file_list.is_empty() {
823 let file_list = std::env::join_paths(file_list)?;
824 base.env("CARGO_SBOM_PATH", file_list);
825 }
826 }
827
828 if unit.target.is_test() || unit.target.is_bench() {
829 let tmp = build_runner
830 .files()
831 .layout(unit.kind)
832 .build_dir()
833 .prepare_tmp()?;
834 base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
835 }
836
837 if build_runner.bcx.gctx.cli_unstable().cargo_lints {
838 base.arg("-Wunused_crate_dependencies");
841 }
842
843 Ok(base)
844}
845
846fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
853 let bcx = build_runner.bcx;
854 let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
856 if unit.pkg.manifest().is_embedded() {
857 if !bcx.gctx.cli_unstable().script {
858 anyhow::bail!(
859 "parsing `{}` requires `-Zscript`",
860 unit.pkg.manifest_path().display()
861 );
862 }
863 rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
864 rustdoc.arg("-Z").arg("crate-attr=allow(unused_features)");
865 }
866 rustdoc.inherit_jobserver(&build_runner.jobserver);
867 let crate_name = unit.target.crate_name();
868 rustdoc.arg("--crate-name").arg(&crate_name);
869 add_path_args(bcx.ws, unit, &mut rustdoc);
870 add_cap_lints(bcx, unit, &mut rustdoc);
871
872 unit.kind.add_target_arg(&mut rustdoc);
873 let doc_dir = build_runner.files().output_dir(unit);
874 rustdoc.arg("-o").arg(&doc_dir);
875 rustdoc.args(&features_args(unit));
876 rustdoc.args(&check_cfg_args(unit));
877
878 add_error_format_and_color(build_runner, &mut rustdoc);
879 add_allow_features(build_runner, &mut rustdoc);
880
881 if build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo {
882 let mut arg = if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
885 OsString::from("--emit=html-non-static-files,dep-info=")
887 } else {
888 OsString::from("--emit=html-static-files,html-non-static-files,dep-info=")
890 };
891 arg.push(rustdoc_dep_info_loc(build_runner, unit));
892 rustdoc.arg(arg);
893
894 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
895 rustdoc.arg("-Z").arg("checksum-hash-algorithm=blake3");
896 }
897
898 rustdoc.arg("-Zunstable-options");
899 } else if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
900 rustdoc.arg("--emit=html-non-static-files");
902 rustdoc.arg("-Zunstable-options");
903 }
904
905 if build_runner.bcx.gctx.cli_unstable().rustdoc_mergeable_info {
906 rustdoc.arg("--merge=none");
908 let mut arg = OsString::from("--parts-out-dir=");
909 arg.push(build_runner.files().out_dir_new_layout(unit));
911 rustdoc.arg(arg);
912 }
913
914 if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
915 trim_paths_args_rustdoc(&mut rustdoc, build_runner, unit, trim_paths)?;
916 }
917
918 rustdoc.args(unit.pkg.manifest().lint_rustflags());
919
920 let metadata = build_runner.metadata_for_doc_units[unit];
921 rustdoc
922 .arg("-C")
923 .arg(format!("metadata={}", metadata.c_metadata()));
924
925 if unit.mode.is_doc_scrape() {
926 debug_assert!(build_runner.bcx.scrape_units.contains(unit));
927
928 if unit.target.is_test() {
929 rustdoc.arg("--scrape-tests");
930 }
931
932 rustdoc.arg("-Zunstable-options");
933
934 rustdoc
935 .arg("--scrape-examples-output-path")
936 .arg(scrape_output_path(build_runner, unit)?);
937
938 for pkg in build_runner.bcx.packages.packages() {
940 let names = pkg
941 .targets()
942 .iter()
943 .map(|target| target.crate_name())
944 .collect::<HashSet<_>>();
945 for name in names {
946 rustdoc.arg("--scrape-examples-target-crate").arg(name);
947 }
948 }
949 }
950
951 if should_include_scrape_units(build_runner.bcx, unit) {
952 rustdoc.arg("-Zunstable-options");
953 }
954
955 build_deps_args(&mut rustdoc, build_runner, unit)?;
956 rustdoc::add_root_urls(build_runner, unit, &mut rustdoc)?;
957
958 rustdoc::add_output_format(build_runner, &mut rustdoc)?;
959
960 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
961 rustdoc.args(args);
962 }
963 rustdoc.args(&unit.rustdocflags);
964
965 if !crate_version_flag_already_present(&rustdoc) {
966 append_crate_version_flag(unit, &mut rustdoc);
967 }
968
969 Ok(rustdoc)
970}
971
972fn rustdoc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Work> {
974 let mut rustdoc = prepare_rustdoc(build_runner, unit)?;
975
976 let crate_name = unit.target.crate_name();
977 let doc_dir = build_runner.files().output_dir(unit);
978 paths::create_dir_all(&doc_dir)?;
982
983 let target_desc = unit.target.description_named();
984 let name = unit.pkg.name();
985 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
986 let package_id = unit.pkg.package_id();
987 let target = Target::clone(&unit.target);
988 let manifest = ManifestErrorContext::new(build_runner, unit);
989
990 let rustdoc_dep_info_loc = rustdoc_dep_info_loc(build_runner, unit);
991 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
992 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
993 let pkg_root = unit.pkg.root().to_path_buf();
994 let cwd = rustdoc
995 .get_cwd()
996 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
997 .to_path_buf();
998 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
999 let is_local = unit.is_local();
1000 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
1001 let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
1002
1003 let mut output_options = OutputOptions::for_dirty(build_runner, unit);
1004 let script_metadatas = build_runner.find_build_script_metadatas(unit);
1005 let scrape_outputs = if should_include_scrape_units(build_runner.bcx, unit) {
1006 Some(
1007 build_runner
1008 .bcx
1009 .scrape_units
1010 .iter()
1011 .map(|unit| {
1012 Ok((
1013 build_runner.files().metadata(unit).unit_id(),
1014 scrape_output_path(build_runner, unit)?,
1015 ))
1016 })
1017 .collect::<CargoResult<HashMap<_, _>>>()?,
1018 )
1019 } else {
1020 None
1021 };
1022
1023 let failed_scrape_units = Arc::clone(&build_runner.failed_scrape_units);
1024 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
1025 && !matches!(
1026 build_runner.bcx.gctx.shell().verbosity(),
1027 Verbosity::Verbose
1028 );
1029 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
1030 make_failed_scrape_diagnostic(
1031 build_runner,
1032 unit,
1033 format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
1034 )
1035 });
1036 if hide_diagnostics_for_scrape_unit {
1037 output_options.show_diagnostics = false;
1038 }
1039
1040 Ok(Work::new(move |state| {
1041 add_custom_flags(
1042 &mut rustdoc,
1043 &build_script_outputs.lock().unwrap(),
1044 script_metadatas,
1045 )?;
1046
1047 if let Some(scrape_outputs) = scrape_outputs {
1052 let failed_scrape_units = failed_scrape_units.lock().unwrap();
1053 for (metadata, output_path) in &scrape_outputs {
1054 if !failed_scrape_units.contains(metadata) {
1055 rustdoc.arg("--with-examples").arg(output_path);
1056 }
1057 }
1058 }
1059
1060 let crate_dir = doc_dir.join(&crate_name);
1061 if crate_dir.exists() {
1062 debug!("removing pre-existing doc directory {:?}", crate_dir);
1065 paths::remove_dir_all(crate_dir)?;
1066 }
1067 state.running(&rustdoc);
1068 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
1069
1070 let result = rustdoc
1071 .exec_with_streaming(
1072 &mut |line| on_stdout_line(state, line, package_id, &target),
1073 &mut |line| {
1074 on_stderr_line(
1075 state,
1076 line,
1077 package_id,
1078 &manifest,
1079 &target,
1080 &mut output_options,
1081 )
1082 },
1083 false,
1084 )
1085 .map_err(verbose_if_simple_exit_code)
1086 .with_context(|| format!("could not document `{}`", name));
1087
1088 if let Err(e) = result {
1089 if let Some(diagnostic) = failed_scrape_diagnostic {
1090 state.warning(diagnostic);
1091 }
1092
1093 return Err(e);
1094 }
1095
1096 if rustdoc_depinfo_enabled && rustdoc_dep_info_loc.exists() {
1097 fingerprint::translate_dep_info(
1098 &rustdoc_dep_info_loc,
1099 &dep_info_loc,
1100 &cwd,
1101 &pkg_root,
1102 &build_dir,
1103 &rustdoc,
1104 is_local,
1106 &env_config,
1107 )
1108 .with_context(|| {
1109 internal(format_args!(
1110 "could not parse/generate dep info at: {}",
1111 rustdoc_dep_info_loc.display()
1112 ))
1113 })?;
1114 paths::set_file_time_no_err(dep_info_loc, timestamp);
1117 }
1118
1119 Ok(())
1120 }))
1121}
1122
1123fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
1126 rustdoc.get_args().any(|flag| {
1127 flag.to_str()
1128 .map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
1129 })
1130}
1131
1132fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
1133 rustdoc
1134 .arg(RUSTDOC_CRATE_VERSION_FLAG)
1135 .arg(unit.pkg.version().to_string());
1136}
1137
1138fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
1142 if !unit.show_warnings(bcx.gctx) {
1145 cmd.arg("--cap-lints").arg("allow");
1146
1147 } else if !unit.is_local() {
1150 cmd.arg("--cap-lints").arg("warn");
1151 }
1152}
1153
1154fn add_allow_features(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1158 if let Some(allow) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1159 use std::fmt::Write;
1160 let mut arg = String::from("-Zallow-features=");
1161 for f in allow {
1162 let _ = write!(&mut arg, "{f},");
1163 }
1164 cmd.arg(arg.trim_end_matches(','));
1165 }
1166}
1167
1168fn add_error_format_and_color(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1179 let enable_timings =
1180 build_runner.bcx.gctx.cli_unstable().section_timings && build_runner.bcx.logger.is_some();
1181 if enable_timings {
1182 cmd.arg("-Zunstable-options");
1183 }
1184
1185 cmd.arg("--error-format=json");
1186
1187 let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
1188 if build_runner.bcx.gctx.cli_unstable().cargo_lints {
1189 json.push_str(",unused-externs-silent");
1190 }
1191 if let MessageFormat::Short | MessageFormat::Json { short: true, .. } =
1192 build_runner.bcx.build_config.message_format
1193 {
1194 json.push_str(",diagnostic-short");
1195 } else if build_runner.bcx.gctx.shell().err_unicode()
1196 && build_runner.bcx.gctx.cli_unstable().rustc_unicode
1197 {
1198 json.push_str(",diagnostic-unicode");
1199 }
1200 if enable_timings {
1201 json.push_str(",timings");
1202 }
1203 cmd.arg(json);
1204
1205 let gctx = build_runner.bcx.gctx;
1206 if let Some(width) = gctx.shell().err_width().diagnostic_terminal_width() {
1207 cmd.arg(format!("--diagnostic-width={width}"));
1208 }
1209}
1210
1211fn build_base_args(
1213 build_runner: &BuildRunner<'_, '_>,
1214 cmd: &mut ProcessBuilder,
1215 unit: &Unit,
1216) -> CargoResult<()> {
1217 assert!(!unit.mode.is_run_custom_build());
1218
1219 let bcx = build_runner.bcx;
1220 let Profile {
1221 ref opt_level,
1222 codegen_backend,
1223 codegen_units,
1224 debuginfo,
1225 debug_assertions,
1226 split_debuginfo,
1227 overflow_checks,
1228 rpath,
1229 ref panic,
1230 incremental,
1231 strip,
1232 rustflags: profile_rustflags,
1233 trim_paths,
1234 hint_mostly_unused: profile_hint_mostly_unused,
1235 frame_pointers,
1236 ..
1237 } = unit.profile.clone();
1238 let hints = unit.pkg.hints().cloned().unwrap_or_default();
1239 let test = unit.mode.is_any_test();
1240
1241 let warn = |msg: &str| {
1242 bcx.gctx.shell().warn(format!(
1243 "{}@{}: {msg}",
1244 unit.pkg.package_id().name(),
1245 unit.pkg.package_id().version()
1246 ))
1247 };
1248 let unit_capped_warn = |msg: &str| {
1249 if unit.show_warnings(bcx.gctx) {
1250 warn(msg)
1251 } else {
1252 Ok(())
1253 }
1254 };
1255
1256 cmd.arg("--crate-name").arg(&unit.target.crate_name());
1257
1258 let edition = unit.target.edition();
1259 edition.cmd_edition_arg(cmd);
1260
1261 add_path_args(bcx.ws, unit, cmd);
1262 add_error_format_and_color(build_runner, cmd);
1263 add_allow_features(build_runner, cmd);
1264
1265 let mut contains_dy_lib = false;
1266 if !test {
1267 for crate_type in &unit.target.rustc_crate_types() {
1268 cmd.arg("--crate-type").arg(crate_type.as_str());
1269 contains_dy_lib |= crate_type == &CrateType::Dylib;
1270 }
1271 }
1272
1273 if unit.mode.is_check() {
1274 cmd.arg("--emit=dep-info,metadata");
1275 } else if build_runner.bcx.gctx.cli_unstable().no_embed_metadata {
1276 if unit.benefits_from_no_embed_metadata() {
1286 cmd.arg("--emit=dep-info,metadata,link");
1287 cmd.args(&["-Z", "embed-metadata=no"]);
1288 } else {
1289 cmd.arg("--emit=dep-info,link");
1290 }
1291 } else {
1292 if !unit.requires_upstream_objects() {
1296 cmd.arg("--emit=dep-info,metadata,link");
1297 } else {
1298 cmd.arg("--emit=dep-info,link");
1299 }
1300 }
1301
1302 let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
1303 || (contains_dy_lib && !build_runner.is_primary_package(unit));
1304 if prefer_dynamic {
1305 cmd.arg("-C").arg("prefer-dynamic");
1306 }
1307
1308 if opt_level.as_str() != "0" {
1309 cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
1310 }
1311
1312 if *panic != PanicStrategy::Unwind {
1313 cmd.arg("-C").arg(format!("panic={}", panic));
1314 }
1315 if *panic == PanicStrategy::ImmediateAbort {
1316 cmd.arg("-Z").arg("unstable-options");
1317 }
1318
1319 cmd.args(<o_args(build_runner, unit));
1320
1321 if let Some(backend) = codegen_backend {
1322 cmd.arg("-Z").arg(&format!("codegen-backend={}", backend));
1323 }
1324
1325 if let Some(n) = codegen_units {
1326 cmd.arg("-C").arg(&format!("codegen-units={}", n));
1327 }
1328
1329 let debuginfo = debuginfo.into_inner();
1330 if debuginfo != TomlDebugInfo::None {
1332 cmd.arg("-C").arg(format!("debuginfo={debuginfo}"));
1333 if let Some(split) = split_debuginfo {
1340 if build_runner
1341 .bcx
1342 .target_data
1343 .info(unit.kind)
1344 .supports_debuginfo_split(split)
1345 {
1346 cmd.arg("-C").arg(format!("split-debuginfo={split}"));
1347 }
1348 }
1349 }
1350
1351 if let Some(trim_paths) = trim_paths {
1352 trim_paths_args(cmd, build_runner, unit, &trim_paths)?;
1353 }
1354
1355 cmd.args(unit.pkg.manifest().lint_rustflags());
1356 cmd.args(&profile_rustflags);
1357
1358 if opt_level.as_str() != "0" {
1362 if debug_assertions {
1363 cmd.args(&["-C", "debug-assertions=on"]);
1364 if !overflow_checks {
1365 cmd.args(&["-C", "overflow-checks=off"]);
1366 }
1367 } else if overflow_checks {
1368 cmd.args(&["-C", "overflow-checks=on"]);
1369 }
1370 } else if !debug_assertions {
1371 cmd.args(&["-C", "debug-assertions=off"]);
1372 if overflow_checks {
1373 cmd.args(&["-C", "overflow-checks=on"]);
1374 }
1375 } else if !overflow_checks {
1376 cmd.args(&["-C", "overflow-checks=off"]);
1377 }
1378
1379 if test && unit.target.harness() {
1380 cmd.arg("--test");
1381
1382 if *panic == PanicStrategy::Abort || *panic == PanicStrategy::ImmediateAbort {
1390 cmd.arg("-Z").arg("panic-abort-tests");
1391 }
1392 } else if test {
1393 cmd.arg("--cfg").arg("test");
1394 }
1395
1396 cmd.args(&features_args(unit));
1397 cmd.args(&check_cfg_args(unit));
1398
1399 let meta = build_runner.files().metadata(unit);
1400 cmd.arg("-C")
1401 .arg(&format!("metadata={}", meta.c_metadata()));
1402 if let Some(c_extra_filename) = meta.c_extra_filename() {
1403 cmd.arg("-C")
1404 .arg(&format!("extra-filename=-{c_extra_filename}"));
1405 }
1406
1407 if rpath {
1408 cmd.arg("-C").arg("rpath");
1409 }
1410
1411 cmd.arg("--out-dir")
1412 .arg(&build_runner.files().output_dir(unit));
1413
1414 unit.kind.add_target_arg(cmd);
1415
1416 add_codegen_linker(cmd, build_runner, unit, bcx.gctx.target_applies_to_host()?);
1417
1418 if incremental {
1419 add_codegen_incremental(cmd, build_runner, unit)
1420 }
1421
1422 let pkg_hint_mostly_unused = match hints.mostly_unused {
1423 None => None,
1424 Some(toml::Value::Boolean(b)) => Some(b),
1425 Some(v) => {
1426 unit_capped_warn(&format!(
1427 "ignoring unsupported value type ({}) for 'hints.mostly-unused', which expects a boolean",
1428 v.type_str()
1429 ))?;
1430 None
1431 }
1432 };
1433 if profile_hint_mostly_unused
1434 .or(pkg_hint_mostly_unused)
1435 .unwrap_or(false)
1436 {
1437 if bcx.gctx.cli_unstable().profile_hint_mostly_unused {
1438 cmd.arg("-Zhint-mostly-unused");
1439 } else {
1440 if profile_hint_mostly_unused.is_some() {
1441 warn(
1443 "ignoring 'hint-mostly-unused' profile option, pass `-Zprofile-hint-mostly-unused` to enable it",
1444 )?;
1445 } else if pkg_hint_mostly_unused.is_some() {
1446 unit_capped_warn(
1447 "ignoring 'hints.mostly-unused', pass `-Zprofile-hint-mostly-unused` to enable it",
1448 )?;
1449 }
1450 }
1451 }
1452
1453 let strip = strip.into_inner();
1454 if strip != StripInner::None {
1455 cmd.arg("-C").arg(format!("strip={}", strip));
1456 }
1457
1458 if let Some(frame_pointers) = frame_pointers {
1459 let val = match frame_pointers {
1460 FramePointers::ForceOn => "on",
1461 FramePointers::ForceOff => "off",
1462 };
1463 cmd.arg("-C").arg(format!("force-frame-pointers={}", val));
1464 }
1465
1466 if unit.is_std {
1467 cmd.arg("-Z")
1473 .arg("force-unstable-if-unmarked")
1474 .env("RUSTC_BOOTSTRAP", "1");
1475 }
1476
1477 Ok(())
1478}
1479
1480fn features_args(unit: &Unit) -> Vec<OsString> {
1482 let mut args = Vec::with_capacity(unit.features.len() * 2);
1483
1484 for feat in &unit.features {
1485 args.push(OsString::from("--cfg"));
1486 args.push(OsString::from(format!("feature=\"{}\"", feat)));
1487 }
1488
1489 args
1490}
1491
1492fn trim_paths_args_rustdoc(
1494 cmd: &mut ProcessBuilder,
1495 build_runner: &BuildRunner<'_, '_>,
1496 unit: &Unit,
1497 trim_paths: &TomlTrimPaths,
1498) -> CargoResult<()> {
1499 match trim_paths {
1500 TomlTrimPaths::Values(values) if !values.contains(&TomlTrimPathsValue::Diagnostics) => {
1502 return Ok(());
1503 }
1504 _ => {}
1505 }
1506
1507 cmd.arg("-Zunstable-options");
1509
1510 cmd.arg(package_remap(build_runner, unit));
1513 cmd.arg(build_dir_remap(build_runner));
1514 cmd.arg(sysroot_remap(build_runner, unit));
1515
1516 Ok(())
1517}
1518
1519fn trim_paths_args(
1525 cmd: &mut ProcessBuilder,
1526 build_runner: &BuildRunner<'_, '_>,
1527 unit: &Unit,
1528 trim_paths: &TomlTrimPaths,
1529) -> CargoResult<()> {
1530 if trim_paths.is_none() {
1531 return Ok(());
1532 }
1533
1534 cmd.arg(format!("--remap-path-scope={trim_paths}"));
1536
1537 cmd.arg(package_remap(build_runner, unit));
1540 cmd.arg(build_dir_remap(build_runner));
1541 cmd.arg(sysroot_remap(build_runner, unit));
1542
1543 Ok(())
1544}
1545
1546fn sysroot_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1551 let mut remap = OsString::from("--remap-path-prefix=");
1552 remap.push({
1553 let mut sysroot = build_runner.bcx.target_data.info(unit.kind).sysroot.clone();
1555 sysroot.push("lib");
1556 sysroot.push("rustlib");
1557 sysroot.push("src");
1558 sysroot.push("rust");
1559 sysroot
1560 });
1561 remap.push("=");
1562 remap.push("/rustc/");
1563 if let Some(commit_hash) = build_runner.bcx.rustc().commit_hash.as_ref() {
1564 remap.push(commit_hash);
1565 } else {
1566 remap.push(build_runner.bcx.rustc().version.to_string());
1567 }
1568 remap
1569}
1570
1571fn package_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1579 let pkg_root = unit.pkg.root();
1580 let ws_root = build_runner.bcx.ws.root();
1581 let mut remap = OsString::from("--remap-path-prefix=");
1582 let source_id = unit.pkg.package_id().source_id();
1583 if source_id.is_git() {
1584 remap.push(
1585 build_runner
1586 .bcx
1587 .gctx
1588 .git_checkouts_path()
1589 .as_path_unlocked(),
1590 );
1591 remap.push("=");
1592 } else if source_id.is_registry() {
1593 remap.push(
1594 build_runner
1595 .bcx
1596 .gctx
1597 .registry_source_path()
1598 .as_path_unlocked(),
1599 );
1600 remap.push("=");
1601 } else if pkg_root.strip_prefix(ws_root).is_ok() {
1602 remap.push(ws_root);
1603 remap.push("=."); } else {
1605 remap.push(pkg_root);
1606 remap.push("=");
1607 remap.push(unit.pkg.name());
1608 remap.push("-");
1609 remap.push(unit.pkg.version().to_string());
1610 }
1611 remap
1612}
1613
1614fn build_dir_remap(build_runner: &BuildRunner<'_, '_>) -> OsString {
1627 let build_dir = build_runner.bcx.ws.build_dir();
1628 let mut remap = OsString::from("--remap-path-prefix=");
1629 remap.push(build_dir.as_path_unlocked());
1630 remap.push("=/cargo/build-dir");
1631 remap
1632}
1633
1634fn check_cfg_args(unit: &Unit) -> Vec<OsString> {
1636 let gross_cap_estimation = unit.pkg.summary().features().len() * 7 + 25;
1654 let mut arg_feature = OsString::with_capacity(gross_cap_estimation);
1655
1656 arg_feature.push("cfg(feature, values(");
1657 for (i, feature) in unit.pkg.summary().features().keys().enumerate() {
1658 if i != 0 {
1659 arg_feature.push(", ");
1660 }
1661 arg_feature.push("\"");
1662 arg_feature.push(feature);
1663 arg_feature.push("\"");
1664 }
1665 arg_feature.push("))");
1666
1667 vec![
1676 OsString::from("--check-cfg"),
1677 OsString::from("cfg(docsrs,test)"),
1678 OsString::from("--check-cfg"),
1679 arg_feature,
1680 ]
1681}
1682
1683fn lto_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1685 let mut result = Vec::new();
1686 let mut push = |arg: &str| {
1687 result.push(OsString::from("-C"));
1688 result.push(OsString::from(arg));
1689 };
1690 match build_runner.lto[unit] {
1691 lto::Lto::Run(None) => push("lto"),
1692 lto::Lto::Run(Some(s)) => push(&format!("lto={}", s)),
1693 lto::Lto::Off => {
1694 push("lto=off");
1695 push("embed-bitcode=no");
1696 }
1697 lto::Lto::ObjectAndBitcode => {} lto::Lto::OnlyBitcode => push("linker-plugin-lto"),
1699 lto::Lto::OnlyObject => push("embed-bitcode=no"),
1700 }
1701 result
1702}
1703
1704fn build_deps_args(
1710 cmd: &mut ProcessBuilder,
1711 build_runner: &BuildRunner<'_, '_>,
1712 unit: &Unit,
1713) -> CargoResult<()> {
1714 let bcx = build_runner.bcx;
1715
1716 for arg in lib_search_paths(build_runner, unit)? {
1717 cmd.arg(arg);
1718 }
1719
1720 let deps = build_runner.unit_deps(unit);
1721
1722 if !deps
1726 .iter()
1727 .any(|dep| !dep.unit.mode.is_doc() && dep.unit.target.is_linkable())
1728 {
1729 if let Some(dep) = deps.iter().find(|dep| {
1730 !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true()
1731 }) {
1732 let dep_name = dep.unit.target.crate_name();
1733 let name = unit.target.crate_name();
1734 bcx.gctx.shell().print_report(&[
1735 Level::WARNING.secondary_title(format!("the package `{dep_name}` provides no linkable target"))
1736 .elements([
1737 Level::NOTE.message(format!("this might cause `{name}` to fail compilation")),
1738 Level::NOTE.message("this warning might turn into a hard error in the future"),
1739 Level::HELP.message(format!("consider adding 'dylib' or 'rlib' to key 'crate-type' in `{dep_name}`'s Cargo.toml"))
1740 ])
1741 ], false)?;
1742 }
1743 }
1744
1745 let mut unstable_opts = false;
1746
1747 let first_custom_build_dep = deps.iter().find(|dep| dep.unit.mode.is_run_custom_build());
1749 if let Some(dep) = first_custom_build_dep {
1750 let out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
1751 build_runner.files().out_dir_new_layout(&dep.unit)
1752 } else {
1753 build_runner.files().build_script_out_dir(&dep.unit)
1754 };
1755 cmd.env("OUT_DIR", &out_dir);
1756 }
1757
1758 let is_multiple_build_scripts_enabled = unit
1760 .pkg
1761 .manifest()
1762 .unstable_features()
1763 .require(Feature::multiple_build_scripts())
1764 .is_ok();
1765
1766 if is_multiple_build_scripts_enabled {
1767 for dep in deps {
1768 if dep.unit.mode.is_run_custom_build() {
1769 let out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
1770 build_runner.files().out_dir_new_layout(&dep.unit)
1771 } else {
1772 build_runner.files().build_script_out_dir(&dep.unit)
1773 };
1774 let target_name = dep.unit.target.name();
1775 let out_dir_prefix = target_name
1776 .strip_prefix("build-script-")
1777 .unwrap_or(target_name);
1778 let out_dir_name = format!("{out_dir_prefix}_OUT_DIR");
1779 cmd.env(&out_dir_name, &out_dir);
1780 }
1781 }
1782 }
1783 for arg in extern_args(build_runner, unit, &mut unstable_opts)? {
1784 cmd.arg(arg);
1785 }
1786
1787 for (var, env) in artifact::get_env(build_runner, unit, deps)? {
1788 cmd.env(&var, env);
1789 }
1790
1791 if unstable_opts {
1794 cmd.arg("-Z").arg("unstable-options");
1795 }
1796
1797 Ok(())
1798}
1799
1800fn add_dep_arg<'a, 'b: 'a>(
1801 map: &mut BTreeMap<&'a Unit, PathBuf>,
1802 build_runner: &'b BuildRunner<'b, '_>,
1803 unit: &'a Unit,
1804) {
1805 if map.contains_key(&unit) {
1806 return;
1807 }
1808 map.insert(&unit, build_runner.files().deps_dir(&unit));
1809
1810 for dep in build_runner.unit_deps(unit) {
1811 add_dep_arg(map, build_runner, &dep.unit);
1812 }
1813}
1814
1815fn add_custom_flags(
1819 cmd: &mut ProcessBuilder,
1820 build_script_outputs: &BuildScriptOutputs,
1821 metadata_vec: Option<Vec<UnitHash>>,
1822) -> CargoResult<()> {
1823 if let Some(metadata_vec) = metadata_vec {
1824 for metadata in metadata_vec {
1825 if let Some(output) = build_script_outputs.get(metadata) {
1826 for cfg in output.cfgs.iter() {
1827 cmd.arg("--cfg").arg(cfg);
1828 }
1829 for check_cfg in &output.check_cfgs {
1830 cmd.arg("--check-cfg").arg(check_cfg);
1831 }
1832 for (name, value) in output.env.iter() {
1833 cmd.env(name, value);
1834 }
1835 }
1836 }
1837 }
1838
1839 Ok(())
1840}
1841
1842pub fn lib_search_paths(
1844 build_runner: &BuildRunner<'_, '_>,
1845 unit: &Unit,
1846) -> CargoResult<Vec<OsString>> {
1847 let mut lib_search_paths = Vec::new();
1848 if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1849 let mut map = BTreeMap::new();
1850
1851 add_dep_arg(&mut map, build_runner, unit);
1853
1854 let paths = map.into_iter().map(|(_, path)| path).sorted_unstable();
1855
1856 for path in paths {
1857 let mut deps = OsString::from("dependency=");
1858 deps.push(path);
1859 lib_search_paths.extend(["-L".into(), deps]);
1860 }
1861 } else {
1862 let mut deps = OsString::from("dependency=");
1863 deps.push(build_runner.files().deps_dir(unit));
1864 lib_search_paths.extend(["-L".into(), deps]);
1865 }
1866
1867 if !unit.kind.is_host() {
1870 let mut deps = OsString::from("dependency=");
1871 deps.push(build_runner.files().host_deps(unit));
1872 lib_search_paths.extend(["-L".into(), deps]);
1873 }
1874
1875 Ok(lib_search_paths)
1876}
1877
1878pub fn extern_args(
1880 build_runner: &BuildRunner<'_, '_>,
1881 unit: &Unit,
1882 unstable_opts: &mut bool,
1883) -> CargoResult<Vec<OsString>> {
1884 let mut result = Vec::new();
1885 let deps = build_runner.unit_deps(unit);
1886
1887 let no_embed_metadata = build_runner.bcx.gctx.cli_unstable().no_embed_metadata;
1888
1889 let mut link_to = |dep: &UnitDep,
1891 extern_crate_name: InternedString,
1892 noprelude: bool,
1893 nounused: bool|
1894 -> CargoResult<()> {
1895 let mut value = OsString::new();
1896 let mut opts = Vec::new();
1897 let is_public_dependency_enabled = unit
1898 .pkg
1899 .manifest()
1900 .unstable_features()
1901 .require(Feature::public_dependency())
1902 .is_ok()
1903 || build_runner.bcx.gctx.cli_unstable().public_dependency;
1904 if !dep.public && unit.target.is_lib() && is_public_dependency_enabled {
1905 opts.push("priv");
1906 *unstable_opts = true;
1907 }
1908 if noprelude {
1909 opts.push("noprelude");
1910 *unstable_opts = true;
1911 }
1912 if nounused {
1913 opts.push("nounused");
1914 *unstable_opts = true;
1915 }
1916 if !opts.is_empty() {
1917 value.push(opts.join(","));
1918 value.push(":");
1919 }
1920 value.push(extern_crate_name.as_str());
1921 value.push("=");
1922
1923 let mut pass = |file| {
1924 let mut value = value.clone();
1925 value.push(file);
1926 result.push(OsString::from("--extern"));
1927 result.push(value);
1928 };
1929
1930 let outputs = build_runner.outputs(&dep.unit)?;
1931
1932 if build_runner.only_requires_rmeta(unit, &dep.unit) || dep.unit.mode.is_check() {
1933 let output = outputs
1935 .iter()
1936 .find(|output| output.flavor == FileFlavor::Rmeta)
1937 .expect("failed to find rmeta dep for pipelined dep");
1938 pass(&output.path);
1939 } else {
1940 for output in outputs.iter() {
1942 if output.flavor == FileFlavor::Linkable {
1943 pass(&output.path);
1944 }
1945 else if no_embed_metadata && output.flavor == FileFlavor::Rmeta {
1949 pass(&output.path);
1950 }
1951 }
1952 }
1953 Ok(())
1954 };
1955
1956 for dep in deps {
1957 if dep.unit.target.is_linkable() && !dep.unit.mode.is_doc() {
1958 link_to(dep, dep.extern_crate_name, dep.noprelude, dep.nounused)?;
1959 }
1960 }
1961 if unit.target.proc_macro() {
1962 result.push(OsString::from("--extern"));
1964 result.push(OsString::from("proc_macro"));
1965 }
1966
1967 Ok(result)
1968}
1969
1970fn add_codegen_linker(
1972 cmd: &mut ProcessBuilder,
1973 build_runner: &BuildRunner<'_, '_>,
1974 unit: &Unit,
1975 target_applies_to_host: bool,
1976) {
1977 let linker = if unit.target.for_host() && !target_applies_to_host {
1978 build_runner
1979 .compilation
1980 .host_linker()
1981 .map(|s| s.as_os_str())
1982 } else {
1983 build_runner
1984 .compilation
1985 .target_linker(unit.kind)
1986 .map(|s| s.as_os_str())
1987 };
1988
1989 if let Some(linker) = linker {
1990 let mut arg = OsString::from("linker=");
1991 arg.push(linker);
1992 cmd.arg("-C").arg(arg);
1993 }
1994}
1995
1996fn add_codegen_incremental(
1998 cmd: &mut ProcessBuilder,
1999 build_runner: &BuildRunner<'_, '_>,
2000 unit: &Unit,
2001) {
2002 let dir = build_runner.files().incremental_dir(&unit);
2003 let mut arg = OsString::from("incremental=");
2004 arg.push(dir.as_os_str());
2005 cmd.arg("-C").arg(arg);
2006}
2007
2008fn envify(s: &str) -> String {
2009 s.chars()
2010 .flat_map(|c| c.to_uppercase())
2011 .map(|c| if c == '-' { '_' } else { c })
2012 .collect()
2013}
2014
2015struct OutputOptions {
2018 format: MessageFormat,
2020 cache_cell: Option<(PathBuf, OnceCell<File>)>,
2025 show_diagnostics: bool,
2033 warnings_seen: usize,
2035 errors_seen: usize,
2037}
2038
2039impl OutputOptions {
2040 fn for_dirty(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2041 let path = build_runner.files().message_cache_path(unit);
2042 drop(fs::remove_file(&path));
2044 let cache_cell = Some((path, OnceCell::new()));
2045
2046 let show_diagnostics = true;
2047
2048 let format = build_runner.bcx.build_config.message_format;
2049
2050 OutputOptions {
2051 format,
2052 cache_cell,
2053 show_diagnostics,
2054 warnings_seen: 0,
2055 errors_seen: 0,
2056 }
2057 }
2058
2059 fn for_fresh(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
2060 let cache_cell = None;
2061
2062 let show_diagnostics = unit.show_warnings(build_runner.bcx.gctx);
2065
2066 let format = build_runner.bcx.build_config.message_format;
2067
2068 OutputOptions {
2069 format,
2070 cache_cell,
2071 show_diagnostics,
2072 warnings_seen: 0,
2073 errors_seen: 0,
2074 }
2075 }
2076}
2077
2078struct ManifestErrorContext {
2084 path: PathBuf,
2086 spans: Option<toml::Spanned<toml::de::DeTable<'static>>>,
2088 contents: Option<String>,
2090 rename_table: HashMap<InternedString, InternedString>,
2093 requested_kinds: Vec<CompileKind>,
2096 cfgs: Vec<Vec<Cfg>>,
2099 host_name: InternedString,
2100 cwd: PathBuf,
2102 term_width: usize,
2104}
2105
2106fn on_stdout_line(
2107 state: &JobState<'_, '_>,
2108 line: &str,
2109 _package_id: PackageId,
2110 _target: &Target,
2111) -> CargoResult<()> {
2112 state.stdout(line.to_string())?;
2113 Ok(())
2114}
2115
2116fn on_stderr_line(
2117 state: &JobState<'_, '_>,
2118 line: &str,
2119 package_id: PackageId,
2120 manifest: &ManifestErrorContext,
2121 target: &Target,
2122 options: &mut OutputOptions,
2123) -> CargoResult<()> {
2124 if on_stderr_line_inner(state, line, package_id, manifest, target, options)? {
2125 if let Some((path, cell)) = &mut options.cache_cell {
2127 let f = cell.try_borrow_mut_with(|| paths::create(path))?;
2129 debug_assert!(!line.contains('\n'));
2130 f.write_all(line.as_bytes())?;
2131 f.write_all(&[b'\n'])?;
2132 }
2133 }
2134 Ok(())
2135}
2136
2137fn on_stderr_line_inner(
2139 state: &JobState<'_, '_>,
2140 line: &str,
2141 package_id: PackageId,
2142 manifest: &ManifestErrorContext,
2143 target: &Target,
2144 options: &mut OutputOptions,
2145) -> CargoResult<bool> {
2146 if !line.starts_with('{') {
2152 state.stderr(line.to_string())?;
2153 return Ok(true);
2154 }
2155
2156 let mut compiler_message: Box<serde_json::value::RawValue> = match serde_json::from_str(line) {
2157 Ok(msg) => msg,
2158
2159 Err(e) => {
2163 debug!("failed to parse json: {:?}", e);
2164 state.stderr(line.to_string())?;
2165 return Ok(true);
2166 }
2167 };
2168
2169 let count_diagnostic = |level, options: &mut OutputOptions| {
2170 if level == "warning" {
2171 options.warnings_seen += 1;
2172 } else if level == "error" {
2173 options.errors_seen += 1;
2174 }
2175 };
2176
2177 if let Ok(report) = serde_json::from_str::<FutureIncompatReport>(compiler_message.get()) {
2178 for item in &report.future_incompat_report {
2179 count_diagnostic(&*item.diagnostic.level, options);
2180 }
2181 state.future_incompat_report(report.future_incompat_report);
2182 return Ok(true);
2183 }
2184
2185 let res = serde_json::from_str::<SectionTiming>(compiler_message.get());
2186 if let Ok(timing_record) = res {
2187 state.on_section_timing_emitted(timing_record);
2188 return Ok(false);
2189 }
2190
2191 let add_pub_in_priv_diagnostic = |diag: &mut String| -> bool {
2193 static PRIV_DEP_REGEX: LazyLock<Regex> =
2202 LazyLock::new(|| Regex::new("from private dependency '([A-Za-z0-9-_]+)'").unwrap());
2203 if let Some(crate_name) = PRIV_DEP_REGEX.captures(diag).and_then(|m| m.get(1))
2204 && let Some(ref contents) = manifest.contents
2205 && let Some(span) = manifest.find_crate_span(crate_name.as_str())
2206 {
2207 let rel_path = pathdiff::diff_paths(&manifest.path, &manifest.cwd)
2208 .unwrap_or_else(|| manifest.path.clone())
2209 .display()
2210 .to_string();
2211 let report = [Group::with_title(Level::NOTE.secondary_title(format!(
2212 "dependency `{}` declared here",
2213 crate_name.as_str()
2214 )))
2215 .element(
2216 Snippet::source(contents)
2217 .path(rel_path)
2218 .annotation(AnnotationKind::Context.span(span)),
2219 )];
2220
2221 let rendered = Renderer::styled()
2222 .term_width(manifest.term_width)
2223 .render(&report);
2224 diag.push_str(&rendered);
2225 diag.push('\n');
2226 return true;
2227 }
2228 false
2229 };
2230
2231 match options.format {
2234 MessageFormat::Human
2239 | MessageFormat::Short
2240 | MessageFormat::Json {
2241 render_diagnostics: true,
2242 ..
2243 } => {
2244 #[derive(serde::Deserialize)]
2245 struct CompilerMessage<'a> {
2246 rendered: String,
2250 #[serde(borrow)]
2251 message: Cow<'a, str>,
2252 #[serde(borrow)]
2253 level: Cow<'a, str>,
2254 children: Vec<PartialDiagnostic>,
2255 code: Option<DiagnosticCode>,
2256 }
2257
2258 #[derive(serde::Deserialize)]
2267 struct PartialDiagnostic {
2268 spans: Vec<PartialDiagnosticSpan>,
2269 }
2270
2271 #[derive(serde::Deserialize)]
2273 struct PartialDiagnosticSpan {
2274 suggestion_applicability: Option<Applicability>,
2275 }
2276
2277 #[derive(serde::Deserialize)]
2278 struct DiagnosticCode {
2279 code: String,
2280 }
2281
2282 if let Ok(mut msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2283 {
2284 if msg.message.starts_with("aborting due to")
2285 || msg.message.ends_with("warning emitted")
2286 || msg.message.ends_with("warnings emitted")
2287 {
2288 return Ok(true);
2290 }
2291 if msg.rendered.ends_with('\n') {
2293 msg.rendered.pop();
2294 }
2295 let mut rendered = msg.rendered;
2296 if options.show_diagnostics {
2297 let machine_applicable: bool = msg
2298 .children
2299 .iter()
2300 .map(|child| {
2301 child
2302 .spans
2303 .iter()
2304 .filter_map(|span| span.suggestion_applicability)
2305 .any(|app| app == Applicability::MachineApplicable)
2306 })
2307 .any(|b| b);
2308 count_diagnostic(&msg.level, options);
2309 if msg
2310 .code
2311 .as_ref()
2312 .is_some_and(|c| c.code == "exported_private_dependencies")
2313 && options.format != MessageFormat::Short
2314 {
2315 add_pub_in_priv_diagnostic(&mut rendered);
2316 }
2317 let lint = msg.code.is_some();
2318 state.emit_diag(&msg.level, rendered, lint, machine_applicable)?;
2319 }
2320 return Ok(true);
2321 }
2322 }
2323
2324 MessageFormat::Json { ansi, .. } => {
2325 #[derive(serde::Deserialize, serde::Serialize)]
2326 struct CompilerMessage<'a> {
2327 rendered: String,
2328 #[serde(flatten, borrow)]
2329 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2330 code: Option<DiagnosticCode<'a>>,
2331 }
2332
2333 #[derive(serde::Deserialize, serde::Serialize)]
2334 struct DiagnosticCode<'a> {
2335 code: String,
2336 #[serde(flatten, borrow)]
2337 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2338 }
2339
2340 if let Ok(mut error) =
2341 serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2342 {
2343 let modified_diag = if error
2344 .code
2345 .as_ref()
2346 .is_some_and(|c| c.code == "exported_private_dependencies")
2347 {
2348 add_pub_in_priv_diagnostic(&mut error.rendered)
2349 } else {
2350 false
2351 };
2352
2353 if !ansi {
2357 error.rendered = anstream::adapter::strip_str(&error.rendered).to_string();
2358 }
2359 if !ansi || modified_diag {
2360 let new_line = serde_json::to_string(&error)?;
2361 compiler_message = serde_json::value::RawValue::from_string(new_line)?;
2362 }
2363 }
2364 }
2365 }
2366
2367 #[derive(serde::Deserialize)]
2374 struct ArtifactNotification<'a> {
2375 #[serde(borrow)]
2376 artifact: Cow<'a, str>,
2377 }
2378
2379 if let Ok(artifact) = serde_json::from_str::<ArtifactNotification<'_>>(compiler_message.get()) {
2380 trace!("found directive from rustc: `{}`", artifact.artifact);
2381 if artifact.artifact.ends_with(".rmeta") {
2382 debug!("looks like metadata finished early!");
2383 state.rmeta_produced();
2384 }
2385 return Ok(false);
2386 }
2387
2388 #[derive(serde::Deserialize)]
2389 struct UnusedExterns {
2390 unused_extern_names: Vec<String>,
2391 }
2392 if let Ok(uext) = serde_json::from_str::<UnusedExterns>(compiler_message.get()) {
2393 trace!(
2394 "obtained unused externs list from rustc: `{:?}`",
2395 uext.unused_extern_names
2396 );
2397 state.unused_externs(uext.unused_extern_names);
2398 return Ok(true);
2399 }
2400
2401 if !options.show_diagnostics {
2406 return Ok(true);
2407 }
2408
2409 #[derive(serde::Deserialize)]
2410 struct CompilerMessage<'a> {
2411 #[serde(borrow)]
2412 message: Cow<'a, str>,
2413 #[serde(borrow)]
2414 level: Cow<'a, str>,
2415 }
2416
2417 if let Ok(msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get()) {
2418 if msg.message.starts_with("aborting due to")
2419 || msg.message.ends_with("warning emitted")
2420 || msg.message.ends_with("warnings emitted")
2421 {
2422 return Ok(true);
2424 }
2425 count_diagnostic(&msg.level, options);
2426 }
2427
2428 let msg = machine_message::FromCompiler {
2429 package_id: package_id.to_spec(),
2430 manifest_path: &manifest.path,
2431 target,
2432 message: compiler_message,
2433 }
2434 .to_json_string();
2435
2436 state.stdout(msg)?;
2440 Ok(true)
2441}
2442
2443impl ManifestErrorContext {
2444 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> ManifestErrorContext {
2445 let mut duplicates = HashSet::new();
2446 let mut rename_table = HashMap::new();
2447
2448 for dep in build_runner.unit_deps(unit) {
2449 let unrenamed_id = dep.unit.pkg.package_id().name();
2450 if duplicates.contains(&unrenamed_id) {
2451 continue;
2452 }
2453 match rename_table.entry(unrenamed_id) {
2454 std::collections::hash_map::Entry::Occupied(occ) => {
2455 occ.remove_entry();
2456 duplicates.insert(unrenamed_id);
2457 }
2458 std::collections::hash_map::Entry::Vacant(vac) => {
2459 vac.insert(dep.extern_crate_name);
2460 }
2461 }
2462 }
2463
2464 let bcx = build_runner.bcx;
2465 ManifestErrorContext {
2466 path: unit.pkg.manifest_path().to_owned(),
2467 spans: unit.pkg.manifest().document().cloned(),
2468 contents: unit.pkg.manifest().contents().map(String::from),
2469 requested_kinds: bcx.target_data.requested_kinds().to_owned(),
2470 host_name: bcx.rustc().host,
2471 rename_table,
2472 cwd: path_args(build_runner.bcx.ws, unit).1,
2473 cfgs: bcx
2474 .target_data
2475 .requested_kinds()
2476 .iter()
2477 .map(|k| bcx.target_data.cfg(*k).to_owned())
2478 .collect(),
2479 term_width: bcx
2480 .gctx
2481 .shell()
2482 .err_width()
2483 .diagnostic_terminal_width()
2484 .unwrap_or(cargo_util_terminal::report::renderer::DEFAULT_TERM_WIDTH),
2485 }
2486 }
2487
2488 fn requested_target_names(&self) -> impl Iterator<Item = &str> {
2489 self.requested_kinds.iter().map(|kind| match kind {
2490 CompileKind::Host => &self.host_name,
2491 CompileKind::Target(target) => target.short_name(),
2492 })
2493 }
2494
2495 fn find_crate_span(&self, unrenamed: &str) -> Option<Range<usize>> {
2509 let Some(ref spans) = self.spans else {
2510 return None;
2511 };
2512
2513 let orig_name = self.rename_table.get(unrenamed)?.as_str();
2514
2515 if let Some((k, v)) = get_key_value(&spans, &["dependencies", orig_name]) {
2516 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package")) {
2525 return Some(package.span());
2526 } else {
2527 return Some(k.span());
2528 }
2529 }
2530
2531 if let Some(target) = spans
2536 .as_ref()
2537 .get("target")
2538 .and_then(|t| t.as_ref().as_table())
2539 {
2540 for (platform, platform_table) in target.iter() {
2541 match platform.as_ref().parse::<Platform>() {
2542 Ok(Platform::Name(name)) => {
2543 if !self.requested_target_names().any(|n| n == name) {
2544 continue;
2545 }
2546 }
2547 Ok(Platform::Cfg(cfg_expr)) => {
2548 if !self.cfgs.iter().any(|cfgs| cfg_expr.matches(cfgs)) {
2549 continue;
2550 }
2551 }
2552 Err(_) => continue,
2553 }
2554
2555 let Some(platform_table) = platform_table.as_ref().as_table() else {
2556 continue;
2557 };
2558
2559 if let Some(deps) = platform_table
2560 .get("dependencies")
2561 .and_then(|d| d.as_ref().as_table())
2562 {
2563 if let Some((k, v)) = deps.get_key_value(orig_name) {
2564 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package"))
2565 {
2566 return Some(package.span());
2567 } else {
2568 return Some(k.span());
2569 }
2570 }
2571 }
2572 }
2573 }
2574 None
2575 }
2576}
2577
2578fn replay_output_cache(
2582 package_id: PackageId,
2583 manifest: ManifestErrorContext,
2584 target: &Target,
2585 path: PathBuf,
2586 mut output_options: OutputOptions,
2587) -> Work {
2588 let target = target.clone();
2589 Work::new(move |state| {
2590 if !path.exists() {
2591 return Ok(());
2593 }
2594 let file = paths::open(&path)?;
2598 let mut reader = std::io::BufReader::new(file);
2599 let mut line = String::new();
2600 loop {
2601 let length = reader.read_line(&mut line)?;
2602 if length == 0 {
2603 break;
2604 }
2605 let trimmed = line.trim_end_matches(&['\n', '\r'][..]);
2606 on_stderr_line(
2607 state,
2608 trimmed,
2609 package_id,
2610 &manifest,
2611 &target,
2612 &mut output_options,
2613 )?;
2614 line.clear();
2615 }
2616 Ok(())
2617 })
2618}
2619
2620fn descriptive_pkg_name(name: &str, target: &Target, mode: &CompileMode) -> String {
2623 let desc_name = target.description_named();
2624 let mode = if mode.is_rustc_test() && !(target.is_test() || target.is_bench()) {
2625 " test"
2626 } else if mode.is_doc_test() {
2627 " doctest"
2628 } else if mode.is_doc() {
2629 " doc"
2630 } else {
2631 ""
2632 };
2633 format!("`{name}` ({desc_name}{mode})")
2634}
2635
2636pub(crate) fn apply_env_config(
2638 gctx: &crate::GlobalContext,
2639 cmd: &mut ProcessBuilder,
2640) -> CargoResult<()> {
2641 for (key, value) in gctx.env_config()?.iter() {
2642 if cmd.get_envs().contains_key(key) {
2644 continue;
2645 }
2646 cmd.env(key, value);
2647 }
2648 Ok(())
2649}
2650
2651fn should_include_scrape_units(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
2653 unit.mode.is_doc() && bcx.scrape_units.len() > 0 && bcx.ws.unit_needs_doc_scrape(unit)
2654}
2655
2656fn scrape_output_path(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<PathBuf> {
2658 assert!(unit.mode.is_doc() || unit.mode.is_doc_scrape());
2659 build_runner
2660 .outputs(unit)
2661 .map(|outputs| outputs[0].path.clone())
2662}
2663
2664fn rustdoc_dep_info_loc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
2666 let mut loc = build_runner.files().fingerprint_file_path(unit, "");
2667 loc.set_extension("d");
2668 loc
2669}