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};
11
12use clap::ValueEnum;
13#[cfg(feature = "tracing")]
14use tracing::instrument;
15
16pub use self::cargo::{Cargo, cargo_profile_var};
17pub use crate::Compiler;
18use crate::core::build_steps::compile::{Std, StdLink};
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::cli_paths::CLIStepPath;
24use crate::core::config::flags::Subcommand;
25use crate::core::config::{DryRun, TargetSelection};
26use crate::utils::build_stamp::BuildStamp;
27use crate::utils::cache::Cache;
28use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
29use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
30use crate::{Build, Crate, trace};
31
32mod cargo;
33mod cli_paths;
34#[cfg(test)]
35mod tests;
36
37pub struct Builder<'a> {
40 pub build: &'a Build,
42
43 pub top_stage: u32,
47
48 pub kind: Kind,
50
51 cache: Cache,
54
55 stack: RefCell<Vec<Box<dyn AnyDebug>>>,
58
59 time_spent_on_dependencies: Cell<Duration>,
61
62 pub paths: Vec<PathBuf>,
66
67 submodule_paths_cache: OnceLock<Vec<String>>,
69
70 #[expect(clippy::type_complexity)]
74 log_cli_step_for_tests: Option<Box<dyn Fn(&StepDescription, &[PathSet], &[TargetSelection])>>,
75}
76
77impl Deref for Builder<'_> {
78 type Target = Build;
79
80 fn deref(&self) -> &Self::Target {
81 self.build
82 }
83}
84
85pub trait AnyDebug: Any + Debug {}
90impl<T: Any + Debug> AnyDebug for T {}
91impl dyn AnyDebug {
92 fn downcast_ref<T: Any>(&self) -> Option<&T> {
94 (self as &dyn Any).downcast_ref()
95 }
96
97 }
99
100pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
101 type Output: Clone;
103
104 const IS_HOST: bool = false;
111
112 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
115
116 fn is_default_step(_builder: &Builder<'_>) -> bool {
130 false
131 }
132
133 fn run(self, builder: &Builder<'_>) -> Self::Output;
147
148 fn make_run(_run: RunConfig<'_>) {
152 unimplemented!()
157 }
158
159 fn metadata(&self) -> Option<StepMetadata> {
161 None
162 }
163}
164
165#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct StepMetadata {
168 name: String,
169 kind: Kind,
170 target: TargetSelection,
171 built_by: Option<Compiler>,
172 stage: Option<u32>,
173 metadata: Option<String>,
175}
176
177impl StepMetadata {
178 pub fn build(name: &str, target: TargetSelection) -> Self {
179 Self::new(name, target, Kind::Build)
180 }
181
182 pub fn check(name: &str, target: TargetSelection) -> Self {
183 Self::new(name, target, Kind::Check)
184 }
185
186 pub fn clippy(name: &str, target: TargetSelection) -> Self {
187 Self::new(name, target, Kind::Clippy)
188 }
189
190 pub fn doc(name: &str, target: TargetSelection) -> Self {
191 Self::new(name, target, Kind::Doc)
192 }
193
194 pub fn dist(name: &str, target: TargetSelection) -> Self {
195 Self::new(name, target, Kind::Dist)
196 }
197
198 pub fn test(name: &str, target: TargetSelection) -> Self {
199 Self::new(name, target, Kind::Test)
200 }
201
202 pub fn run(name: &str, target: TargetSelection) -> Self {
203 Self::new(name, target, Kind::Run)
204 }
205
206 fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
207 Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
208 }
209
210 pub fn built_by(mut self, compiler: Compiler) -> Self {
211 self.built_by = Some(compiler);
212 self
213 }
214
215 pub fn stage(mut self, stage: u32) -> Self {
216 self.stage = Some(stage);
217 self
218 }
219
220 pub fn with_metadata(mut self, metadata: String) -> Self {
221 self.metadata = Some(metadata);
222 self
223 }
224
225 pub fn get_stage(&self) -> Option<u32> {
226 self.stage.or(self
227 .built_by
228 .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
231 }
232
233 pub fn get_name(&self) -> &str {
234 &self.name
235 }
236
237 pub fn get_target(&self) -> TargetSelection {
238 self.target
239 }
240}
241
242pub struct RunConfig<'a> {
243 pub builder: &'a Builder<'a>,
244 pub target: TargetSelection,
245 pub paths: Vec<PathSet>,
246}
247
248impl RunConfig<'_> {
249 pub fn build_triple(&self) -> TargetSelection {
250 self.builder.build.host_target
251 }
252
253 #[track_caller]
255 pub fn cargo_crates_in_set(&self) -> Vec<String> {
256 let mut crates = Vec::new();
257 for krate in &self.paths {
258 let path = &krate.assert_single_path().path;
259
260 let crate_name = self
261 .builder
262 .crate_paths
263 .get(path)
264 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
265
266 crates.push(crate_name.to_string());
267 }
268 crates
269 }
270
271 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
278 let has_alias =
279 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
280 if !has_alias {
281 return self.cargo_crates_in_set();
282 }
283
284 let crates = match alias {
285 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
286 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
287 };
288
289 crates.into_iter().map(|krate| krate.name.to_string()).collect()
290 }
291}
292
293#[derive(Debug, Copy, Clone)]
294pub enum Alias {
295 Library,
296 Compiler,
297}
298
299impl Alias {
300 fn as_str(self) -> &'static str {
301 match self {
302 Alias::Library => "library",
303 Alias::Compiler => "compiler",
304 }
305 }
306}
307
308pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
312 if crates.is_empty() {
313 return "".into();
314 }
315
316 let mut descr = String::from("{");
317 descr.push_str(crates[0].as_ref());
318 for krate in &crates[1..] {
319 descr.push_str(", ");
320 descr.push_str(krate.as_ref());
321 }
322 descr.push('}');
323 descr
324}
325
326struct StepDescription {
327 is_host: bool,
328 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
329 is_default_step_fn: fn(&Builder<'_>) -> bool,
330 make_run: fn(RunConfig<'_>),
331 name: &'static str,
332 kind: Kind,
333}
334
335#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
336pub struct TaskPath {
337 pub path: PathBuf,
338 pub kind: Option<Kind>,
339}
340
341impl Debug for TaskPath {
342 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343 if let Some(kind) = &self.kind {
344 write!(f, "{}::", kind.as_str())?;
345 }
346 write!(f, "{}", self.path.display())
347 }
348}
349
350#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
352pub enum PathSet {
353 Set(BTreeSet<TaskPath>),
364 Suite(TaskPath),
371}
372
373impl PathSet {
374 fn empty() -> PathSet {
375 PathSet::Set(BTreeSet::new())
376 }
377
378 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
379 let mut set = BTreeSet::new();
380 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
381 PathSet::Set(set)
382 }
383
384 fn has(&self, needle: &Path, module: Kind) -> bool {
385 match self {
386 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
387 PathSet::Suite(suite) => Self::check(suite, needle, module),
388 }
389 }
390
391 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
393 let check_path = || {
394 p.path.ends_with(needle) || p.path.starts_with(needle)
396 };
397 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
398 }
399
400 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
407 let mut check = |p| {
408 let mut result = false;
409 for n in needles.iter_mut() {
410 let matched = Self::check(p, &n.path, module);
411 if matched {
412 n.will_be_executed = true;
413 result = true;
414 }
415 }
416 result
417 };
418 match self {
419 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
420 PathSet::Suite(suite) => {
421 if check(suite) {
422 self.clone()
423 } else {
424 PathSet::empty()
425 }
426 }
427 }
428 }
429
430 #[track_caller]
434 pub fn assert_single_path(&self) -> &TaskPath {
435 match self {
436 PathSet::Set(set) => {
437 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
438 set.iter().next().unwrap()
439 }
440 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
441 }
442 }
443}
444
445impl StepDescription {
446 fn from<S: Step>(kind: Kind) -> StepDescription {
447 StepDescription {
448 is_host: S::IS_HOST,
449 should_run: S::should_run,
450 is_default_step_fn: S::is_default_step,
451 make_run: S::make_run,
452 name: std::any::type_name::<S>(),
453 kind,
454 }
455 }
456
457 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
458 pathsets.retain(|set| !self.is_excluded(builder, set));
459
460 if pathsets.is_empty() {
461 return;
462 }
463
464 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
466
467 if let Some(ref log_cli_step) = builder.log_cli_step_for_tests {
469 log_cli_step(self, &pathsets, targets);
470 return;
472 }
473
474 for target in targets {
475 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
476 (self.make_run)(run);
477 }
478 }
479
480 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
481 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
482 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
483 println!("Skipping {pathset:?} because it is excluded");
484 }
485 return true;
486 }
487
488 if !builder.config.skip.is_empty()
489 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
490 {
491 builder.do_if_verbose(|| {
492 println!(
493 "{:?} not skipped for {:?} -- not in {:?}",
494 pathset, self.name, builder.config.skip
495 )
496 });
497 }
498 false
499 }
500}
501
502pub struct ShouldRun<'a> {
509 pub builder: &'a Builder<'a>,
510 kind: Kind,
511
512 paths: BTreeSet<PathSet>,
514}
515
516impl<'a> ShouldRun<'a> {
517 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
518 ShouldRun { builder, kind, paths: BTreeSet::new() }
519 }
520
521 pub fn crate_or_deps(self, name: &str) -> Self {
526 let crates = self.builder.in_tree_crates(name, None);
527 self.crates(crates)
528 }
529
530 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
536 for krate in crates {
537 let path = krate.local_path(self.builder);
538 self.paths.insert(PathSet::one(path, self.kind));
539 }
540 self
541 }
542
543 pub fn alias(mut self, alias: &str) -> Self {
545 assert!(
549 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
550 "use `builder.path()` for real paths: {alias}"
551 );
552 self.paths.insert(PathSet::Set(
553 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
554 ));
555 self
556 }
557
558 pub fn path(self, path: &str) -> Self {
562 self.paths(&[path])
563 }
564
565 pub fn paths(mut self, paths: &[&str]) -> Self {
575 let submodules_paths = self.builder.submodule_paths();
576
577 self.paths.insert(PathSet::Set(
578 paths
579 .iter()
580 .map(|p| {
581 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
583 assert!(
584 self.builder.src.join(p).exists(),
585 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
586 );
587 }
588
589 TaskPath { path: p.into(), kind: Some(self.kind) }
590 })
591 .collect(),
592 ));
593 self
594 }
595
596 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
598 self.paths.iter().find(|pathset| match pathset {
599 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
600 PathSet::Set(_) => false,
601 })
602 }
603
604 pub fn suite_path(mut self, suite: &str) -> Self {
605 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
606 self
607 }
608
609 pub fn never(mut self) -> ShouldRun<'a> {
611 self.paths.insert(PathSet::empty());
612 self
613 }
614
615 fn pathset_for_paths_removing_matches(
625 &self,
626 paths: &mut [CLIStepPath],
627 kind: Kind,
628 ) -> Vec<PathSet> {
629 let mut sets = vec![];
630 for pathset in &self.paths {
631 let subset = pathset.intersection_removing_matches(paths, kind);
632 if subset != PathSet::empty() {
633 sets.push(subset);
634 }
635 }
636 sets
637 }
638}
639
640#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
641pub enum Kind {
642 #[value(alias = "b")]
643 Build,
644 #[value(alias = "c")]
645 Check,
646 Clippy,
647 Fix,
648 Format,
649 #[value(alias = "t")]
650 Test,
651 Miri,
652 MiriSetup,
653 MiriTest,
654 Bench,
655 #[value(alias = "d")]
656 Doc,
657 Clean,
658 Dist,
659 Install,
660 #[value(alias = "r")]
661 Run,
662 Setup,
663 Vendor,
664 Perf,
665}
666
667impl Kind {
668 pub fn as_str(&self) -> &'static str {
669 match self {
670 Kind::Build => "build",
671 Kind::Check => "check",
672 Kind::Clippy => "clippy",
673 Kind::Fix => "fix",
674 Kind::Format => "fmt",
675 Kind::Test => "test",
676 Kind::Miri => "miri",
677 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
678 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
679 Kind::Bench => "bench",
680 Kind::Doc => "doc",
681 Kind::Clean => "clean",
682 Kind::Dist => "dist",
683 Kind::Install => "install",
684 Kind::Run => "run",
685 Kind::Setup => "setup",
686 Kind::Vendor => "vendor",
687 Kind::Perf => "perf",
688 }
689 }
690
691 pub fn description(&self) -> String {
692 match self {
693 Kind::Test => "Testing",
694 Kind::Bench => "Benchmarking",
695 Kind::Doc => "Documenting",
696 Kind::Run => "Running",
697 Kind::Clippy => "Linting",
698 Kind::Perf => "Profiling & benchmarking",
699 _ => {
700 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
701 return format!("{title_letter}{}ing", &self.as_str()[1..]);
702 }
703 }
704 .to_owned()
705 }
706}
707
708#[derive(Debug, Clone, Hash, PartialEq, Eq)]
709struct Libdir {
710 compiler: Compiler,
711 target: TargetSelection,
712}
713
714impl Step for Libdir {
715 type Output = PathBuf;
716
717 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
718 run.never()
719 }
720
721 fn run(self, builder: &Builder<'_>) -> PathBuf {
722 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
723 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
724
725 if !builder.config.dry_run() {
726 if !builder.download_rustc() {
729 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
730 builder.do_if_verbose(|| {
731 eprintln!(
732 "Removing sysroot {} to avoid caching bugs",
733 sysroot_target_libdir.display()
734 )
735 });
736 let _ = fs::remove_dir_all(&sysroot_target_libdir);
737 t!(fs::create_dir_all(&sysroot_target_libdir));
738 }
739
740 if self.compiler.stage == 0 {
741 dist::maybe_install_llvm_target(
745 builder,
746 self.compiler.host,
747 &builder.sysroot(self.compiler),
748 );
749 }
750 }
751
752 sysroot
753 }
754}
755
756#[cfg(feature = "tracing")]
757pub const STEP_SPAN_TARGET: &str = "STEP";
758
759impl<'a> Builder<'a> {
760 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
761 macro_rules! describe {
762 ($($rule:ty),+ $(,)?) => {{
763 vec![$(StepDescription::from::<$rule>(kind)),+]
764 }};
765 }
766 match kind {
767 Kind::Build => describe!(
768 compile::Std,
769 compile::Rustc,
770 compile::Assemble,
771 compile::CraneliftCodegenBackend,
772 compile::GccCodegenBackend,
773 compile::StartupObjects,
774 tool::BuildManifest,
775 tool::Rustbook,
776 tool::ErrorIndex,
777 tool::UnstableBookGen,
778 tool::Tidy,
779 tool::Linkchecker,
780 tool::CargoTest,
781 tool::Compiletest,
782 tool::RemoteTestServer,
783 tool::RemoteTestClient,
784 tool::RustInstaller,
785 tool::FeaturesStatusDump,
786 tool::Cargo,
787 tool::RustAnalyzer,
788 tool::RustAnalyzerProcMacroSrv,
789 tool::Rustdoc,
790 tool::Clippy,
791 tool::CargoClippy,
792 llvm::Llvm,
793 gcc::Gcc,
794 llvm::Sanitizers,
795 tool::Rustfmt,
796 tool::Cargofmt,
797 tool::Miri,
798 tool::CargoMiri,
799 llvm::Lld,
800 llvm::Enzyme,
801 llvm::CrtBeginEnd,
802 tool::RustdocGUITest,
803 tool::OptimizedDist,
804 tool::CoverageDump,
805 tool::LlvmBitcodeLinker,
806 tool::RustcPerf,
807 tool::WasmComponentLd,
808 tool::LldWrapper
809 ),
810 Kind::Clippy => describe!(
811 clippy::Std,
812 clippy::Rustc,
813 clippy::Bootstrap,
814 clippy::BuildHelper,
815 clippy::BuildManifest,
816 clippy::CargoMiri,
817 clippy::Clippy,
818 clippy::CodegenGcc,
819 clippy::CollectLicenseMetadata,
820 clippy::Compiletest,
821 clippy::CoverageDump,
822 clippy::Jsondocck,
823 clippy::Jsondoclint,
824 clippy::LintDocs,
825 clippy::LlvmBitcodeLinker,
826 clippy::Miri,
827 clippy::MiroptTestTools,
828 clippy::OptDist,
829 clippy::RemoteTestClient,
830 clippy::RemoteTestServer,
831 clippy::RustAnalyzer,
832 clippy::Rustdoc,
833 clippy::Rustfmt,
834 clippy::RustInstaller,
835 clippy::TestFloatParse,
836 clippy::Tidy,
837 clippy::CI,
838 ),
839 Kind::Check | Kind::Fix => describe!(
840 check::Rustc,
841 check::Rustdoc,
842 check::CraneliftCodegenBackend,
843 check::GccCodegenBackend,
844 check::Clippy,
845 check::Miri,
846 check::CargoMiri,
847 check::MiroptTestTools,
848 check::Rustfmt,
849 check::RustAnalyzer,
850 check::TestFloatParse,
851 check::Bootstrap,
852 check::RunMakeSupport,
853 check::Compiletest,
854 check::RustdocGuiTest,
855 check::FeaturesStatusDump,
856 check::CoverageDump,
857 check::Linkchecker,
858 check::BumpStage0,
859 check::Tidy,
860 check::Std,
867 ),
868 Kind::Test => describe!(
869 crate::core::build_steps::toolstate::ToolStateCheck,
870 test::Tidy,
871 test::BootstrapPy,
872 test::Bootstrap,
873 test::Ui,
874 test::Crashes,
875 test::Coverage,
876 test::MirOpt,
877 test::CodegenLlvm,
878 test::CodegenUnits,
879 test::AssemblyLlvm,
880 test::Incremental,
881 test::Debuginfo,
882 test::UiFullDeps,
883 test::RustdocHtml,
884 test::CoverageRunRustdoc,
885 test::Pretty,
886 test::CodegenCranelift,
887 test::CodegenGCC,
888 test::Crate,
889 test::CrateLibrustc,
890 test::CrateRustdoc,
891 test::CrateRustdocJsonTypes,
892 test::CrateBootstrap,
893 test::RemoteTestClientTests,
894 test::Linkcheck,
895 test::TierCheck,
896 test::Cargotest,
897 test::Cargo,
898 test::RustAnalyzer,
899 test::ErrorIndex,
900 test::Distcheck,
901 test::Nomicon,
902 test::Reference,
903 test::RustdocBook,
904 test::RustByExample,
905 test::TheBook,
906 test::UnstableBook,
907 test::RustcBook,
908 test::LintDocs,
909 test::EmbeddedBook,
910 test::EditionGuide,
911 test::Rustfmt,
912 test::Miri,
913 test::CargoMiri,
914 test::Clippy,
915 test::CompiletestTest,
916 test::CrateRunMakeSupport,
917 test::CrateBuildHelper,
918 test::RustdocJSStd,
919 test::RustdocJSNotStd,
920 test::RustdocGUI,
921 test::RustdocTheme,
922 test::RustdocUi,
923 test::RustdocJson,
924 test::HtmlCheck,
925 test::RustInstaller,
926 test::TestFloatParse,
927 test::CollectLicenseMetadata,
928 test::RunMake,
929 test::RunMakeCargo,
930 test::BuildStd,
931 ),
932 Kind::Miri => describe!(test::Crate),
933 Kind::Bench => describe!(test::Crate, test::CrateLibrustc, test::CrateRustdoc),
934 Kind::Doc => describe!(
935 doc::UnstableBook,
936 doc::UnstableBookGen,
937 doc::TheBook,
938 doc::Standalone,
939 doc::Std,
940 doc::Rustc,
941 doc::Rustdoc,
942 doc::Rustfmt,
943 doc::ErrorIndex,
944 doc::Nomicon,
945 doc::Reference,
946 doc::RustdocBook,
947 doc::RustByExample,
948 doc::RustcBook,
949 doc::Cargo,
950 doc::CargoBook,
951 doc::Clippy,
952 doc::ClippyBook,
953 doc::Miri,
954 doc::EmbeddedBook,
955 doc::EditionGuide,
956 doc::StyleGuide,
957 doc::Tidy,
958 doc::Bootstrap,
959 doc::Releases,
960 doc::RunMakeSupport,
961 doc::BuildHelper,
962 doc::Compiletest,
963 ),
964 Kind::Dist => describe!(
965 dist::Docs,
966 dist::RustcDocs,
967 dist::JsonDocs,
968 dist::Mingw,
969 dist::Rustc,
970 dist::CraneliftCodegenBackend,
971 dist::GccCodegenBackend,
972 dist::Std,
973 dist::RustcDev,
974 dist::Analysis,
975 dist::Src,
976 dist::Cargo,
977 dist::RustAnalyzer,
978 dist::Rustfmt,
979 dist::Clippy,
980 dist::Miri,
981 dist::LlvmTools,
982 dist::LlvmBitcodeLinker,
983 dist::RustDev,
984 dist::Enzyme,
985 dist::Bootstrap,
986 dist::Extended,
987 dist::PlainSourceTarball,
992 dist::PlainSourceTarballGpl,
993 dist::BuildManifest,
994 dist::ReproducibleArtifacts,
995 dist::GccDev,
996 dist::Gcc
997 ),
998 Kind::Install => describe!(
999 install::Docs,
1000 install::Std,
1001 install::Rustc,
1006 install::RustcDev,
1007 install::Cargo,
1008 install::RustAnalyzer,
1009 install::Rustfmt,
1010 install::Clippy,
1011 install::Miri,
1012 install::LlvmTools,
1013 install::Src,
1014 install::RustcCodegenCranelift,
1015 install::LlvmBitcodeLinker
1016 ),
1017 Kind::Run => describe!(
1018 run::BuildManifest,
1019 run::BumpStage0,
1020 run::ReplaceVersionPlaceholder,
1021 run::Miri,
1022 run::CollectLicenseMetadata,
1023 run::GenerateCopyright,
1024 run::GenerateWindowsSys,
1025 run::GenerateCompletions,
1026 run::UnicodeTableGenerator,
1027 run::FeaturesStatusDump,
1028 run::CyclicStep,
1029 run::CoverageDump,
1030 run::Rustfmt,
1031 run::GenerateHelp,
1032 ),
1033 Kind::Setup => {
1034 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1035 }
1036 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1037 Kind::Vendor => describe!(vendor::Vendor),
1038 Kind::Format | Kind::Perf => vec![],
1040 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1041 }
1042 }
1043
1044 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1045 let step_descriptions = Builder::get_step_descriptions(kind);
1046 if step_descriptions.is_empty() {
1047 return None;
1048 }
1049
1050 let builder = Self::new_internal(build, kind, vec![]);
1051 let builder = &builder;
1052 let mut should_run = ShouldRun::new(builder, Kind::Build);
1055 for desc in step_descriptions {
1056 should_run.kind = desc.kind;
1057 should_run = (desc.should_run)(should_run);
1058 }
1059 let mut help = String::from("Available paths:\n");
1060 let mut add_path = |path: &Path| {
1061 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1062 };
1063 for pathset in should_run.paths {
1064 match pathset {
1065 PathSet::Set(set) => {
1066 for path in set {
1067 add_path(&path.path);
1068 }
1069 }
1070 PathSet::Suite(path) => {
1071 add_path(&path.path.join("..."));
1072 }
1073 }
1074 }
1075 Some(help)
1076 }
1077
1078 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1079 Builder {
1080 build,
1081 top_stage: build.config.stage,
1082 kind,
1083 cache: Cache::new(),
1084 stack: RefCell::new(Vec::new()),
1085 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1086 paths,
1087 submodule_paths_cache: Default::default(),
1088 log_cli_step_for_tests: None,
1089 }
1090 }
1091
1092 pub fn new(build: &Build) -> Builder<'_> {
1093 let paths = &build.config.paths;
1094 let (kind, paths) = match build.config.cmd {
1095 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1096 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1097 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1098 Subcommand::Fix => (Kind::Fix, &paths[..]),
1099 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1100 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1101 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1102 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1103 Subcommand::Dist => (Kind::Dist, &paths[..]),
1104 Subcommand::Install => (Kind::Install, &paths[..]),
1105 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1106 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1107 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1108 Subcommand::Setup { profile: ref path } => (
1109 Kind::Setup,
1110 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1111 ),
1112 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1113 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1114 };
1115
1116 Self::new_internal(build, kind, paths.to_owned())
1117 }
1118
1119 pub fn execute_cli(&self) {
1120 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1121 }
1122
1123 pub fn run_default_doc_steps(&self) {
1125 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), &[]);
1126 }
1127
1128 pub fn doc_rust_lang_org_channel(&self) -> String {
1129 let channel = match &*self.config.channel {
1130 "stable" => &self.version,
1131 "beta" => "beta",
1132 "nightly" | "dev" => "nightly",
1133 _ => "stable",
1135 };
1136
1137 format!("https://doc.rust-lang.org/{channel}")
1138 }
1139
1140 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1141 cli_paths::match_paths_to_steps_and_run(self, v, paths);
1142 }
1143
1144 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1147 !target.triple.ends_with("-windows-gnu")
1148 }
1149
1150 #[cfg_attr(
1155 feature = "tracing",
1156 instrument(
1157 level = "trace",
1158 name = "Builder::compiler",
1159 target = "COMPILER",
1160 skip_all,
1161 fields(
1162 stage = stage,
1163 host = ?host,
1164 ),
1165 ),
1166 )]
1167 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1168 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1169 }
1170
1171 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1188 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1189 self.compiler(1, self.host_target)
1190 } else {
1191 self.compiler(stage, self.host_target)
1192 }
1193 }
1194
1195 #[cfg_attr(
1207 feature = "tracing",
1208 instrument(
1209 level = "trace",
1210 name = "Builder::compiler_for",
1211 target = "COMPILER_FOR",
1212 skip_all,
1213 fields(
1214 stage = stage,
1215 host = ?host,
1216 target = ?target,
1217 ),
1218 ),
1219 )]
1220 pub fn compiler_for(
1223 &self,
1224 stage: u32,
1225 host: TargetSelection,
1226 target: TargetSelection,
1227 ) -> Compiler {
1228 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1229 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1230 self.compiler(2, self.config.host_target)
1231 } else if self.build.force_use_stage1(stage, target) {
1232 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1233 self.compiler(1, self.config.host_target)
1234 } else {
1235 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1236 self.compiler(stage, host)
1237 };
1238
1239 if stage != resolved_compiler.stage {
1240 resolved_compiler.forced_compiler(true);
1241 }
1242
1243 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1244 resolved_compiler
1245 }
1246
1247 #[cfg_attr(
1254 feature = "tracing",
1255 instrument(
1256 level = "trace",
1257 name = "Builder::std",
1258 target = "STD",
1259 skip_all,
1260 fields(
1261 compiler = ?compiler,
1262 target = ?target,
1263 ),
1264 ),
1265 )]
1266 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1267 if compiler.stage == 0 {
1277 if target != compiler.host {
1278 if self.local_rebuild {
1279 self.ensure(Std::new(compiler, target))
1280 } else {
1281 panic!(
1282 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1283You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1284Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1285",
1286 compiler.host
1287 )
1288 }
1289 } else {
1290 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1292 None
1293 }
1294 } else {
1295 self.ensure(Std::new(compiler, target))
1298 }
1299 }
1300
1301 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1302 self.ensure(compile::Sysroot::new(compiler))
1303 }
1304
1305 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1307 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1308 }
1309
1310 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1313 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1314 }
1315
1316 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1317 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1318 }
1319
1320 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1326 if compiler.is_snapshot(self) {
1327 self.rustc_snapshot_libdir()
1328 } else {
1329 match self.config.libdir_relative() {
1330 Some(relative_libdir) if compiler.stage >= 1 => {
1331 self.sysroot(compiler).join(relative_libdir)
1332 }
1333 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1334 }
1335 }
1336 }
1337
1338 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1344 if compiler.is_snapshot(self) {
1345 libdir(self.config.host_target).as_ref()
1346 } else {
1347 match self.config.libdir_relative() {
1348 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1349 _ => libdir(compiler.host).as_ref(),
1350 }
1351 }
1352 }
1353
1354 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1359 match self.config.libdir_relative() {
1360 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1361 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1362 _ => Path::new("lib"),
1363 }
1364 }
1365
1366 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1367 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1368
1369 if self.config.llvm_from_ci {
1371 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1372 dylib_dirs.push(ci_llvm_lib);
1373 }
1374
1375 dylib_dirs
1376 }
1377
1378 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1381 if cfg!(any(windows, target_os = "cygwin")) {
1385 return;
1386 }
1387
1388 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1389 }
1390
1391 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1393 if compiler.is_snapshot(self) {
1394 self.initial_rustc.clone()
1395 } else {
1396 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1397 }
1398 }
1399
1400 pub fn rustc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1403 let mut cmd = command(self.rustc(compiler));
1404 self.add_rustc_lib_path(compiler, &mut cmd);
1405 cmd
1406 }
1407
1408 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1410 fs::read_dir(self.sysroot_codegen_backends(compiler))
1411 .into_iter()
1412 .flatten()
1413 .filter_map(Result::ok)
1414 .map(|entry| entry.path())
1415 }
1416
1417 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1421 self.ensure(tool::Rustdoc { target_compiler })
1422 }
1423
1424 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1425 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1426
1427 let compilers =
1428 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1429 assert_eq!(run_compiler, compilers.target_compiler());
1430
1431 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1433 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1434 let mut cmd = command(cargo_miri.tool_path);
1436 cmd.env("MIRI", &miri.tool_path);
1437 cmd.env("CARGO", &self.initial_cargo);
1438 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1447 cmd
1448 }
1449
1450 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1453 if build_compiler.stage == 0 {
1454 let cargo_clippy = self
1455 .config
1456 .initial_cargo_clippy
1457 .clone()
1458 .unwrap_or_else(|| self.build.config.download_clippy());
1459
1460 let mut cmd = command(cargo_clippy);
1461 cmd.env("CARGO", &self.initial_cargo);
1462 return cmd;
1463 }
1464
1465 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1469
1470 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1471 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1472 let mut dylib_path = helpers::dylib_path();
1473 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1474
1475 let mut cmd = command(cargo_clippy.tool_path);
1476 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1477 cmd.env("CARGO", &self.initial_cargo);
1478 cmd
1479 }
1480
1481 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1482 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1483 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1484 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1485 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1488 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1489 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1490 .env("RUSTC_BOOTSTRAP", "1");
1491
1492 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1493
1494 if self.config.deny_warnings {
1495 cmd.arg("-Dwarnings");
1496 }
1497 cmd.arg("-Znormalize-docs");
1498 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1499 cmd
1500 }
1501
1502 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1511 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1512 let llvm::LlvmResult { host_llvm_config, .. } = self.ensure(llvm::Llvm { target });
1513 if host_llvm_config.is_file() {
1514 return Some(host_llvm_config);
1515 }
1516 }
1517 None
1518 }
1519
1520 pub fn require_and_update_all_submodules(&self) {
1523 for submodule in self.submodule_paths() {
1524 self.require_submodule(submodule, None);
1525 }
1526 }
1527
1528 pub fn submodule_paths(&self) -> &[String] {
1530 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1531 }
1532
1533 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1537 {
1538 let mut stack = self.stack.borrow_mut();
1539 for stack_step in stack.iter() {
1540 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1542 continue;
1543 }
1544 let mut out = String::new();
1545 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1546 for el in stack.iter().rev() {
1547 out += &format!("\t{el:?}\n");
1548 }
1549 panic!("{}", out);
1550 }
1551 if let Some(out) = self.cache.get(&step) {
1552 #[cfg(feature = "tracing")]
1553 {
1554 if let Some(parent) = stack.last() {
1555 let mut graph = self.build.step_graph.borrow_mut();
1556 graph.register_cached_step(&step, parent, self.config.dry_run());
1557 }
1558 }
1559 return out;
1560 }
1561
1562 #[cfg(feature = "tracing")]
1563 {
1564 let parent = stack.last();
1565 let mut graph = self.build.step_graph.borrow_mut();
1566 graph.register_step_execution(&step, parent, self.config.dry_run());
1567 }
1568
1569 stack.push(Box::new(step.clone()));
1570 }
1571
1572 #[cfg(feature = "build-metrics")]
1573 self.metrics.enter_step(&step, self);
1574
1575 if self.config.print_step_timings && !self.config.dry_run() {
1576 println!("[TIMING:start] {}", pretty_print_step(&step));
1577 }
1578
1579 let (out, dur) = {
1580 let start = Instant::now();
1581 let zero = Duration::new(0, 0);
1582 let parent = self.time_spent_on_dependencies.replace(zero);
1583
1584 #[cfg(feature = "tracing")]
1585 let _span = {
1586 let span = tracing::info_span!(
1588 target: STEP_SPAN_TARGET,
1589 "step",
1592 step_name = pretty_step_name::<S>(),
1593 args = step_debug_args(&step)
1594 );
1595 span.entered()
1596 };
1597
1598 let out = step.clone().run(self);
1599 let dur = start.elapsed();
1600 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1601 (out, dur.saturating_sub(deps))
1602 };
1603
1604 if self.config.print_step_timings && !self.config.dry_run() {
1605 println!(
1606 "[TIMING:end] {} -- {}.{:03}",
1607 pretty_print_step(&step),
1608 dur.as_secs(),
1609 dur.subsec_millis()
1610 );
1611 }
1612
1613 #[cfg(feature = "build-metrics")]
1614 self.metrics.exit_step(self);
1615
1616 {
1617 let mut stack = self.stack.borrow_mut();
1618 let cur_step = stack.pop().expect("step stack empty");
1619 assert_eq!(cur_step.downcast_ref(), Some(&step));
1620 }
1621 self.cache.put(step, out.clone());
1622 out
1623 }
1624
1625 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1629 &'a self,
1630 step: S,
1631 kind: Kind,
1632 ) -> Option<S::Output> {
1633 let desc = StepDescription::from::<S>(kind);
1634 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1635
1636 for pathset in &should_run.paths {
1638 if desc.is_excluded(self, pathset) {
1639 return None;
1640 }
1641 }
1642
1643 if (desc.is_default_step_fn)(self) { Some(self.ensure(step)) } else { None }
1645 }
1646
1647 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1649 let desc = StepDescription::from::<S>(kind);
1650 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1651
1652 for path in &self.paths {
1653 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1654 && !desc.is_excluded(
1655 self,
1656 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1657 )
1658 {
1659 return true;
1660 }
1661 }
1662
1663 false
1664 }
1665
1666 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1667 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1668 self.open_in_browser(path);
1669 } else {
1670 self.info(&format!("Doc path: {}", path.as_ref().display()));
1671 }
1672 }
1673
1674 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1675 let path = path.as_ref();
1676
1677 if self.config.dry_run() || !self.config.cmd.open() {
1678 self.info(&format!("Doc path: {}", path.display()));
1679 return;
1680 }
1681
1682 self.info(&format!("Opening doc {}", path.display()));
1683 if let Err(err) = opener::open(path) {
1684 self.info(&format!("{err}\n"));
1685 }
1686 }
1687
1688 pub fn exec_ctx(&self) -> &ExecutionContext {
1689 &self.config.exec_ctx
1690 }
1691}
1692
1693pub fn pretty_step_name<S: Step>() -> String {
1695 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1697 path.into_iter().rev().collect::<Vec<_>>().join("::")
1698}
1699
1700fn step_debug_args<S: Step>(step: &S) -> String {
1702 let step_dbg_repr = format!("{step:?}");
1703
1704 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1706 (Some(brace_start), Some(brace_end)) => {
1707 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1708 }
1709 _ => String::new(),
1710 }
1711}
1712
1713fn pretty_print_step<S: Step>(step: &S) -> String {
1714 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1715}
1716
1717impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1718 fn as_ref(&self) -> &ExecutionContext {
1719 self.exec_ctx()
1720 }
1721}