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