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::{LazyLock, 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 DEFAULT: bool = false;
110
111 const IS_HOST: bool = false;
118
119 fn run(self, builder: &Builder<'_>) -> Self::Output;
133
134 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
136
137 fn make_run(_run: RunConfig<'_>) {
141 unimplemented!()
146 }
147
148 fn metadata(&self) -> Option<StepMetadata> {
150 None
151 }
152}
153
154#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct StepMetadata {
157 name: String,
158 kind: Kind,
159 target: TargetSelection,
160 built_by: Option<Compiler>,
161 stage: Option<u32>,
162 metadata: Option<String>,
164}
165
166impl StepMetadata {
167 pub fn build(name: &str, target: TargetSelection) -> Self {
168 Self::new(name, target, Kind::Build)
169 }
170
171 pub fn check(name: &str, target: TargetSelection) -> Self {
172 Self::new(name, target, Kind::Check)
173 }
174
175 pub fn clippy(name: &str, target: TargetSelection) -> Self {
176 Self::new(name, target, Kind::Clippy)
177 }
178
179 pub fn doc(name: &str, target: TargetSelection) -> Self {
180 Self::new(name, target, Kind::Doc)
181 }
182
183 pub fn dist(name: &str, target: TargetSelection) -> Self {
184 Self::new(name, target, Kind::Dist)
185 }
186
187 pub fn test(name: &str, target: TargetSelection) -> Self {
188 Self::new(name, target, Kind::Test)
189 }
190
191 pub fn run(name: &str, target: TargetSelection) -> Self {
192 Self::new(name, target, Kind::Run)
193 }
194
195 fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
196 Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
197 }
198
199 pub fn built_by(mut self, compiler: Compiler) -> Self {
200 self.built_by = Some(compiler);
201 self
202 }
203
204 pub fn stage(mut self, stage: u32) -> Self {
205 self.stage = Some(stage);
206 self
207 }
208
209 pub fn with_metadata(mut self, metadata: String) -> Self {
210 self.metadata = Some(metadata);
211 self
212 }
213
214 pub fn get_stage(&self) -> Option<u32> {
215 self.stage.or(self
216 .built_by
217 .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
220 }
221
222 pub fn get_name(&self) -> &str {
223 &self.name
224 }
225
226 pub fn get_target(&self) -> TargetSelection {
227 self.target
228 }
229}
230
231pub struct RunConfig<'a> {
232 pub builder: &'a Builder<'a>,
233 pub target: TargetSelection,
234 pub paths: Vec<PathSet>,
235}
236
237impl RunConfig<'_> {
238 pub fn build_triple(&self) -> TargetSelection {
239 self.builder.build.host_target
240 }
241
242 #[track_caller]
244 pub fn cargo_crates_in_set(&self) -> Vec<String> {
245 let mut crates = Vec::new();
246 for krate in &self.paths {
247 let path = &krate.assert_single_path().path;
248
249 let crate_name = self
250 .builder
251 .crate_paths
252 .get(path)
253 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
254
255 crates.push(crate_name.to_string());
256 }
257 crates
258 }
259
260 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
267 let has_alias =
268 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
269 if !has_alias {
270 return self.cargo_crates_in_set();
271 }
272
273 let crates = match alias {
274 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
275 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
276 };
277
278 crates.into_iter().map(|krate| krate.name.to_string()).collect()
279 }
280}
281
282#[derive(Debug, Copy, Clone)]
283pub enum Alias {
284 Library,
285 Compiler,
286}
287
288impl Alias {
289 fn as_str(self) -> &'static str {
290 match self {
291 Alias::Library => "library",
292 Alias::Compiler => "compiler",
293 }
294 }
295}
296
297pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
301 if crates.is_empty() {
302 return "".into();
303 }
304
305 let mut descr = String::from("{");
306 descr.push_str(crates[0].as_ref());
307 for krate in &crates[1..] {
308 descr.push_str(", ");
309 descr.push_str(krate.as_ref());
310 }
311 descr.push('}');
312 descr
313}
314
315struct StepDescription {
316 default: bool,
317 is_host: bool,
318 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
319 make_run: fn(RunConfig<'_>),
320 name: &'static str,
321 kind: Kind,
322}
323
324#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
325pub struct TaskPath {
326 pub path: PathBuf,
327 pub kind: Option<Kind>,
328}
329
330impl Debug for TaskPath {
331 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332 if let Some(kind) = &self.kind {
333 write!(f, "{}::", kind.as_str())?;
334 }
335 write!(f, "{}", self.path.display())
336 }
337}
338
339#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
341pub enum PathSet {
342 Set(BTreeSet<TaskPath>),
353 Suite(TaskPath),
360}
361
362impl PathSet {
363 fn empty() -> PathSet {
364 PathSet::Set(BTreeSet::new())
365 }
366
367 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
368 let mut set = BTreeSet::new();
369 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
370 PathSet::Set(set)
371 }
372
373 fn has(&self, needle: &Path, module: Kind) -> bool {
374 match self {
375 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
376 PathSet::Suite(suite) => Self::check(suite, needle, module),
377 }
378 }
379
380 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
382 let check_path = || {
383 p.path.ends_with(needle) || p.path.starts_with(needle)
385 };
386 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
387 }
388
389 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
396 let mut check = |p| {
397 let mut result = false;
398 for n in needles.iter_mut() {
399 let matched = Self::check(p, &n.path, module);
400 if matched {
401 n.will_be_executed = true;
402 result = true;
403 }
404 }
405 result
406 };
407 match self {
408 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
409 PathSet::Suite(suite) => {
410 if check(suite) {
411 self.clone()
412 } else {
413 PathSet::empty()
414 }
415 }
416 }
417 }
418
419 #[track_caller]
423 pub fn assert_single_path(&self) -> &TaskPath {
424 match self {
425 PathSet::Set(set) => {
426 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
427 set.iter().next().unwrap()
428 }
429 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
430 }
431 }
432}
433
434impl StepDescription {
435 fn from<S: Step>(kind: Kind) -> StepDescription {
436 StepDescription {
437 default: S::DEFAULT,
438 is_host: S::IS_HOST,
439 should_run: S::should_run,
440 make_run: S::make_run,
441 name: std::any::type_name::<S>(),
442 kind,
443 }
444 }
445
446 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
447 pathsets.retain(|set| !self.is_excluded(builder, set));
448
449 if pathsets.is_empty() {
450 return;
451 }
452
453 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
455
456 if let Some(ref log_cli_step) = builder.log_cli_step_for_tests {
458 log_cli_step(self, &pathsets, targets);
459 return;
461 }
462
463 for target in targets {
464 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
465 (self.make_run)(run);
466 }
467 }
468
469 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
470 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
471 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
472 println!("Skipping {pathset:?} because it is excluded");
473 }
474 return true;
475 }
476
477 if !builder.config.skip.is_empty()
478 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
479 {
480 builder.do_if_verbose(|| {
481 println!(
482 "{:?} not skipped for {:?} -- not in {:?}",
483 pathset, self.name, builder.config.skip
484 )
485 });
486 }
487 false
488 }
489}
490
491enum ReallyDefault<'a> {
492 Bool(bool),
493 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
494}
495
496pub struct ShouldRun<'a> {
497 pub builder: &'a Builder<'a>,
498 kind: Kind,
499
500 paths: BTreeSet<PathSet>,
502
503 is_really_default: ReallyDefault<'a>,
506}
507
508impl<'a> ShouldRun<'a> {
509 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
510 ShouldRun {
511 builder,
512 kind,
513 paths: BTreeSet::new(),
514 is_really_default: ReallyDefault::Bool(true), }
516 }
517
518 pub fn default_condition(mut self, cond: bool) -> Self {
519 self.is_really_default = ReallyDefault::Bool(cond);
520 self
521 }
522
523 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
524 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
525 self
526 }
527
528 pub fn is_really_default(&self) -> bool {
529 match &self.is_really_default {
530 ReallyDefault::Bool(val) => *val,
531 ReallyDefault::Lazy(lazy) => *lazy.deref(),
532 }
533 }
534
535 pub fn crate_or_deps(self, name: &str) -> Self {
540 let crates = self.builder.in_tree_crates(name, None);
541 self.crates(crates)
542 }
543
544 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
550 for krate in crates {
551 let path = krate.local_path(self.builder);
552 self.paths.insert(PathSet::one(path, self.kind));
553 }
554 self
555 }
556
557 pub fn alias(mut self, alias: &str) -> Self {
559 assert!(
563 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
564 "use `builder.path()` for real paths: {alias}"
565 );
566 self.paths.insert(PathSet::Set(
567 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
568 ));
569 self
570 }
571
572 pub fn path(self, path: &str) -> Self {
576 self.paths(&[path])
577 }
578
579 pub fn paths(mut self, paths: &[&str]) -> Self {
589 let submodules_paths = self.builder.submodule_paths();
590
591 self.paths.insert(PathSet::Set(
592 paths
593 .iter()
594 .map(|p| {
595 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
597 assert!(
598 self.builder.src.join(p).exists(),
599 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
600 );
601 }
602
603 TaskPath { path: p.into(), kind: Some(self.kind) }
604 })
605 .collect(),
606 ));
607 self
608 }
609
610 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
612 self.paths.iter().find(|pathset| match pathset {
613 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
614 PathSet::Set(_) => false,
615 })
616 }
617
618 pub fn suite_path(mut self, suite: &str) -> Self {
619 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
620 self
621 }
622
623 pub fn never(mut self) -> ShouldRun<'a> {
625 self.paths.insert(PathSet::empty());
626 self
627 }
628
629 fn pathset_for_paths_removing_matches(
639 &self,
640 paths: &mut [CLIStepPath],
641 kind: Kind,
642 ) -> Vec<PathSet> {
643 let mut sets = vec![];
644 for pathset in &self.paths {
645 let subset = pathset.intersection_removing_matches(paths, kind);
646 if subset != PathSet::empty() {
647 sets.push(subset);
648 }
649 }
650 sets
651 }
652}
653
654#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
655pub enum Kind {
656 #[value(alias = "b")]
657 Build,
658 #[value(alias = "c")]
659 Check,
660 Clippy,
661 Fix,
662 Format,
663 #[value(alias = "t")]
664 Test,
665 Miri,
666 MiriSetup,
667 MiriTest,
668 Bench,
669 #[value(alias = "d")]
670 Doc,
671 Clean,
672 Dist,
673 Install,
674 #[value(alias = "r")]
675 Run,
676 Setup,
677 Vendor,
678 Perf,
679}
680
681impl Kind {
682 pub fn as_str(&self) -> &'static str {
683 match self {
684 Kind::Build => "build",
685 Kind::Check => "check",
686 Kind::Clippy => "clippy",
687 Kind::Fix => "fix",
688 Kind::Format => "fmt",
689 Kind::Test => "test",
690 Kind::Miri => "miri",
691 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
692 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
693 Kind::Bench => "bench",
694 Kind::Doc => "doc",
695 Kind::Clean => "clean",
696 Kind::Dist => "dist",
697 Kind::Install => "install",
698 Kind::Run => "run",
699 Kind::Setup => "setup",
700 Kind::Vendor => "vendor",
701 Kind::Perf => "perf",
702 }
703 }
704
705 pub fn description(&self) -> String {
706 match self {
707 Kind::Test => "Testing",
708 Kind::Bench => "Benchmarking",
709 Kind::Doc => "Documenting",
710 Kind::Run => "Running",
711 Kind::Clippy => "Linting",
712 Kind::Perf => "Profiling & benchmarking",
713 _ => {
714 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
715 return format!("{title_letter}{}ing", &self.as_str()[1..]);
716 }
717 }
718 .to_owned()
719 }
720}
721
722#[derive(Debug, Clone, Hash, PartialEq, Eq)]
723struct Libdir {
724 compiler: Compiler,
725 target: TargetSelection,
726}
727
728impl Step for Libdir {
729 type Output = PathBuf;
730
731 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
732 run.never()
733 }
734
735 fn run(self, builder: &Builder<'_>) -> PathBuf {
736 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
737 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
738
739 if !builder.config.dry_run() {
740 if !builder.download_rustc() {
743 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
744 builder.do_if_verbose(|| {
745 eprintln!(
746 "Removing sysroot {} to avoid caching bugs",
747 sysroot_target_libdir.display()
748 )
749 });
750 let _ = fs::remove_dir_all(&sysroot_target_libdir);
751 t!(fs::create_dir_all(&sysroot_target_libdir));
752 }
753
754 if self.compiler.stage == 0 {
755 dist::maybe_install_llvm_target(
759 builder,
760 self.compiler.host,
761 &builder.sysroot(self.compiler),
762 );
763 }
764 }
765
766 sysroot
767 }
768}
769
770#[cfg(feature = "tracing")]
771pub const STEP_SPAN_TARGET: &str = "STEP";
772
773impl<'a> Builder<'a> {
774 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
775 macro_rules! describe {
776 ($($rule:ty),+ $(,)?) => {{
777 vec![$(StepDescription::from::<$rule>(kind)),+]
778 }};
779 }
780 match kind {
781 Kind::Build => describe!(
782 compile::Std,
783 compile::Rustc,
784 compile::Assemble,
785 compile::CraneliftCodegenBackend,
786 compile::GccCodegenBackend,
787 compile::StartupObjects,
788 tool::BuildManifest,
789 tool::Rustbook,
790 tool::ErrorIndex,
791 tool::UnstableBookGen,
792 tool::Tidy,
793 tool::Linkchecker,
794 tool::CargoTest,
795 tool::Compiletest,
796 tool::RemoteTestServer,
797 tool::RemoteTestClient,
798 tool::RustInstaller,
799 tool::FeaturesStatusDump,
800 tool::Cargo,
801 tool::RustAnalyzer,
802 tool::RustAnalyzerProcMacroSrv,
803 tool::Rustdoc,
804 tool::Clippy,
805 tool::CargoClippy,
806 llvm::Llvm,
807 gcc::Gcc,
808 llvm::Sanitizers,
809 tool::Rustfmt,
810 tool::Cargofmt,
811 tool::Miri,
812 tool::CargoMiri,
813 llvm::Lld,
814 llvm::Enzyme,
815 llvm::CrtBeginEnd,
816 tool::RustdocGUITest,
817 tool::OptimizedDist,
818 tool::CoverageDump,
819 tool::LlvmBitcodeLinker,
820 tool::RustcPerf,
821 tool::WasmComponentLd,
822 tool::LldWrapper
823 ),
824 Kind::Clippy => describe!(
825 clippy::Std,
826 clippy::Rustc,
827 clippy::Bootstrap,
828 clippy::BuildHelper,
829 clippy::BuildManifest,
830 clippy::CargoMiri,
831 clippy::Clippy,
832 clippy::CodegenGcc,
833 clippy::CollectLicenseMetadata,
834 clippy::Compiletest,
835 clippy::CoverageDump,
836 clippy::Jsondocck,
837 clippy::Jsondoclint,
838 clippy::LintDocs,
839 clippy::LlvmBitcodeLinker,
840 clippy::Miri,
841 clippy::MiroptTestTools,
842 clippy::OptDist,
843 clippy::RemoteTestClient,
844 clippy::RemoteTestServer,
845 clippy::RustAnalyzer,
846 clippy::Rustdoc,
847 clippy::Rustfmt,
848 clippy::RustInstaller,
849 clippy::TestFloatParse,
850 clippy::Tidy,
851 clippy::CI,
852 ),
853 Kind::Check | Kind::Fix => describe!(
854 check::Rustc,
855 check::Rustdoc,
856 check::CraneliftCodegenBackend,
857 check::GccCodegenBackend,
858 check::Clippy,
859 check::Miri,
860 check::CargoMiri,
861 check::MiroptTestTools,
862 check::Rustfmt,
863 check::RustAnalyzer,
864 check::TestFloatParse,
865 check::Bootstrap,
866 check::RunMakeSupport,
867 check::Compiletest,
868 check::RustdocGuiTest,
869 check::FeaturesStatusDump,
870 check::CoverageDump,
871 check::Linkchecker,
872 check::BumpStage0,
873 check::Tidy,
874 check::Std,
881 ),
882 Kind::Test => describe!(
883 crate::core::build_steps::toolstate::ToolStateCheck,
884 test::Tidy,
885 test::BootstrapPy,
886 test::Bootstrap,
887 test::Ui,
888 test::Crashes,
889 test::Coverage,
890 test::MirOpt,
891 test::CodegenLlvm,
892 test::CodegenUnits,
893 test::AssemblyLlvm,
894 test::Incremental,
895 test::Debuginfo,
896 test::UiFullDeps,
897 test::Rustdoc,
898 test::CoverageRunRustdoc,
899 test::Pretty,
900 test::CodegenCranelift,
901 test::CodegenGCC,
902 test::Crate,
903 test::CrateLibrustc,
904 test::CrateRustdoc,
905 test::CrateRustdocJsonTypes,
906 test::CrateBootstrap,
907 test::RemoteTestClientTests,
908 test::Linkcheck,
909 test::TierCheck,
910 test::Cargotest,
911 test::Cargo,
912 test::RustAnalyzer,
913 test::ErrorIndex,
914 test::Distcheck,
915 test::Nomicon,
916 test::Reference,
917 test::RustdocBook,
918 test::RustByExample,
919 test::TheBook,
920 test::UnstableBook,
921 test::RustcBook,
922 test::LintDocs,
923 test::EmbeddedBook,
924 test::EditionGuide,
925 test::Rustfmt,
926 test::Miri,
927 test::CargoMiri,
928 test::Clippy,
929 test::CompiletestTest,
930 test::CrateRunMakeSupport,
931 test::CrateBuildHelper,
932 test::RustdocJSStd,
933 test::RustdocJSNotStd,
934 test::RustdocGUI,
935 test::RustdocTheme,
936 test::RustdocUi,
937 test::RustdocJson,
938 test::HtmlCheck,
939 test::RustInstaller,
940 test::TestFloatParse,
941 test::CollectLicenseMetadata,
942 test::RunMake,
943 test::RunMakeCargo,
944 ),
945 Kind::Miri => describe!(test::Crate),
946 Kind::Bench => describe!(test::Crate, test::CrateLibrustc, test::CrateRustdoc),
947 Kind::Doc => describe!(
948 doc::UnstableBook,
949 doc::UnstableBookGen,
950 doc::TheBook,
951 doc::Standalone,
952 doc::Std,
953 doc::Rustc,
954 doc::Rustdoc,
955 doc::Rustfmt,
956 doc::ErrorIndex,
957 doc::Nomicon,
958 doc::Reference,
959 doc::RustdocBook,
960 doc::RustByExample,
961 doc::RustcBook,
962 doc::Cargo,
963 doc::CargoBook,
964 doc::Clippy,
965 doc::ClippyBook,
966 doc::Miri,
967 doc::EmbeddedBook,
968 doc::EditionGuide,
969 doc::StyleGuide,
970 doc::Tidy,
971 doc::Bootstrap,
972 doc::Releases,
973 doc::RunMakeSupport,
974 doc::BuildHelper,
975 doc::Compiletest,
976 ),
977 Kind::Dist => describe!(
978 dist::Docs,
979 dist::RustcDocs,
980 dist::JsonDocs,
981 dist::Mingw,
982 dist::Rustc,
983 dist::CraneliftCodegenBackend,
984 dist::Std,
985 dist::RustcDev,
986 dist::Analysis,
987 dist::Src,
988 dist::Cargo,
989 dist::RustAnalyzer,
990 dist::Rustfmt,
991 dist::Clippy,
992 dist::Miri,
993 dist::LlvmTools,
994 dist::LlvmBitcodeLinker,
995 dist::RustDev,
996 dist::Bootstrap,
997 dist::Extended,
998 dist::PlainSourceTarball,
1003 dist::BuildManifest,
1004 dist::ReproducibleArtifacts,
1005 dist::Gcc
1006 ),
1007 Kind::Install => describe!(
1008 install::Docs,
1009 install::Std,
1010 install::Rustc,
1015 install::Cargo,
1016 install::RustAnalyzer,
1017 install::Rustfmt,
1018 install::Clippy,
1019 install::Miri,
1020 install::LlvmTools,
1021 install::Src,
1022 install::RustcCodegenCranelift,
1023 install::LlvmBitcodeLinker
1024 ),
1025 Kind::Run => describe!(
1026 run::BuildManifest,
1027 run::BumpStage0,
1028 run::ReplaceVersionPlaceholder,
1029 run::Miri,
1030 run::CollectLicenseMetadata,
1031 run::GenerateCopyright,
1032 run::GenerateWindowsSys,
1033 run::GenerateCompletions,
1034 run::UnicodeTableGenerator,
1035 run::FeaturesStatusDump,
1036 run::CyclicStep,
1037 run::CoverageDump,
1038 run::Rustfmt,
1039 run::GenerateHelp,
1040 ),
1041 Kind::Setup => {
1042 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1043 }
1044 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1045 Kind::Vendor => describe!(vendor::Vendor),
1046 Kind::Format | Kind::Perf => vec![],
1048 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1049 }
1050 }
1051
1052 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1053 let step_descriptions = Builder::get_step_descriptions(kind);
1054 if step_descriptions.is_empty() {
1055 return None;
1056 }
1057
1058 let builder = Self::new_internal(build, kind, vec![]);
1059 let builder = &builder;
1060 let mut should_run = ShouldRun::new(builder, Kind::Build);
1063 for desc in step_descriptions {
1064 should_run.kind = desc.kind;
1065 should_run = (desc.should_run)(should_run);
1066 }
1067 let mut help = String::from("Available paths:\n");
1068 let mut add_path = |path: &Path| {
1069 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1070 };
1071 for pathset in should_run.paths {
1072 match pathset {
1073 PathSet::Set(set) => {
1074 for path in set {
1075 add_path(&path.path);
1076 }
1077 }
1078 PathSet::Suite(path) => {
1079 add_path(&path.path.join("..."));
1080 }
1081 }
1082 }
1083 Some(help)
1084 }
1085
1086 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1087 Builder {
1088 build,
1089 top_stage: build.config.stage,
1090 kind,
1091 cache: Cache::new(),
1092 stack: RefCell::new(Vec::new()),
1093 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1094 paths,
1095 submodule_paths_cache: Default::default(),
1096 log_cli_step_for_tests: None,
1097 }
1098 }
1099
1100 pub fn new(build: &Build) -> Builder<'_> {
1101 let paths = &build.config.paths;
1102 let (kind, paths) = match build.config.cmd {
1103 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1104 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1105 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1106 Subcommand::Fix => (Kind::Fix, &paths[..]),
1107 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1108 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1109 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1110 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1111 Subcommand::Dist => (Kind::Dist, &paths[..]),
1112 Subcommand::Install => (Kind::Install, &paths[..]),
1113 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1114 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1115 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1116 Subcommand::Setup { profile: ref path } => (
1117 Kind::Setup,
1118 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1119 ),
1120 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1121 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1122 };
1123
1124 Self::new_internal(build, kind, paths.to_owned())
1125 }
1126
1127 pub fn execute_cli(&self) {
1128 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1129 }
1130
1131 pub fn run_default_doc_steps(&self) {
1133 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), &[]);
1134 }
1135
1136 pub fn doc_rust_lang_org_channel(&self) -> String {
1137 let channel = match &*self.config.channel {
1138 "stable" => &self.version,
1139 "beta" => "beta",
1140 "nightly" | "dev" => "nightly",
1141 _ => "stable",
1143 };
1144
1145 format!("https://doc.rust-lang.org/{channel}")
1146 }
1147
1148 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1149 cli_paths::match_paths_to_steps_and_run(self, v, paths);
1150 }
1151
1152 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1155 !target.triple.ends_with("-windows-gnu")
1156 }
1157
1158 #[cfg_attr(
1163 feature = "tracing",
1164 instrument(
1165 level = "trace",
1166 name = "Builder::compiler",
1167 target = "COMPILER",
1168 skip_all,
1169 fields(
1170 stage = stage,
1171 host = ?host,
1172 ),
1173 ),
1174 )]
1175 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1176 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1177 }
1178
1179 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1196 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1197 self.compiler(1, self.host_target)
1198 } else {
1199 self.compiler(stage, self.host_target)
1200 }
1201 }
1202
1203 #[cfg_attr(
1215 feature = "tracing",
1216 instrument(
1217 level = "trace",
1218 name = "Builder::compiler_for",
1219 target = "COMPILER_FOR",
1220 skip_all,
1221 fields(
1222 stage = stage,
1223 host = ?host,
1224 target = ?target,
1225 ),
1226 ),
1227 )]
1228 pub fn compiler_for(
1231 &self,
1232 stage: u32,
1233 host: TargetSelection,
1234 target: TargetSelection,
1235 ) -> Compiler {
1236 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1237 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1238 self.compiler(2, self.config.host_target)
1239 } else if self.build.force_use_stage1(stage, target) {
1240 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1241 self.compiler(1, self.config.host_target)
1242 } else {
1243 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1244 self.compiler(stage, host)
1245 };
1246
1247 if stage != resolved_compiler.stage {
1248 resolved_compiler.forced_compiler(true);
1249 }
1250
1251 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1252 resolved_compiler
1253 }
1254
1255 #[cfg_attr(
1262 feature = "tracing",
1263 instrument(
1264 level = "trace",
1265 name = "Builder::std",
1266 target = "STD",
1267 skip_all,
1268 fields(
1269 compiler = ?compiler,
1270 target = ?target,
1271 ),
1272 ),
1273 )]
1274 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1275 if compiler.stage == 0 {
1285 if target != compiler.host {
1286 if self.local_rebuild {
1287 self.ensure(Std::new(compiler, target))
1288 } else {
1289 panic!(
1290 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1291You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1292Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1293",
1294 compiler.host
1295 )
1296 }
1297 } else {
1298 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1300 None
1301 }
1302 } else {
1303 self.ensure(Std::new(compiler, target))
1306 }
1307 }
1308
1309 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1310 self.ensure(compile::Sysroot::new(compiler))
1311 }
1312
1313 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1315 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1316 }
1317
1318 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1321 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1322 }
1323
1324 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1325 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1326 }
1327
1328 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1334 if compiler.is_snapshot(self) {
1335 self.rustc_snapshot_libdir()
1336 } else {
1337 match self.config.libdir_relative() {
1338 Some(relative_libdir) if compiler.stage >= 1 => {
1339 self.sysroot(compiler).join(relative_libdir)
1340 }
1341 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1342 }
1343 }
1344 }
1345
1346 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1352 if compiler.is_snapshot(self) {
1353 libdir(self.config.host_target).as_ref()
1354 } else {
1355 match self.config.libdir_relative() {
1356 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1357 _ => libdir(compiler.host).as_ref(),
1358 }
1359 }
1360 }
1361
1362 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1367 match self.config.libdir_relative() {
1368 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1369 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1370 _ => Path::new("lib"),
1371 }
1372 }
1373
1374 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1375 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1376
1377 if self.config.llvm_from_ci {
1379 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1380 dylib_dirs.push(ci_llvm_lib);
1381 }
1382
1383 dylib_dirs
1384 }
1385
1386 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1389 if cfg!(any(windows, target_os = "cygwin")) {
1393 return;
1394 }
1395
1396 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1397 }
1398
1399 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1401 if compiler.is_snapshot(self) {
1402 self.initial_rustc.clone()
1403 } else {
1404 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1405 }
1406 }
1407
1408 pub fn rustc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1411 let mut cmd = command(self.rustc(compiler));
1412 self.add_rustc_lib_path(compiler, &mut cmd);
1413 cmd
1414 }
1415
1416 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1418 fs::read_dir(self.sysroot_codegen_backends(compiler))
1419 .into_iter()
1420 .flatten()
1421 .filter_map(Result::ok)
1422 .map(|entry| entry.path())
1423 }
1424
1425 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1429 self.ensure(tool::Rustdoc { target_compiler })
1430 }
1431
1432 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1433 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1434
1435 let compilers =
1436 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1437 assert_eq!(run_compiler, compilers.target_compiler());
1438
1439 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1441 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1442 let mut cmd = command(cargo_miri.tool_path);
1444 cmd.env("MIRI", &miri.tool_path);
1445 cmd.env("CARGO", &self.initial_cargo);
1446 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1455 cmd
1456 }
1457
1458 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1461 if build_compiler.stage == 0 {
1462 let cargo_clippy = self
1463 .config
1464 .initial_cargo_clippy
1465 .clone()
1466 .unwrap_or_else(|| self.build.config.download_clippy());
1467
1468 let mut cmd = command(cargo_clippy);
1469 cmd.env("CARGO", &self.initial_cargo);
1470 return cmd;
1471 }
1472
1473 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1477
1478 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1479 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1480 let mut dylib_path = helpers::dylib_path();
1481 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1482
1483 let mut cmd = command(cargo_clippy.tool_path);
1484 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1485 cmd.env("CARGO", &self.initial_cargo);
1486 cmd
1487 }
1488
1489 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1490 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1491 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1492 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1493 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1496 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1497 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1498 .env("RUSTC_BOOTSTRAP", "1");
1499
1500 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1501
1502 if self.config.deny_warnings {
1503 cmd.arg("-Dwarnings");
1504 }
1505 cmd.arg("-Znormalize-docs");
1506 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1507 cmd
1508 }
1509
1510 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1519 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1520 let llvm::LlvmResult { host_llvm_config, .. } = self.ensure(llvm::Llvm { target });
1521 if host_llvm_config.is_file() {
1522 return Some(host_llvm_config);
1523 }
1524 }
1525 None
1526 }
1527
1528 pub fn require_and_update_all_submodules(&self) {
1531 for submodule in self.submodule_paths() {
1532 self.require_submodule(submodule, None);
1533 }
1534 }
1535
1536 pub fn submodule_paths(&self) -> &[String] {
1538 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1539 }
1540
1541 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1545 {
1546 let mut stack = self.stack.borrow_mut();
1547 for stack_step in stack.iter() {
1548 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1550 continue;
1551 }
1552 let mut out = String::new();
1553 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1554 for el in stack.iter().rev() {
1555 out += &format!("\t{el:?}\n");
1556 }
1557 panic!("{}", out);
1558 }
1559 if let Some(out) = self.cache.get(&step) {
1560 #[cfg(feature = "tracing")]
1561 {
1562 if let Some(parent) = stack.last() {
1563 let mut graph = self.build.step_graph.borrow_mut();
1564 graph.register_cached_step(&step, parent, self.config.dry_run());
1565 }
1566 }
1567 return out;
1568 }
1569
1570 #[cfg(feature = "tracing")]
1571 {
1572 let parent = stack.last();
1573 let mut graph = self.build.step_graph.borrow_mut();
1574 graph.register_step_execution(&step, parent, self.config.dry_run());
1575 }
1576
1577 stack.push(Box::new(step.clone()));
1578 }
1579
1580 #[cfg(feature = "build-metrics")]
1581 self.metrics.enter_step(&step, self);
1582
1583 if self.config.print_step_timings && !self.config.dry_run() {
1584 println!("[TIMING:start] {}", pretty_print_step(&step));
1585 }
1586
1587 let (out, dur) = {
1588 let start = Instant::now();
1589 let zero = Duration::new(0, 0);
1590 let parent = self.time_spent_on_dependencies.replace(zero);
1591
1592 #[cfg(feature = "tracing")]
1593 let _span = {
1594 let span = tracing::info_span!(
1596 target: STEP_SPAN_TARGET,
1597 "step",
1600 step_name = pretty_step_name::<S>(),
1601 args = step_debug_args(&step)
1602 );
1603 span.entered()
1604 };
1605
1606 let out = step.clone().run(self);
1607 let dur = start.elapsed();
1608 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1609 (out, dur.saturating_sub(deps))
1610 };
1611
1612 if self.config.print_step_timings && !self.config.dry_run() {
1613 println!(
1614 "[TIMING:end] {} -- {}.{:03}",
1615 pretty_print_step(&step),
1616 dur.as_secs(),
1617 dur.subsec_millis()
1618 );
1619 }
1620
1621 #[cfg(feature = "build-metrics")]
1622 self.metrics.exit_step(self);
1623
1624 {
1625 let mut stack = self.stack.borrow_mut();
1626 let cur_step = stack.pop().expect("step stack empty");
1627 assert_eq!(cur_step.downcast_ref(), Some(&step));
1628 }
1629 self.cache.put(step, out.clone());
1630 out
1631 }
1632
1633 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1637 &'a self,
1638 step: S,
1639 kind: Kind,
1640 ) -> Option<S::Output> {
1641 let desc = StepDescription::from::<S>(kind);
1642 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1643
1644 for pathset in &should_run.paths {
1646 if desc.is_excluded(self, pathset) {
1647 return None;
1648 }
1649 }
1650
1651 if desc.default && should_run.is_really_default() { Some(self.ensure(step)) } else { None }
1653 }
1654
1655 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1657 let desc = StepDescription::from::<S>(kind);
1658 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1659
1660 for path in &self.paths {
1661 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1662 && !desc.is_excluded(
1663 self,
1664 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1665 )
1666 {
1667 return true;
1668 }
1669 }
1670
1671 false
1672 }
1673
1674 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1675 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1676 self.open_in_browser(path);
1677 } else {
1678 self.info(&format!("Doc path: {}", path.as_ref().display()));
1679 }
1680 }
1681
1682 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1683 let path = path.as_ref();
1684
1685 if self.config.dry_run() || !self.config.cmd.open() {
1686 self.info(&format!("Doc path: {}", path.display()));
1687 return;
1688 }
1689
1690 self.info(&format!("Opening doc {}", path.display()));
1691 if let Err(err) = opener::open(path) {
1692 self.info(&format!("{err}\n"));
1693 }
1694 }
1695
1696 pub fn exec_ctx(&self) -> &ExecutionContext {
1697 &self.config.exec_ctx
1698 }
1699}
1700
1701pub fn pretty_step_name<S: Step>() -> String {
1703 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1705 path.into_iter().rev().collect::<Vec<_>>().join("::")
1706}
1707
1708fn step_debug_args<S: Step>(step: &S) -> String {
1710 let step_dbg_repr = format!("{step:?}");
1711
1712 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1714 (Some(brace_start), Some(brace_end)) => {
1715 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1716 }
1717 _ => String::new(),
1718 }
1719}
1720
1721fn pretty_print_step<S: Step>(step: &S) -> String {
1722 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1723}
1724
1725impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1726 fn as_ref(&self) -> &ExecutionContext {
1727 self.exec_ctx()
1728 }
1729}