1use std::any::{Any, type_name};
2use std::cell::{Cell, RefCell};
3use std::collections::BTreeSet;
4use std::fmt::{self, Debug, Write};
5use std::hash::Hash;
6use std::ops::Deref;
7use std::path::{Path, PathBuf};
8use std::sync::LazyLock;
9use std::time::{Duration, Instant};
10use std::{env, fs};
11
12use clap::ValueEnum;
13
14pub use self::cargo::{Cargo, cargo_profile_var};
15pub use crate::Compiler;
16use crate::core::build_steps::{
17 check, clean, clippy, compile, dist, doc, gcc, install, llvm, run, setup, test, tool, vendor,
18};
19use crate::core::config::flags::Subcommand;
20use crate::core::config::{DryRun, TargetSelection};
21use crate::utils::cache::Cache;
22use crate::utils::exec::{BootstrapCommand, command};
23use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
24use crate::{Build, Crate};
25
26mod cargo;
27
28#[cfg(test)]
29mod tests;
30
31pub struct Builder<'a> {
34 pub build: &'a Build,
36
37 pub top_stage: u32,
41
42 pub kind: Kind,
44
45 cache: Cache,
48
49 stack: RefCell<Vec<Box<dyn Any>>>,
52
53 time_spent_on_dependencies: Cell<Duration>,
55
56 pub paths: Vec<PathBuf>,
60}
61
62impl Deref for Builder<'_> {
63 type Target = Build;
64
65 fn deref(&self) -> &Self::Target {
66 self.build
67 }
68}
69
70pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
71 type Output: Clone;
73
74 const DEFAULT: bool = false;
80
81 const ONLY_HOSTS: bool = false;
83
84 fn run(self, builder: &Builder<'_>) -> Self::Output;
98
99 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
101
102 fn make_run(_run: RunConfig<'_>) {
106 unimplemented!()
111 }
112}
113
114pub struct RunConfig<'a> {
115 pub builder: &'a Builder<'a>,
116 pub target: TargetSelection,
117 pub paths: Vec<PathSet>,
118}
119
120impl RunConfig<'_> {
121 pub fn build_triple(&self) -> TargetSelection {
122 self.builder.build.build
123 }
124
125 #[track_caller]
127 pub fn cargo_crates_in_set(&self) -> Vec<String> {
128 let mut crates = Vec::new();
129 for krate in &self.paths {
130 let path = krate.assert_single_path();
131 let Some(crate_name) = self.builder.crate_paths.get(&path.path) else {
132 panic!("missing crate for path {}", path.path.display())
133 };
134 crates.push(crate_name.to_string());
135 }
136 crates
137 }
138
139 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
146 let has_alias =
147 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
148 if !has_alias {
149 return self.cargo_crates_in_set();
150 }
151
152 let crates = match alias {
153 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
154 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
155 };
156
157 crates.into_iter().map(|krate| krate.name.to_string()).collect()
158 }
159}
160
161#[derive(Debug, Copy, Clone)]
162pub enum Alias {
163 Library,
164 Compiler,
165}
166
167impl Alias {
168 fn as_str(self) -> &'static str {
169 match self {
170 Alias::Library => "library",
171 Alias::Compiler => "compiler",
172 }
173 }
174}
175
176pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
180 if crates.is_empty() {
181 return "".into();
182 }
183
184 let mut descr = String::from(" {");
185 descr.push_str(crates[0].as_ref());
186 for krate in &crates[1..] {
187 descr.push_str(", ");
188 descr.push_str(krate.as_ref());
189 }
190 descr.push('}');
191 descr
192}
193
194struct StepDescription {
195 default: bool,
196 only_hosts: bool,
197 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
198 make_run: fn(RunConfig<'_>),
199 name: &'static str,
200 kind: Kind,
201}
202
203#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
204pub struct TaskPath {
205 pub path: PathBuf,
206 pub kind: Option<Kind>,
207}
208
209impl Debug for TaskPath {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 if let Some(kind) = &self.kind {
212 write!(f, "{}::", kind.as_str())?;
213 }
214 write!(f, "{}", self.path.display())
215 }
216}
217
218#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
220pub enum PathSet {
221 Set(BTreeSet<TaskPath>),
232 Suite(TaskPath),
239}
240
241impl PathSet {
242 fn empty() -> PathSet {
243 PathSet::Set(BTreeSet::new())
244 }
245
246 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
247 let mut set = BTreeSet::new();
248 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
249 PathSet::Set(set)
250 }
251
252 fn has(&self, needle: &Path, module: Kind) -> bool {
253 match self {
254 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
255 PathSet::Suite(suite) => Self::check(suite, needle, module),
256 }
257 }
258
259 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
261 let check_path = || {
262 p.path.ends_with(needle) || p.path.starts_with(needle)
264 };
265 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
266 }
267
268 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
275 let mut check = |p| {
276 let mut result = false;
277 for n in needles.iter_mut() {
278 let matched = Self::check(p, &n.path, module);
279 if matched {
280 n.will_be_executed = true;
281 result = true;
282 }
283 }
284 result
285 };
286 match self {
287 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
288 PathSet::Suite(suite) => {
289 if check(suite) {
290 self.clone()
291 } else {
292 PathSet::empty()
293 }
294 }
295 }
296 }
297
298 #[track_caller]
302 pub fn assert_single_path(&self) -> &TaskPath {
303 match self {
304 PathSet::Set(set) => {
305 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
306 set.iter().next().unwrap()
307 }
308 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
309 }
310 }
311}
312
313const PATH_REMAP: &[(&str, &[&str])] = &[
314 ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
317 (
319 "tests",
320 &[
321 "tests/assembly",
323 "tests/codegen",
324 "tests/codegen-units",
325 "tests/coverage",
326 "tests/coverage-run-rustdoc",
327 "tests/crashes",
328 "tests/debuginfo",
329 "tests/incremental",
330 "tests/mir-opt",
331 "tests/pretty",
332 "tests/run-make",
333 "tests/rustdoc",
334 "tests/rustdoc-gui",
335 "tests/rustdoc-js",
336 "tests/rustdoc-js-std",
337 "tests/rustdoc-json",
338 "tests/rustdoc-ui",
339 "tests/ui",
340 "tests/ui-fulldeps",
341 ],
343 ),
344];
345
346fn remap_paths(paths: &mut Vec<PathBuf>) {
347 let mut remove = vec![];
348 let mut add = vec![];
349 for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
350 {
351 for &(search, replace) in PATH_REMAP {
352 if path.trim_matches(std::path::is_separator) == search {
354 remove.push(i);
355 add.extend(replace.iter().map(PathBuf::from));
356 break;
357 }
358 }
359 }
360 remove.sort();
361 remove.dedup();
362 for idx in remove.into_iter().rev() {
363 paths.remove(idx);
364 }
365 paths.append(&mut add);
366}
367
368#[derive(Clone, PartialEq)]
369struct CLIStepPath {
370 path: PathBuf,
371 will_be_executed: bool,
372}
373
374#[cfg(test)]
375impl CLIStepPath {
376 fn will_be_executed(mut self, will_be_executed: bool) -> Self {
377 self.will_be_executed = will_be_executed;
378 self
379 }
380}
381
382impl Debug for CLIStepPath {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 write!(f, "{}", self.path.display())
385 }
386}
387
388impl From<PathBuf> for CLIStepPath {
389 fn from(path: PathBuf) -> Self {
390 Self { path, will_be_executed: false }
391 }
392}
393
394impl StepDescription {
395 fn from<S: Step>(kind: Kind) -> StepDescription {
396 StepDescription {
397 default: S::DEFAULT,
398 only_hosts: S::ONLY_HOSTS,
399 should_run: S::should_run,
400 make_run: S::make_run,
401 name: std::any::type_name::<S>(),
402 kind,
403 }
404 }
405
406 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
407 pathsets.retain(|set| !self.is_excluded(builder, set));
408
409 if pathsets.is_empty() {
410 return;
411 }
412
413 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
415
416 for target in targets {
417 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
418 (self.make_run)(run);
419 }
420 }
421
422 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
423 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
424 if !matches!(builder.config.dry_run, DryRun::SelfCheck) {
425 println!("Skipping {pathset:?} because it is excluded");
426 }
427 return true;
428 }
429
430 if !builder.config.skip.is_empty() && !matches!(builder.config.dry_run, DryRun::SelfCheck) {
431 builder.verbose(|| {
432 println!(
433 "{:?} not skipped for {:?} -- not in {:?}",
434 pathset, self.name, builder.config.skip
435 )
436 });
437 }
438 false
439 }
440
441 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
442 let should_runs = v
443 .iter()
444 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
445 .collect::<Vec<_>>();
446
447 if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
448 {
449 eprintln!(
450 "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
451 builder.kind.as_str()
452 );
453 crate::exit!(1);
454 }
455
456 for (desc, should_run) in v.iter().zip(&should_runs) {
458 assert!(
459 !should_run.paths.is_empty(),
460 "{:?} should have at least one pathset",
461 desc.name
462 );
463 }
464
465 if paths.is_empty() || builder.config.include_default_paths {
466 for (desc, should_run) in v.iter().zip(&should_runs) {
467 if desc.default && should_run.is_really_default() {
468 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
469 }
470 }
471 }
472
473 let mut paths: Vec<PathBuf> = paths
475 .iter()
476 .map(|p| {
477 if !p.exists() {
479 return p.clone();
480 }
481
482 match std::path::absolute(p) {
484 Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
485 Err(e) => {
486 eprintln!("ERROR: {:?}", e);
487 panic!("Due to the above error, failed to resolve path: {:?}", p);
488 }
489 }
490 })
491 .collect();
492
493 remap_paths(&mut paths);
494
495 paths.retain(|path| {
498 for (desc, should_run) in v.iter().zip(&should_runs) {
499 if let Some(suite) = should_run.is_suite_path(path) {
500 desc.maybe_run(builder, vec![suite.clone()]);
501 return false;
502 }
503 }
504 true
505 });
506
507 if paths.is_empty() {
508 return;
509 }
510
511 let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
512 let mut path_lookup: Vec<(CLIStepPath, bool)> =
513 paths.clone().into_iter().map(|p| (p, false)).collect();
514
515 let mut steps_to_run = vec![];
519
520 for (desc, should_run) in v.iter().zip(&should_runs) {
521 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
522
523 let mut closest_index = usize::MAX;
529
530 for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
532 if !*is_used && !paths.contains(path) {
533 closest_index = index;
534 *is_used = true;
535 break;
536 }
537 }
538
539 steps_to_run.push((closest_index, desc, pathsets));
540 }
541
542 steps_to_run.sort_by_key(|(index, _, _)| *index);
544
545 for (_index, desc, pathsets) in steps_to_run {
547 if !pathsets.is_empty() {
548 desc.maybe_run(builder, pathsets);
549 }
550 }
551
552 paths.retain(|p| !p.will_be_executed);
553
554 if !paths.is_empty() {
555 eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
556 eprintln!(
557 "HELP: run `x.py {} --help --verbose` to show a list of available paths",
558 builder.kind.as_str()
559 );
560 eprintln!(
561 "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
562 );
563 crate::exit!(1);
564 }
565 }
566}
567
568enum ReallyDefault<'a> {
569 Bool(bool),
570 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
571}
572
573pub struct ShouldRun<'a> {
574 pub builder: &'a Builder<'a>,
575 kind: Kind,
576
577 paths: BTreeSet<PathSet>,
579
580 is_really_default: ReallyDefault<'a>,
583}
584
585impl<'a> ShouldRun<'a> {
586 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
587 ShouldRun {
588 builder,
589 kind,
590 paths: BTreeSet::new(),
591 is_really_default: ReallyDefault::Bool(true), }
593 }
594
595 pub fn default_condition(mut self, cond: bool) -> Self {
596 self.is_really_default = ReallyDefault::Bool(cond);
597 self
598 }
599
600 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
601 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
602 self
603 }
604
605 pub fn is_really_default(&self) -> bool {
606 match &self.is_really_default {
607 ReallyDefault::Bool(val) => *val,
608 ReallyDefault::Lazy(lazy) => *lazy.deref(),
609 }
610 }
611
612 pub fn crate_or_deps(self, name: &str) -> Self {
617 let crates = self.builder.in_tree_crates(name, None);
618 self.crates(crates)
619 }
620
621 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
627 for krate in crates {
628 let path = krate.local_path(self.builder);
629 self.paths.insert(PathSet::one(path, self.kind));
630 }
631 self
632 }
633
634 pub fn alias(mut self, alias: &str) -> Self {
636 assert!(
640 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
641 "use `builder.path()` for real paths: {alias}"
642 );
643 self.paths.insert(PathSet::Set(
644 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
645 ));
646 self
647 }
648
649 pub fn path(self, path: &str) -> Self {
653 self.paths(&[path])
654 }
655
656 pub fn paths(mut self, paths: &[&str]) -> Self {
666 let submodules_paths = build_helper::util::parse_gitmodules(&self.builder.src);
667
668 self.paths.insert(PathSet::Set(
669 paths
670 .iter()
671 .map(|p| {
672 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
674 assert!(
675 self.builder.src.join(p).exists(),
676 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
677 p
678 );
679 }
680
681 TaskPath { path: p.into(), kind: Some(self.kind) }
682 })
683 .collect(),
684 ));
685 self
686 }
687
688 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
690 self.paths.iter().find(|pathset| match pathset {
691 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
692 PathSet::Set(_) => false,
693 })
694 }
695
696 pub fn suite_path(mut self, suite: &str) -> Self {
697 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
698 self
699 }
700
701 pub fn never(mut self) -> ShouldRun<'a> {
703 self.paths.insert(PathSet::empty());
704 self
705 }
706
707 fn pathset_for_paths_removing_matches(
717 &self,
718 paths: &mut [CLIStepPath],
719 kind: Kind,
720 ) -> Vec<PathSet> {
721 let mut sets = vec![];
722 for pathset in &self.paths {
723 let subset = pathset.intersection_removing_matches(paths, kind);
724 if subset != PathSet::empty() {
725 sets.push(subset);
726 }
727 }
728 sets
729 }
730}
731
732#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
733pub enum Kind {
734 #[value(alias = "b")]
735 Build,
736 #[value(alias = "c")]
737 Check,
738 Clippy,
739 Fix,
740 Format,
741 #[value(alias = "t")]
742 Test,
743 Miri,
744 MiriSetup,
745 MiriTest,
746 Bench,
747 #[value(alias = "d")]
748 Doc,
749 Clean,
750 Dist,
751 Install,
752 #[value(alias = "r")]
753 Run,
754 Setup,
755 Suggest,
756 Vendor,
757 Perf,
758}
759
760impl Kind {
761 pub fn as_str(&self) -> &'static str {
762 match self {
763 Kind::Build => "build",
764 Kind::Check => "check",
765 Kind::Clippy => "clippy",
766 Kind::Fix => "fix",
767 Kind::Format => "fmt",
768 Kind::Test => "test",
769 Kind::Miri => "miri",
770 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
771 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
772 Kind::Bench => "bench",
773 Kind::Doc => "doc",
774 Kind::Clean => "clean",
775 Kind::Dist => "dist",
776 Kind::Install => "install",
777 Kind::Run => "run",
778 Kind::Setup => "setup",
779 Kind::Suggest => "suggest",
780 Kind::Vendor => "vendor",
781 Kind::Perf => "perf",
782 }
783 }
784
785 pub fn description(&self) -> String {
786 match self {
787 Kind::Test => "Testing",
788 Kind::Bench => "Benchmarking",
789 Kind::Doc => "Documenting",
790 Kind::Run => "Running",
791 Kind::Suggest => "Suggesting",
792 Kind::Clippy => "Linting",
793 Kind::Perf => "Profiling & benchmarking",
794 _ => {
795 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
796 return format!("{title_letter}{}ing", &self.as_str()[1..]);
797 }
798 }
799 .to_owned()
800 }
801}
802
803#[derive(Debug, Clone, Hash, PartialEq, Eq)]
804struct Libdir {
805 compiler: Compiler,
806 target: TargetSelection,
807}
808
809impl Step for Libdir {
810 type Output = PathBuf;
811
812 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
813 run.never()
814 }
815
816 fn run(self, builder: &Builder<'_>) -> PathBuf {
817 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
818 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
819
820 if !builder.config.dry_run() {
821 if !builder.download_rustc() {
824 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
825 builder.verbose(|| {
826 eprintln!(
827 "Removing sysroot {} to avoid caching bugs",
828 sysroot_target_libdir.display()
829 )
830 });
831 let _ = fs::remove_dir_all(&sysroot_target_libdir);
832 t!(fs::create_dir_all(&sysroot_target_libdir));
833 }
834
835 if self.compiler.stage == 0 {
836 dist::maybe_install_llvm_target(
840 builder,
841 self.compiler.host,
842 &builder.sysroot(self.compiler),
843 );
844 }
845 }
846
847 sysroot
848 }
849}
850
851impl<'a> Builder<'a> {
852 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
853 macro_rules! describe {
854 ($($rule:ty),+ $(,)?) => {{
855 vec![$(StepDescription::from::<$rule>(kind)),+]
856 }};
857 }
858 match kind {
859 Kind::Build => describe!(
860 compile::Std,
861 compile::Rustc,
862 compile::Assemble,
863 compile::CodegenBackend,
864 compile::StartupObjects,
865 tool::BuildManifest,
866 tool::Rustbook,
867 tool::ErrorIndex,
868 tool::UnstableBookGen,
869 tool::Tidy,
870 tool::Linkchecker,
871 tool::CargoTest,
872 tool::Compiletest,
873 tool::RemoteTestServer,
874 tool::RemoteTestClient,
875 tool::RustInstaller,
876 tool::Cargo,
877 tool::Rls,
878 tool::RustAnalyzer,
879 tool::RustAnalyzerProcMacroSrv,
880 tool::Rustdoc,
881 tool::Clippy,
882 tool::CargoClippy,
883 llvm::Llvm,
884 gcc::Gcc,
885 llvm::Sanitizers,
886 tool::Rustfmt,
887 tool::Miri,
888 tool::CargoMiri,
889 llvm::Lld,
890 llvm::Enzyme,
891 llvm::CrtBeginEnd,
892 tool::RustdocGUITest,
893 tool::OptimizedDist,
894 tool::CoverageDump,
895 tool::LlvmBitcodeLinker,
896 tool::RustcPerf,
897 ),
898 Kind::Clippy => describe!(
899 clippy::Std,
900 clippy::Rustc,
901 clippy::Bootstrap,
902 clippy::BuildHelper,
903 clippy::BuildManifest,
904 clippy::CargoMiri,
905 clippy::Clippy,
906 clippy::CodegenGcc,
907 clippy::CollectLicenseMetadata,
908 clippy::Compiletest,
909 clippy::CoverageDump,
910 clippy::Jsondocck,
911 clippy::Jsondoclint,
912 clippy::LintDocs,
913 clippy::LlvmBitcodeLinker,
914 clippy::Miri,
915 clippy::MiroptTestTools,
916 clippy::OptDist,
917 clippy::RemoteTestClient,
918 clippy::RemoteTestServer,
919 clippy::Rls,
920 clippy::RustAnalyzer,
921 clippy::Rustdoc,
922 clippy::Rustfmt,
923 clippy::RustInstaller,
924 clippy::TestFloatParse,
925 clippy::Tidy,
926 clippy::CI,
927 ),
928 Kind::Check | Kind::Fix => describe!(
929 check::Std,
930 check::Rustc,
931 check::Rustdoc,
932 check::CodegenBackend,
933 check::Clippy,
934 check::Miri,
935 check::CargoMiri,
936 check::MiroptTestTools,
937 check::Rls,
938 check::Rustfmt,
939 check::RustAnalyzer,
940 check::TestFloatParse,
941 check::Bootstrap,
942 check::RunMakeSupport,
943 check::Compiletest,
944 check::FeaturesStatusDump,
945 ),
946 Kind::Test => describe!(
947 crate::core::build_steps::toolstate::ToolStateCheck,
948 test::Tidy,
949 test::Ui,
950 test::Crashes,
951 test::Coverage,
952 test::MirOpt,
953 test::Codegen,
954 test::CodegenUnits,
955 test::Assembly,
956 test::Incremental,
957 test::Debuginfo,
958 test::UiFullDeps,
959 test::Rustdoc,
960 test::CoverageRunRustdoc,
961 test::Pretty,
962 test::CodegenCranelift,
963 test::CodegenGCC,
964 test::Crate,
965 test::CrateLibrustc,
966 test::CrateRustdoc,
967 test::CrateRustdocJsonTypes,
968 test::CrateBootstrap,
969 test::Linkcheck,
970 test::TierCheck,
971 test::Cargotest,
972 test::Cargo,
973 test::RustAnalyzer,
974 test::ErrorIndex,
975 test::Distcheck,
976 test::Nomicon,
977 test::Reference,
978 test::RustdocBook,
979 test::RustByExample,
980 test::TheBook,
981 test::UnstableBook,
982 test::RustcBook,
983 test::LintDocs,
984 test::EmbeddedBook,
985 test::EditionGuide,
986 test::Rustfmt,
987 test::Miri,
988 test::CargoMiri,
989 test::Clippy,
990 test::CompiletestTest,
991 test::CrateRunMakeSupport,
992 test::CrateBuildHelper,
993 test::RustdocJSStd,
994 test::RustdocJSNotStd,
995 test::RustdocGUI,
996 test::RustdocTheme,
997 test::RustdocUi,
998 test::RustdocJson,
999 test::HtmlCheck,
1000 test::RustInstaller,
1001 test::TestFloatParse,
1002 test::CollectLicenseMetadata,
1003 test::Bootstrap,
1005 test::RunMake,
1007 ),
1008 Kind::Miri => describe!(test::Crate),
1009 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1010 Kind::Doc => describe!(
1011 doc::UnstableBook,
1012 doc::UnstableBookGen,
1013 doc::TheBook,
1014 doc::Standalone,
1015 doc::Std,
1016 doc::Rustc,
1017 doc::Rustdoc,
1018 doc::Rustfmt,
1019 doc::ErrorIndex,
1020 doc::Nomicon,
1021 doc::Reference,
1022 doc::RustdocBook,
1023 doc::RustByExample,
1024 doc::RustcBook,
1025 doc::Cargo,
1026 doc::CargoBook,
1027 doc::Clippy,
1028 doc::ClippyBook,
1029 doc::Miri,
1030 doc::EmbeddedBook,
1031 doc::EditionGuide,
1032 doc::StyleGuide,
1033 doc::Tidy,
1034 doc::Bootstrap,
1035 doc::Releases,
1036 doc::RunMakeSupport,
1037 doc::BuildHelper,
1038 doc::Compiletest,
1039 ),
1040 Kind::Dist => describe!(
1041 dist::Docs,
1042 dist::RustcDocs,
1043 dist::JsonDocs,
1044 dist::Mingw,
1045 dist::Rustc,
1046 dist::CodegenBackend,
1047 dist::Std,
1048 dist::RustcDev,
1049 dist::Analysis,
1050 dist::Src,
1051 dist::Cargo,
1052 dist::Rls,
1053 dist::RustAnalyzer,
1054 dist::Rustfmt,
1055 dist::Clippy,
1056 dist::Miri,
1057 dist::LlvmTools,
1058 dist::LlvmBitcodeLinker,
1059 dist::RustDev,
1060 dist::Bootstrap,
1061 dist::Extended,
1062 dist::PlainSourceTarball,
1067 dist::BuildManifest,
1068 dist::ReproducibleArtifacts,
1069 ),
1070 Kind::Install => describe!(
1071 install::Docs,
1072 install::Std,
1073 install::Rustc,
1078 install::Cargo,
1079 install::RustAnalyzer,
1080 install::Rustfmt,
1081 install::Clippy,
1082 install::Miri,
1083 install::LlvmTools,
1084 install::Src,
1085 ),
1086 Kind::Run => describe!(
1087 run::BuildManifest,
1088 run::BumpStage0,
1089 run::ReplaceVersionPlaceholder,
1090 run::Miri,
1091 run::CollectLicenseMetadata,
1092 run::GenerateCopyright,
1093 run::GenerateWindowsSys,
1094 run::GenerateCompletions,
1095 run::UnicodeTableGenerator,
1096 run::FeaturesStatusDump,
1097 ),
1098 Kind::Setup => {
1099 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1100 }
1101 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1102 Kind::Vendor => describe!(vendor::Vendor),
1103 Kind::Format | Kind::Suggest | Kind::Perf => vec![],
1105 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1106 }
1107 }
1108
1109 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1110 let step_descriptions = Builder::get_step_descriptions(kind);
1111 if step_descriptions.is_empty() {
1112 return None;
1113 }
1114
1115 let builder = Self::new_internal(build, kind, vec![]);
1116 let builder = &builder;
1117 let mut should_run = ShouldRun::new(builder, Kind::Build);
1120 for desc in step_descriptions {
1121 should_run.kind = desc.kind;
1122 should_run = (desc.should_run)(should_run);
1123 }
1124 let mut help = String::from("Available paths:\n");
1125 let mut add_path = |path: &Path| {
1126 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1127 };
1128 for pathset in should_run.paths {
1129 match pathset {
1130 PathSet::Set(set) => {
1131 for path in set {
1132 add_path(&path.path);
1133 }
1134 }
1135 PathSet::Suite(path) => {
1136 add_path(&path.path.join("..."));
1137 }
1138 }
1139 }
1140 Some(help)
1141 }
1142
1143 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1144 Builder {
1145 build,
1146 top_stage: build.config.stage,
1147 kind,
1148 cache: Cache::new(),
1149 stack: RefCell::new(Vec::new()),
1150 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1151 paths,
1152 }
1153 }
1154
1155 pub fn new(build: &Build) -> Builder<'_> {
1156 let paths = &build.config.paths;
1157 let (kind, paths) = match build.config.cmd {
1158 Subcommand::Build => (Kind::Build, &paths[..]),
1159 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1160 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1161 Subcommand::Fix => (Kind::Fix, &paths[..]),
1162 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1163 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1164 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1165 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1166 Subcommand::Dist => (Kind::Dist, &paths[..]),
1167 Subcommand::Install => (Kind::Install, &paths[..]),
1168 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1169 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1170 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1171 Subcommand::Suggest { .. } => (Kind::Suggest, &[][..]),
1172 Subcommand::Setup { profile: ref path } => (
1173 Kind::Setup,
1174 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1175 ),
1176 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1177 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1178 };
1179
1180 Self::new_internal(build, kind, paths.to_owned())
1181 }
1182
1183 pub fn execute_cli(&self) {
1184 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1185 }
1186
1187 pub fn default_doc(&self, paths: &[PathBuf]) {
1188 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1189 }
1190
1191 pub fn doc_rust_lang_org_channel(&self) -> String {
1192 let channel = match &*self.config.channel {
1193 "stable" => &self.version,
1194 "beta" => "beta",
1195 "nightly" | "dev" => "nightly",
1196 _ => "stable",
1198 };
1199
1200 format!("https://doc.rust-lang.org/{channel}")
1201 }
1202
1203 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1204 StepDescription::run(v, self, paths);
1205 }
1206
1207 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1210 !target.triple.ends_with("-windows-gnu")
1211 }
1212
1213 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1218 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
1219 }
1220
1221 pub fn compiler_for(
1233 &self,
1234 stage: u32,
1235 host: TargetSelection,
1236 target: TargetSelection,
1237 ) -> Compiler {
1238 if self.build.force_use_stage2(stage) {
1239 self.compiler(2, self.config.build)
1240 } else if self.build.force_use_stage1(stage, target) {
1241 self.compiler(1, self.config.build)
1242 } else {
1243 self.compiler(stage, host)
1244 }
1245 }
1246
1247 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1248 self.ensure(compile::Sysroot::new(compiler))
1249 }
1250
1251 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1253 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1254 }
1255
1256 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1259 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1260 }
1261
1262 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1263 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1264 }
1265
1266 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1272 if compiler.is_snapshot(self) {
1273 self.rustc_snapshot_libdir()
1274 } else {
1275 match self.config.libdir_relative() {
1276 Some(relative_libdir) if compiler.stage >= 1 => {
1277 self.sysroot(compiler).join(relative_libdir)
1278 }
1279 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1280 }
1281 }
1282 }
1283
1284 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1290 if compiler.is_snapshot(self) {
1291 libdir(self.config.build).as_ref()
1292 } else {
1293 match self.config.libdir_relative() {
1294 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1295 _ => libdir(compiler.host).as_ref(),
1296 }
1297 }
1298 }
1299
1300 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1305 match self.config.libdir_relative() {
1306 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1307 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1308 _ => Path::new("lib"),
1309 }
1310 }
1311
1312 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1313 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1314
1315 if self.config.llvm_from_ci {
1317 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1318 dylib_dirs.push(ci_llvm_lib);
1319 }
1320
1321 dylib_dirs
1322 }
1323
1324 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1327 if cfg!(windows) {
1331 return;
1332 }
1333
1334 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1335 }
1336
1337 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1339 if compiler.is_snapshot(self) {
1340 self.initial_rustc.clone()
1341 } else {
1342 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1343 }
1344 }
1345
1346 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1348 fs::read_dir(self.sysroot_codegen_backends(compiler))
1349 .into_iter()
1350 .flatten()
1351 .filter_map(Result::ok)
1352 .map(|entry| entry.path())
1353 }
1354
1355 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1356 self.ensure(tool::Rustdoc { compiler })
1357 }
1358
1359 pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1360 if run_compiler.stage == 0 {
1361 let cargo_clippy = self
1362 .config
1363 .initial_cargo_clippy
1364 .clone()
1365 .unwrap_or_else(|| self.build.config.download_clippy());
1366
1367 let mut cmd = command(cargo_clippy);
1368 cmd.env("CARGO", &self.initial_cargo);
1369 return cmd;
1370 }
1371
1372 let build_compiler = self.compiler(run_compiler.stage - 1, self.build.build);
1373 self.ensure(tool::Clippy { compiler: build_compiler, target: self.build.build });
1374 let cargo_clippy =
1375 self.ensure(tool::CargoClippy { compiler: build_compiler, target: self.build.build });
1376 let mut dylib_path = helpers::dylib_path();
1377 dylib_path.insert(0, self.sysroot(run_compiler).join("lib"));
1378
1379 let mut cmd = command(cargo_clippy);
1380 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1381 cmd.env("CARGO", &self.initial_cargo);
1382 cmd
1383 }
1384
1385 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1386 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1387 let build_compiler = self.compiler(run_compiler.stage - 1, self.build.build);
1388
1389 let miri = self.ensure(tool::Miri { compiler: build_compiler, target: self.build.build });
1391 let cargo_miri =
1392 self.ensure(tool::CargoMiri { compiler: build_compiler, target: self.build.build });
1393 let mut cmd = command(cargo_miri);
1395 cmd.env("MIRI", &miri);
1396 cmd.env("CARGO", &self.initial_cargo);
1397 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1406 cmd
1407 }
1408
1409 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1410 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1411 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1412 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1413 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1416 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1417 .env("RUSTDOC_REAL", self.rustdoc(compiler))
1418 .env("RUSTC_BOOTSTRAP", "1");
1419
1420 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1421
1422 if self.config.deny_warnings {
1423 cmd.arg("-Dwarnings");
1424 }
1425 cmd.arg("-Znormalize-docs");
1426 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1427 cmd
1428 }
1429
1430 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1435 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1436 let llvm::LlvmResult { llvm_config, .. } = self.ensure(llvm::Llvm { target });
1437 if llvm_config.is_file() {
1438 return Some(llvm_config);
1439 }
1440 }
1441 None
1442 }
1443
1444 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1448 {
1449 let mut stack = self.stack.borrow_mut();
1450 for stack_step in stack.iter() {
1451 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1453 continue;
1454 }
1455 let mut out = String::new();
1456 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1457 for el in stack.iter().rev() {
1458 out += &format!("\t{el:?}\n");
1459 }
1460 panic!("{}", out);
1461 }
1462 if let Some(out) = self.cache.get(&step) {
1463 self.verbose_than(1, || println!("{}c {:?}", " ".repeat(stack.len()), step));
1464
1465 return out;
1466 }
1467 self.verbose_than(1, || println!("{}> {:?}", " ".repeat(stack.len()), step));
1468 stack.push(Box::new(step.clone()));
1469 }
1470
1471 #[cfg(feature = "build-metrics")]
1472 self.metrics.enter_step(&step, self);
1473
1474 let (out, dur) = {
1475 let start = Instant::now();
1476 let zero = Duration::new(0, 0);
1477 let parent = self.time_spent_on_dependencies.replace(zero);
1478 let out = step.clone().run(self);
1479 let dur = start.elapsed();
1480 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1481 (out, dur - deps)
1482 };
1483
1484 if self.config.print_step_timings && !self.config.dry_run() {
1485 let step_string = format!("{step:?}");
1486 let brace_index = step_string.find('{').unwrap_or(0);
1487 let type_string = type_name::<S>();
1488 println!(
1489 "[TIMING] {} {} -- {}.{:03}",
1490 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1491 &step_string[brace_index..],
1492 dur.as_secs(),
1493 dur.subsec_millis()
1494 );
1495 }
1496
1497 #[cfg(feature = "build-metrics")]
1498 self.metrics.exit_step(self);
1499
1500 {
1501 let mut stack = self.stack.borrow_mut();
1502 let cur_step = stack.pop().expect("step stack empty");
1503 assert_eq!(cur_step.downcast_ref(), Some(&step));
1504 }
1505 self.verbose_than(1, || println!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1506 self.cache.put(step, out.clone());
1507 out
1508 }
1509
1510 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1514 &'a self,
1515 step: S,
1516 kind: Kind,
1517 ) -> S::Output {
1518 let desc = StepDescription::from::<S>(kind);
1519 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1520
1521 for pathset in &should_run.paths {
1523 if desc.is_excluded(self, pathset) {
1524 return None;
1525 }
1526 }
1527
1528 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1530 }
1531
1532 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1534 let desc = StepDescription::from::<S>(kind);
1535 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1536
1537 for path in &self.paths {
1538 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1539 && !desc.is_excluded(
1540 self,
1541 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1542 )
1543 {
1544 return true;
1545 }
1546 }
1547
1548 false
1549 }
1550
1551 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1552 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1553 self.open_in_browser(path);
1554 } else {
1555 self.info(&format!("Doc path: {}", path.as_ref().display()));
1556 }
1557 }
1558
1559 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1560 let path = path.as_ref();
1561
1562 if self.config.dry_run() || !self.config.cmd.open() {
1563 self.info(&format!("Doc path: {}", path.display()));
1564 return;
1565 }
1566
1567 self.info(&format!("Opening doc {}", path.display()));
1568 if let Err(err) = opener::open(path) {
1569 self.info(&format!("{err}\n"));
1570 }
1571 }
1572}