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