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
348 let mut descr = String::from("{");
349 descr.push_str(crates[0].as_ref());
350 for krate in &crates[1..] {
351 descr.push_str(", ");
352 descr.push_str(krate.as_ref());
353 }
354 descr.push('}');
355 descr
356}
357
358struct CommandLineStepDescription {
359 is_host: bool,
360 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
361 is_default_step_fn: fn(&Builder<'_>) -> bool,
362 make_run: fn(RunConfig<'_>),
363 name: &'static str,
364
365 #[cfg_attr(not(test), expect(dead_code, reason = "currently only needed by tests"))]
367 kind: Kind,
368}
369
370#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
371pub struct TaskPath {
372 pub path: PathBuf,
373}
374
375impl Debug for TaskPath {
376 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377 write!(f, "{}", self.path.display())
378 }
379}
380
381#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
383pub enum PathSet {
384 Set(BTreeSet<TaskPath>),
395 Suite(TaskPath),
402}
403
404impl PathSet {
405 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
406 let mut set = BTreeSet::new();
407 set.insert(TaskPath { path: path.into() });
408 PathSet::Set(set)
409 }
410
411 fn has(&self, needle: &Path) -> bool {
412 match self {
413 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle)),
414 PathSet::Suite(suite) => Self::check(suite, needle),
415 }
416 }
417
418 fn check(p: &TaskPath, needle: &Path) -> bool {
420 p.path.ends_with(needle) || p.path.starts_with(needle)
422 }
423
424 #[track_caller]
428 pub fn assert_single_path(&self) -> &TaskPath {
429 match self {
430 PathSet::Set(set) => {
431 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
432 set.iter().next().unwrap()
433 }
434 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
435 }
436 }
437}
438
439impl CommandLineStepDescription {
440 fn from<S: CommandLineStep>(kind: Kind) -> CommandLineStepDescription {
441 CommandLineStepDescription {
442 is_host: S::IS_HOST,
443 should_run: S::should_run,
444 is_default_step_fn: S::is_default_step,
445 make_run: S::make_run,
446 name: std::any::type_name::<S>(),
447 kind,
448 }
449 }
450
451 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
452 pathsets.retain(|set| !self.is_excluded(builder, set));
453
454 if pathsets.is_empty() {
455 return;
456 }
457
458 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
460
461 if let Some(ref log_cli_step) = builder.log_cli_step_for_tests {
463 log_cli_step(self, &pathsets, targets);
464 return;
466 }
467
468 for target in targets {
469 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
470 (self.make_run)(run);
471 }
472 }
473
474 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
475 if builder.config.skip.iter().any(|e| pathset.has(e)) {
476 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
477 println!("Skipping {pathset:?} because it is excluded");
478 }
479 return true;
480 }
481
482 if !builder.config.skip.is_empty()
483 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
484 {
485 builder.do_if_verbose(|| {
486 println!(
487 "{:?} not skipped for {:?} -- not in {:?}",
488 pathset, self.name, builder.config.skip
489 )
490 });
491 }
492 false
493 }
494}
495
496pub struct ShouldRun<'a> {
503 pub builder: &'a Builder<'a>,
504
505 paths: BTreeSet<PathSet>,
507}
508
509impl<'a> ShouldRun<'a> {
510 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
511 ShouldRun { builder, paths: BTreeSet::new() }
512 }
513
514 pub(crate) fn crate_or_deps(self, root_crate_name: &str) -> Self {
519 self.crate_or_deps_filtered(root_crate_name, |_: &Crate| true)
520 }
521
522 pub(crate) fn crate_or_deps_filtered(
528 mut self,
529 root_crate_name: &str,
530 crate_filter_fn: impl Fn(&Crate) -> bool,
531 ) -> Self {
532 let crates = self.builder.in_tree_crates(root_crate_name, None);
533 for krate in crates {
534 if !crate_filter_fn(krate) {
535 continue;
536 }
537
538 let path = krate.local_path(self.builder);
539 self.paths.insert(PathSet::one(path));
540 }
541 self
542 }
543
544 pub fn alias(self, alias: &str) -> Self {
546 self.assert_valid_alias(alias);
547 self.alias_without_assert(alias)
548 }
549
550 pub fn alias_without_assert(mut self, alias: &str) -> Self {
555 self.paths.insert(PathSet::Set(iter::once(TaskPath { path: alias.into() }).collect()));
556 self
557 }
558
559 fn assert_valid_alias(&self, alias: &str) {
560 assert!(
561 !self.builder.src.join(alias).exists(),
562 "use `builder.path()` for real paths: {alias}"
563 );
564 }
565
566 fn assert_valid_path(&self, path: &str) {
567 let submodules_paths = self.builder.submodule_paths();
568
569 if !submodules_paths.iter().any(|sm_p| path.contains(sm_p)) {
571 assert!(
572 self.builder.src.join(path).exists(),
573 "`should_run.path` should correspond to a real on-disk path - use `alias` if there is no relevant path: {path}"
574 );
575 }
576 }
577
578 pub fn path(mut self, path: &str) -> Self {
583 self.assert_valid_path(path);
584
585 let task = TaskPath { path: path.into() };
586 self.paths.insert(PathSet::Set(BTreeSet::from_iter([task])));
587 self
588 }
589
590 pub fn path_with_alias(mut self, path: &str, alias: &str) -> Self {
592 self.assert_valid_path(path);
593 self.assert_valid_alias(alias);
594
595 let set = [path, alias]
596 .into_iter()
597 .map(|p| TaskPath { path: PathBuf::from(p) })
598 .collect::<BTreeSet<_>>();
599 self.paths.insert(PathSet::Set(set));
600 self
601 }
602
603 pub fn multi_path(mut self, paths: &[&str]) -> Self {
605 let mut set = BTreeSet::new();
606 for path in paths {
607 self.assert_valid_path(path);
608 set.insert(TaskPath { path: (*path).into() });
609 }
610 self.paths.insert(PathSet::Set(set));
611 self
612 }
613
614 pub fn suite_path(mut self, suite: &str) -> Self {
615 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into() }));
616 self
617 }
618
619 fn default_pathsets(&self) -> Vec<PathSet> {
622 self.paths.iter().cloned().collect::<Vec<_>>()
623 }
624}
625
626#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
627pub enum Kind {
628 #[value(alias = "b")]
629 Build,
630 #[value(alias = "c")]
631 Check,
632 Clippy,
633 Fix,
634 Format,
635 #[value(alias = "t")]
636 Test,
637 Miri,
638 MiriSetup,
639 MiriTest,
640 Bench,
641 #[value(alias = "d")]
642 Doc,
643 Clean,
644 Dist,
645 Install,
646 #[value(alias = "r")]
647 Run,
648 Setup,
649 Vendor,
650 Perf,
651}
652
653impl Kind {
654 pub fn as_str(&self) -> &'static str {
655 match self {
656 Kind::Build => "build",
657 Kind::Check => "check",
658 Kind::Clippy => "clippy",
659 Kind::Fix => "fix",
660 Kind::Format => "fmt",
661 Kind::Test => "test",
662 Kind::Miri => "miri",
663 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
664 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
665 Kind::Bench => "bench",
666 Kind::Doc => "doc",
667 Kind::Clean => "clean",
668 Kind::Dist => "dist",
669 Kind::Install => "install",
670 Kind::Run => "run",
671 Kind::Setup => "setup",
672 Kind::Vendor => "vendor",
673 Kind::Perf => "perf",
674 }
675 }
676
677 pub fn description(&self) -> String {
678 match self {
679 Kind::Test => "Testing",
680 Kind::Bench => "Benchmarking",
681 Kind::Doc => "Documenting",
682 Kind::Run => "Running",
683 Kind::Clippy => "Linting",
684 Kind::Perf => "Profiling & benchmarking",
685 _ => {
686 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
687 return format!("{title_letter}{}ing", &self.as_str()[1..]);
688 }
689 }
690 .to_owned()
691 }
692
693 pub fn is_check_like(&self) -> bool {
696 match self {
697 Kind::Check | Kind::Clippy | Kind::Fix | Kind::Doc => true,
698 Kind::Build
699 | Kind::Format
700 | Kind::Test
701 | Kind::Miri
702 | Kind::MiriSetup
703 | Kind::MiriTest
704 | Kind::Bench
705 | Kind::Clean
706 | Kind::Dist
707 | Kind::Install
708 | Kind::Run
709 | Kind::Setup
710 | Kind::Vendor
711 | Kind::Perf => false,
712 }
713 }
714}
715
716#[derive(Debug, Clone, Hash, PartialEq, Eq)]
717struct Libdir {
718 compiler: Compiler,
719 target: TargetSelection,
720}
721
722impl Step for Libdir {
723 type Output = PathBuf;
724
725 fn run(self, builder: &Builder<'_>) -> PathBuf {
726 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
727 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
728
729 if !builder.config.dry_run() {
730 if !builder.download_rustc() {
733 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
734 builder.do_if_verbose(|| {
735 eprintln!(
736 "Removing sysroot {} to avoid caching bugs",
737 sysroot_target_libdir.display()
738 )
739 });
740 let _ = fs::remove_dir_all(&sysroot_target_libdir);
741 t!(fs::create_dir_all(&sysroot_target_libdir));
742 }
743
744 if self.compiler.stage == 0 {
745 dist::maybe_install_llvm_target(
749 builder,
750 self.compiler.host,
751 &builder.sysroot(self.compiler),
752 );
753 }
754 }
755
756 sysroot
757 }
758}
759
760#[cfg(feature = "tracing")]
761pub const STEP_SPAN_TARGET: &str = "STEP";
762
763impl<'a> Builder<'a> {
764 fn get_step_descriptions(kind: Kind) -> Vec<CommandLineStepDescription> {
765 macro_rules! describe {
766 ($($rule:ty),+ $(,)?) => {{
767 vec![$(CommandLineStepDescription::from::<$rule>(kind)),+]
768 }};
769 }
770 match kind {
771 Kind::Build => describe!(
772 compile::Std,
773 compile::Rustc,
774 compile::Assemble,
775 compile::CraneliftCodegenBackend,
776 compile::GccCodegenBackend,
777 compile::StartupObjects,
778 tool::BuildManifest,
779 tool::Rustbook,
780 tool::ErrorIndex,
781 tool::UnstableBookGen,
782 tool::Tidy,
783 tool::Linkchecker,
784 tool::CargoTest,
785 tool::Compiletest,
786 tool::RemoteTestServer,
787 tool::RemoteTestClient,
788 tool::RustInstaller,
789 tool::FeaturesStatusDump,
790 tool::Cargo,
791 tool::RustAnalyzer,
792 tool::RustAnalyzerProcMacroSrv,
793 tool::Rustdoc,
794 tool::Clippy,
795 tool::CargoClippy,
796 llvm::Llvm,
797 gcc::Gcc,
798 llvm::Sanitizers,
799 tool::Rustfmt,
800 tool::Cargofmt,
801 tool::Miri,
802 tool::CargoMiri,
803 llvm::Lld,
804 llvm::Enzyme,
805 llvm::RustOffload,
806 llvm::CrtBeginEnd,
807 tool::RustdocGUITest,
808 tool::OptimizedDist,
809 tool::CoverageDump,
810 tool::LlvmBitcodeLinker,
811 tool::RustcPerf,
812 tool::WasmComponentLd,
813 tool::LldWrapper
814 ),
815 Kind::Clippy => describe!(
816 clippy::Std,
817 clippy::Rustc,
818 clippy::Bootstrap,
819 clippy::BuildHelper,
820 clippy::BuildManifest,
821 clippy::CargoMiri,
822 clippy::Clippy,
823 clippy::CodegenGcc,
824 clippy::CollectLicenseMetadata,
825 clippy::Compiletest,
826 clippy::CoverageDump,
827 clippy::Jsondocck,
828 clippy::Jsondoclint,
829 clippy::LintDocs,
830 clippy::LlvmBitcodeLinker,
831 clippy::Miri,
832 clippy::MiroptTestTools,
833 clippy::OptDist,
834 clippy::RemoteTestClient,
835 clippy::RemoteTestServer,
836 clippy::RustAnalyzer,
837 clippy::Rustdoc,
838 clippy::Rustfmt,
839 clippy::RustInstaller,
840 clippy::TestFloatParse,
841 clippy::Tidy,
842 clippy::CI,
843 ),
844 Kind::Check | Kind::Fix => describe!(
845 check::Rustc,
846 check::Rustdoc,
847 check::CraneliftCodegenBackend,
848 check::GccCodegenBackend,
849 check::Clippy,
850 check::Miri,
851 check::CargoMiri,
852 check::Priroda,
853 check::MiroptTestTools,
854 check::Rustfmt,
855 check::RustAnalyzer,
856 check::TestFloatParse,
857 check::Bootstrap,
858 check::RunMakeSupport,
859 check::Compiletest,
860 check::RustdocGuiTest,
861 check::FeaturesStatusDump,
862 check::CoverageDump,
863 check::Linkchecker,
864 check::BumpStage0,
865 check::Tidy,
866 check::Std,
873 ),
874 Kind::Test => describe!(
875 crate::core::build_steps::toolstate::ToolStateCheck,
876 test::Tidy,
877 test::BootstrapPy,
878 test::Bootstrap,
879 test::Ui,
880 test::Crashes,
881 test::Coverage,
882 test::CoverageModeAlias,
883 test::MirOpt,
884 test::CodegenLlvm,
885 test::CodegenUnits,
886 test::AssemblyLlvm,
887 test::Incremental,
888 test::Debuginfo,
889 test::UiFullDeps,
890 test::RustdocHtml,
891 test::CoverageRunRustdoc,
892 test::Pretty,
893 test::CodegenCranelift,
894 test::CodegenGCC,
895 test::Crate,
896 test::CrateLibrustc,
897 test::CrateRustdoc,
898 test::CrateRustdocJsonTypes,
899 test::CrateBootstrap,
900 test::RemoteTestClientTests,
901 test::Linkcheck,
902 test::TierCheck,
903 test::Cargotest,
904 test::Cargo,
905 test::RustAnalyzer,
906 test::ErrorIndex,
907 test::Distcheck,
908 test::Nomicon,
909 test::Reference,
910 test::RustdocBook,
911 test::RustByExample,
912 test::TheBook,
913 test::UnstableBook,
914 test::RustcBook,
915 test::LintDocs,
916 test::EmbeddedBook,
917 test::EditionGuide,
918 test::Rustfmt,
919 test::Miri,
920 test::CargoMiri,
921 test::Priroda,
922 test::Clippy,
923 test::CompiletestTest,
924 test::StdarchVerify,
925 test::CrateRunMakeSupport,
926 test::CrateBuildHelper,
927 test::RustdocJSStd,
928 test::RustdocJSNotStd,
929 test::RustdocGUI,
930 test::RustdocTheme,
931 test::RustdocUi,
932 test::RustdocJson,
933 test::HtmlCheck,
934 test::RustInstaller,
935 test::TestFloatParse,
936 test::CollectLicenseMetadata,
937 test::RunMake,
938 test::RunMakeCargo,
939 test::BuildStd,
940 test::StdSemverCheck,
941 test::IntrinsicTest,
942 ),
943 Kind::Miri => describe!(test::Crate),
944 Kind::Bench => describe!(test::Crate, test::CrateLibrustc, test::CrateRustdoc),
945 Kind::Doc => describe!(
946 doc::UnstableBook,
947 doc::UnstableBookGen,
948 doc::TheBook,
949 doc::Standalone,
950 doc::Std,
951 doc::Rustc,
952 doc::Rustdoc,
953 doc::Rustfmt,
954 doc::ErrorIndex,
955 doc::Nomicon,
956 doc::Reference,
957 doc::RustdocBook,
958 doc::RustByExample,
959 doc::RustcBook,
960 doc::Cargo,
961 doc::CargoBook,
962 doc::Clippy,
963 doc::ClippyBook,
964 doc::Miri,
965 doc::EmbeddedBook,
966 doc::EditionGuide,
967 doc::StyleGuide,
968 doc::Tidy,
969 doc::Bootstrap,
970 doc::Releases,
971 doc::RunMakeSupport,
972 doc::BuildHelper,
973 doc::Compiletest,
974 ),
975 Kind::Dist => describe!(
976 dist::Docs,
977 dist::RustcDocs,
978 dist::JsonDocs,
979 dist::Mingw,
980 dist::Rustc,
981 dist::CraneliftCodegenBackend,
982 dist::GccCodegenBackend,
983 dist::Std,
984 dist::RustcDev,
985 dist::Analysis,
986 dist::Src,
987 dist::Cargo,
988 dist::RustAnalyzer,
989 dist::Rustfmt,
990 dist::Clippy,
991 dist::Miri,
992 dist::LlvmTools,
993 dist::LlvmBitcodeLinker,
994 dist::RustDev,
995 dist::Enzyme,
996 dist::Offload,
997 dist::Bootstrap,
998 dist::Extended,
999 dist::PlainSourceTarball,
1004 dist::PlainSourceTarballGpl,
1005 dist::BuildManifest,
1006 dist::ReproducibleArtifacts,
1007 dist::GccDev,
1008 dist::Gcc
1009 ),
1010 Kind::Install => describe!(
1011 install::Docs,
1012 install::Std,
1013 install::Rustc,
1018 install::RustcDev,
1019 install::Cargo,
1020 install::RustAnalyzer,
1021 install::Rustfmt,
1022 install::Clippy,
1023 install::Miri,
1024 install::LlvmTools,
1025 install::Src,
1026 install::RustcCodegenCranelift,
1027 install::LlvmBitcodeLinker
1028 ),
1029 Kind::Run => describe!(
1030 run::BuildManifest,
1031 run::BumpStage0,
1032 run::ReplaceVersionPlaceholder,
1033 run::Miri,
1034 run::CollectLicenseMetadata,
1035 run::GenerateCopyright,
1036 run::GenerateWindowsSys,
1037 run::GenerateCompletions,
1038 run::UnicodeTableGenerator,
1039 run::FeaturesStatusDump,
1040 run::CyclicStep,
1041 run::CoverageDump,
1042 run::Rustfmt,
1043 run::GenerateHelp,
1044 ),
1045 Kind::Setup => {
1046 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1047 }
1048 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1049 Kind::Vendor => describe!(vendor::Vendor),
1050 Kind::Format | Kind::Perf => vec![],
1052 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1053 }
1054 }
1055
1056 pub fn get_help(sess: &Session, kind: Kind) -> Option<String> {
1057 let step_descriptions = Builder::get_step_descriptions(kind);
1058 if step_descriptions.is_empty() {
1059 return None;
1060 }
1061
1062 let builder = Self::new_internal(sess, kind, vec![]);
1063 let builder = &builder;
1064
1065 let mut should_run = ShouldRun::new(builder);
1066 for desc in step_descriptions {
1067 should_run = (desc.should_run)(should_run);
1068 }
1069 let mut help = String::from("Available paths:\n");
1070 let mut add_path = |path: &Path| {
1071 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1072 };
1073 for pathset in should_run.paths {
1074 match pathset {
1075 PathSet::Set(set) => {
1076 for path in set {
1077 add_path(&path.path);
1078 }
1079 }
1080 PathSet::Suite(path) => {
1081 add_path(&path.path.join("..."));
1082 }
1083 }
1084 }
1085 Some(help)
1086 }
1087
1088 fn new_internal(sess: &Session, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1089 Builder {
1090 sess,
1091 top_stage: sess.config.stage,
1092 kind,
1093 cache: Cache::new(),
1094 stack: RefCell::new(Vec::new()),
1095 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1096 paths,
1097 submodule_paths_cache: Default::default(),
1098 log_cli_step_for_tests: None,
1099 }
1100 }
1101
1102 pub fn new(sess: &Session) -> Builder<'_> {
1103 let paths = &sess.config.paths;
1104 let (kind, paths) = match sess.config.cmd {
1105 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1106 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1107 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1108 Subcommand::Fix { .. } => (Kind::Fix, &paths[..]),
1109 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1110 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1111 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1112 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1113 Subcommand::Dist => (Kind::Dist, &paths[..]),
1114 Subcommand::Install => (Kind::Install, &paths[..]),
1115 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1116 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1117 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1118 Subcommand::Setup { profile: ref path } => (
1119 Kind::Setup,
1120 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1121 ),
1122 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1123 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1124 };
1125
1126 StepStack::with_current(|stack| stack.clear());
1127 Self::new_internal(sess, kind, paths.to_owned())
1128 }
1129
1130 pub fn execute_cli(&self) {
1131 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1132 }
1133
1134 pub fn run_default_doc_steps(&self) {
1136 for desc in &Builder::get_step_descriptions(Kind::Doc) {
1145 if !(desc.is_default_step_fn)(self) {
1146 continue;
1147 }
1148
1149 let should_run = (desc.should_run)(ShouldRun::new(self));
1150 let default_pathsets = should_run.default_pathsets();
1151
1152 let targets = if desc.is_host { &self.hosts } else { &self.targets };
1153 for &target in targets {
1154 let run = RunConfig { builder: self, target, paths: default_pathsets.clone() };
1155 (desc.make_run)(run);
1156 }
1157 }
1158 }
1159
1160 pub fn doc_rust_lang_org_channel(&self) -> String {
1161 let channel = match &*self.config.channel {
1162 "stable" => &self.version,
1163 "beta" => "beta",
1164 "nightly" | "dev" => "nightly",
1165 _ => "stable",
1167 };
1168
1169 format!("https://doc.rust-lang.org/{channel}")
1170 }
1171
1172 fn run_step_descriptions(&self, v: &[CommandLineStepDescription], paths: &[PathBuf]) {
1173 cli_paths::match_paths_to_steps_and_run(self, v, paths);
1174 }
1175
1176 #[track_caller]
1181 #[cfg_attr(
1182 feature = "tracing",
1183 instrument(
1184 level = "trace",
1185 name = "Builder::compiler",
1186 target = "COMPILER",
1187 skip_all,
1188 fields(
1189 stage = stage,
1190 host = ?host,
1191 ),
1192 ),
1193 )]
1194 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1195 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1196 }
1197
1198 #[track_caller]
1215 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1216 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1217 self.compiler(1, self.host_target)
1218 } else {
1219 self.compiler(stage, self.host_target)
1220 }
1221 }
1222
1223 #[track_caller]
1235 #[cfg_attr(
1236 feature = "tracing",
1237 instrument(
1238 level = "trace",
1239 name = "Builder::compiler_for",
1240 target = "COMPILER_FOR",
1241 skip_all,
1242 fields(
1243 stage = stage,
1244 host = ?host,
1245 target = ?target,
1246 ),
1247 ),
1248 )]
1249 pub fn compiler_for(
1252 &self,
1253 stage: u32,
1254 host: TargetSelection,
1255 target: TargetSelection,
1256 ) -> Compiler {
1257 let mut resolved_compiler = if self.sess.force_use_stage2(stage) {
1258 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1259 self.compiler(2, self.config.host_target)
1260 } else if self.sess.force_use_stage1(stage, target) {
1261 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1262 self.compiler(1, self.config.host_target)
1263 } else {
1264 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1265 self.compiler(stage, host)
1266 };
1267
1268 if stage != resolved_compiler.stage {
1269 resolved_compiler.forced_compiler(true);
1270 }
1271
1272 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1273 resolved_compiler
1274 }
1275
1276 #[track_caller]
1283 #[cfg_attr(
1284 feature = "tracing",
1285 instrument(
1286 level = "trace",
1287 name = "Builder::std",
1288 target = "STD",
1289 skip_all,
1290 fields(
1291 compiler = ?compiler,
1292 target = ?target,
1293 ),
1294 ),
1295 )]
1296 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1297 if compiler.stage == 0 {
1307 if target != compiler.host {
1308 if self.local_rebuild {
1309 self.ensure(Std::new(compiler, target))
1310 } else {
1311 panic!(
1312 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1313You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1314Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1315",
1316 compiler.host
1317 )
1318 }
1319 } else {
1320 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1322 None
1323 }
1324 } else {
1325 self.ensure(Std::new(compiler, target))
1328 }
1329 }
1330
1331 #[track_caller]
1332 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1333 self.ensure(compile::Sysroot::new(compiler))
1334 }
1335
1336 #[track_caller]
1338 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1339 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1340 }
1341
1342 #[track_caller]
1345 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1346 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1347 }
1348
1349 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1350 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1351 }
1352
1353 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1359 if compiler.is_snapshot(self) {
1360 self.rustc_snapshot_libdir()
1361 } else {
1362 match self.config.libdir_relative() {
1363 Some(relative_libdir) if compiler.stage >= 1 => {
1364 self.sysroot(compiler).join(relative_libdir)
1365 }
1366 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1367 }
1368 }
1369 }
1370
1371 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1377 if compiler.is_snapshot(self) {
1378 libdir(self.config.host_target).as_ref()
1379 } else {
1380 match self.config.libdir_relative() {
1381 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1382 _ => libdir(compiler.host).as_ref(),
1383 }
1384 }
1385 }
1386
1387 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1392 match self.config.libdir_relative() {
1393 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1394 _ if compiler.stage == 0 => &self.sess.initial_relative_libdir,
1395 _ => Path::new("lib"),
1396 }
1397 }
1398
1399 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1400 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1401
1402 if get_llvm_build_status(self, compiler.host).llvm_output().kind()
1405 == LlvmKind::DownloadedFromCi
1406 {
1407 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1408 dylib_dirs.push(ci_llvm_lib);
1409 }
1410
1411 dylib_dirs
1412 }
1413
1414 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1417 if cfg!(any(windows, target_os = "cygwin")) {
1421 return;
1422 }
1423
1424 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1425 }
1426
1427 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1429 if compiler.is_snapshot(self) {
1430 self.initial_rustc.clone()
1431 } else {
1432 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1433 }
1434 }
1435
1436 pub fn rustc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1439 let mut cmd = command(self.rustc(compiler));
1440 self.add_rustc_lib_path(compiler, &mut cmd);
1441 cmd
1442 }
1443
1444 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1446 fs::read_dir(self.sysroot_codegen_backends(compiler))
1447 .into_iter()
1448 .flatten()
1449 .filter_map(Result::ok)
1450 .filter(|path| looks_like_codegen_backend(&path.path()))
1451 .map(|entry| entry.path())
1452 }
1453
1454 #[track_caller]
1458 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1459 self.ensure(tool::Rustdoc { target_compiler })
1460 }
1461
1462 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1463 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1464
1465 let compilers = RustcPrivateCompilers::new(self, run_compiler.stage, self.sess.host_target);
1466 assert_eq!(run_compiler, compilers.target_compiler());
1467
1468 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1470 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1471 let mut cmd = command(cargo_miri.tool_path);
1473 cmd.env("MIRI", &miri.tool_path);
1474 cmd.env("CARGO", &self.initial_cargo);
1475 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1484 cmd
1485 }
1486
1487 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1490 if build_compiler.stage == 0 {
1491 let cargo_clippy =
1492 self.config.external_cargo_clippy.clone().unwrap_or_else(|| {
1493 self.sess.config.download_clippy(&self.sess.initial_sysroot)
1494 });
1495
1496 let mut cmd = command(cargo_clippy);
1497 cmd.env("CARGO", &self.initial_cargo);
1498 return cmd;
1499 }
1500
1501 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1505
1506 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1507 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1508 let mut dylib_path = helpers::dylib_path();
1509 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1510
1511 let mut cmd = command(cargo_clippy.tool_path);
1512 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1513 cmd.env("CARGO", &self.initial_cargo);
1514 cmd
1515 }
1516
1517 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1518 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1519 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1520 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1521 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1524 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1525 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1526 .env("RUSTC_BOOTSTRAP", "1");
1527
1528 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1529
1530 if self.config.deny_warnings {
1531 cmd.arg("-Dwarnings");
1532 }
1533 cmd.arg("-Znormalize-docs");
1534 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1535 cmd
1536 }
1537
1538 pub fn is_llvm_enabled_for(&self, target: TargetSelection) -> bool {
1543 self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run()
1544 }
1545
1546 pub fn host_llvm_config(&self) -> PathBuf {
1548 self.ensure(llvm::Llvm { target: self.host_target }).llvm_config().to_owned()
1549 }
1550
1551 pub fn require_and_update_all_submodules(&self) {
1554 for submodule in self.submodule_paths() {
1555 self.require_submodule(submodule, None);
1556 }
1557 }
1558
1559 pub fn submodule_paths(&self) -> &[String] {
1561 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1562 }
1563
1564 #[track_caller]
1568 pub(crate) fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1569 {
1570 let mut stack = self.stack.borrow_mut();
1571 for stack_step in stack.iter() {
1572 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1574 continue;
1575 }
1576 let mut out = String::new();
1577 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1578 for el in stack.iter().rev() {
1579 out += &format!("\t{el:?}\n");
1580 }
1581 panic!("{}", out);
1582 }
1583 if let Some(out) = self.cache.get(&step) {
1584 #[cfg(feature = "tracing")]
1585 {
1586 if let Some(parent) = stack.last() {
1587 let mut graph = self.sess.step_graph.borrow_mut();
1588 graph.register_cached_step(&step, parent, self.config.dry_run());
1589 }
1590 }
1591 return out;
1592 }
1593
1594 #[cfg(feature = "tracing")]
1595 {
1596 let parent = stack.last();
1597 let mut graph = self.sess.step_graph.borrow_mut();
1598 graph.register_step_execution(&step, parent, self.config.dry_run());
1599 }
1600
1601 let location = format_location(*std::panic::Location::caller());
1604 StepStack::with_current(|stack| {
1605 stack.push(StepRecord { info: pretty_print_step(&step), location });
1606 });
1607 stack.push(Box::new(step.clone()));
1608 }
1609
1610 #[cfg(feature = "build-metrics")]
1611 self.metrics.enter_step(&step, self);
1612
1613 if self.config.print_step_timings && !self.config.dry_run() {
1614 println!("[TIMING:start] {}", pretty_print_step(&step));
1615 }
1616
1617 let (out, dur) = {
1618 let start = Instant::now();
1619 let zero = Duration::new(0, 0);
1620 let parent = self.time_spent_on_dependencies.replace(zero);
1621
1622 #[cfg(feature = "tracing")]
1623 let _span = {
1624 let span = tracing::info_span!(
1626 target: STEP_SPAN_TARGET,
1627 "step",
1630 step_name = pretty_step_name::<S>(),
1631 args = step_debug_args(&step),
1632 location = format_location(*std::panic::Location::caller())
1633 );
1634 span.entered()
1635 };
1636
1637 let out = step.clone().run(self);
1638 let dur = start.elapsed();
1639 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1640 (out, dur.saturating_sub(deps))
1641 };
1642
1643 if self.config.print_step_timings && !self.config.dry_run() {
1644 println!(
1645 "[TIMING:end] {} -- {}.{:03}",
1646 pretty_print_step(&step),
1647 dur.as_secs(),
1648 dur.subsec_millis()
1649 );
1650 }
1651
1652 #[cfg(feature = "build-metrics")]
1653 self.metrics.exit_step(self);
1654
1655 {
1656 let mut stack = self.stack.borrow_mut();
1657 let cur_step = stack.pop().expect("step stack empty");
1658 assert_eq!(cur_step.downcast_ref(), Some(&step));
1659
1660 StepStack::with_current(|stack| {
1661 stack.pop();
1662 });
1663 }
1664 self.cache.put(step, out.clone());
1665 out
1666 }
1667
1668 pub(crate) fn ensure_if_default<T, S: CommandLineStep<Output = T>>(
1672 &'a self,
1673 step: S,
1674 kind: Kind,
1675 ) -> Option<S::Output> {
1676 let desc = CommandLineStepDescription::from::<S>(kind);
1677 let should_run = (desc.should_run)(ShouldRun::new(self));
1678
1679 for pathset in &should_run.paths {
1681 if desc.is_excluded(self, pathset) {
1682 return None;
1683 }
1684 }
1685
1686 if (desc.is_default_step_fn)(self) { Some(self.ensure(step)) } else { None }
1688 }
1689
1690 pub(crate) fn was_invoked_explicitly<S: CommandLineStep>(&'a self, kind: Kind) -> bool {
1692 let desc = CommandLineStepDescription::from::<S>(kind);
1693 let should_run = (desc.should_run)(ShouldRun::new(self));
1694
1695 for path in &self.paths {
1696 if should_run.paths.iter().any(|s| s.has(path))
1697 && !desc.is_excluded(self, &PathSet::Suite(TaskPath { path: path.clone() }))
1698 {
1699 return true;
1700 }
1701 }
1702
1703 false
1704 }
1705
1706 pub(crate) fn maybe_open_in_browser<S: CommandLineStep>(&self, path: impl AsRef<Path>) {
1707 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1708 self.open_in_browser(path);
1709 } else {
1710 self.info(&format!("Doc path: {}", path.as_ref().display()));
1711 }
1712 }
1713
1714 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1715 let path = path.as_ref();
1716
1717 if self.config.dry_run() || !self.config.cmd.open() {
1718 self.info(&format!("Doc path: {}", path.display()));
1719 return;
1720 }
1721
1722 self.info(&format!("Opening doc {}", path.display()));
1723 if let Err(err) = opener::open(path) {
1724 self.info(&format!("{err}\n"));
1725 }
1726 }
1727
1728 pub fn exec_ctx(&self) -> &ExecutionContext {
1729 &self.config.exec_ctx
1730 }
1731}
1732
1733pub fn pretty_step_name<S: Step>() -> String {
1735 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1737 path.into_iter().rev().collect::<Vec<_>>().join("::")
1738}
1739
1740fn step_debug_args<S: Step>(step: &S) -> String {
1742 let step_dbg_repr = format!("{step:?}");
1743
1744 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1746 (Some(brace_start), Some(brace_end)) => {
1747 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1748 }
1749 _ => String::new(),
1750 }
1751}
1752
1753fn pretty_print_step<S: Step>(step: &S) -> String {
1754 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1755}
1756
1757impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1758 fn as_ref(&self) -> &ExecutionContext {
1759 self.exec_ctx()
1760 }
1761}