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 lto;
45mod output_depinfo;
46mod output_sbom;
47pub mod rustdoc;
48pub mod standard_lib;
49mod timings;
50mod unit;
51pub mod unit_dependencies;
52pub mod unit_graph;
53
54use std::borrow::Cow;
55use std::cell::OnceCell;
56use std::collections::{BTreeMap, HashMap, HashSet};
57use std::env;
58use std::ffi::{OsStr, OsString};
59use std::fmt::Display;
60use std::fs::{self, File};
61use std::io::{BufRead, BufWriter, Write};
62use std::ops::Range;
63use std::path::{Path, PathBuf};
64use std::sync::{Arc, LazyLock};
65
66use annotate_snippets::{AnnotationKind, Group, Level, Renderer, Snippet};
67use anyhow::{Context as _, Error};
68use cargo_platform::{Cfg, Platform};
69use itertools::Itertools;
70use regex::Regex;
71use tracing::{debug, instrument, trace};
72
73pub use self::build_config::UserIntent;
74pub use self::build_config::{BuildConfig, CompileMode, MessageFormat, TimingOutput};
75pub use self::build_context::{
76 BuildContext, FileFlavor, FileType, RustDocFingerprint, RustcTargetData, TargetInfo,
77};
78pub use self::build_runner::{BuildRunner, Metadata, UnitHash};
79pub use self::compilation::{Compilation, Doctest, UnitOutput};
80pub use self::compile_kind::{CompileKind, CompileKindFallback, CompileTarget};
81pub use self::crate_type::CrateType;
82pub use self::custom_build::LinkArgTarget;
83pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts, LibraryPath};
84pub(crate) use self::fingerprint::DirtyReason;
85pub use self::job_queue::Freshness;
86use self::job_queue::{Job, JobQueue, JobState, Work};
87pub(crate) use self::layout::Layout;
88pub use self::lto::Lto;
89use self::output_depinfo::output_depinfo;
90use self::output_sbom::build_sbom;
91use self::unit_graph::UnitDep;
92use crate::core::compiler::future_incompat::FutureIncompatReport;
93use crate::core::compiler::timings::SectionTiming;
94pub use crate::core::compiler::unit::{Unit, UnitInterner};
95use crate::core::manifest::TargetSourcePath;
96use crate::core::profiles::{PanicStrategy, Profile, StripInner};
97use crate::core::{Feature, PackageId, Target, Verbosity};
98use crate::util::OnceExt;
99use crate::util::context::WarningHandling;
100use crate::util::errors::{CargoResult, VerboseError};
101use crate::util::interning::InternedString;
102use crate::util::lints::get_key_value;
103use crate::util::machine_message::{self, Message};
104use crate::util::{add_path_args, internal, path_args};
105use cargo_util::{ProcessBuilder, ProcessError, paths};
106use cargo_util_schemas::manifest::TomlDebugInfo;
107use cargo_util_schemas::manifest::TomlTrimPaths;
108use cargo_util_schemas::manifest::TomlTrimPathsValue;
109use rustfix::diagnostics::Applicability;
110pub(crate) use timings::CompilationSection;
111
112const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
113
114pub trait Executor: Send + Sync + 'static {
118 fn init(&self, _build_runner: &BuildRunner<'_, '_>, _unit: &Unit) {}
122
123 fn exec(
126 &self,
127 cmd: &ProcessBuilder,
128 id: PackageId,
129 target: &Target,
130 mode: CompileMode,
131 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
132 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
133 ) -> CargoResult<()>;
134
135 fn force_rebuild(&self, _unit: &Unit) -> bool {
138 false
139 }
140}
141
142#[derive(Copy, Clone)]
145pub struct DefaultExecutor;
146
147impl Executor for DefaultExecutor {
148 #[instrument(name = "rustc", skip_all, fields(package = id.name().as_str(), process = cmd.to_string()))]
149 fn exec(
150 &self,
151 cmd: &ProcessBuilder,
152 id: PackageId,
153 _target: &Target,
154 _mode: CompileMode,
155 on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
156 on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
157 ) -> CargoResult<()> {
158 cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
159 .map(drop)
160 }
161}
162
163#[tracing::instrument(skip(build_runner, jobs, exec))]
173fn compile<'gctx>(
174 build_runner: &mut BuildRunner<'_, 'gctx>,
175 jobs: &mut JobQueue<'gctx>,
176 unit: &Unit,
177 exec: &Arc<dyn Executor>,
178 force_rebuild: bool,
179) -> CargoResult<()> {
180 let bcx = build_runner.bcx;
181 if !build_runner.compiled.insert(unit.clone()) {
182 return Ok(());
183 }
184
185 if !unit.skip_non_compile_time_dep {
189 fingerprint::prepare_init(build_runner, unit)?;
192
193 let job = if unit.mode.is_run_custom_build() {
194 custom_build::prepare(build_runner, unit)?
195 } else if unit.mode.is_doc_test() {
196 Job::new_fresh()
198 } else {
199 let force = exec.force_rebuild(unit) || force_rebuild;
200 let mut job = fingerprint::prepare_target(build_runner, unit, force)?;
201 job.before(if job.freshness().is_dirty() {
202 let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
203 rustdoc(build_runner, unit)?
204 } else {
205 rustc(build_runner, unit, exec)?
206 };
207 work.then(link_targets(build_runner, unit, false)?)
208 } else {
209 let show_diagnostics = unit.show_warnings(bcx.gctx)
212 && build_runner.bcx.gctx.warning_handling()? != WarningHandling::Allow;
213 let manifest = ManifestErrorContext::new(build_runner, unit);
214 let work = replay_output_cache(
215 unit.pkg.package_id(),
216 manifest,
217 &unit.target,
218 build_runner.files().message_cache_path(unit),
219 build_runner.bcx.build_config.message_format,
220 show_diagnostics,
221 );
222 work.then(link_targets(build_runner, unit, true)?)
224 });
225
226 job
227 };
228 jobs.enqueue(build_runner, unit, job)?;
229 }
230
231 let deps = Vec::from(build_runner.unit_deps(unit)); for dep in deps {
234 compile(build_runner, jobs, &dep.unit, exec, false)?;
235 }
236
237 Ok(())
238}
239
240fn make_failed_scrape_diagnostic(
243 build_runner: &BuildRunner<'_, '_>,
244 unit: &Unit,
245 top_line: impl Display,
246) -> String {
247 let manifest_path = unit.pkg.manifest_path();
248 let relative_manifest_path = manifest_path
249 .strip_prefix(build_runner.bcx.ws.root())
250 .unwrap_or(&manifest_path);
251
252 format!(
253 "\
254{top_line}
255 Try running with `--verbose` to see the error message.
256 If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
257 relative_manifest_path.display()
258 )
259}
260
261fn rustc(
263 build_runner: &mut BuildRunner<'_, '_>,
264 unit: &Unit,
265 exec: &Arc<dyn Executor>,
266) -> CargoResult<Work> {
267 let mut rustc = prepare_rustc(build_runner, unit)?;
268
269 let name = unit.pkg.name();
270
271 let outputs = build_runner.outputs(unit)?;
272 let root = build_runner.files().out_dir(unit);
273
274 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
276 let current_id = unit.pkg.package_id();
277 let manifest = ManifestErrorContext::new(build_runner, unit);
278 let build_scripts = build_runner.build_scripts.get(unit).cloned();
279
280 let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
283
284 let dep_info_name =
285 if let Some(c_extra_filename) = build_runner.files().metadata(unit).c_extra_filename() {
286 format!("{}-{}.d", unit.target.crate_name(), c_extra_filename)
287 } else {
288 format!("{}.d", unit.target.crate_name())
289 };
290 let rustc_dep_info_loc = root.join(dep_info_name);
291 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
292
293 let mut output_options = OutputOptions::new(build_runner, unit);
294 let package_id = unit.pkg.package_id();
295 let target = Target::clone(&unit.target);
296 let mode = unit.mode;
297
298 exec.init(build_runner, unit);
299 let exec = exec.clone();
300
301 let root_output = build_runner.files().host_dest().map(|v| v.to_path_buf());
302 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
303 let pkg_root = unit.pkg.root().to_path_buf();
304 let cwd = rustc
305 .get_cwd()
306 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
307 .to_path_buf();
308 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
309 let script_metadatas = build_runner.find_build_script_metadatas(unit);
310 let is_local = unit.is_local();
311 let artifact = unit.artifact;
312 let sbom_files = build_runner.sbom_output_files(unit)?;
313 let sbom = build_sbom(build_runner, unit)?;
314
315 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
316 && !matches!(
317 build_runner.bcx.gctx.shell().verbosity(),
318 Verbosity::Verbose
319 );
320 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
321 let target_desc = unit.target.description_named();
324 let mut for_scrape_units = build_runner
325 .bcx
326 .scrape_units_have_dep_on(unit)
327 .into_iter()
328 .map(|unit| unit.target.description_named())
329 .collect::<Vec<_>>();
330 for_scrape_units.sort();
331 let for_scrape_units = for_scrape_units.join(", ");
332 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}"))
333 });
334 if hide_diagnostics_for_scrape_unit {
335 output_options.show_diagnostics = false;
336 }
337 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
338 return Ok(Work::new(move |state| {
339 if artifact.is_true() {
343 paths::create_dir_all(&root)?;
344 }
345
346 if let Some(build_scripts) = build_scripts {
354 let script_outputs = build_script_outputs.lock().unwrap();
355 add_native_deps(
356 &mut rustc,
357 &script_outputs,
358 &build_scripts,
359 pass_l_flag,
360 &target,
361 current_id,
362 mode,
363 )?;
364 if let Some(ref root_output) = root_output {
365 add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, root_output)?;
366 }
367 add_custom_flags(&mut rustc, &script_outputs, script_metadatas)?;
368 }
369
370 for output in outputs.iter() {
371 if output.path.extension() == Some(OsStr::new("rmeta")) {
375 let dst = root.join(&output.path).with_extension("rlib");
376 if dst.exists() {
377 paths::remove_file(&dst)?;
378 }
379 }
380
381 if output.hardlink.is_some() && output.path.exists() {
386 _ = paths::remove_file(&output.path).map_err(|e| {
387 tracing::debug!(
388 "failed to delete previous output file `{:?}`: {e:?}",
389 output.path
390 );
391 });
392 }
393 }
394
395 state.running(&rustc);
396 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
397 for file in sbom_files {
398 tracing::debug!("writing sbom to {}", file.display());
399 let outfile = BufWriter::new(paths::create(&file)?);
400 serde_json::to_writer(outfile, &sbom)?;
401 }
402
403 let result = exec
404 .exec(
405 &rustc,
406 package_id,
407 &target,
408 mode,
409 &mut |line| on_stdout_line(state, line, package_id, &target),
410 &mut |line| {
411 on_stderr_line(
412 state,
413 line,
414 package_id,
415 &manifest,
416 &target,
417 &mut output_options,
418 )
419 },
420 )
421 .map_err(|e| {
422 if output_options.errors_seen == 0 {
423 e
428 } else {
429 verbose_if_simple_exit_code(e)
430 }
431 })
432 .with_context(|| {
433 let warnings = match output_options.warnings_seen {
435 0 => String::new(),
436 1 => "; 1 warning emitted".to_string(),
437 count => format!("; {} warnings emitted", count),
438 };
439 let errors = match output_options.errors_seen {
440 0 => String::new(),
441 1 => " due to 1 previous error".to_string(),
442 count => format!(" due to {} previous errors", count),
443 };
444 let name = descriptive_pkg_name(&name, &target, &mode);
445 format!("could not compile {name}{errors}{warnings}")
446 });
447
448 if let Err(e) = result {
449 if let Some(diagnostic) = failed_scrape_diagnostic {
450 state.warning(diagnostic);
451 }
452
453 return Err(e);
454 }
455
456 debug_assert_eq!(output_options.errors_seen, 0);
458
459 if rustc_dep_info_loc.exists() {
460 fingerprint::translate_dep_info(
461 &rustc_dep_info_loc,
462 &dep_info_loc,
463 &cwd,
464 &pkg_root,
465 &build_dir,
466 &rustc,
467 is_local,
469 &env_config,
470 )
471 .with_context(|| {
472 internal(format!(
473 "could not parse/generate dep info at: {}",
474 rustc_dep_info_loc.display()
475 ))
476 })?;
477 paths::set_file_time_no_err(dep_info_loc, timestamp);
480 }
481
482 if mode.is_check() {
496 for output in outputs.iter() {
497 paths::set_file_time_no_err(&output.path, timestamp);
498 }
499 }
500
501 Ok(())
502 }));
503
504 fn add_native_deps(
507 rustc: &mut ProcessBuilder,
508 build_script_outputs: &BuildScriptOutputs,
509 build_scripts: &BuildScripts,
510 pass_l_flag: bool,
511 target: &Target,
512 current_id: PackageId,
513 mode: CompileMode,
514 ) -> CargoResult<()> {
515 let mut library_paths = vec![];
516
517 for key in build_scripts.to_link.iter() {
518 let output = build_script_outputs.get(key.1).ok_or_else(|| {
519 internal(format!(
520 "couldn't find build script output for {}/{}",
521 key.0, key.1
522 ))
523 })?;
524 library_paths.extend(output.library_paths.iter());
525 }
526
527 library_paths.sort_by_key(|p| match p {
533 LibraryPath::CargoArtifact(_) => 0,
534 LibraryPath::External(_) => 1,
535 });
536
537 for path in library_paths.iter() {
538 rustc.arg("-L").arg(path.as_ref());
539 }
540
541 for key in build_scripts.to_link.iter() {
542 let output = build_script_outputs.get(key.1).ok_or_else(|| {
543 internal(format!(
544 "couldn't find build script output for {}/{}",
545 key.0, key.1
546 ))
547 })?;
548
549 if key.0 == current_id {
550 if pass_l_flag {
551 for name in output.library_links.iter() {
552 rustc.arg("-l").arg(name);
553 }
554 }
555 }
556
557 for (lt, arg) in &output.linker_args {
558 if lt.applies_to(target, mode)
564 && (key.0 == current_id || *lt == LinkArgTarget::Cdylib)
565 {
566 rustc.arg("-C").arg(format!("link-arg={}", arg));
567 }
568 }
569 }
570 Ok(())
571 }
572}
573
574fn verbose_if_simple_exit_code(err: Error) -> Error {
575 match err
578 .downcast_ref::<ProcessError>()
579 .as_ref()
580 .and_then(|perr| perr.code)
581 {
582 Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
583 _ => err,
584 }
585}
586
587fn link_targets(
590 build_runner: &mut BuildRunner<'_, '_>,
591 unit: &Unit,
592 fresh: bool,
593) -> CargoResult<Work> {
594 let bcx = build_runner.bcx;
595 let outputs = build_runner.outputs(unit)?;
596 let export_dir = build_runner.files().export_dir();
597 let package_id = unit.pkg.package_id();
598 let manifest_path = PathBuf::from(unit.pkg.manifest_path());
599 let profile = unit.profile.clone();
600 let unit_mode = unit.mode;
601 let features = unit.features.iter().map(|s| s.to_string()).collect();
602 let json_messages = bcx.build_config.emit_json();
603 let executable = build_runner.get_executable(unit)?;
604 let mut target = Target::clone(&unit.target);
605 if let TargetSourcePath::Metabuild = target.src_path() {
606 let path = unit
608 .pkg
609 .manifest()
610 .metabuild_path(build_runner.bcx.ws.build_dir());
611 target.set_src_path(TargetSourcePath::Path(path));
612 }
613
614 Ok(Work::new(move |state| {
615 let mut destinations = vec![];
620 for output in outputs.iter() {
621 let src = &output.path;
622 if !src.exists() {
625 continue;
626 }
627 let Some(dst) = output.hardlink.as_ref() else {
628 destinations.push(src.clone());
629 continue;
630 };
631 destinations.push(dst.clone());
632 paths::link_or_copy(src, dst)?;
633 if let Some(ref path) = output.export_path {
634 let export_dir = export_dir.as_ref().unwrap();
635 paths::create_dir_all(export_dir)?;
636
637 paths::link_or_copy(src, path)?;
638 }
639 }
640
641 if json_messages {
642 let debuginfo = match profile.debuginfo.into_inner() {
643 TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
644 TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
645 TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
646 TomlDebugInfo::LineDirectivesOnly => {
647 machine_message::ArtifactDebuginfo::Named("line-directives-only")
648 }
649 TomlDebugInfo::LineTablesOnly => {
650 machine_message::ArtifactDebuginfo::Named("line-tables-only")
651 }
652 };
653 let art_profile = machine_message::ArtifactProfile {
654 opt_level: profile.opt_level.as_str(),
655 debuginfo: Some(debuginfo),
656 debug_assertions: profile.debug_assertions,
657 overflow_checks: profile.overflow_checks,
658 test: unit_mode.is_any_test(),
659 };
660
661 let msg = machine_message::Artifact {
662 package_id: package_id.to_spec(),
663 manifest_path,
664 target: &target,
665 profile: art_profile,
666 features,
667 filenames: destinations,
668 executable,
669 fresh,
670 }
671 .to_json_string();
672 state.stdout(msg)?;
673 }
674 Ok(())
675 }))
676}
677
678fn add_plugin_deps(
682 rustc: &mut ProcessBuilder,
683 build_script_outputs: &BuildScriptOutputs,
684 build_scripts: &BuildScripts,
685 root_output: &Path,
686) -> CargoResult<()> {
687 let var = paths::dylib_path_envvar();
688 let search_path = rustc.get_env(var).unwrap_or_default();
689 let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
690 for (pkg_id, metadata) in &build_scripts.plugins {
691 let output = build_script_outputs
692 .get(*metadata)
693 .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
694 search_path.append(&mut filter_dynamic_search_path(
695 output.library_paths.iter().map(AsRef::as_ref),
696 root_output,
697 ));
698 }
699 let search_path = paths::join_paths(&search_path, var)?;
700 rustc.env(var, &search_path);
701 Ok(())
702}
703
704fn get_dynamic_search_path(path: &Path) -> &Path {
705 match path.to_str().and_then(|s| s.split_once("=")) {
706 Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => Path::new(path),
707 _ => path,
708 }
709}
710
711fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
717where
718 I: Iterator<Item = &'a PathBuf>,
719{
720 let mut search_path = vec![];
721 for dir in paths {
722 let dir = get_dynamic_search_path(dir);
723 if dir.starts_with(&root_output) {
724 search_path.push(dir.to_path_buf());
725 } else {
726 debug!(
727 "Not including path {} in runtime library search path because it is \
728 outside target root {}",
729 dir.display(),
730 root_output.display()
731 );
732 }
733 }
734 search_path
735}
736
737fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
744 let gctx = build_runner.bcx.gctx;
745 let is_primary = build_runner.is_primary_package(unit);
746 let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg);
747
748 let mut base = build_runner
749 .compilation
750 .rustc_process(unit, is_primary, is_workspace)?;
751 build_base_args(build_runner, &mut base, unit)?;
752 if unit.pkg.manifest().is_embedded() {
753 if !gctx.cli_unstable().script {
754 anyhow::bail!(
755 "parsing `{}` requires `-Zscript`",
756 unit.pkg.manifest_path().display()
757 );
758 }
759 base.arg("-Z").arg("crate-attr=feature(frontmatter)");
760 }
761
762 base.inherit_jobserver(&build_runner.jobserver);
763 build_deps_args(&mut base, build_runner, unit)?;
764 add_cap_lints(build_runner.bcx, unit, &mut base);
765 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
766 base.args(args);
767 }
768 base.args(&unit.rustflags);
769 if gctx.cli_unstable().binary_dep_depinfo {
770 base.arg("-Z").arg("binary-dep-depinfo");
771 }
772 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
773 base.arg("-Z").arg("checksum-hash-algorithm=blake3");
774 }
775
776 if is_primary {
777 base.env("CARGO_PRIMARY_PACKAGE", "1");
778 let file_list = std::env::join_paths(build_runner.sbom_output_files(unit)?)?;
779 base.env("CARGO_SBOM_PATH", file_list);
780 }
781
782 if unit.target.is_test() || unit.target.is_bench() {
783 let tmp = build_runner
784 .files()
785 .layout(unit.kind)
786 .build_dir()
787 .prepare_tmp()?;
788 base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
789 }
790
791 Ok(base)
792}
793
794fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
801 let bcx = build_runner.bcx;
802 let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
804 if unit.pkg.manifest().is_embedded() {
805 if !bcx.gctx.cli_unstable().script {
806 anyhow::bail!(
807 "parsing `{}` requires `-Zscript`",
808 unit.pkg.manifest_path().display()
809 );
810 }
811 rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
812 }
813 rustdoc.inherit_jobserver(&build_runner.jobserver);
814 let crate_name = unit.target.crate_name();
815 rustdoc.arg("--crate-name").arg(&crate_name);
816 add_path_args(bcx.ws, unit, &mut rustdoc);
817 add_cap_lints(bcx, unit, &mut rustdoc);
818
819 if let CompileKind::Target(target) = unit.kind {
820 rustdoc.arg("--target").arg(target.rustc_target());
821 }
822 let doc_dir = build_runner.files().out_dir(unit);
823 rustdoc.arg("-o").arg(&doc_dir);
824 rustdoc.args(&features_args(unit));
825 rustdoc.args(&check_cfg_args(unit));
826
827 add_error_format_and_color(build_runner, &mut rustdoc);
828 add_allow_features(build_runner, &mut rustdoc);
829
830 if build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo {
831 let mut arg =
834 OsString::from("--emit=toolchain-shared-resources,invocation-specific,dep-info=");
835 arg.push(rustdoc_dep_info_loc(build_runner, unit));
836 rustdoc.arg(arg);
837
838 if build_runner.bcx.gctx.cli_unstable().checksum_freshness {
839 rustdoc.arg("-Z").arg("checksum-hash-algorithm=blake3");
840 }
841
842 rustdoc.arg("-Zunstable-options");
843 }
844
845 if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
846 trim_paths_args_rustdoc(&mut rustdoc, build_runner, unit, trim_paths)?;
847 }
848
849 rustdoc.args(unit.pkg.manifest().lint_rustflags());
850
851 let metadata = build_runner.metadata_for_doc_units[unit];
852 rustdoc
853 .arg("-C")
854 .arg(format!("metadata={}", metadata.c_metadata()));
855
856 if unit.mode.is_doc_scrape() {
857 debug_assert!(build_runner.bcx.scrape_units.contains(unit));
858
859 if unit.target.is_test() {
860 rustdoc.arg("--scrape-tests");
861 }
862
863 rustdoc.arg("-Zunstable-options");
864
865 rustdoc
866 .arg("--scrape-examples-output-path")
867 .arg(scrape_output_path(build_runner, unit)?);
868
869 for pkg in build_runner.bcx.packages.packages() {
871 let names = pkg
872 .targets()
873 .iter()
874 .map(|target| target.crate_name())
875 .collect::<HashSet<_>>();
876 for name in names {
877 rustdoc.arg("--scrape-examples-target-crate").arg(name);
878 }
879 }
880 }
881
882 if should_include_scrape_units(build_runner.bcx, unit) {
883 rustdoc.arg("-Zunstable-options");
884 }
885
886 build_deps_args(&mut rustdoc, build_runner, unit)?;
887 rustdoc::add_root_urls(build_runner, unit, &mut rustdoc)?;
888
889 rustdoc::add_output_format(build_runner, &mut rustdoc)?;
890
891 if let Some(args) = build_runner.bcx.extra_args_for(unit) {
892 rustdoc.args(args);
893 }
894 rustdoc.args(&unit.rustdocflags);
895
896 if !crate_version_flag_already_present(&rustdoc) {
897 append_crate_version_flag(unit, &mut rustdoc);
898 }
899
900 Ok(rustdoc)
901}
902
903fn rustdoc(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Work> {
905 let mut rustdoc = prepare_rustdoc(build_runner, unit)?;
906
907 let crate_name = unit.target.crate_name();
908 let doc_dir = build_runner.files().out_dir(unit);
909 paths::create_dir_all(&doc_dir)?;
913
914 let target_desc = unit.target.description_named();
915 let name = unit.pkg.name();
916 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
917 let package_id = unit.pkg.package_id();
918 let target = Target::clone(&unit.target);
919 let manifest = ManifestErrorContext::new(build_runner, unit);
920
921 let rustdoc_dep_info_loc = rustdoc_dep_info_loc(build_runner, unit);
922 let dep_info_loc = fingerprint::dep_info_loc(build_runner, unit);
923 let build_dir = build_runner.bcx.ws.build_dir().into_path_unlocked();
924 let pkg_root = unit.pkg.root().to_path_buf();
925 let cwd = rustdoc
926 .get_cwd()
927 .unwrap_or_else(|| build_runner.bcx.gctx.cwd())
928 .to_path_buf();
929 let fingerprint_dir = build_runner.files().fingerprint_dir(unit);
930 let is_local = unit.is_local();
931 let env_config = Arc::clone(build_runner.bcx.gctx.env_config()?);
932 let rustdoc_depinfo_enabled = build_runner.bcx.gctx.cli_unstable().rustdoc_depinfo;
933
934 let mut output_options = OutputOptions::new(build_runner, unit);
935 let script_metadatas = build_runner.find_build_script_metadatas(unit);
936 let scrape_outputs = if should_include_scrape_units(build_runner.bcx, unit) {
937 Some(
938 build_runner
939 .bcx
940 .scrape_units
941 .iter()
942 .map(|unit| {
943 Ok((
944 build_runner.files().metadata(unit).unit_id(),
945 scrape_output_path(build_runner, unit)?,
946 ))
947 })
948 .collect::<CargoResult<HashMap<_, _>>>()?,
949 )
950 } else {
951 None
952 };
953
954 let failed_scrape_units = Arc::clone(&build_runner.failed_scrape_units);
955 let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit)
956 && !matches!(
957 build_runner.bcx.gctx.shell().verbosity(),
958 Verbosity::Verbose
959 );
960 let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
961 make_failed_scrape_diagnostic(
962 build_runner,
963 unit,
964 format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
965 )
966 });
967 if hide_diagnostics_for_scrape_unit {
968 output_options.show_diagnostics = false;
969 }
970
971 Ok(Work::new(move |state| {
972 add_custom_flags(
973 &mut rustdoc,
974 &build_script_outputs.lock().unwrap(),
975 script_metadatas,
976 )?;
977
978 if let Some(scrape_outputs) = scrape_outputs {
983 let failed_scrape_units = failed_scrape_units.lock().unwrap();
984 for (metadata, output_path) in &scrape_outputs {
985 if !failed_scrape_units.contains(metadata) {
986 rustdoc.arg("--with-examples").arg(output_path);
987 }
988 }
989 }
990
991 let crate_dir = doc_dir.join(&crate_name);
992 if crate_dir.exists() {
993 debug!("removing pre-existing doc directory {:?}", crate_dir);
996 paths::remove_dir_all(crate_dir)?;
997 }
998 state.running(&rustdoc);
999 let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
1000
1001 let result = rustdoc
1002 .exec_with_streaming(
1003 &mut |line| on_stdout_line(state, line, package_id, &target),
1004 &mut |line| {
1005 on_stderr_line(
1006 state,
1007 line,
1008 package_id,
1009 &manifest,
1010 &target,
1011 &mut output_options,
1012 )
1013 },
1014 false,
1015 )
1016 .map_err(verbose_if_simple_exit_code)
1017 .with_context(|| format!("could not document `{}`", name));
1018
1019 if let Err(e) = result {
1020 if let Some(diagnostic) = failed_scrape_diagnostic {
1021 state.warning(diagnostic);
1022 }
1023
1024 return Err(e);
1025 }
1026
1027 if rustdoc_depinfo_enabled && rustdoc_dep_info_loc.exists() {
1028 fingerprint::translate_dep_info(
1029 &rustdoc_dep_info_loc,
1030 &dep_info_loc,
1031 &cwd,
1032 &pkg_root,
1033 &build_dir,
1034 &rustdoc,
1035 is_local,
1037 &env_config,
1038 )
1039 .with_context(|| {
1040 internal(format_args!(
1041 "could not parse/generate dep info at: {}",
1042 rustdoc_dep_info_loc.display()
1043 ))
1044 })?;
1045 paths::set_file_time_no_err(dep_info_loc, timestamp);
1048 }
1049
1050 Ok(())
1051 }))
1052}
1053
1054fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
1057 rustdoc.get_args().any(|flag| {
1058 flag.to_str()
1059 .map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
1060 })
1061}
1062
1063fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
1064 rustdoc
1065 .arg(RUSTDOC_CRATE_VERSION_FLAG)
1066 .arg(unit.pkg.version().to_string());
1067}
1068
1069fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
1073 if !unit.show_warnings(bcx.gctx) {
1076 cmd.arg("--cap-lints").arg("allow");
1077
1078 } else if !unit.is_local() {
1081 cmd.arg("--cap-lints").arg("warn");
1082 }
1083}
1084
1085fn add_allow_features(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1089 if let Some(allow) = &build_runner.bcx.gctx.cli_unstable().allow_features {
1090 use std::fmt::Write;
1091 let mut arg = String::from("-Zallow-features=");
1092 for f in allow {
1093 let _ = write!(&mut arg, "{f},");
1094 }
1095 cmd.arg(arg.trim_end_matches(','));
1096 }
1097}
1098
1099fn add_error_format_and_color(build_runner: &BuildRunner<'_, '_>, cmd: &mut ProcessBuilder) {
1110 let enable_timings = build_runner.bcx.gctx.cli_unstable().section_timings
1111 && !build_runner.bcx.build_config.timing_outputs.is_empty();
1112 if enable_timings {
1113 cmd.arg("-Zunstable-options");
1114 }
1115
1116 cmd.arg("--error-format=json");
1117 let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
1118
1119 if let MessageFormat::Short | MessageFormat::Json { short: true, .. } =
1120 build_runner.bcx.build_config.message_format
1121 {
1122 json.push_str(",diagnostic-short");
1123 } else if build_runner.bcx.gctx.shell().err_unicode()
1124 && build_runner.bcx.gctx.cli_unstable().rustc_unicode
1125 {
1126 json.push_str(",diagnostic-unicode");
1127 }
1128
1129 if enable_timings {
1130 json.push_str(",timings");
1131 }
1132
1133 cmd.arg(json);
1134
1135 let gctx = build_runner.bcx.gctx;
1136 if let Some(width) = gctx.shell().err_width().diagnostic_terminal_width() {
1137 cmd.arg(format!("--diagnostic-width={width}"));
1138 }
1139}
1140
1141fn build_base_args(
1143 build_runner: &BuildRunner<'_, '_>,
1144 cmd: &mut ProcessBuilder,
1145 unit: &Unit,
1146) -> CargoResult<()> {
1147 assert!(!unit.mode.is_run_custom_build());
1148
1149 let bcx = build_runner.bcx;
1150 let Profile {
1151 ref opt_level,
1152 codegen_backend,
1153 codegen_units,
1154 debuginfo,
1155 debug_assertions,
1156 split_debuginfo,
1157 overflow_checks,
1158 rpath,
1159 ref panic,
1160 incremental,
1161 strip,
1162 rustflags: profile_rustflags,
1163 trim_paths,
1164 hint_mostly_unused: profile_hint_mostly_unused,
1165 ..
1166 } = unit.profile.clone();
1167 let hints = unit.pkg.hints().cloned().unwrap_or_default();
1168 let test = unit.mode.is_any_test();
1169
1170 let warn = |msg: &str| {
1171 bcx.gctx.shell().warn(format!(
1172 "{}@{}: {msg}",
1173 unit.pkg.package_id().name(),
1174 unit.pkg.package_id().version()
1175 ))
1176 };
1177 let unit_capped_warn = |msg: &str| {
1178 if unit.show_warnings(bcx.gctx) {
1179 warn(msg)
1180 } else {
1181 Ok(())
1182 }
1183 };
1184
1185 cmd.arg("--crate-name").arg(&unit.target.crate_name());
1186
1187 let edition = unit.target.edition();
1188 edition.cmd_edition_arg(cmd);
1189
1190 add_path_args(bcx.ws, unit, cmd);
1191 add_error_format_and_color(build_runner, cmd);
1192 add_allow_features(build_runner, cmd);
1193
1194 let mut contains_dy_lib = false;
1195 if !test {
1196 for crate_type in &unit.target.rustc_crate_types() {
1197 cmd.arg("--crate-type").arg(crate_type.as_str());
1198 contains_dy_lib |= crate_type == &CrateType::Dylib;
1199 }
1200 }
1201
1202 if unit.mode.is_check() {
1203 cmd.arg("--emit=dep-info,metadata");
1204 } else if build_runner.bcx.gctx.cli_unstable().no_embed_metadata {
1205 if unit.benefits_from_no_embed_metadata() {
1215 cmd.arg("--emit=dep-info,metadata,link");
1216 cmd.args(&["-Z", "embed-metadata=no"]);
1217 } else {
1218 cmd.arg("--emit=dep-info,link");
1219 }
1220 } else {
1221 if !unit.requires_upstream_objects() {
1225 cmd.arg("--emit=dep-info,metadata,link");
1226 } else {
1227 cmd.arg("--emit=dep-info,link");
1228 }
1229 }
1230
1231 let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
1232 || (contains_dy_lib && !build_runner.is_primary_package(unit));
1233 if prefer_dynamic {
1234 cmd.arg("-C").arg("prefer-dynamic");
1235 }
1236
1237 if opt_level.as_str() != "0" {
1238 cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
1239 }
1240
1241 if *panic != PanicStrategy::Unwind {
1242 cmd.arg("-C").arg(format!("panic={}", panic));
1243 }
1244 if *panic == PanicStrategy::ImmediateAbort {
1245 cmd.arg("-Z").arg("unstable-options");
1246 }
1247
1248 cmd.args(<o_args(build_runner, unit));
1249
1250 if let Some(backend) = codegen_backend {
1251 cmd.arg("-Z").arg(&format!("codegen-backend={}", backend));
1252 }
1253
1254 if let Some(n) = codegen_units {
1255 cmd.arg("-C").arg(&format!("codegen-units={}", n));
1256 }
1257
1258 let debuginfo = debuginfo.into_inner();
1259 if debuginfo != TomlDebugInfo::None {
1261 cmd.arg("-C").arg(format!("debuginfo={debuginfo}"));
1262 if let Some(split) = split_debuginfo {
1269 if build_runner
1270 .bcx
1271 .target_data
1272 .info(unit.kind)
1273 .supports_debuginfo_split(split)
1274 {
1275 cmd.arg("-C").arg(format!("split-debuginfo={split}"));
1276 }
1277 }
1278 }
1279
1280 if let Some(trim_paths) = trim_paths {
1281 trim_paths_args(cmd, build_runner, unit, &trim_paths)?;
1282 }
1283
1284 cmd.args(unit.pkg.manifest().lint_rustflags());
1285 cmd.args(&profile_rustflags);
1286
1287 if opt_level.as_str() != "0" {
1291 if debug_assertions {
1292 cmd.args(&["-C", "debug-assertions=on"]);
1293 if !overflow_checks {
1294 cmd.args(&["-C", "overflow-checks=off"]);
1295 }
1296 } else if overflow_checks {
1297 cmd.args(&["-C", "overflow-checks=on"]);
1298 }
1299 } else if !debug_assertions {
1300 cmd.args(&["-C", "debug-assertions=off"]);
1301 if overflow_checks {
1302 cmd.args(&["-C", "overflow-checks=on"]);
1303 }
1304 } else if !overflow_checks {
1305 cmd.args(&["-C", "overflow-checks=off"]);
1306 }
1307
1308 if test && unit.target.harness() {
1309 cmd.arg("--test");
1310
1311 if *panic == PanicStrategy::Abort || *panic == PanicStrategy::ImmediateAbort {
1319 cmd.arg("-Z").arg("panic-abort-tests");
1320 }
1321 } else if test {
1322 cmd.arg("--cfg").arg("test");
1323 }
1324
1325 cmd.args(&features_args(unit));
1326 cmd.args(&check_cfg_args(unit));
1327
1328 let meta = build_runner.files().metadata(unit);
1329 cmd.arg("-C")
1330 .arg(&format!("metadata={}", meta.c_metadata()));
1331 if let Some(c_extra_filename) = meta.c_extra_filename() {
1332 cmd.arg("-C")
1333 .arg(&format!("extra-filename=-{c_extra_filename}"));
1334 }
1335
1336 if rpath {
1337 cmd.arg("-C").arg("rpath");
1338 }
1339
1340 cmd.arg("--out-dir")
1341 .arg(&build_runner.files().out_dir(unit));
1342
1343 fn opt(cmd: &mut ProcessBuilder, key: &str, prefix: &str, val: Option<&OsStr>) {
1344 if let Some(val) = val {
1345 let mut joined = OsString::from(prefix);
1346 joined.push(val);
1347 cmd.arg(key).arg(joined);
1348 }
1349 }
1350
1351 if let CompileKind::Target(n) = unit.kind {
1352 cmd.arg("--target").arg(n.rustc_target());
1353 }
1354
1355 opt(
1356 cmd,
1357 "-C",
1358 "linker=",
1359 build_runner
1360 .compilation
1361 .target_linker(unit.kind)
1362 .as_ref()
1363 .map(|s| s.as_ref()),
1364 );
1365 if incremental {
1366 let dir = build_runner.files().incremental_dir(&unit);
1367 opt(cmd, "-C", "incremental=", Some(dir.as_os_str()));
1368 }
1369
1370 let pkg_hint_mostly_unused = match hints.mostly_unused {
1371 None => None,
1372 Some(toml::Value::Boolean(b)) => Some(b),
1373 Some(v) => {
1374 unit_capped_warn(&format!(
1375 "ignoring unsupported value type ({}) for 'hints.mostly-unused', which expects a boolean",
1376 v.type_str()
1377 ))?;
1378 None
1379 }
1380 };
1381 if profile_hint_mostly_unused
1382 .or(pkg_hint_mostly_unused)
1383 .unwrap_or(false)
1384 {
1385 if bcx.gctx.cli_unstable().profile_hint_mostly_unused {
1386 cmd.arg("-Zhint-mostly-unused");
1387 } else {
1388 if profile_hint_mostly_unused.is_some() {
1389 warn(
1391 "ignoring 'hint-mostly-unused' profile option, pass `-Zprofile-hint-mostly-unused` to enable it",
1392 )?;
1393 } else if pkg_hint_mostly_unused.is_some() {
1394 unit_capped_warn(
1395 "ignoring 'hints.mostly-unused', pass `-Zprofile-hint-mostly-unused` to enable it",
1396 )?;
1397 }
1398 }
1399 }
1400
1401 let strip = strip.into_inner();
1402 if strip != StripInner::None {
1403 cmd.arg("-C").arg(format!("strip={}", strip));
1404 }
1405
1406 if unit.is_std {
1407 cmd.arg("-Z")
1413 .arg("force-unstable-if-unmarked")
1414 .env("RUSTC_BOOTSTRAP", "1");
1415 }
1416
1417 if unit.target.is_test() || unit.target.is_bench() {
1419 for bin_target in unit
1420 .pkg
1421 .manifest()
1422 .targets()
1423 .iter()
1424 .filter(|target| target.is_bin())
1425 {
1426 let exe_path = build_runner
1430 .files()
1431 .bin_link_for_target(bin_target, unit.kind, build_runner.bcx)?
1432 .map(|path| path.as_os_str().to_os_string())
1433 .unwrap_or_else(|| OsString::from(format!("placeholder:{}", bin_target.name())));
1434
1435 let name = bin_target
1436 .binary_filename()
1437 .unwrap_or(bin_target.name().to_string());
1438 let key = format!("CARGO_BIN_EXE_{}", name);
1439 cmd.env(&key, exe_path);
1440 }
1441 }
1442 Ok(())
1443}
1444
1445fn features_args(unit: &Unit) -> Vec<OsString> {
1447 let mut args = Vec::with_capacity(unit.features.len() * 2);
1448
1449 for feat in &unit.features {
1450 args.push(OsString::from("--cfg"));
1451 args.push(OsString::from(format!("feature=\"{}\"", feat)));
1452 }
1453
1454 args
1455}
1456
1457fn trim_paths_args_rustdoc(
1459 cmd: &mut ProcessBuilder,
1460 build_runner: &BuildRunner<'_, '_>,
1461 unit: &Unit,
1462 trim_paths: &TomlTrimPaths,
1463) -> CargoResult<()> {
1464 match trim_paths {
1465 TomlTrimPaths::Values(values) if !values.contains(&TomlTrimPathsValue::Diagnostics) => {
1467 return Ok(());
1468 }
1469 _ => {}
1470 }
1471
1472 cmd.arg("-Zunstable-options");
1474
1475 cmd.arg(package_remap(build_runner, unit));
1478 cmd.arg(build_dir_remap(build_runner));
1479 cmd.arg(sysroot_remap(build_runner, unit));
1480
1481 Ok(())
1482}
1483
1484fn trim_paths_args(
1490 cmd: &mut ProcessBuilder,
1491 build_runner: &BuildRunner<'_, '_>,
1492 unit: &Unit,
1493 trim_paths: &TomlTrimPaths,
1494) -> CargoResult<()> {
1495 if trim_paths.is_none() {
1496 return Ok(());
1497 }
1498
1499 cmd.arg("-Zunstable-options");
1501 cmd.arg(format!("-Zremap-path-scope={trim_paths}"));
1502
1503 cmd.arg(package_remap(build_runner, unit));
1506 cmd.arg(build_dir_remap(build_runner));
1507 cmd.arg(sysroot_remap(build_runner, unit));
1508
1509 Ok(())
1510}
1511
1512fn sysroot_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1517 let mut remap = OsString::from("--remap-path-prefix=");
1518 remap.push({
1519 let mut sysroot = build_runner.bcx.target_data.info(unit.kind).sysroot.clone();
1521 sysroot.push("lib");
1522 sysroot.push("rustlib");
1523 sysroot.push("src");
1524 sysroot.push("rust");
1525 sysroot
1526 });
1527 remap.push("=");
1528 remap.push("/rustc/");
1529 if let Some(commit_hash) = build_runner.bcx.rustc().commit_hash.as_ref() {
1530 remap.push(commit_hash);
1531 } else {
1532 remap.push(build_runner.bcx.rustc().version.to_string());
1533 }
1534 remap
1535}
1536
1537fn package_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OsString {
1545 let pkg_root = unit.pkg.root();
1546 let ws_root = build_runner.bcx.ws.root();
1547 let mut remap = OsString::from("--remap-path-prefix=");
1548 let source_id = unit.pkg.package_id().source_id();
1549 if source_id.is_git() {
1550 remap.push(
1551 build_runner
1552 .bcx
1553 .gctx
1554 .git_checkouts_path()
1555 .as_path_unlocked(),
1556 );
1557 remap.push("=");
1558 } else if source_id.is_registry() {
1559 remap.push(
1560 build_runner
1561 .bcx
1562 .gctx
1563 .registry_source_path()
1564 .as_path_unlocked(),
1565 );
1566 remap.push("=");
1567 } else if pkg_root.strip_prefix(ws_root).is_ok() {
1568 remap.push(ws_root);
1569 remap.push("=."); } else {
1571 remap.push(pkg_root);
1572 remap.push("=");
1573 remap.push(unit.pkg.name());
1574 remap.push("-");
1575 remap.push(unit.pkg.version().to_string());
1576 }
1577 remap
1578}
1579
1580fn build_dir_remap(build_runner: &BuildRunner<'_, '_>) -> OsString {
1593 let build_dir = build_runner.bcx.ws.build_dir();
1594 let mut remap = OsString::from("--remap-path-prefix=");
1595 remap.push(build_dir.as_path_unlocked());
1596 remap.push("=/cargo/build-dir");
1597 remap
1598}
1599
1600fn check_cfg_args(unit: &Unit) -> Vec<OsString> {
1602 let gross_cap_estimation = unit.pkg.summary().features().len() * 7 + 25;
1620 let mut arg_feature = OsString::with_capacity(gross_cap_estimation);
1621
1622 arg_feature.push("cfg(feature, values(");
1623 for (i, feature) in unit.pkg.summary().features().keys().enumerate() {
1624 if i != 0 {
1625 arg_feature.push(", ");
1626 }
1627 arg_feature.push("\"");
1628 arg_feature.push(feature);
1629 arg_feature.push("\"");
1630 }
1631 arg_feature.push("))");
1632
1633 vec![
1642 OsString::from("--check-cfg"),
1643 OsString::from("cfg(docsrs,test)"),
1644 OsString::from("--check-cfg"),
1645 arg_feature,
1646 ]
1647}
1648
1649fn lto_args(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
1651 let mut result = Vec::new();
1652 let mut push = |arg: &str| {
1653 result.push(OsString::from("-C"));
1654 result.push(OsString::from(arg));
1655 };
1656 match build_runner.lto[unit] {
1657 lto::Lto::Run(None) => push("lto"),
1658 lto::Lto::Run(Some(s)) => push(&format!("lto={}", s)),
1659 lto::Lto::Off => {
1660 push("lto=off");
1661 push("embed-bitcode=no");
1662 }
1663 lto::Lto::ObjectAndBitcode => {} lto::Lto::OnlyBitcode => push("linker-plugin-lto"),
1665 lto::Lto::OnlyObject => push("embed-bitcode=no"),
1666 }
1667 result
1668}
1669
1670fn build_deps_args(
1676 cmd: &mut ProcessBuilder,
1677 build_runner: &BuildRunner<'_, '_>,
1678 unit: &Unit,
1679) -> CargoResult<()> {
1680 let bcx = build_runner.bcx;
1681 if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1682 let mut map = BTreeMap::new();
1683
1684 add_dep_arg(&mut map, build_runner, unit);
1686
1687 let paths = map.into_iter().map(|(_, path)| path).sorted_unstable();
1688
1689 for path in paths {
1690 cmd.arg("-L").arg(&{
1691 let mut deps = OsString::from("dependency=");
1692 deps.push(path);
1693 deps
1694 });
1695 }
1696 } else {
1697 cmd.arg("-L").arg(&{
1698 let mut deps = OsString::from("dependency=");
1699 deps.push(build_runner.files().deps_dir(unit));
1700 deps
1701 });
1702 }
1703
1704 if !unit.kind.is_host() {
1707 cmd.arg("-L").arg(&{
1708 let mut deps = OsString::from("dependency=");
1709 deps.push(build_runner.files().host_deps(unit));
1710 deps
1711 });
1712 }
1713
1714 let deps = build_runner.unit_deps(unit);
1715
1716 if !deps
1720 .iter()
1721 .any(|dep| !dep.unit.mode.is_doc() && dep.unit.target.is_linkable())
1722 {
1723 if let Some(dep) = deps.iter().find(|dep| {
1724 !dep.unit.mode.is_doc() && dep.unit.target.is_lib() && !dep.unit.artifact.is_true()
1725 }) {
1726 let dep_name = dep.unit.target.crate_name();
1727 let name = unit.target.crate_name();
1728 bcx.gctx.shell().print_report(&[
1729 Level::WARNING.secondary_title(format!("the package `{dep_name}` provides no linkable target"))
1730 .elements([
1731 Level::NOTE.message(format!("this might cause `{name}` to fail compilation")),
1732 Level::NOTE.message("this warning might turn into a hard error in the future"),
1733 Level::HELP.message(format!("consider adding 'dylib' or 'rlib' to key 'crate-type' in `{dep_name}`'s Cargo.toml"))
1734 ])
1735 ], false)?;
1736 }
1737 }
1738
1739 let mut unstable_opts = false;
1740
1741 let first_custom_build_dep = deps.iter().find(|dep| dep.unit.mode.is_run_custom_build());
1743 if let Some(dep) = first_custom_build_dep {
1744 let out_dir = &build_runner.files().build_script_out_dir(&dep.unit);
1745 cmd.env("OUT_DIR", &out_dir);
1746 }
1747
1748 let is_multiple_build_scripts_enabled = unit
1750 .pkg
1751 .manifest()
1752 .unstable_features()
1753 .require(Feature::multiple_build_scripts())
1754 .is_ok();
1755
1756 if is_multiple_build_scripts_enabled {
1757 for dep in deps {
1758 if dep.unit.mode.is_run_custom_build() {
1759 let out_dir = &build_runner.files().build_script_out_dir(&dep.unit);
1760 let target_name = dep.unit.target.name();
1761 let out_dir_prefix = target_name
1762 .strip_prefix("build-script-")
1763 .unwrap_or(target_name);
1764 let out_dir_name = format!("{out_dir_prefix}_OUT_DIR");
1765 cmd.env(&out_dir_name, &out_dir);
1766 }
1767 }
1768 }
1769 for arg in extern_args(build_runner, unit, &mut unstable_opts)? {
1770 cmd.arg(arg);
1771 }
1772
1773 for (var, env) in artifact::get_env(build_runner, deps)? {
1774 cmd.env(&var, env);
1775 }
1776
1777 if unstable_opts {
1780 cmd.arg("-Z").arg("unstable-options");
1781 }
1782
1783 Ok(())
1784}
1785
1786fn add_dep_arg<'a, 'b: 'a>(
1787 map: &mut BTreeMap<&'a Unit, PathBuf>,
1788 build_runner: &'b BuildRunner<'b, '_>,
1789 unit: &'a Unit,
1790) {
1791 if map.contains_key(&unit) {
1792 return;
1793 }
1794 map.insert(&unit, build_runner.files().deps_dir(&unit));
1795
1796 for dep in build_runner.unit_deps(unit) {
1797 add_dep_arg(map, build_runner, &dep.unit);
1798 }
1799}
1800
1801fn add_custom_flags(
1805 cmd: &mut ProcessBuilder,
1806 build_script_outputs: &BuildScriptOutputs,
1807 metadata_vec: Option<Vec<UnitHash>>,
1808) -> CargoResult<()> {
1809 if let Some(metadata_vec) = metadata_vec {
1810 for metadata in metadata_vec {
1811 if let Some(output) = build_script_outputs.get(metadata) {
1812 for cfg in output.cfgs.iter() {
1813 cmd.arg("--cfg").arg(cfg);
1814 }
1815 for check_cfg in &output.check_cfgs {
1816 cmd.arg("--check-cfg").arg(check_cfg);
1817 }
1818 for (name, value) in output.env.iter() {
1819 cmd.env(name, value);
1820 }
1821 }
1822 }
1823 }
1824
1825 Ok(())
1826}
1827
1828pub fn extern_args(
1830 build_runner: &BuildRunner<'_, '_>,
1831 unit: &Unit,
1832 unstable_opts: &mut bool,
1833) -> CargoResult<Vec<OsString>> {
1834 let mut result = Vec::new();
1835 let deps = build_runner.unit_deps(unit);
1836
1837 let no_embed_metadata = build_runner.bcx.gctx.cli_unstable().no_embed_metadata;
1838
1839 let mut link_to =
1841 |dep: &UnitDep, extern_crate_name: InternedString, noprelude: bool| -> CargoResult<()> {
1842 let mut value = OsString::new();
1843 let mut opts = Vec::new();
1844 let is_public_dependency_enabled = unit
1845 .pkg
1846 .manifest()
1847 .unstable_features()
1848 .require(Feature::public_dependency())
1849 .is_ok()
1850 || build_runner.bcx.gctx.cli_unstable().public_dependency;
1851 if !dep.public && unit.target.is_lib() && is_public_dependency_enabled {
1852 opts.push("priv");
1853 *unstable_opts = true;
1854 }
1855 if noprelude {
1856 opts.push("noprelude");
1857 *unstable_opts = true;
1858 }
1859 if !opts.is_empty() {
1860 value.push(opts.join(","));
1861 value.push(":");
1862 }
1863 value.push(extern_crate_name.as_str());
1864 value.push("=");
1865
1866 let mut pass = |file| {
1867 let mut value = value.clone();
1868 value.push(file);
1869 result.push(OsString::from("--extern"));
1870 result.push(value);
1871 };
1872
1873 let outputs = build_runner.outputs(&dep.unit)?;
1874
1875 if build_runner.only_requires_rmeta(unit, &dep.unit) || dep.unit.mode.is_check() {
1876 let output = outputs
1878 .iter()
1879 .find(|output| output.flavor == FileFlavor::Rmeta)
1880 .expect("failed to find rmeta dep for pipelined dep");
1881 pass(&output.path);
1882 } else {
1883 for output in outputs.iter() {
1885 if output.flavor == FileFlavor::Linkable {
1886 pass(&output.path);
1887 }
1888 else if no_embed_metadata && output.flavor == FileFlavor::Rmeta {
1892 pass(&output.path);
1893 }
1894 }
1895 }
1896 Ok(())
1897 };
1898
1899 for dep in deps {
1900 if dep.unit.target.is_linkable() && !dep.unit.mode.is_doc() {
1901 link_to(dep, dep.extern_crate_name, dep.noprelude)?;
1902 }
1903 }
1904 if unit.target.proc_macro() {
1905 result.push(OsString::from("--extern"));
1907 result.push(OsString::from("proc_macro"));
1908 }
1909
1910 Ok(result)
1911}
1912
1913fn envify(s: &str) -> String {
1914 s.chars()
1915 .flat_map(|c| c.to_uppercase())
1916 .map(|c| if c == '-' { '_' } else { c })
1917 .collect()
1918}
1919
1920struct OutputOptions {
1923 format: MessageFormat,
1925 cache_cell: Option<(PathBuf, OnceCell<File>)>,
1930 show_diagnostics: bool,
1938 warnings_seen: usize,
1940 errors_seen: usize,
1942}
1943
1944impl OutputOptions {
1945 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> OutputOptions {
1946 let path = build_runner.files().message_cache_path(unit);
1947 drop(fs::remove_file(&path));
1949 let cache_cell = Some((path, OnceCell::new()));
1950 let show_diagnostics =
1951 build_runner.bcx.gctx.warning_handling().unwrap_or_default() != WarningHandling::Allow;
1952 OutputOptions {
1953 format: build_runner.bcx.build_config.message_format,
1954 cache_cell,
1955 show_diagnostics,
1956 warnings_seen: 0,
1957 errors_seen: 0,
1958 }
1959 }
1960}
1961
1962struct ManifestErrorContext {
1968 path: PathBuf,
1970 spans: toml::Spanned<toml::de::DeTable<'static>>,
1972 contents: String,
1974 rename_table: HashMap<InternedString, InternedString>,
1977 requested_kinds: Vec<CompileKind>,
1980 cfgs: Vec<Vec<Cfg>>,
1983 host_name: InternedString,
1984 cwd: PathBuf,
1986 term_width: usize,
1988}
1989
1990fn on_stdout_line(
1991 state: &JobState<'_, '_>,
1992 line: &str,
1993 _package_id: PackageId,
1994 _target: &Target,
1995) -> CargoResult<()> {
1996 state.stdout(line.to_string())?;
1997 Ok(())
1998}
1999
2000fn on_stderr_line(
2001 state: &JobState<'_, '_>,
2002 line: &str,
2003 package_id: PackageId,
2004 manifest: &ManifestErrorContext,
2005 target: &Target,
2006 options: &mut OutputOptions,
2007) -> CargoResult<()> {
2008 if on_stderr_line_inner(state, line, package_id, manifest, target, options)? {
2009 if let Some((path, cell)) = &mut options.cache_cell {
2011 let f = cell.try_borrow_mut_with(|| paths::create(path))?;
2013 debug_assert!(!line.contains('\n'));
2014 f.write_all(line.as_bytes())?;
2015 f.write_all(&[b'\n'])?;
2016 }
2017 }
2018 Ok(())
2019}
2020
2021fn on_stderr_line_inner(
2023 state: &JobState<'_, '_>,
2024 line: &str,
2025 package_id: PackageId,
2026 manifest: &ManifestErrorContext,
2027 target: &Target,
2028 options: &mut OutputOptions,
2029) -> CargoResult<bool> {
2030 if !line.starts_with('{') {
2036 state.stderr(line.to_string())?;
2037 return Ok(true);
2038 }
2039
2040 let mut compiler_message: Box<serde_json::value::RawValue> = match serde_json::from_str(line) {
2041 Ok(msg) => msg,
2042
2043 Err(e) => {
2047 debug!("failed to parse json: {:?}", e);
2048 state.stderr(line.to_string())?;
2049 return Ok(true);
2050 }
2051 };
2052
2053 let count_diagnostic = |level, options: &mut OutputOptions| {
2054 if level == "warning" {
2055 options.warnings_seen += 1;
2056 } else if level == "error" {
2057 options.errors_seen += 1;
2058 }
2059 };
2060
2061 if let Ok(report) = serde_json::from_str::<FutureIncompatReport>(compiler_message.get()) {
2062 for item in &report.future_incompat_report {
2063 count_diagnostic(&*item.diagnostic.level, options);
2064 }
2065 state.future_incompat_report(report.future_incompat_report);
2066 return Ok(true);
2067 }
2068
2069 let res = serde_json::from_str::<SectionTiming>(compiler_message.get());
2070 if let Ok(timing_record) = res {
2071 state.on_section_timing_emitted(timing_record);
2072 return Ok(false);
2073 }
2074
2075 let add_pub_in_priv_diagnostic = |diag: &mut String| -> bool {
2077 static PRIV_DEP_REGEX: LazyLock<Regex> =
2086 LazyLock::new(|| Regex::new("from private dependency '([A-Za-z0-9-_]+)'").unwrap());
2087 if let Some(crate_name) = PRIV_DEP_REGEX.captures(diag).and_then(|m| m.get(1))
2088 && let Some(span) = manifest.find_crate_span(crate_name.as_str())
2089 {
2090 let rel_path = pathdiff::diff_paths(&manifest.path, &manifest.cwd)
2091 .unwrap_or_else(|| manifest.path.clone())
2092 .display()
2093 .to_string();
2094 let report = [Group::with_title(Level::NOTE.secondary_title(format!(
2095 "dependency `{}` declared here",
2096 crate_name.as_str()
2097 )))
2098 .element(
2099 Snippet::source(&manifest.contents)
2100 .path(rel_path)
2101 .annotation(AnnotationKind::Context.span(span)),
2102 )];
2103
2104 let rendered = Renderer::styled()
2105 .term_width(manifest.term_width)
2106 .render(&report);
2107 diag.push_str(&rendered);
2108 diag.push('\n');
2109 return true;
2110 }
2111 false
2112 };
2113
2114 match options.format {
2117 MessageFormat::Human
2122 | MessageFormat::Short
2123 | MessageFormat::Json {
2124 render_diagnostics: true,
2125 ..
2126 } => {
2127 #[derive(serde::Deserialize)]
2128 struct CompilerMessage<'a> {
2129 rendered: String,
2133 #[serde(borrow)]
2134 message: Cow<'a, str>,
2135 #[serde(borrow)]
2136 level: Cow<'a, str>,
2137 children: Vec<PartialDiagnostic>,
2138 code: Option<DiagnosticCode>,
2139 }
2140
2141 #[derive(serde::Deserialize)]
2150 struct PartialDiagnostic {
2151 spans: Vec<PartialDiagnosticSpan>,
2152 }
2153
2154 #[derive(serde::Deserialize)]
2156 struct PartialDiagnosticSpan {
2157 suggestion_applicability: Option<Applicability>,
2158 }
2159
2160 #[derive(serde::Deserialize)]
2161 struct DiagnosticCode {
2162 code: String,
2163 }
2164
2165 if let Ok(mut msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2166 {
2167 if msg.message.starts_with("aborting due to")
2168 || msg.message.ends_with("warning emitted")
2169 || msg.message.ends_with("warnings emitted")
2170 {
2171 return Ok(true);
2173 }
2174 if msg.rendered.ends_with('\n') {
2176 msg.rendered.pop();
2177 }
2178 let mut rendered = msg.rendered;
2179 if options.show_diagnostics {
2180 let machine_applicable: bool = msg
2181 .children
2182 .iter()
2183 .map(|child| {
2184 child
2185 .spans
2186 .iter()
2187 .filter_map(|span| span.suggestion_applicability)
2188 .any(|app| app == Applicability::MachineApplicable)
2189 })
2190 .any(|b| b);
2191 count_diagnostic(&msg.level, options);
2192 if msg
2193 .code
2194 .as_ref()
2195 .is_some_and(|c| c.code == "exported_private_dependencies")
2196 && options.format != MessageFormat::Short
2197 {
2198 add_pub_in_priv_diagnostic(&mut rendered);
2199 }
2200 let lint = msg.code.is_some();
2201 state.emit_diag(&msg.level, rendered, lint, machine_applicable)?;
2202 }
2203 return Ok(true);
2204 }
2205 }
2206
2207 MessageFormat::Json { ansi, .. } => {
2208 #[derive(serde::Deserialize, serde::Serialize)]
2209 struct CompilerMessage<'a> {
2210 rendered: String,
2211 #[serde(flatten, borrow)]
2212 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2213 code: Option<DiagnosticCode<'a>>,
2214 }
2215
2216 #[derive(serde::Deserialize, serde::Serialize)]
2217 struct DiagnosticCode<'a> {
2218 code: String,
2219 #[serde(flatten, borrow)]
2220 other: std::collections::BTreeMap<Cow<'a, str>, serde_json::Value>,
2221 }
2222
2223 if let Ok(mut error) =
2224 serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get())
2225 {
2226 let modified_diag = if error
2227 .code
2228 .as_ref()
2229 .is_some_and(|c| c.code == "exported_private_dependencies")
2230 {
2231 add_pub_in_priv_diagnostic(&mut error.rendered)
2232 } else {
2233 false
2234 };
2235
2236 if !ansi {
2240 error.rendered = anstream::adapter::strip_str(&error.rendered).to_string();
2241 }
2242 if !ansi || modified_diag {
2243 let new_line = serde_json::to_string(&error)?;
2244 compiler_message = serde_json::value::RawValue::from_string(new_line)?;
2245 }
2246 }
2247 }
2248 }
2249
2250 #[derive(serde::Deserialize)]
2257 struct ArtifactNotification<'a> {
2258 #[serde(borrow)]
2259 artifact: Cow<'a, str>,
2260 }
2261
2262 if let Ok(artifact) = serde_json::from_str::<ArtifactNotification<'_>>(compiler_message.get()) {
2263 trace!("found directive from rustc: `{}`", artifact.artifact);
2264 if artifact.artifact.ends_with(".rmeta") {
2265 debug!("looks like metadata finished early!");
2266 state.rmeta_produced();
2267 }
2268 return Ok(false);
2269 }
2270
2271 if !options.show_diagnostics {
2276 return Ok(true);
2277 }
2278
2279 #[derive(serde::Deserialize)]
2280 struct CompilerMessage<'a> {
2281 #[serde(borrow)]
2282 message: Cow<'a, str>,
2283 #[serde(borrow)]
2284 level: Cow<'a, str>,
2285 }
2286
2287 if let Ok(msg) = serde_json::from_str::<CompilerMessage<'_>>(compiler_message.get()) {
2288 if msg.message.starts_with("aborting due to")
2289 || msg.message.ends_with("warning emitted")
2290 || msg.message.ends_with("warnings emitted")
2291 {
2292 return Ok(true);
2294 }
2295 count_diagnostic(&msg.level, options);
2296 }
2297
2298 let msg = machine_message::FromCompiler {
2299 package_id: package_id.to_spec(),
2300 manifest_path: &manifest.path,
2301 target,
2302 message: compiler_message,
2303 }
2304 .to_json_string();
2305
2306 state.stdout(msg)?;
2310 Ok(true)
2311}
2312
2313impl ManifestErrorContext {
2314 fn new(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> ManifestErrorContext {
2315 let mut duplicates = HashSet::new();
2316 let mut rename_table = HashMap::new();
2317
2318 for dep in build_runner.unit_deps(unit) {
2319 let unrenamed_id = dep.unit.pkg.package_id().name();
2320 if duplicates.contains(&unrenamed_id) {
2321 continue;
2322 }
2323 match rename_table.entry(unrenamed_id) {
2324 std::collections::hash_map::Entry::Occupied(occ) => {
2325 occ.remove_entry();
2326 duplicates.insert(unrenamed_id);
2327 }
2328 std::collections::hash_map::Entry::Vacant(vac) => {
2329 vac.insert(dep.extern_crate_name);
2330 }
2331 }
2332 }
2333
2334 let bcx = build_runner.bcx;
2335 ManifestErrorContext {
2336 path: unit.pkg.manifest_path().to_owned(),
2337 spans: unit.pkg.manifest().document().clone(),
2338 contents: unit.pkg.manifest().contents().to_owned(),
2339 requested_kinds: bcx.target_data.requested_kinds().to_owned(),
2340 host_name: bcx.rustc().host,
2341 rename_table,
2342 cwd: path_args(build_runner.bcx.ws, unit).1,
2343 cfgs: bcx
2344 .target_data
2345 .requested_kinds()
2346 .iter()
2347 .map(|k| bcx.target_data.cfg(*k).to_owned())
2348 .collect(),
2349 term_width: bcx
2350 .gctx
2351 .shell()
2352 .err_width()
2353 .diagnostic_terminal_width()
2354 .unwrap_or(annotate_snippets::renderer::DEFAULT_TERM_WIDTH),
2355 }
2356 }
2357
2358 fn requested_target_names(&self) -> impl Iterator<Item = &str> {
2359 self.requested_kinds.iter().map(|kind| match kind {
2360 CompileKind::Host => &self.host_name,
2361 CompileKind::Target(target) => target.short_name(),
2362 })
2363 }
2364
2365 fn find_crate_span(&self, unrenamed: &str) -> Option<Range<usize>> {
2379 let orig_name = self.rename_table.get(unrenamed)?.as_str();
2380
2381 if let Some((k, v)) = get_key_value(&self.spans, &["dependencies", orig_name]) {
2382 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package")) {
2391 return Some(package.span());
2392 } else {
2393 return Some(k.span());
2394 }
2395 }
2396
2397 if let Some(target) = self
2402 .spans
2403 .as_ref()
2404 .get("target")
2405 .and_then(|t| t.as_ref().as_table())
2406 {
2407 for (platform, platform_table) in target.iter() {
2408 match platform.as_ref().parse::<Platform>() {
2409 Ok(Platform::Name(name)) => {
2410 if !self.requested_target_names().any(|n| n == name) {
2411 continue;
2412 }
2413 }
2414 Ok(Platform::Cfg(cfg_expr)) => {
2415 if !self.cfgs.iter().any(|cfgs| cfg_expr.matches(cfgs)) {
2416 continue;
2417 }
2418 }
2419 Err(_) => continue,
2420 }
2421
2422 let Some(platform_table) = platform_table.as_ref().as_table() else {
2423 continue;
2424 };
2425
2426 if let Some(deps) = platform_table
2427 .get("dependencies")
2428 .and_then(|d| d.as_ref().as_table())
2429 {
2430 if let Some((k, v)) = deps.get_key_value(orig_name) {
2431 if let Some(package) = v.get_ref().as_table().and_then(|t| t.get("package"))
2432 {
2433 return Some(package.span());
2434 } else {
2435 return Some(k.span());
2436 }
2437 }
2438 }
2439 }
2440 }
2441 None
2442 }
2443}
2444
2445fn replay_output_cache(
2449 package_id: PackageId,
2450 manifest: ManifestErrorContext,
2451 target: &Target,
2452 path: PathBuf,
2453 format: MessageFormat,
2454 show_diagnostics: bool,
2455) -> Work {
2456 let target = target.clone();
2457 let mut options = OutputOptions {
2458 format,
2459 cache_cell: None,
2460 show_diagnostics,
2461 warnings_seen: 0,
2462 errors_seen: 0,
2463 };
2464 Work::new(move |state| {
2465 if !path.exists() {
2466 return Ok(());
2468 }
2469 let file = paths::open(&path)?;
2473 let mut reader = std::io::BufReader::new(file);
2474 let mut line = String::new();
2475 loop {
2476 let length = reader.read_line(&mut line)?;
2477 if length == 0 {
2478 break;
2479 }
2480 let trimmed = line.trim_end_matches(&['\n', '\r'][..]);
2481 on_stderr_line(state, trimmed, package_id, &manifest, &target, &mut options)?;
2482 line.clear();
2483 }
2484 Ok(())
2485 })
2486}
2487
2488fn descriptive_pkg_name(name: &str, target: &Target, mode: &CompileMode) -> String {
2491 let desc_name = target.description_named();
2492 let mode = if mode.is_rustc_test() && !(target.is_test() || target.is_bench()) {
2493 " test"
2494 } else if mode.is_doc_test() {
2495 " doctest"
2496 } else if mode.is_doc() {
2497 " doc"
2498 } else {
2499 ""
2500 };
2501 format!("`{name}` ({desc_name}{mode})")
2502}
2503
2504pub(crate) fn apply_env_config(
2506 gctx: &crate::GlobalContext,
2507 cmd: &mut ProcessBuilder,
2508) -> CargoResult<()> {
2509 for (key, value) in gctx.env_config()?.iter() {
2510 if cmd.get_envs().contains_key(key) {
2512 continue;
2513 }
2514 cmd.env(key, value);
2515 }
2516 Ok(())
2517}
2518
2519fn should_include_scrape_units(bcx: &BuildContext<'_, '_>, unit: &Unit) -> bool {
2521 unit.mode.is_doc() && bcx.scrape_units.len() > 0 && bcx.ws.unit_needs_doc_scrape(unit)
2522}
2523
2524fn scrape_output_path(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<PathBuf> {
2526 assert!(unit.mode.is_doc() || unit.mode.is_doc_scrape());
2527 build_runner
2528 .outputs(unit)
2529 .map(|outputs| outputs[0].path.clone())
2530}
2531
2532fn rustdoc_dep_info_loc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> PathBuf {
2534 let mut loc = build_runner.files().fingerprint_file_path(unit, "");
2535 loc.set_extension("d");
2536 loc
2537}