1use std::any::{Any, type_name};
2use std::cell::{Cell, RefCell};
3use std::collections::BTreeSet;
4use std::fmt::{Debug, Write};
5use std::hash::Hash;
6use std::ops::Deref;
7use std::path::{Path, PathBuf};
8use std::sync::OnceLock;
9use std::time::{Duration, Instant};
10use std::{env, fs, iter};
11
12use clap::ValueEnum;
13#[cfg(feature = "tracing")]
14use tracing::instrument;
15
16pub(crate) use self::cargo::{Cargo, apply_pgo, cargo_profile_var};
17use crate::core::build_steps::compile::{Std, StdLink, looks_like_codegen_backend};
18use crate::core::build_steps::llvm::{LlvmKind, get_llvm_build_status};
19use crate::core::build_steps::tool::RustcPrivateCompilers;
20use crate::core::build_steps::{
21 check, clean, clippy, compile, dist, doc, gcc, install, llvm, run, setup, test, tool, vendor,
22};
23use crate::core::builder::step_stack::StepRecord;
24pub use crate::core::builder::step_stack::StepStack;
25use crate::core::compiler::Compiler;
26use crate::core::config::flags::Subcommand;
27use crate::core::config::{DryRun, TargetSelection};
28use crate::core::metadata::Crate;
29use crate::core::session::Session;
30use crate::trace;
31use crate::utils::build_stamp::BuildStamp;
32use crate::utils::cache::Cache;
33use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
34use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
35use crate::utils::tracing::format_location;
36
37mod cargo;
38mod cli_paths;
39mod step_stack;
40#[cfg(test)]
41mod tests;
42
43pub(crate) struct Builder<'a> {
46 pub sess: &'a Session,
48
49 pub top_stage: u32,
53
54 pub kind: Kind,
56
57 cache: Cache,
60
61 stack: RefCell<Vec<Box<dyn AnyDebug>>>,
64
65 time_spent_on_dependencies: Cell<Duration>,
67
68 pub paths: Vec<PathBuf>,
72
73 submodule_paths_cache: OnceLock<Vec<String>>,
75
76 #[expect(clippy::type_complexity)]
80 log_cli_step_for_tests:
81 Option<Box<dyn Fn(&CommandLineStepDescription, &[PathSet], &[TargetSelection])>>,
82}
83
84impl Deref for Builder<'_> {
85 type Target = Session;
86
87 fn deref(&self) -> &Self::Target {
88 self.sess
89 }
90}
91
92pub trait AnyDebug: Any + Debug {}
97impl<T: Any + Debug> AnyDebug for T {}
98impl dyn AnyDebug {
99 fn downcast_ref<T: Any>(&self) -> Option<&T> {
101 (self as &dyn Any).downcast_ref()
102 }
103
104 }
106
107pub(crate) trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
114 type Output: Clone;
116
117 fn run(self, builder: &Builder<'_>) -> Self::Output;
121
122 #[cfg_attr(not(any(test, feature = "tracing")), expect(dead_code))]
124 fn metadata(&self) -> Option<StepMetadata> {
125 None
126 }
127}
128
129impl<S: CommandLineStep> Step for S {
131 type Output = <S as CommandLineStep>::Output;
132
133 fn run(self, builder: &Builder<'_>) -> Self::Output {
134 <S as CommandLineStep>::run(self, builder)
135 }
136
137 fn metadata(&self) -> Option<StepMetadata> {
138 <S as CommandLineStep>::metadata(self)
139 }
140}
141
142pub(crate) trait CommandLineStep: 'static + Clone + Debug + PartialEq + Eq + Hash {
148 type Output: Clone;
150
151 const IS_HOST: bool = false;
158
159 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
162
163 fn is_default_step(_builder: &Builder<'_>) -> bool {
177 false
178 }
179
180 fn make_run(_run: RunConfig<'_>);
184
185 fn run(self, builder: &Builder<'_>) -> Self::Output;
187
188 fn metadata(&self) -> Option<StepMetadata> {
190 None
191 }
192}
193
194#[derive(Clone, Debug, PartialEq, Eq)]
196pub(crate) struct StepMetadata {
197 name: String,
198 kind: Kind,
199 target: TargetSelection,
200 built_by: Option<Compiler>,
201 stage: Option<u32>,
202 metadata: Option<String>,
204}
205
206impl StepMetadata {
207 pub fn build(name: &str, target: TargetSelection) -> Self {
208 Self::new(name, target, Kind::Build)
209 }
210
211 pub fn check(name: &str, target: TargetSelection) -> Self {
212 Self::new(name, target, Kind::Check)
213 }
214
215 pub fn clippy(name: &str, target: TargetSelection) -> Self {
216 Self::new(name, target, Kind::Clippy)
217 }
218
219 pub fn doc(name: &str, target: TargetSelection) -> Self {
220 Self::new(name, target, Kind::Doc)
221 }
222
223 pub fn dist(name: &str, target: TargetSelection) -> Self {
224 Self::new(name, target, Kind::Dist)
225 }
226
227 pub fn test(name: &str, target: TargetSelection) -> Self {
228 Self::new(name, target, Kind::Test)
229 }
230
231 pub fn run(name: &str, target: TargetSelection) -> Self {
232 Self::new(name, target, Kind::Run)
233 }
234
235 pub fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
236 Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
237 }
238
239 pub fn built_by(mut self, compiler: Compiler) -> Self {
240 self.built_by = Some(compiler);
241 self
242 }
243
244 pub fn stage(mut self, stage: u32) -> Self {
245 self.stage = Some(stage);
246 self
247 }
248
249 pub fn with_metadata(mut self, metadata: String) -> Self {
250 self.metadata = Some(metadata);
251 self
252 }
253
254 #[cfg_attr(not(any(test, feature = "tracing")), expect(dead_code))]
255 pub(crate) fn get_stage(&self) -> Option<u32> {
256 self.stage.or(self
257 .built_by
258 .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
261 }
262
263 #[cfg_attr(not(feature = "tracing"), expect(dead_code))]
264 pub(crate) fn get_name(&self) -> &str {
265 &self.name
266 }
267
268 #[cfg_attr(not(feature = "tracing"), expect(dead_code))]
269 pub(crate) fn get_target(&self) -> TargetSelection {
270 self.target
271 }
272}
273
274pub struct RunConfig<'a> {
275 pub builder: &'a Builder<'a>,
276 pub target: TargetSelection,
277 pub paths: Vec<PathSet>,
278}
279
280impl RunConfig<'_> {
281 pub fn build_triple(&self) -> TargetSelection {
282 self.builder.sess.host_target
283 }
284
285 #[track_caller]
287 pub fn cargo_crates_in_set(&self) -> Vec<String> {
288 let mut crates = Vec::new();
289 for krate in &self.paths {
290 let path = &krate.assert_single_path().path;
291
292 let crate_name = self
293 .builder
294 .crate_paths
295 .get(path)
296 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
297
298 crates.push(crate_name.to_string());
299 }
300 crates
301 }
302
303 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
310 let has_alias =
311 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
312 if !has_alias {
313 return self.cargo_crates_in_set();
314 }
315
316 let crates = match alias {
317 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
318 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
319 };
320
321 crates.into_iter().map(|krate| krate.name.to_string()).collect()
322 }
323}
324
325#[derive(Debug, Copy, Clone)]
326pub enum Alias {
327 Library,
328 Compiler,
329}
330
331impl Alias {
332 fn as_str(self) -> &'static str {
333 match self {
334 Alias::Library => "library",
335 Alias::Compiler => "compiler",
336 }
337 }
338}
339
340pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
344 if crates.is_empty() {
345 return "".into();
346 }
347 if crates.len() == 1 {
348 return crates[0].as_ref().into();
349 }
350
351 let mut descr = String::from("{");
352 descr.push_str(crates[0].as_ref());
353 for krate in &crates[1..] {
354 descr.push_str(", ");
355 descr.push_str(krate.as_ref());
356 }
357 descr.push('}');
358 descr
359}
360
361struct CommandLineStepDescription {
362 is_host: bool,
363 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
364 is_default_step_fn: fn(&Builder<'_>) -> bool,
365 make_run: fn(RunConfig<'_>),
366 name: &'static str,
367
368 #[cfg_attr(not(test), expect(dead_code, reason = "currently only needed by tests"))]
370 kind: Kind,
371}
372
373#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
374pub struct TaskPath {
375 pub path: PathBuf,
376}
377
378impl Debug for TaskPath {
379 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380 write!(f, "{}", self.path.display())
381 }
382}
383
384#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
386pub enum PathSet {
387 Set(BTreeSet<TaskPath>),
398 Suite(TaskPath),
405}
406
407impl PathSet {
408 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
409 let mut set = BTreeSet::new();
410 set.insert(TaskPath { path: path.into() });
411 PathSet::Set(set)
412 }
413
414 fn has(&self, needle: &Path) -> bool {
415 match self {
416 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle)),
417 PathSet::Suite(suite) => Self::check(suite, needle),
418 }
419 }
420
421 fn check(p: &TaskPath, needle: &Path) -> bool {
423 p.path.ends_with(needle) || p.path.starts_with(needle)
425 }
426
427 #[track_caller]
431 pub fn assert_single_path(&self) -> &TaskPath {
432 match self {
433 PathSet::Set(set) => {
434 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
435 set.iter().next().unwrap()
436 }
437 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
438 }
439 }
440}
441
442impl CommandLineStepDescription {
443 fn from<S: CommandLineStep>(kind: Kind) -> CommandLineStepDescription {
444 CommandLineStepDescription {
445 is_host: S::IS_HOST,
446 should_run: S::should_run,
447 is_default_step_fn: S::is_default_step,
448 make_run: S::make_run,
449 name: std::any::type_name::<S>(),
450 kind,
451 }
452 }
453
454 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
455 pathsets.retain(|set| !self.is_excluded(builder, set));
456
457 if pathsets.is_empty() {
458 return;
459 }
460
461 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
463
464 if let Some(ref log_cli_step) = builder.log_cli_step_for_tests {
466 log_cli_step(self, &pathsets, targets);
467 return;
469 }
470
471 for target in targets {
472 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
473 (self.make_run)(run);
474 }
475 }
476
477 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
478 if builder.config.skip.iter().any(|e| pathset.has(e)) {
479 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
480 println!("Skipping {pathset:?} because it is excluded");
481 }
482 return true;
483 }
484
485 if !builder.config.skip.is_empty()
486 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
487 {
488 builder.do_if_verbose(|| {
489 println!(
490 "{:?} not skipped for {:?} -- not in {:?}",
491 pathset, self.name, builder.config.skip
492 )
493 });
494 }
495 false
496 }
497}
498
499pub struct ShouldRun<'a> {
506 pub builder: &'a Builder<'a>,
507
508 paths: BTreeSet<PathSet>,
510}
511
512impl<'a> ShouldRun<'a> {
513 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
514 ShouldRun { builder, paths: BTreeSet::new() }
515 }
516
517 pub(crate) fn crate_or_deps(self, root_crate_name: &str) -> Self {
522 self.crate_or_deps_filtered(root_crate_name, |_: &Crate| true)
523 }
524
525 pub(crate) fn crate_or_deps_filtered(
531 mut self,
532 root_crate_name: &str,
533 crate_filter_fn: impl Fn(&Crate) -> bool,
534 ) -> Self {
535 let crates = self.builder.in_tree_crates(root_crate_name, None);
536 for krate in crates {
537 if !crate_filter_fn(krate) {
538 continue;
539 }
540
541 let path = krate.local_path(self.builder);
542 self.paths.insert(PathSet::one(path));
543 }
544 self
545 }
546
547 pub fn alias(self, alias: &str) -> Self {
549 self.assert_valid_alias(alias);
550 self.alias_without_assert(alias)
551 }
552
553 pub fn alias_without_assert(mut self, alias: &str) -> Self {
558 self.paths.insert(PathSet::Set(iter::once(TaskPath { path: alias.into() }).collect()));
559 self
560 }
561
562 fn assert_valid_alias(&self, alias: &str) {
563 assert!(
564 !self.builder.src.join(alias).exists(),
565 "use `builder.path()` for real paths: {alias}"
566 );
567 }
568
569 fn assert_valid_path(&self, path: &str) {
570 let submodules_paths = self.builder.submodule_paths();
571
572 if !submodules_paths.iter().any(|sm_p| path.contains(sm_p)) {
574 assert!(
575 self.builder.src.join(path).exists(),
576 "`should_run.path` should correspond to a real on-disk path - use `alias` if there is no relevant path: {path}"
577 );
578 }
579 }
580
581 pub fn path(mut self, path: &str) -> Self {
586 self.assert_valid_path(path);
587
588 let task = TaskPath { path: path.into() };
589 self.paths.insert(PathSet::Set(BTreeSet::from_iter([task])));
590 self
591 }
592
593 pub fn path_with_alias(mut self, path: &str, alias: &str) -> Self {
595 self.assert_valid_path(path);
596 self.assert_valid_alias(alias);
597
598 let set = [path, alias]
599 .into_iter()
600 .map(|p| TaskPath { path: PathBuf::from(p) })
601 .collect::<BTreeSet<_>>();
602 self.paths.insert(PathSet::Set(set));
603 self
604 }
605
606 pub fn multi_path(mut self, paths: &[&str]) -> Self {
608 let mut set = BTreeSet::new();
609 for path in paths {
610 self.assert_valid_path(path);
611 set.insert(TaskPath { path: (*path).into() });
612 }
613 self.paths.insert(PathSet::Set(set));
614 self
615 }
616
617 pub fn suite_path(mut self, suite: &str) -> Self {
618 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into() }));
619 self
620 }
621
622 fn default_pathsets(&self) -> Vec<PathSet> {
625 self.paths.iter().cloned().collect::<Vec<_>>()
626 }
627}
628
629#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
630pub enum Kind {
631 #[value(alias = "b")]
632 Build,
633 #[value(alias = "c")]
634 Check,
635 Clippy,
636 Fix,
637 Format,
638 #[value(alias = "t")]
639 Test,
640 Miri,
641 MiriSetup,
642 MiriTest,
643 Bench,
644 #[value(alias = "d")]
645 Doc,
646 Clean,
647 Dist,
648 Install,
649 #[value(alias = "r")]
650 Run,
651 Setup,
652 Vendor,
653 Perf,
654}
655
656impl Kind {
657 pub fn as_str(&self) -> &'static str {
658 match self {
659 Kind::Build => "build",
660 Kind::Check => "check",
661 Kind::Clippy => "clippy",
662 Kind::Fix => "fix",
663 Kind::Format => "fmt",
664 Kind::Test => "test",
665 Kind::Miri => "miri",
666 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
667 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
668 Kind::Bench => "bench",
669 Kind::Doc => "doc",
670 Kind::Clean => "clean",
671 Kind::Dist => "dist",
672 Kind::Install => "install",
673 Kind::Run => "run",
674 Kind::Setup => "setup",
675 Kind::Vendor => "vendor",
676 Kind::Perf => "perf",
677 }
678 }
679
680 pub fn description(&self) -> String {
681 match self {
682 Kind::Test => "Testing",
683 Kind::Bench => "Benchmarking",
684 Kind::Doc => "Documenting",
685 Kind::Run => "Running",
686 Kind::Clippy => "Linting",
687 Kind::Perf => "Profiling & benchmarking",
688 _ => {
689 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
690 return format!("{title_letter}{}ing", &self.as_str()[1..]);
691 }
692 }
693 .to_owned()
694 }
695
696 pub fn is_check_like(&self) -> bool {
699 match self {
700 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Doc => true,
701 Kind::Build
702 | Kind::Format
703 | Kind::Test
704 | Kind::Miri
705 | Kind::MiriSetup
706 | Kind::MiriTest
707 | Kind::Bench
708 | Kind::Clean
709 | Kind::Dist
710 | Kind::Install
711 | Kind::Run
712 | Kind::Setup
713 | Kind::Vendor
714 | Kind::Perf => false,
715 }
716 }
717}
718
719#[derive(Debug, Clone, Hash, PartialEq, Eq)]
720struct Libdir {
721 compiler: Compiler,
722 target: TargetSelection,
723}
724
725impl Step for Libdir {
726 type Output = PathBuf;
727
728 fn run(self, builder: &Builder<'_>) -> PathBuf {
729 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
730 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
731
732 if !builder.config.dry_run() {
733 if !builder.download_rustc() {
736 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
737 builder.do_if_verbose(|| {
738 eprintln!(
739 "Removing sysroot {} to avoid caching bugs",
740 sysroot_target_libdir.display()
741 )
742 });
743 let _ = fs::remove_dir_all(&sysroot_target_libdir);
744 t!(fs::create_dir_all(&sysroot_target_libdir));
745 }
746
747 if self.compiler.stage == 0 {
748 dist::maybe_install_llvm_target(
752 builder,
753 self.compiler.host,
754 &builder.sysroot(self.compiler),
755 );
756 }
757 }
758
759 sysroot
760 }
761}
762
763#[cfg(feature = "tracing")]
764pub const STEP_SPAN_TARGET: &str = "STEP";
765
766impl<'a> Builder<'a> {
767 fn get_step_descriptions(kind: Kind) -> Vec<CommandLineStepDescription> {
768 macro_rules! describe {
769 ($($rule:ty),+ $(,)?) => {{
770 vec![$(CommandLineStepDescription::from::<$rule>(kind)),+]
771 }};
772 }
773 match kind {
774 Kind::Build => describe!(
775 compile::Std,
776 compile::Rustc,
777 compile::Assemble,
778 compile::CraneliftCodegenBackend,
779 compile::GccCodegenBackend,
780 compile::StartupObjects,
781 tool::BuildManifest,
782 tool::Rustbook,
783 tool::ErrorIndex,
784 tool::UnstableBookGen,
785 tool::Tidy,
786 tool::Linkchecker,
787 tool::CargoTest,
788 tool::Compiletest,
789 tool::RemoteTestServer,
790 tool::RemoteTestClient,
791 tool::RustInstaller,
792 tool::FeaturesStatusDump,
793 tool::Cargo,
794 tool::RustAnalyzer,
795 tool::RustAnalyzerProcMacroSrv,
796 tool::Rustdoc,
797 tool::Clippy,
798 tool::CargoClippy,
799 llvm::Llvm,
800 gcc::Gcc,
801 llvm::Sanitizers,
802 tool::Rustfmt,
803 tool::Cargofmt,
804 tool::Miri,
805 tool::CargoMiri,
806 llvm::Lld,
807 llvm::Enzyme,
808 llvm::RustOffload,
809 llvm::CrtBeginEnd,
810 tool::RustdocGUITest,
811 tool::OptimizedDist,
812 tool::CoverageDump,
813 tool::LlvmBitcodeLinker,
814 tool::RustcPerf,
815 tool::WasmComponentLd,
816 tool::LldWrapper
817 ),
818 Kind::Clippy => describe!(
819 clippy::Std,
820 clippy::Rustc,
821 clippy::Bootstrap,
822 clippy::BuildHelper,
823 clippy::BuildManifest,
824 clippy::CargoMiri,
825 clippy::Clippy,
826 clippy::CodegenGcc,
827 clippy::CollectLicenseMetadata,
828 clippy::Compiletest,
829 clippy::CoverageDump,
830 clippy::Jsondocck,
831 clippy::Jsondoclint,
832 clippy::LintDocs,
833 clippy::LlvmBitcodeLinker,
834 clippy::Miri,
835 clippy::MiroptTestTools,
836 clippy::OptDist,
837 clippy::RemoteTestClient,
838 clippy::RemoteTestServer,
839 clippy::RustAnalyzer,
840 clippy::Rustdoc,
841 clippy::Rustfmt,
842 clippy::RustInstaller,
843 clippy::TestFloatParse,
844 clippy::Tidy,
845 clippy::CI,
846 ),
847 Kind::Check | Kind::Fix => describe!(
848 check::Rustc,
849 check::Rustdoc,
850 check::CraneliftCodegenBackend,
851 check::GccCodegenBackend,
852 check::Clippy,
853 check::Miri,
854 check::CargoMiri,
855 check::Priroda,
856 check::MiroptTestTools,
857 check::Rustfmt,
858 check::RustAnalyzer,
859 check::TestFloatParse,
860 check::Bootstrap,
861 check::RunMakeSupport,
862 check::Compiletest,
863 check::RustdocGuiTest,
864 check::FeaturesStatusDump,
865 check::CoverageDump,
866 check::Linkchecker,
867 check::BumpStage0,
868 check::Tidy,
869 check::Std,
876 ),
877 Kind::Test => describe!(
878 crate::core::build_steps::toolstate::ToolStateCheck,
879 test::Tidy,
880 test::BootstrapPy,
881 test::Bootstrap,
882 test::Ui,
883 test::Crashes,
884 test::Coverage,
885 test::CoverageModeAlias,
886 test::MirOpt,
887 test::CodegenLlvm,
888 test::CodegenUnits,
889 test::AssemblyLlvm,
890 test::Incremental,
891 test::Debuginfo,
892 test::UiFullDeps,
893 test::RustdocHtml,
894 test::CoverageRunRustdoc,
895 test::Pretty,
896 test::CodegenCranelift,
897 test::CodegenGCC,
898 test::Crate,
899 test::CrateLibrustc,
900 test::CrateRustdoc,
901 test::CrateRustdocJsonTypes,
902 test::CrateBootstrap,
903 test::RemoteTestClientTests,
904 test::Linkcheck,
905 test::TierCheck,
906 test::Cargotest,
907 test::Cargo,
908 test::RustAnalyzer,
909 test::ErrorIndex,
910 test::Distcheck,
911 test::Nomicon,
912 test::Reference,
913 test::RustdocBook,
914 test::RustByExample,
915 test::TheBook,
916 test::UnstableBook,
917 test::RustcBook,
918 test::LintDocs,
919 test::EmbeddedBook,
920 test::EditionGuide,
921 test::Rustfmt,
922 test::Miri,
923 test::CargoMiri,
924 test::Priroda,
925 test::Clippy,
926 test::CompiletestTest,
927 test::StdarchVerify,
928 test::CrateRunMakeSupport,
929 test::CrateBuildHelper,
930 test::RustdocJSStd,
931 test::RustdocJSNotStd,
932 test::RustdocGUI,
933 test::RustdocTheme,
934 test::RustdocUi,
935 test::RustdocJson,
936 test::HtmlCheck,
937 test::RustInstaller,
938 test::TestFloatParse,
939 test::CollectLicenseMetadata,
940 test::RunMake,
941 test::RunMakeCargo,
942 test::BuildStd,
943 test::StdSemverCheck,
944 test::IntrinsicTest,
945 ),
946 Kind::Miri => describe!(test::Crate),
947 Kind::Bench => describe!(test::Crate, test::CrateLibrustc, test::CrateRustdoc),
948 Kind::Doc => describe!(
949 doc::UnstableBook,
950 doc::UnstableBookGen,
951 doc::TheBook,
952 doc::Standalone,
953 doc::Std,
954 doc::Rustc,
955 doc::Rustdoc,
956 doc::Rustfmt,
957 doc::ErrorIndex,
958 doc::Nomicon,
959 doc::Reference,
960 doc::RustdocBook,
961 doc::RustByExample,
962 doc::RustcBook,
963 doc::Cargo,
964 doc::CargoBook,
965 doc::Clippy,
966 doc::ClippyBook,
967 doc::Miri,
968 doc::EmbeddedBook,
969 doc::EditionGuide,
970 doc::StyleGuide,
971 doc::Tidy,
972 doc::Bootstrap,
973 doc::Releases,
974 doc::RunMakeSupport,
975 doc::BuildHelper,
976 doc::Compiletest,
977 ),
978 Kind::Dist => describe!(
979 dist::Docs,
980 dist::RustcDocs,
981 dist::JsonDocs,
982 dist::Mingw,
983 dist::Rustc,
984 dist::CraneliftCodegenBackend,
985 dist::GccCodegenBackend,
986 dist::Std,
987 dist::RustcDev,
988 dist::Analysis,
989 dist::Src,
990 dist::Cargo,
991 dist::RustAnalyzer,
992 dist::Rustfmt,
993 dist::Clippy,
994 dist::Miri,
995 dist::LlvmTools,
996 dist::LlvmBitcodeLinker,
997 dist::RustDev,
998 dist::Enzyme,
999 dist::Offload,
1000 dist::Bootstrap,
1001 dist::Extended,
1002 dist::PlainSourceTarball,
1007 dist::PlainSourceTarballGpl,
1008 dist::BuildManifest,
1009 dist::ReproducibleArtifacts,
1010 dist::GccDev,
1011 dist::Gcc
1012 ),
1013 Kind::Install => describe!(
1014 install::Docs,
1015 install::Std,
1016 install::Rustc,
1021 install::RustcDev,
1022 install::Cargo,
1023 install::RustAnalyzer,
1024 install::Rustfmt,
1025 install::Clippy,
1026 install::Miri,
1027 install::LlvmTools,
1028 install::Src,
1029 install::RustcCodegenCranelift,
1030 install::LlvmBitcodeLinker
1031 ),
1032 Kind::Run => describe!(
1033 run::BuildManifest,
1034 run::BumpStage0,
1035 run::ReplaceVersionPlaceholder,
1036 run::Miri,
1037 run::CollectLicenseMetadata,
1038 run::GenerateCopyright,
1039 run::GenerateWindowsSys,
1040 run::GenerateCompletions,
1041 run::UnicodeTableGenerator,
1042 run::FeaturesStatusDump,
1043 run::CyclicStep,
1044 run::CoverageDump,
1045 run::Rustfmt,
1046 run::GenerateHelp,
1047 ),
1048 Kind::Setup => {
1049 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1050 }
1051 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1052 Kind::Vendor => describe!(vendor::Vendor),
1053 Kind::Format | Kind::Perf => vec![],
1055 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1056 }
1057 }
1058
1059 pub fn get_help(sess: &Session, kind: Kind) -> Option<String> {
1060 let step_descriptions = Builder::get_step_descriptions(kind);
1061 if step_descriptions.is_empty() {
1062 return None;
1063 }
1064
1065 let builder = Self::new_internal(sess, kind, vec![]);
1066 let builder = &builder;
1067
1068 let mut should_run = ShouldRun::new(builder);
1069 for desc in step_descriptions {
1070 should_run = (desc.should_run)(should_run);
1071 }
1072 let mut help = String::from("Available paths:\n");
1073 let mut add_path = |path: &Path| {
1074 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1075 };
1076 for pathset in should_run.paths {
1077 match pathset {
1078 PathSet::Set(set) => {
1079 for path in set {
1080 add_path(&path.path);
1081 }
1082 }
1083 PathSet::Suite(path) => {
1084 add_path(&path.path.join("..."));
1085 }
1086 }
1087 }
1088 Some(help)
1089 }
1090
1091 fn new_internal(sess: &Session, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1092 Builder {
1093 sess,
1094 top_stage: sess.config.stage,
1095 kind,
1096 cache: Cache::new(),
1097 stack: RefCell::new(Vec::new()),
1098 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1099 paths,
1100 submodule_paths_cache: Default::default(),
1101 log_cli_step_for_tests: None,
1102 }
1103 }
1104
1105 pub fn new(sess: &Session) -> Builder<'_> {
1106 let paths = &sess.config.paths;
1107 let (kind, paths) = match sess.config.cmd {
1108 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1109 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1110 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1111 Subcommand::Fix { .. } => (Kind::Fix, &paths[..]),
1112 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1113 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1114 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1115 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1116 Subcommand::Dist => (Kind::Dist, &paths[..]),
1117 Subcommand::Install => (Kind::Install, &paths[..]),
1118 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1119 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1120 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1121 Subcommand::Setup { profile: ref path } => (
1122 Kind::Setup,
1123 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1124 ),
1125 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1126 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1127 };
1128
1129 StepStack::with_current(|stack| stack.clear());
1130 Self::new_internal(sess, kind, paths.to_owned())
1131 }
1132
1133 pub fn execute_cli(&self) {
1134 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1135 }
1136
1137 pub fn run_default_doc_steps(&self) {
1139 for desc in &Builder::get_step_descriptions(Kind::Doc) {
1148 if !(desc.is_default_step_fn)(self) {
1149 continue;
1150 }
1151
1152 let should_run = (desc.should_run)(ShouldRun::new(self));
1153 let default_pathsets = should_run.default_pathsets();
1154
1155 let targets = if desc.is_host { &self.hosts } else { &self.targets };
1156 for &target in targets {
1157 let run = RunConfig { builder: self, target, paths: default_pathsets.clone() };
1158 (desc.make_run)(run);
1159 }
1160 }
1161 }
1162
1163 pub fn doc_rust_lang_org_channel(&self) -> String {
1164 let channel = match &*self.config.channel {
1165 "stable" => &self.version,
1166 "beta" => "beta",
1167 "nightly" | "dev" => "nightly",
1168 _ => "stable",
1170 };
1171
1172 format!("https://doc.rust-lang.org/{channel}")
1173 }
1174
1175 fn run_step_descriptions(&self, v: &[CommandLineStepDescription], paths: &[PathBuf]) {
1176 cli_paths::match_paths_to_steps_and_run(self, v, paths);
1177 }
1178
1179 #[track_caller]
1184 #[cfg_attr(
1185 feature = "tracing",
1186 instrument(
1187 level = "trace",
1188 name = "Builder::compiler",
1189 target = "COMPILER",
1190 skip_all,
1191 fields(
1192 stage = stage,
1193 host = ?host,
1194 ),
1195 ),
1196 )]
1197 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1198 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1199 }
1200
1201 #[track_caller]
1218 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1219 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1220 self.compiler(1, self.host_target)
1221 } else {
1222 self.compiler(stage, self.host_target)
1223 }
1224 }
1225
1226 #[track_caller]
1238 #[cfg_attr(
1239 feature = "tracing",
1240 instrument(
1241 level = "trace",
1242 name = "Builder::compiler_for",
1243 target = "COMPILER_FOR",
1244 skip_all,
1245 fields(
1246 stage = stage,
1247 host = ?host,
1248 target = ?target,
1249 ),
1250 ),
1251 )]
1252 pub fn compiler_for(
1255 &self,
1256 stage: u32,
1257 host: TargetSelection,
1258 target: TargetSelection,
1259 ) -> Compiler {
1260 let mut resolved_compiler = if self.sess.force_use_stage2(stage) {
1261 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1262 self.compiler(2, self.config.host_target)
1263 } else if self.sess.force_use_stage1(stage, target) {
1264 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1265 self.compiler(1, self.config.host_target)
1266 } else {
1267 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1268 self.compiler(stage, host)
1269 };
1270
1271 if stage != resolved_compiler.stage {
1272 resolved_compiler.forced_compiler(true);
1273 }
1274
1275 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1276 resolved_compiler
1277 }
1278
1279 #[track_caller]
1286 #[cfg_attr(
1287 feature = "tracing",
1288 instrument(
1289 level = "trace",
1290 name = "Builder::std",
1291 target = "STD",
1292 skip_all,
1293 fields(
1294 compiler = ?compiler,
1295 target = ?target,
1296 ),
1297 ),
1298 )]
1299 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1300 if compiler.stage == 0 {
1310 if target != compiler.host {
1311 if self.local_rebuild {
1312 self.ensure(Std::new(compiler, target))
1313 } else {
1314 panic!(
1315 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1316You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1317Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1318",
1319 compiler.host
1320 )
1321 }
1322 } else {
1323 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1325 None
1326 }
1327 } else {
1328 self.ensure(Std::new(compiler, target))
1331 }
1332 }
1333
1334 #[track_caller]
1335 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1336 self.ensure(compile::Sysroot::new(compiler))
1337 }
1338
1339 #[track_caller]
1341 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1342 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1343 }
1344
1345 #[track_caller]
1348 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1349 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1350 }
1351
1352 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1353 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1354 }
1355
1356 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1362 if compiler.is_snapshot(self) {
1363 self.rustc_snapshot_libdir()
1364 } else {
1365 match self.config.libdir_relative() {
1366 Some(relative_libdir) if compiler.stage >= 1 => {
1367 self.sysroot(compiler).join(relative_libdir)
1368 }
1369 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1370 }
1371 }
1372 }
1373
1374 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1380 if compiler.is_snapshot(self) {
1381 libdir(self.config.host_target).as_ref()
1382 } else {
1383 match self.config.libdir_relative() {
1384 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1385 _ => libdir(compiler.host).as_ref(),
1386 }
1387 }
1388 }
1389
1390 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1395 match self.config.libdir_relative() {
1396 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1397 _ if compiler.stage == 0 => &self.sess.initial_relative_libdir,
1398 _ => Path::new("lib"),
1399 }
1400 }
1401
1402 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1403 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1404
1405 if get_llvm_build_status(self, compiler.host).llvm_output().kind()
1408 == LlvmKind::DownloadedFromCi
1409 {
1410 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1411 dylib_dirs.push(ci_llvm_lib);
1412 }
1413
1414 dylib_dirs
1415 }
1416
1417 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1420 if cfg!(any(windows, target_os = "cygwin")) {
1424 return;
1425 }
1426
1427 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1428 }
1429
1430 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1432 if compiler.is_snapshot(self) {
1433 self.initial_rustc.clone()
1434 } else {
1435 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1436 }
1437 }
1438
1439 pub fn rustc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1442 let mut cmd = command(self.rustc(compiler));
1443 self.add_rustc_lib_path(compiler, &mut cmd);
1444 cmd
1445 }
1446
1447 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1449 fs::read_dir(self.sysroot_codegen_backends(compiler))
1450 .into_iter()
1451 .flatten()
1452 .filter_map(Result::ok)
1453 .filter(|path| looks_like_codegen_backend(&path.path()))
1454 .map(|entry| entry.path())
1455 }
1456
1457 #[track_caller]
1461 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1462 self.ensure(tool::Rustdoc { target_compiler })
1463 }
1464
1465 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1466 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1467
1468 let compilers = RustcPrivateCompilers::new(self, run_compiler.stage, self.sess.host_target);
1469 assert_eq!(run_compiler, compilers.target_compiler());
1470
1471 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1473 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1474 let mut cmd = command(cargo_miri.tool_path);
1476 cmd.env("MIRI", &miri.tool_path);
1477 cmd.env("CARGO", &self.initial_cargo);
1478 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1487 cmd
1488 }
1489
1490 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1493 if build_compiler.stage == 0 {
1494 let cargo_clippy =
1495 self.config.external_cargo_clippy.clone().unwrap_or_else(|| {
1496 self.sess.config.download_clippy(&self.sess.initial_sysroot)
1497 });
1498
1499 let mut cmd = command(cargo_clippy);
1500 cmd.env("CARGO", &self.initial_cargo);
1501 return cmd;
1502 }
1503
1504 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1508
1509 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1510 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1511 let mut dylib_path = helpers::dylib_path();
1512 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1513
1514 let mut cmd = command(cargo_clippy.tool_path);
1515 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1516 cmd.env("CARGO", &self.initial_cargo);
1517 cmd
1518 }
1519
1520 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1521 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1522 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1523 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1524 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1527 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1528 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1529 .env("RUSTC_BOOTSTRAP", "1");
1530
1531 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1532
1533 if self.config.deny_warnings {
1534 cmd.arg("-Dwarnings");
1535 }
1536 cmd.arg("-Znormalize-docs");
1537 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1538 cmd
1539 }
1540
1541 pub fn is_llvm_enabled_for(&self, target: TargetSelection) -> bool {
1546 self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run()
1547 }
1548
1549 pub fn host_llvm_config(&self) -> PathBuf {
1551 self.ensure(llvm::Llvm { target: self.host_target }).llvm_config().to_owned()
1552 }
1553
1554 pub fn require_and_update_all_submodules(&self) {
1557 for submodule in self.submodule_paths() {
1558 self.require_submodule(submodule, None);
1559 }
1560 }
1561
1562 pub fn submodule_paths(&self) -> &[String] {
1564 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1565 }
1566
1567 #[track_caller]
1571 pub(crate) fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1572 {
1573 let mut stack = self.stack.borrow_mut();
1574 for stack_step in stack.iter() {
1575 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1577 continue;
1578 }
1579 let mut out = String::new();
1580 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1581 for el in stack.iter().rev() {
1582 out += &format!("\t{el:?}\n");
1583 }
1584 panic!("{}", out);
1585 }
1586 if let Some(out) = self.cache.get(&step) {
1587 #[cfg(feature = "tracing")]
1588 {
1589 if let Some(parent) = stack.last() {
1590 let mut graph = self.sess.step_graph.borrow_mut();
1591 graph.register_cached_step(&step, parent, self.config.dry_run());
1592 }
1593 }
1594 return out;
1595 }
1596
1597 #[cfg(feature = "tracing")]
1598 {
1599 let parent = stack.last();
1600 let mut graph = self.sess.step_graph.borrow_mut();
1601 graph.register_step_execution(&step, parent, self.config.dry_run());
1602 }
1603
1604 let location = format_location(*std::panic::Location::caller());
1607 StepStack::with_current(|stack| {
1608 stack.push(StepRecord { info: pretty_print_step(&step), location });
1609 });
1610 stack.push(Box::new(step.clone()));
1611 }
1612
1613 #[cfg(feature = "build-metrics")]
1614 self.metrics.enter_step(&step, self);
1615
1616 if self.config.print_step_timings && !self.config.dry_run() {
1617 println!("[TIMING:start] {}", pretty_print_step(&step));
1618 }
1619
1620 let (out, dur) = {
1621 let start = Instant::now();
1622 let zero = Duration::new(0, 0);
1623 let parent = self.time_spent_on_dependencies.replace(zero);
1624
1625 #[cfg(feature = "tracing")]
1626 let _span = {
1627 let span = tracing::info_span!(
1629 target: STEP_SPAN_TARGET,
1630 "step",
1633 step_name = pretty_step_name::<S>(),
1634 args = step_debug_args(&step),
1635 location = format_location(*std::panic::Location::caller())
1636 );
1637 span.entered()
1638 };
1639
1640 let out = step.clone().run(self);
1641 let dur = start.elapsed();
1642 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1643 (out, dur.saturating_sub(deps))
1644 };
1645
1646 if self.config.print_step_timings && !self.config.dry_run() {
1647 println!(
1648 "[TIMING:end] {} -- {}.{:03}",
1649 pretty_print_step(&step),
1650 dur.as_secs(),
1651 dur.subsec_millis()
1652 );
1653 }
1654
1655 #[cfg(feature = "build-metrics")]
1656 self.metrics.exit_step(self);
1657
1658 {
1659 let mut stack = self.stack.borrow_mut();
1660 let cur_step = stack.pop().expect("step stack empty");
1661 assert_eq!(cur_step.downcast_ref(), Some(&step));
1662
1663 StepStack::with_current(|stack| {
1664 stack.pop();
1665 });
1666 }
1667 self.cache.put(step, out.clone());
1668 out
1669 }
1670
1671 pub(crate) fn ensure_if_default<T, S: CommandLineStep<Output = T>>(
1675 &'a self,
1676 step: S,
1677 kind: Kind,
1678 ) -> Option<S::Output> {
1679 let desc = CommandLineStepDescription::from::<S>(kind);
1680 let should_run = (desc.should_run)(ShouldRun::new(self));
1681
1682 for pathset in &should_run.paths {
1684 if desc.is_excluded(self, pathset) {
1685 return None;
1686 }
1687 }
1688
1689 if (desc.is_default_step_fn)(self) { Some(self.ensure(step)) } else { None }
1691 }
1692
1693 pub(crate) fn was_invoked_explicitly<S: CommandLineStep>(&'a self, kind: Kind) -> bool {
1695 let desc = CommandLineStepDescription::from::<S>(kind);
1696 let should_run = (desc.should_run)(ShouldRun::new(self));
1697
1698 for path in &self.paths {
1699 if should_run.paths.iter().any(|s| s.has(path))
1700 && !desc.is_excluded(self, &PathSet::Suite(TaskPath { path: path.clone() }))
1701 {
1702 return true;
1703 }
1704 }
1705
1706 false
1707 }
1708
1709 pub(crate) fn maybe_open_in_browser<S: CommandLineStep>(&self, path: impl AsRef<Path>) {
1710 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1711 self.open_in_browser(path);
1712 } else {
1713 self.info(&format!("Doc path: {}", path.as_ref().display()));
1714 }
1715 }
1716
1717 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1718 let path = path.as_ref();
1719
1720 if self.config.dry_run() || !self.config.cmd.open() {
1721 self.info(&format!("Doc path: {}", path.display()));
1722 return;
1723 }
1724
1725 self.info(&format!("Opening doc {}", path.display()));
1726 if let Err(err) = opener::open(path) {
1727 self.info(&format!("{err}\n"));
1728 }
1729 }
1730
1731 pub fn exec_ctx(&self) -> &ExecutionContext {
1732 &self.config.exec_ctx
1733 }
1734}
1735
1736pub fn pretty_step_name<S: Step>() -> String {
1738 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1740 path.into_iter().rev().collect::<Vec<_>>().join("::")
1741}
1742
1743fn step_debug_args<S: Step>(step: &S) -> String {
1745 let step_dbg_repr = format!("{step:?}");
1746
1747 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1749 (Some(brace_start), Some(brace_end)) => {
1750 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1751 }
1752 _ => String::new(),
1753 }
1754}
1755
1756fn pretty_print_step<S: Step>(step: &S) -> String {
1757 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1758}
1759
1760impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1761 fn as_ref(&self) -> &ExecutionContext {
1762 self.exec_ctx()
1763 }
1764}