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(mut self, path: &str) -> Self {
562 let submodules_paths = self.builder.submodule_paths();
563
564 if !submodules_paths.iter().any(|sm_p| path.contains(sm_p)) {
566 assert!(
567 self.builder.src.join(path).exists(),
568 "`should_run.path` should correspond to a real on-disk path - use `alias` if there is no relevant path: {path}"
569 );
570 }
571
572 let task = TaskPath { path: path.into(), kind: Some(self.kind) };
573 self.paths.insert(PathSet::Set(BTreeSet::from_iter([task])));
574 self
575 }
576
577 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
579 self.paths.iter().find(|pathset| match pathset {
580 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
581 PathSet::Set(_) => false,
582 })
583 }
584
585 pub fn suite_path(mut self, suite: &str) -> Self {
586 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
587 self
588 }
589
590 pub fn never(mut self) -> ShouldRun<'a> {
592 self.paths.insert(PathSet::empty());
593 self
594 }
595
596 fn pathset_for_paths_removing_matches(
606 &self,
607 paths: &mut [CLIStepPath],
608 kind: Kind,
609 ) -> Vec<PathSet> {
610 let mut sets = vec![];
611 for pathset in &self.paths {
612 let subset = pathset.intersection_removing_matches(paths, kind);
613 if subset != PathSet::empty() {
614 sets.push(subset);
615 }
616 }
617 sets
618 }
619}
620
621#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
622pub enum Kind {
623 #[value(alias = "b")]
624 Build,
625 #[value(alias = "c")]
626 Check,
627 Clippy,
628 Fix,
629 Format,
630 #[value(alias = "t")]
631 Test,
632 Miri,
633 MiriSetup,
634 MiriTest,
635 Bench,
636 #[value(alias = "d")]
637 Doc,
638 Clean,
639 Dist,
640 Install,
641 #[value(alias = "r")]
642 Run,
643 Setup,
644 Vendor,
645 Perf,
646}
647
648impl Kind {
649 pub fn as_str(&self) -> &'static str {
650 match self {
651 Kind::Build => "build",
652 Kind::Check => "check",
653 Kind::Clippy => "clippy",
654 Kind::Fix => "fix",
655 Kind::Format => "fmt",
656 Kind::Test => "test",
657 Kind::Miri => "miri",
658 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
659 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
660 Kind::Bench => "bench",
661 Kind::Doc => "doc",
662 Kind::Clean => "clean",
663 Kind::Dist => "dist",
664 Kind::Install => "install",
665 Kind::Run => "run",
666 Kind::Setup => "setup",
667 Kind::Vendor => "vendor",
668 Kind::Perf => "perf",
669 }
670 }
671
672 pub fn description(&self) -> String {
673 match self {
674 Kind::Test => "Testing",
675 Kind::Bench => "Benchmarking",
676 Kind::Doc => "Documenting",
677 Kind::Run => "Running",
678 Kind::Clippy => "Linting",
679 Kind::Perf => "Profiling & benchmarking",
680 _ => {
681 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
682 return format!("{title_letter}{}ing", &self.as_str()[1..]);
683 }
684 }
685 .to_owned()
686 }
687}
688
689#[derive(Debug, Clone, Hash, PartialEq, Eq)]
690struct Libdir {
691 compiler: Compiler,
692 target: TargetSelection,
693}
694
695impl Step for Libdir {
696 type Output = PathBuf;
697
698 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
699 run.never()
700 }
701
702 fn run(self, builder: &Builder<'_>) -> PathBuf {
703 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
704 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
705
706 if !builder.config.dry_run() {
707 if !builder.download_rustc() {
710 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
711 builder.do_if_verbose(|| {
712 eprintln!(
713 "Removing sysroot {} to avoid caching bugs",
714 sysroot_target_libdir.display()
715 )
716 });
717 let _ = fs::remove_dir_all(&sysroot_target_libdir);
718 t!(fs::create_dir_all(&sysroot_target_libdir));
719 }
720
721 if self.compiler.stage == 0 {
722 dist::maybe_install_llvm_target(
726 builder,
727 self.compiler.host,
728 &builder.sysroot(self.compiler),
729 );
730 }
731 }
732
733 sysroot
734 }
735}
736
737#[cfg(feature = "tracing")]
738pub const STEP_SPAN_TARGET: &str = "STEP";
739
740impl<'a> Builder<'a> {
741 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
742 macro_rules! describe {
743 ($($rule:ty),+ $(,)?) => {{
744 vec![$(StepDescription::from::<$rule>(kind)),+]
745 }};
746 }
747 match kind {
748 Kind::Build => describe!(
749 compile::Std,
750 compile::Rustc,
751 compile::Assemble,
752 compile::CraneliftCodegenBackend,
753 compile::GccCodegenBackend,
754 compile::StartupObjects,
755 tool::BuildManifest,
756 tool::Rustbook,
757 tool::ErrorIndex,
758 tool::UnstableBookGen,
759 tool::Tidy,
760 tool::Linkchecker,
761 tool::CargoTest,
762 tool::Compiletest,
763 tool::RemoteTestServer,
764 tool::RemoteTestClient,
765 tool::RustInstaller,
766 tool::FeaturesStatusDump,
767 tool::Cargo,
768 tool::RustAnalyzer,
769 tool::RustAnalyzerProcMacroSrv,
770 tool::Rustdoc,
771 tool::Clippy,
772 tool::CargoClippy,
773 llvm::Llvm,
774 gcc::Gcc,
775 llvm::Sanitizers,
776 tool::Rustfmt,
777 tool::Cargofmt,
778 tool::Miri,
779 tool::CargoMiri,
780 llvm::Lld,
781 llvm::Enzyme,
782 llvm::CrtBeginEnd,
783 tool::RustdocGUITest,
784 tool::OptimizedDist,
785 tool::CoverageDump,
786 tool::LlvmBitcodeLinker,
787 tool::RustcPerf,
788 tool::WasmComponentLd,
789 tool::LldWrapper
790 ),
791 Kind::Clippy => describe!(
792 clippy::Std,
793 clippy::Rustc,
794 clippy::Bootstrap,
795 clippy::BuildHelper,
796 clippy::BuildManifest,
797 clippy::CargoMiri,
798 clippy::Clippy,
799 clippy::CodegenGcc,
800 clippy::CollectLicenseMetadata,
801 clippy::Compiletest,
802 clippy::CoverageDump,
803 clippy::Jsondocck,
804 clippy::Jsondoclint,
805 clippy::LintDocs,
806 clippy::LlvmBitcodeLinker,
807 clippy::Miri,
808 clippy::MiroptTestTools,
809 clippy::OptDist,
810 clippy::RemoteTestClient,
811 clippy::RemoteTestServer,
812 clippy::RustAnalyzer,
813 clippy::Rustdoc,
814 clippy::Rustfmt,
815 clippy::RustInstaller,
816 clippy::TestFloatParse,
817 clippy::Tidy,
818 clippy::CI,
819 ),
820 Kind::Check | Kind::Fix => describe!(
821 check::Rustc,
822 check::Rustdoc,
823 check::CraneliftCodegenBackend,
824 check::GccCodegenBackend,
825 check::Clippy,
826 check::Miri,
827 check::CargoMiri,
828 check::MiroptTestTools,
829 check::Rustfmt,
830 check::RustAnalyzer,
831 check::TestFloatParse,
832 check::Bootstrap,
833 check::RunMakeSupport,
834 check::Compiletest,
835 check::RustdocGuiTest,
836 check::FeaturesStatusDump,
837 check::CoverageDump,
838 check::Linkchecker,
839 check::BumpStage0,
840 check::Tidy,
841 check::Std,
848 ),
849 Kind::Test => describe!(
850 crate::core::build_steps::toolstate::ToolStateCheck,
851 test::Tidy,
852 test::BootstrapPy,
853 test::Bootstrap,
854 test::Ui,
855 test::Crashes,
856 test::Coverage,
857 test::MirOpt,
858 test::CodegenLlvm,
859 test::CodegenUnits,
860 test::AssemblyLlvm,
861 test::Incremental,
862 test::Debuginfo,
863 test::UiFullDeps,
864 test::RustdocHtml,
865 test::CoverageRunRustdoc,
866 test::Pretty,
867 test::CodegenCranelift,
868 test::CodegenGCC,
869 test::Crate,
870 test::CrateLibrustc,
871 test::CrateRustdoc,
872 test::CrateRustdocJsonTypes,
873 test::CrateBootstrap,
874 test::RemoteTestClientTests,
875 test::Linkcheck,
876 test::TierCheck,
877 test::Cargotest,
878 test::Cargo,
879 test::RustAnalyzer,
880 test::ErrorIndex,
881 test::Distcheck,
882 test::Nomicon,
883 test::Reference,
884 test::RustdocBook,
885 test::RustByExample,
886 test::TheBook,
887 test::UnstableBook,
888 test::RustcBook,
889 test::LintDocs,
890 test::EmbeddedBook,
891 test::EditionGuide,
892 test::Rustfmt,
893 test::Miri,
894 test::CargoMiri,
895 test::Clippy,
896 test::CompiletestTest,
897 test::CrateRunMakeSupport,
898 test::CrateBuildHelper,
899 test::RustdocJSStd,
900 test::RustdocJSNotStd,
901 test::RustdocGUI,
902 test::RustdocTheme,
903 test::RustdocUi,
904 test::RustdocJson,
905 test::HtmlCheck,
906 test::RustInstaller,
907 test::TestFloatParse,
908 test::CollectLicenseMetadata,
909 test::RunMake,
910 test::RunMakeCargo,
911 test::BuildStd,
912 ),
913 Kind::Miri => describe!(test::Crate),
914 Kind::Bench => describe!(test::Crate, test::CrateLibrustc, test::CrateRustdoc),
915 Kind::Doc => describe!(
916 doc::UnstableBook,
917 doc::UnstableBookGen,
918 doc::TheBook,
919 doc::Standalone,
920 doc::Std,
921 doc::Rustc,
922 doc::Rustdoc,
923 doc::Rustfmt,
924 doc::ErrorIndex,
925 doc::Nomicon,
926 doc::Reference,
927 doc::RustdocBook,
928 doc::RustByExample,
929 doc::RustcBook,
930 doc::Cargo,
931 doc::CargoBook,
932 doc::Clippy,
933 doc::ClippyBook,
934 doc::Miri,
935 doc::EmbeddedBook,
936 doc::EditionGuide,
937 doc::StyleGuide,
938 doc::Tidy,
939 doc::Bootstrap,
940 doc::Releases,
941 doc::RunMakeSupport,
942 doc::BuildHelper,
943 doc::Compiletest,
944 ),
945 Kind::Dist => describe!(
946 dist::Docs,
947 dist::RustcDocs,
948 dist::JsonDocs,
949 dist::Mingw,
950 dist::Rustc,
951 dist::CraneliftCodegenBackend,
952 dist::GccCodegenBackend,
953 dist::Std,
954 dist::RustcDev,
955 dist::Analysis,
956 dist::Src,
957 dist::Cargo,
958 dist::RustAnalyzer,
959 dist::Rustfmt,
960 dist::Clippy,
961 dist::Miri,
962 dist::LlvmTools,
963 dist::LlvmBitcodeLinker,
964 dist::RustDev,
965 dist::Enzyme,
966 dist::Bootstrap,
967 dist::Extended,
968 dist::PlainSourceTarball,
973 dist::PlainSourceTarballGpl,
974 dist::BuildManifest,
975 dist::ReproducibleArtifacts,
976 dist::GccDev,
977 dist::Gcc
978 ),
979 Kind::Install => describe!(
980 install::Docs,
981 install::Std,
982 install::Rustc,
987 install::RustcDev,
988 install::Cargo,
989 install::RustAnalyzer,
990 install::Rustfmt,
991 install::Clippy,
992 install::Miri,
993 install::LlvmTools,
994 install::Src,
995 install::RustcCodegenCranelift,
996 install::LlvmBitcodeLinker
997 ),
998 Kind::Run => describe!(
999 run::BuildManifest,
1000 run::BumpStage0,
1001 run::ReplaceVersionPlaceholder,
1002 run::Miri,
1003 run::CollectLicenseMetadata,
1004 run::GenerateCopyright,
1005 run::GenerateWindowsSys,
1006 run::GenerateCompletions,
1007 run::UnicodeTableGenerator,
1008 run::FeaturesStatusDump,
1009 run::CyclicStep,
1010 run::CoverageDump,
1011 run::Rustfmt,
1012 run::GenerateHelp,
1013 ),
1014 Kind::Setup => {
1015 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1016 }
1017 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1018 Kind::Vendor => describe!(vendor::Vendor),
1019 Kind::Format | Kind::Perf => vec![],
1021 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1022 }
1023 }
1024
1025 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1026 let step_descriptions = Builder::get_step_descriptions(kind);
1027 if step_descriptions.is_empty() {
1028 return None;
1029 }
1030
1031 let builder = Self::new_internal(build, kind, vec![]);
1032 let builder = &builder;
1033 let mut should_run = ShouldRun::new(builder, Kind::Build);
1036 for desc in step_descriptions {
1037 should_run.kind = desc.kind;
1038 should_run = (desc.should_run)(should_run);
1039 }
1040 let mut help = String::from("Available paths:\n");
1041 let mut add_path = |path: &Path| {
1042 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1043 };
1044 for pathset in should_run.paths {
1045 match pathset {
1046 PathSet::Set(set) => {
1047 for path in set {
1048 add_path(&path.path);
1049 }
1050 }
1051 PathSet::Suite(path) => {
1052 add_path(&path.path.join("..."));
1053 }
1054 }
1055 }
1056 Some(help)
1057 }
1058
1059 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1060 Builder {
1061 build,
1062 top_stage: build.config.stage,
1063 kind,
1064 cache: Cache::new(),
1065 stack: RefCell::new(Vec::new()),
1066 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1067 paths,
1068 submodule_paths_cache: Default::default(),
1069 log_cli_step_for_tests: None,
1070 }
1071 }
1072
1073 pub fn new(build: &Build) -> Builder<'_> {
1074 let paths = &build.config.paths;
1075 let (kind, paths) = match build.config.cmd {
1076 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1077 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1078 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1079 Subcommand::Fix => (Kind::Fix, &paths[..]),
1080 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1081 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1082 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1083 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1084 Subcommand::Dist => (Kind::Dist, &paths[..]),
1085 Subcommand::Install => (Kind::Install, &paths[..]),
1086 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1087 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1088 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1089 Subcommand::Setup { profile: ref path } => (
1090 Kind::Setup,
1091 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1092 ),
1093 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1094 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1095 };
1096
1097 Self::new_internal(build, kind, paths.to_owned())
1098 }
1099
1100 pub fn execute_cli(&self) {
1101 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1102 }
1103
1104 pub fn run_default_doc_steps(&self) {
1106 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), &[]);
1107 }
1108
1109 pub fn doc_rust_lang_org_channel(&self) -> String {
1110 let channel = match &*self.config.channel {
1111 "stable" => &self.version,
1112 "beta" => "beta",
1113 "nightly" | "dev" => "nightly",
1114 _ => "stable",
1116 };
1117
1118 format!("https://doc.rust-lang.org/{channel}")
1119 }
1120
1121 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1122 cli_paths::match_paths_to_steps_and_run(self, v, paths);
1123 }
1124
1125 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1128 !target.triple.ends_with("-windows-gnu")
1129 }
1130
1131 #[cfg_attr(
1136 feature = "tracing",
1137 instrument(
1138 level = "trace",
1139 name = "Builder::compiler",
1140 target = "COMPILER",
1141 skip_all,
1142 fields(
1143 stage = stage,
1144 host = ?host,
1145 ),
1146 ),
1147 )]
1148 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1149 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1150 }
1151
1152 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1169 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1170 self.compiler(1, self.host_target)
1171 } else {
1172 self.compiler(stage, self.host_target)
1173 }
1174 }
1175
1176 #[cfg_attr(
1188 feature = "tracing",
1189 instrument(
1190 level = "trace",
1191 name = "Builder::compiler_for",
1192 target = "COMPILER_FOR",
1193 skip_all,
1194 fields(
1195 stage = stage,
1196 host = ?host,
1197 target = ?target,
1198 ),
1199 ),
1200 )]
1201 pub fn compiler_for(
1204 &self,
1205 stage: u32,
1206 host: TargetSelection,
1207 target: TargetSelection,
1208 ) -> Compiler {
1209 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1210 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1211 self.compiler(2, self.config.host_target)
1212 } else if self.build.force_use_stage1(stage, target) {
1213 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1214 self.compiler(1, self.config.host_target)
1215 } else {
1216 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1217 self.compiler(stage, host)
1218 };
1219
1220 if stage != resolved_compiler.stage {
1221 resolved_compiler.forced_compiler(true);
1222 }
1223
1224 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1225 resolved_compiler
1226 }
1227
1228 #[cfg_attr(
1235 feature = "tracing",
1236 instrument(
1237 level = "trace",
1238 name = "Builder::std",
1239 target = "STD",
1240 skip_all,
1241 fields(
1242 compiler = ?compiler,
1243 target = ?target,
1244 ),
1245 ),
1246 )]
1247 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1248 if compiler.stage == 0 {
1258 if target != compiler.host {
1259 if self.local_rebuild {
1260 self.ensure(Std::new(compiler, target))
1261 } else {
1262 panic!(
1263 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1264You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1265Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1266",
1267 compiler.host
1268 )
1269 }
1270 } else {
1271 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1273 None
1274 }
1275 } else {
1276 self.ensure(Std::new(compiler, target))
1279 }
1280 }
1281
1282 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1283 self.ensure(compile::Sysroot::new(compiler))
1284 }
1285
1286 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1288 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1289 }
1290
1291 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1294 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1295 }
1296
1297 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1298 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1299 }
1300
1301 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1307 if compiler.is_snapshot(self) {
1308 self.rustc_snapshot_libdir()
1309 } else {
1310 match self.config.libdir_relative() {
1311 Some(relative_libdir) if compiler.stage >= 1 => {
1312 self.sysroot(compiler).join(relative_libdir)
1313 }
1314 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1315 }
1316 }
1317 }
1318
1319 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1325 if compiler.is_snapshot(self) {
1326 libdir(self.config.host_target).as_ref()
1327 } else {
1328 match self.config.libdir_relative() {
1329 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1330 _ => libdir(compiler.host).as_ref(),
1331 }
1332 }
1333 }
1334
1335 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1340 match self.config.libdir_relative() {
1341 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1342 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1343 _ => Path::new("lib"),
1344 }
1345 }
1346
1347 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1348 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1349
1350 if self.config.llvm_from_ci {
1352 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1353 dylib_dirs.push(ci_llvm_lib);
1354 }
1355
1356 dylib_dirs
1357 }
1358
1359 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1362 if cfg!(any(windows, target_os = "cygwin")) {
1366 return;
1367 }
1368
1369 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1370 }
1371
1372 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1374 if compiler.is_snapshot(self) {
1375 self.initial_rustc.clone()
1376 } else {
1377 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1378 }
1379 }
1380
1381 pub fn rustc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1384 let mut cmd = command(self.rustc(compiler));
1385 self.add_rustc_lib_path(compiler, &mut cmd);
1386 cmd
1387 }
1388
1389 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1391 fs::read_dir(self.sysroot_codegen_backends(compiler))
1392 .into_iter()
1393 .flatten()
1394 .filter_map(Result::ok)
1395 .map(|entry| entry.path())
1396 }
1397
1398 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1402 self.ensure(tool::Rustdoc { target_compiler })
1403 }
1404
1405 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1406 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1407
1408 let compilers =
1409 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1410 assert_eq!(run_compiler, compilers.target_compiler());
1411
1412 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1414 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1415 let mut cmd = command(cargo_miri.tool_path);
1417 cmd.env("MIRI", &miri.tool_path);
1418 cmd.env("CARGO", &self.initial_cargo);
1419 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1428 cmd
1429 }
1430
1431 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1434 if build_compiler.stage == 0 {
1435 let cargo_clippy = self
1436 .config
1437 .initial_cargo_clippy
1438 .clone()
1439 .unwrap_or_else(|| self.build.config.download_clippy());
1440
1441 let mut cmd = command(cargo_clippy);
1442 cmd.env("CARGO", &self.initial_cargo);
1443 return cmd;
1444 }
1445
1446 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1450
1451 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1452 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1453 let mut dylib_path = helpers::dylib_path();
1454 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1455
1456 let mut cmd = command(cargo_clippy.tool_path);
1457 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1458 cmd.env("CARGO", &self.initial_cargo);
1459 cmd
1460 }
1461
1462 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1463 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1464 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1465 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1466 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1469 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1470 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1471 .env("RUSTC_BOOTSTRAP", "1");
1472
1473 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1474
1475 if self.config.deny_warnings {
1476 cmd.arg("-Dwarnings");
1477 }
1478 cmd.arg("-Znormalize-docs");
1479 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1480 cmd
1481 }
1482
1483 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1492 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1493 let llvm::LlvmResult { host_llvm_config, .. } = self.ensure(llvm::Llvm { target });
1494 if host_llvm_config.is_file() {
1495 return Some(host_llvm_config);
1496 }
1497 }
1498 None
1499 }
1500
1501 pub fn require_and_update_all_submodules(&self) {
1504 for submodule in self.submodule_paths() {
1505 self.require_submodule(submodule, None);
1506 }
1507 }
1508
1509 pub fn submodule_paths(&self) -> &[String] {
1511 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1512 }
1513
1514 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1518 {
1519 let mut stack = self.stack.borrow_mut();
1520 for stack_step in stack.iter() {
1521 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1523 continue;
1524 }
1525 let mut out = String::new();
1526 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1527 for el in stack.iter().rev() {
1528 out += &format!("\t{el:?}\n");
1529 }
1530 panic!("{}", out);
1531 }
1532 if let Some(out) = self.cache.get(&step) {
1533 #[cfg(feature = "tracing")]
1534 {
1535 if let Some(parent) = stack.last() {
1536 let mut graph = self.build.step_graph.borrow_mut();
1537 graph.register_cached_step(&step, parent, self.config.dry_run());
1538 }
1539 }
1540 return out;
1541 }
1542
1543 #[cfg(feature = "tracing")]
1544 {
1545 let parent = stack.last();
1546 let mut graph = self.build.step_graph.borrow_mut();
1547 graph.register_step_execution(&step, parent, self.config.dry_run());
1548 }
1549
1550 stack.push(Box::new(step.clone()));
1551 }
1552
1553 #[cfg(feature = "build-metrics")]
1554 self.metrics.enter_step(&step, self);
1555
1556 if self.config.print_step_timings && !self.config.dry_run() {
1557 println!("[TIMING:start] {}", pretty_print_step(&step));
1558 }
1559
1560 let (out, dur) = {
1561 let start = Instant::now();
1562 let zero = Duration::new(0, 0);
1563 let parent = self.time_spent_on_dependencies.replace(zero);
1564
1565 #[cfg(feature = "tracing")]
1566 let _span = {
1567 let span = tracing::info_span!(
1569 target: STEP_SPAN_TARGET,
1570 "step",
1573 step_name = pretty_step_name::<S>(),
1574 args = step_debug_args(&step)
1575 );
1576 span.entered()
1577 };
1578
1579 let out = step.clone().run(self);
1580 let dur = start.elapsed();
1581 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1582 (out, dur.saturating_sub(deps))
1583 };
1584
1585 if self.config.print_step_timings && !self.config.dry_run() {
1586 println!(
1587 "[TIMING:end] {} -- {}.{:03}",
1588 pretty_print_step(&step),
1589 dur.as_secs(),
1590 dur.subsec_millis()
1591 );
1592 }
1593
1594 #[cfg(feature = "build-metrics")]
1595 self.metrics.exit_step(self);
1596
1597 {
1598 let mut stack = self.stack.borrow_mut();
1599 let cur_step = stack.pop().expect("step stack empty");
1600 assert_eq!(cur_step.downcast_ref(), Some(&step));
1601 }
1602 self.cache.put(step, out.clone());
1603 out
1604 }
1605
1606 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1610 &'a self,
1611 step: S,
1612 kind: Kind,
1613 ) -> Option<S::Output> {
1614 let desc = StepDescription::from::<S>(kind);
1615 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1616
1617 for pathset in &should_run.paths {
1619 if desc.is_excluded(self, pathset) {
1620 return None;
1621 }
1622 }
1623
1624 if (desc.is_default_step_fn)(self) { Some(self.ensure(step)) } else { None }
1626 }
1627
1628 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1630 let desc = StepDescription::from::<S>(kind);
1631 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1632
1633 for path in &self.paths {
1634 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1635 && !desc.is_excluded(
1636 self,
1637 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1638 )
1639 {
1640 return true;
1641 }
1642 }
1643
1644 false
1645 }
1646
1647 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1648 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1649 self.open_in_browser(path);
1650 } else {
1651 self.info(&format!("Doc path: {}", path.as_ref().display()));
1652 }
1653 }
1654
1655 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1656 let path = path.as_ref();
1657
1658 if self.config.dry_run() || !self.config.cmd.open() {
1659 self.info(&format!("Doc path: {}", path.display()));
1660 return;
1661 }
1662
1663 self.info(&format!("Opening doc {}", path.display()));
1664 if let Err(err) = opener::open(path) {
1665 self.info(&format!("{err}\n"));
1666 }
1667 }
1668
1669 pub fn exec_ctx(&self) -> &ExecutionContext {
1670 &self.config.exec_ctx
1671 }
1672}
1673
1674pub fn pretty_step_name<S: Step>() -> String {
1676 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1678 path.into_iter().rev().collect::<Vec<_>>().join("::")
1679}
1680
1681fn step_debug_args<S: Step>(step: &S) -> String {
1683 let step_dbg_repr = format!("{step:?}");
1684
1685 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1687 (Some(brace_start), Some(brace_end)) => {
1688 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1689 }
1690 _ => String::new(),
1691 }
1692}
1693
1694fn pretty_print_step<S: Step>(step: &S) -> String {
1695 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1696}
1697
1698impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1699 fn as_ref(&self) -> &ExecutionContext {
1700 self.exec_ctx()
1701 }
1702}