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#[cfg(feature = "tracing")]
14use tracing::instrument;
15
16pub use self::cargo::{Cargo, cargo_profile_var};
17pub use crate::Compiler;
18use crate::core::build_steps::{
19 check, clean, clippy, compile, dist, doc, gcc, install, llvm, run, setup, test, tool, vendor,
20};
21use crate::core::config::flags::Subcommand;
22use crate::core::config::{DryRun, TargetSelection};
23use crate::utils::cache::Cache;
24use crate::utils::exec::{BootstrapCommand, command};
25use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
26use crate::{Build, Crate, trace};
27
28mod cargo;
29
30#[cfg(test)]
31mod tests;
32
33pub struct Builder<'a> {
36 pub build: &'a Build,
38
39 pub top_stage: u32,
43
44 pub kind: Kind,
46
47 cache: Cache,
50
51 stack: RefCell<Vec<Box<dyn AnyDebug>>>,
54
55 time_spent_on_dependencies: Cell<Duration>,
57
58 pub paths: Vec<PathBuf>,
62}
63
64impl Deref for Builder<'_> {
65 type Target = Build;
66
67 fn deref(&self) -> &Self::Target {
68 self.build
69 }
70}
71
72trait AnyDebug: Any + Debug {}
77impl<T: Any + Debug> AnyDebug for T {}
78impl dyn AnyDebug {
79 fn downcast_ref<T: Any>(&self) -> Option<&T> {
81 (self as &dyn Any).downcast_ref()
82 }
83
84 }
86
87pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
88 type Output: Clone;
90
91 const DEFAULT: bool = false;
97
98 const ONLY_HOSTS: bool = false;
100
101 fn run(self, builder: &Builder<'_>) -> Self::Output;
115
116 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
118
119 fn make_run(_run: RunConfig<'_>) {
123 unimplemented!()
128 }
129}
130
131pub struct RunConfig<'a> {
132 pub builder: &'a Builder<'a>,
133 pub target: TargetSelection,
134 pub paths: Vec<PathSet>,
135}
136
137impl RunConfig<'_> {
138 pub fn build_triple(&self) -> TargetSelection {
139 self.builder.build.build
140 }
141
142 #[track_caller]
144 pub fn cargo_crates_in_set(&self) -> Vec<String> {
145 let mut crates = Vec::new();
146 for krate in &self.paths {
147 let path = &krate.assert_single_path().path;
148
149 let crate_name = self
150 .builder
151 .crate_paths
152 .get(path)
153 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
154
155 crates.push(crate_name.to_string());
156 }
157 crates
158 }
159
160 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
167 let has_alias =
168 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
169 if !has_alias {
170 return self.cargo_crates_in_set();
171 }
172
173 let crates = match alias {
174 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
175 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
176 };
177
178 crates.into_iter().map(|krate| krate.name.to_string()).collect()
179 }
180}
181
182#[derive(Debug, Copy, Clone)]
183pub enum Alias {
184 Library,
185 Compiler,
186}
187
188impl Alias {
189 fn as_str(self) -> &'static str {
190 match self {
191 Alias::Library => "library",
192 Alias::Compiler => "compiler",
193 }
194 }
195}
196
197pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
201 if crates.is_empty() {
202 return "".into();
203 }
204
205 let mut descr = String::from(" {");
206 descr.push_str(crates[0].as_ref());
207 for krate in &crates[1..] {
208 descr.push_str(", ");
209 descr.push_str(krate.as_ref());
210 }
211 descr.push('}');
212 descr
213}
214
215struct StepDescription {
216 default: bool,
217 only_hosts: bool,
218 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
219 make_run: fn(RunConfig<'_>),
220 name: &'static str,
221 kind: Kind,
222}
223
224#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
225pub struct TaskPath {
226 pub path: PathBuf,
227 pub kind: Option<Kind>,
228}
229
230impl Debug for TaskPath {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 if let Some(kind) = &self.kind {
233 write!(f, "{}::", kind.as_str())?;
234 }
235 write!(f, "{}", self.path.display())
236 }
237}
238
239#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
241pub enum PathSet {
242 Set(BTreeSet<TaskPath>),
253 Suite(TaskPath),
260}
261
262impl PathSet {
263 fn empty() -> PathSet {
264 PathSet::Set(BTreeSet::new())
265 }
266
267 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
268 let mut set = BTreeSet::new();
269 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
270 PathSet::Set(set)
271 }
272
273 fn has(&self, needle: &Path, module: Kind) -> bool {
274 match self {
275 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
276 PathSet::Suite(suite) => Self::check(suite, needle, module),
277 }
278 }
279
280 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
282 let check_path = || {
283 p.path.ends_with(needle) || p.path.starts_with(needle)
285 };
286 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
287 }
288
289 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
296 let mut check = |p| {
297 let mut result = false;
298 for n in needles.iter_mut() {
299 let matched = Self::check(p, &n.path, module);
300 if matched {
301 n.will_be_executed = true;
302 result = true;
303 }
304 }
305 result
306 };
307 match self {
308 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
309 PathSet::Suite(suite) => {
310 if check(suite) {
311 self.clone()
312 } else {
313 PathSet::empty()
314 }
315 }
316 }
317 }
318
319 #[track_caller]
323 pub fn assert_single_path(&self) -> &TaskPath {
324 match self {
325 PathSet::Set(set) => {
326 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
327 set.iter().next().unwrap()
328 }
329 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
330 }
331 }
332}
333
334const PATH_REMAP: &[(&str, &[&str])] = &[
335 ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
338 (
340 "tests",
341 &[
342 "tests/assembly",
344 "tests/codegen",
345 "tests/codegen-units",
346 "tests/coverage",
347 "tests/coverage-run-rustdoc",
348 "tests/crashes",
349 "tests/debuginfo",
350 "tests/incremental",
351 "tests/mir-opt",
352 "tests/pretty",
353 "tests/run-make",
354 "tests/rustdoc",
355 "tests/rustdoc-gui",
356 "tests/rustdoc-js",
357 "tests/rustdoc-js-std",
358 "tests/rustdoc-json",
359 "tests/rustdoc-ui",
360 "tests/ui",
361 "tests/ui-fulldeps",
362 ],
364 ),
365];
366
367fn remap_paths(paths: &mut Vec<PathBuf>) {
368 let mut remove = vec![];
369 let mut add = vec![];
370 for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
371 {
372 for &(search, replace) in PATH_REMAP {
373 if path.trim_matches(std::path::is_separator) == search {
375 remove.push(i);
376 add.extend(replace.iter().map(PathBuf::from));
377 break;
378 }
379 }
380 }
381 remove.sort();
382 remove.dedup();
383 for idx in remove.into_iter().rev() {
384 paths.remove(idx);
385 }
386 paths.append(&mut add);
387}
388
389#[derive(Clone, PartialEq)]
390struct CLIStepPath {
391 path: PathBuf,
392 will_be_executed: bool,
393}
394
395#[cfg(test)]
396impl CLIStepPath {
397 fn will_be_executed(mut self, will_be_executed: bool) -> Self {
398 self.will_be_executed = will_be_executed;
399 self
400 }
401}
402
403impl Debug for CLIStepPath {
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 write!(f, "{}", self.path.display())
406 }
407}
408
409impl From<PathBuf> for CLIStepPath {
410 fn from(path: PathBuf) -> Self {
411 Self { path, will_be_executed: false }
412 }
413}
414
415impl StepDescription {
416 fn from<S: Step>(kind: Kind) -> StepDescription {
417 StepDescription {
418 default: S::DEFAULT,
419 only_hosts: S::ONLY_HOSTS,
420 should_run: S::should_run,
421 make_run: S::make_run,
422 name: std::any::type_name::<S>(),
423 kind,
424 }
425 }
426
427 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
428 pathsets.retain(|set| !self.is_excluded(builder, set));
429
430 if pathsets.is_empty() {
431 return;
432 }
433
434 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
436
437 for target in targets {
438 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
439 (self.make_run)(run);
440 }
441 }
442
443 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
444 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
445 if !matches!(builder.config.dry_run, DryRun::SelfCheck) {
446 println!("Skipping {pathset:?} because it is excluded");
447 }
448 return true;
449 }
450
451 if !builder.config.skip.is_empty() && !matches!(builder.config.dry_run, DryRun::SelfCheck) {
452 builder.verbose(|| {
453 println!(
454 "{:?} not skipped for {:?} -- not in {:?}",
455 pathset, self.name, builder.config.skip
456 )
457 });
458 }
459 false
460 }
461
462 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
463 let should_runs = v
464 .iter()
465 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
466 .collect::<Vec<_>>();
467
468 if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
469 {
470 eprintln!(
471 "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
472 builder.kind.as_str()
473 );
474 crate::exit!(1);
475 }
476
477 for (desc, should_run) in v.iter().zip(&should_runs) {
479 assert!(
480 !should_run.paths.is_empty(),
481 "{:?} should have at least one pathset",
482 desc.name
483 );
484 }
485
486 if paths.is_empty() || builder.config.include_default_paths {
487 for (desc, should_run) in v.iter().zip(&should_runs) {
488 if desc.default && should_run.is_really_default() {
489 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
490 }
491 }
492 }
493
494 let mut paths: Vec<PathBuf> = paths
496 .iter()
497 .map(|p| {
498 if !p.exists() {
500 return p.clone();
501 }
502
503 match std::path::absolute(p) {
505 Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
506 Err(e) => {
507 eprintln!("ERROR: {:?}", e);
508 panic!("Due to the above error, failed to resolve path: {:?}", p);
509 }
510 }
511 })
512 .collect();
513
514 remap_paths(&mut paths);
515
516 paths.retain(|path| {
519 for (desc, should_run) in v.iter().zip(&should_runs) {
520 if let Some(suite) = should_run.is_suite_path(path) {
521 desc.maybe_run(builder, vec![suite.clone()]);
522 return false;
523 }
524 }
525 true
526 });
527
528 if paths.is_empty() {
529 return;
530 }
531
532 let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
533 let mut path_lookup: Vec<(CLIStepPath, bool)> =
534 paths.clone().into_iter().map(|p| (p, false)).collect();
535
536 let mut steps_to_run = vec![];
540
541 for (desc, should_run) in v.iter().zip(&should_runs) {
542 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
543
544 let mut closest_index = usize::MAX;
550
551 for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
553 if !*is_used && !paths.contains(path) {
554 closest_index = index;
555 *is_used = true;
556 break;
557 }
558 }
559
560 steps_to_run.push((closest_index, desc, pathsets));
561 }
562
563 steps_to_run.sort_by_key(|(index, _, _)| *index);
565
566 for (_index, desc, pathsets) in steps_to_run {
568 if !pathsets.is_empty() {
569 desc.maybe_run(builder, pathsets);
570 }
571 }
572
573 paths.retain(|p| !p.will_be_executed);
574
575 if !paths.is_empty() {
576 eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
577 eprintln!(
578 "HELP: run `x.py {} --help --verbose` to show a list of available paths",
579 builder.kind.as_str()
580 );
581 eprintln!(
582 "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
583 );
584 crate::exit!(1);
585 }
586 }
587}
588
589enum ReallyDefault<'a> {
590 Bool(bool),
591 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
592}
593
594pub struct ShouldRun<'a> {
595 pub builder: &'a Builder<'a>,
596 kind: Kind,
597
598 paths: BTreeSet<PathSet>,
600
601 is_really_default: ReallyDefault<'a>,
604}
605
606impl<'a> ShouldRun<'a> {
607 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
608 ShouldRun {
609 builder,
610 kind,
611 paths: BTreeSet::new(),
612 is_really_default: ReallyDefault::Bool(true), }
614 }
615
616 pub fn default_condition(mut self, cond: bool) -> Self {
617 self.is_really_default = ReallyDefault::Bool(cond);
618 self
619 }
620
621 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
622 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
623 self
624 }
625
626 pub fn is_really_default(&self) -> bool {
627 match &self.is_really_default {
628 ReallyDefault::Bool(val) => *val,
629 ReallyDefault::Lazy(lazy) => *lazy.deref(),
630 }
631 }
632
633 pub fn crate_or_deps(self, name: &str) -> Self {
638 let crates = self.builder.in_tree_crates(name, None);
639 self.crates(crates)
640 }
641
642 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
648 for krate in crates {
649 let path = krate.local_path(self.builder);
650 self.paths.insert(PathSet::one(path, self.kind));
651 }
652 self
653 }
654
655 pub fn alias(mut self, alias: &str) -> Self {
657 assert!(
661 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
662 "use `builder.path()` for real paths: {alias}"
663 );
664 self.paths.insert(PathSet::Set(
665 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
666 ));
667 self
668 }
669
670 pub fn path(self, path: &str) -> Self {
674 self.paths(&[path])
675 }
676
677 pub fn paths(mut self, paths: &[&str]) -> Self {
687 let submodules_paths = build_helper::util::parse_gitmodules(&self.builder.src);
688
689 self.paths.insert(PathSet::Set(
690 paths
691 .iter()
692 .map(|p| {
693 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
695 assert!(
696 self.builder.src.join(p).exists(),
697 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
698 p
699 );
700 }
701
702 TaskPath { path: p.into(), kind: Some(self.kind) }
703 })
704 .collect(),
705 ));
706 self
707 }
708
709 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
711 self.paths.iter().find(|pathset| match pathset {
712 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
713 PathSet::Set(_) => false,
714 })
715 }
716
717 pub fn suite_path(mut self, suite: &str) -> Self {
718 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
719 self
720 }
721
722 pub fn never(mut self) -> ShouldRun<'a> {
724 self.paths.insert(PathSet::empty());
725 self
726 }
727
728 fn pathset_for_paths_removing_matches(
738 &self,
739 paths: &mut [CLIStepPath],
740 kind: Kind,
741 ) -> Vec<PathSet> {
742 let mut sets = vec![];
743 for pathset in &self.paths {
744 let subset = pathset.intersection_removing_matches(paths, kind);
745 if subset != PathSet::empty() {
746 sets.push(subset);
747 }
748 }
749 sets
750 }
751}
752
753#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
754pub enum Kind {
755 #[value(alias = "b")]
756 Build,
757 #[value(alias = "c")]
758 Check,
759 Clippy,
760 Fix,
761 Format,
762 #[value(alias = "t")]
763 Test,
764 Miri,
765 MiriSetup,
766 MiriTest,
767 Bench,
768 #[value(alias = "d")]
769 Doc,
770 Clean,
771 Dist,
772 Install,
773 #[value(alias = "r")]
774 Run,
775 Setup,
776 Suggest,
777 Vendor,
778 Perf,
779}
780
781impl Kind {
782 pub fn as_str(&self) -> &'static str {
783 match self {
784 Kind::Build => "build",
785 Kind::Check => "check",
786 Kind::Clippy => "clippy",
787 Kind::Fix => "fix",
788 Kind::Format => "fmt",
789 Kind::Test => "test",
790 Kind::Miri => "miri",
791 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
792 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
793 Kind::Bench => "bench",
794 Kind::Doc => "doc",
795 Kind::Clean => "clean",
796 Kind::Dist => "dist",
797 Kind::Install => "install",
798 Kind::Run => "run",
799 Kind::Setup => "setup",
800 Kind::Suggest => "suggest",
801 Kind::Vendor => "vendor",
802 Kind::Perf => "perf",
803 }
804 }
805
806 pub fn description(&self) -> String {
807 match self {
808 Kind::Test => "Testing",
809 Kind::Bench => "Benchmarking",
810 Kind::Doc => "Documenting",
811 Kind::Run => "Running",
812 Kind::Suggest => "Suggesting",
813 Kind::Clippy => "Linting",
814 Kind::Perf => "Profiling & benchmarking",
815 _ => {
816 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
817 return format!("{title_letter}{}ing", &self.as_str()[1..]);
818 }
819 }
820 .to_owned()
821 }
822}
823
824#[derive(Debug, Clone, Hash, PartialEq, Eq)]
825struct Libdir {
826 compiler: Compiler,
827 target: TargetSelection,
828}
829
830impl Step for Libdir {
831 type Output = PathBuf;
832
833 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
834 run.never()
835 }
836
837 fn run(self, builder: &Builder<'_>) -> PathBuf {
838 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
839 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
840
841 if !builder.config.dry_run() {
842 if !builder.download_rustc() {
845 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
846 builder.verbose(|| {
847 eprintln!(
848 "Removing sysroot {} to avoid caching bugs",
849 sysroot_target_libdir.display()
850 )
851 });
852 let _ = fs::remove_dir_all(&sysroot_target_libdir);
853 t!(fs::create_dir_all(&sysroot_target_libdir));
854 }
855
856 if self.compiler.stage == 0 {
857 dist::maybe_install_llvm_target(
861 builder,
862 self.compiler.host,
863 &builder.sysroot(self.compiler),
864 );
865 }
866 }
867
868 sysroot
869 }
870}
871
872impl<'a> Builder<'a> {
873 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
874 macro_rules! describe {
875 ($($rule:ty),+ $(,)?) => {{
876 vec![$(StepDescription::from::<$rule>(kind)),+]
877 }};
878 }
879 match kind {
880 Kind::Build => describe!(
881 compile::Std,
882 compile::Rustc,
883 compile::Assemble,
884 compile::CodegenBackend,
885 compile::StartupObjects,
886 tool::BuildManifest,
887 tool::Rustbook,
888 tool::ErrorIndex,
889 tool::UnstableBookGen,
890 tool::Tidy,
891 tool::Linkchecker,
892 tool::CargoTest,
893 tool::Compiletest,
894 tool::RemoteTestServer,
895 tool::RemoteTestClient,
896 tool::RustInstaller,
897 tool::Cargo,
898 tool::RustAnalyzer,
899 tool::RustAnalyzerProcMacroSrv,
900 tool::Rustdoc,
901 tool::Clippy,
902 tool::CargoClippy,
903 llvm::Llvm,
904 gcc::Gcc,
905 llvm::Sanitizers,
906 tool::Rustfmt,
907 tool::Cargofmt,
908 tool::Miri,
909 tool::CargoMiri,
910 llvm::Lld,
911 llvm::Enzyme,
912 llvm::CrtBeginEnd,
913 tool::RustdocGUITest,
914 tool::OptimizedDist,
915 tool::CoverageDump,
916 tool::LlvmBitcodeLinker,
917 tool::RustcPerf,
918 ),
919 Kind::Clippy => describe!(
920 clippy::Std,
921 clippy::Rustc,
922 clippy::Bootstrap,
923 clippy::BuildHelper,
924 clippy::BuildManifest,
925 clippy::CargoMiri,
926 clippy::Clippy,
927 clippy::CodegenGcc,
928 clippy::CollectLicenseMetadata,
929 clippy::Compiletest,
930 clippy::CoverageDump,
931 clippy::Jsondocck,
932 clippy::Jsondoclint,
933 clippy::LintDocs,
934 clippy::LlvmBitcodeLinker,
935 clippy::Miri,
936 clippy::MiroptTestTools,
937 clippy::OptDist,
938 clippy::RemoteTestClient,
939 clippy::RemoteTestServer,
940 clippy::RustAnalyzer,
941 clippy::Rustdoc,
942 clippy::Rustfmt,
943 clippy::RustInstaller,
944 clippy::TestFloatParse,
945 clippy::Tidy,
946 clippy::CI,
947 ),
948 Kind::Check | Kind::Fix => describe!(
949 check::Std,
950 check::Rustc,
951 check::Rustdoc,
952 check::CodegenBackend,
953 check::Clippy,
954 check::Miri,
955 check::CargoMiri,
956 check::MiroptTestTools,
957 check::Rustfmt,
958 check::RustAnalyzer,
959 check::TestFloatParse,
960 check::Bootstrap,
961 check::RunMakeSupport,
962 check::Compiletest,
963 check::FeaturesStatusDump,
964 ),
965 Kind::Test => describe!(
966 crate::core::build_steps::toolstate::ToolStateCheck,
967 test::Tidy,
968 test::Ui,
969 test::Crashes,
970 test::Coverage,
971 test::MirOpt,
972 test::Codegen,
973 test::CodegenUnits,
974 test::Assembly,
975 test::Incremental,
976 test::Debuginfo,
977 test::UiFullDeps,
978 test::Rustdoc,
979 test::CoverageRunRustdoc,
980 test::Pretty,
981 test::CodegenCranelift,
982 test::CodegenGCC,
983 test::Crate,
984 test::CrateLibrustc,
985 test::CrateRustdoc,
986 test::CrateRustdocJsonTypes,
987 test::CrateBootstrap,
988 test::Linkcheck,
989 test::TierCheck,
990 test::Cargotest,
991 test::Cargo,
992 test::RustAnalyzer,
993 test::ErrorIndex,
994 test::Distcheck,
995 test::Nomicon,
996 test::Reference,
997 test::RustdocBook,
998 test::RustByExample,
999 test::TheBook,
1000 test::UnstableBook,
1001 test::RustcBook,
1002 test::LintDocs,
1003 test::EmbeddedBook,
1004 test::EditionGuide,
1005 test::Rustfmt,
1006 test::Miri,
1007 test::CargoMiri,
1008 test::Clippy,
1009 test::CompiletestTest,
1010 test::CrateRunMakeSupport,
1011 test::CrateBuildHelper,
1012 test::RustdocJSStd,
1013 test::RustdocJSNotStd,
1014 test::RustdocGUI,
1015 test::RustdocTheme,
1016 test::RustdocUi,
1017 test::RustdocJson,
1018 test::HtmlCheck,
1019 test::RustInstaller,
1020 test::TestFloatParse,
1021 test::CollectLicenseMetadata,
1022 test::Bootstrap,
1024 test::RunMake,
1026 ),
1027 Kind::Miri => describe!(test::Crate),
1028 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1029 Kind::Doc => describe!(
1030 doc::UnstableBook,
1031 doc::UnstableBookGen,
1032 doc::TheBook,
1033 doc::Standalone,
1034 doc::Std,
1035 doc::Rustc,
1036 doc::Rustdoc,
1037 doc::Rustfmt,
1038 doc::ErrorIndex,
1039 doc::Nomicon,
1040 doc::Reference,
1041 doc::RustdocBook,
1042 doc::RustByExample,
1043 doc::RustcBook,
1044 doc::Cargo,
1045 doc::CargoBook,
1046 doc::Clippy,
1047 doc::ClippyBook,
1048 doc::Miri,
1049 doc::EmbeddedBook,
1050 doc::EditionGuide,
1051 doc::StyleGuide,
1052 doc::Tidy,
1053 doc::Bootstrap,
1054 doc::Releases,
1055 doc::RunMakeSupport,
1056 doc::BuildHelper,
1057 doc::Compiletest,
1058 ),
1059 Kind::Dist => describe!(
1060 dist::Docs,
1061 dist::RustcDocs,
1062 dist::JsonDocs,
1063 dist::Mingw,
1064 dist::Rustc,
1065 dist::CodegenBackend,
1066 dist::Std,
1067 dist::RustcDev,
1068 dist::Analysis,
1069 dist::Src,
1070 dist::Cargo,
1071 dist::RustAnalyzer,
1072 dist::Rustfmt,
1073 dist::Clippy,
1074 dist::Miri,
1075 dist::LlvmTools,
1076 dist::LlvmBitcodeLinker,
1077 dist::RustDev,
1078 dist::Bootstrap,
1079 dist::Extended,
1080 dist::PlainSourceTarball,
1085 dist::BuildManifest,
1086 dist::ReproducibleArtifacts,
1087 dist::Gcc
1088 ),
1089 Kind::Install => describe!(
1090 install::Docs,
1091 install::Std,
1092 install::Rustc,
1097 install::Cargo,
1098 install::RustAnalyzer,
1099 install::Rustfmt,
1100 install::Clippy,
1101 install::Miri,
1102 install::LlvmTools,
1103 install::Src,
1104 ),
1105 Kind::Run => describe!(
1106 run::BuildManifest,
1107 run::BumpStage0,
1108 run::ReplaceVersionPlaceholder,
1109 run::Miri,
1110 run::CollectLicenseMetadata,
1111 run::GenerateCopyright,
1112 run::GenerateWindowsSys,
1113 run::GenerateCompletions,
1114 run::UnicodeTableGenerator,
1115 run::FeaturesStatusDump,
1116 run::CyclicStep,
1117 ),
1118 Kind::Setup => {
1119 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1120 }
1121 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1122 Kind::Vendor => describe!(vendor::Vendor),
1123 Kind::Format | Kind::Suggest | Kind::Perf => vec![],
1125 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1126 }
1127 }
1128
1129 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1130 let step_descriptions = Builder::get_step_descriptions(kind);
1131 if step_descriptions.is_empty() {
1132 return None;
1133 }
1134
1135 let builder = Self::new_internal(build, kind, vec![]);
1136 let builder = &builder;
1137 let mut should_run = ShouldRun::new(builder, Kind::Build);
1140 for desc in step_descriptions {
1141 should_run.kind = desc.kind;
1142 should_run = (desc.should_run)(should_run);
1143 }
1144 let mut help = String::from("Available paths:\n");
1145 let mut add_path = |path: &Path| {
1146 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1147 };
1148 for pathset in should_run.paths {
1149 match pathset {
1150 PathSet::Set(set) => {
1151 for path in set {
1152 add_path(&path.path);
1153 }
1154 }
1155 PathSet::Suite(path) => {
1156 add_path(&path.path.join("..."));
1157 }
1158 }
1159 }
1160 Some(help)
1161 }
1162
1163 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1164 Builder {
1165 build,
1166 top_stage: build.config.stage,
1167 kind,
1168 cache: Cache::new(),
1169 stack: RefCell::new(Vec::new()),
1170 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1171 paths,
1172 }
1173 }
1174
1175 pub fn new(build: &Build) -> Builder<'_> {
1176 let paths = &build.config.paths;
1177 let (kind, paths) = match build.config.cmd {
1178 Subcommand::Build => (Kind::Build, &paths[..]),
1179 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1180 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1181 Subcommand::Fix => (Kind::Fix, &paths[..]),
1182 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1183 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1184 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1185 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1186 Subcommand::Dist => (Kind::Dist, &paths[..]),
1187 Subcommand::Install => (Kind::Install, &paths[..]),
1188 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1189 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1190 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1191 Subcommand::Suggest { .. } => (Kind::Suggest, &[][..]),
1192 Subcommand::Setup { profile: ref path } => (
1193 Kind::Setup,
1194 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1195 ),
1196 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1197 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1198 };
1199
1200 Self::new_internal(build, kind, paths.to_owned())
1201 }
1202
1203 pub fn execute_cli(&self) {
1204 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1205 }
1206
1207 pub fn default_doc(&self, paths: &[PathBuf]) {
1208 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1209 }
1210
1211 pub fn doc_rust_lang_org_channel(&self) -> String {
1212 let channel = match &*self.config.channel {
1213 "stable" => &self.version,
1214 "beta" => "beta",
1215 "nightly" | "dev" => "nightly",
1216 _ => "stable",
1218 };
1219
1220 format!("https://doc.rust-lang.org/{channel}")
1221 }
1222
1223 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1224 StepDescription::run(v, self, paths);
1225 }
1226
1227 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1230 !target.triple.ends_with("-windows-gnu")
1231 }
1232
1233 #[cfg_attr(
1238 feature = "tracing",
1239 instrument(
1240 level = "trace",
1241 name = "Builder::compiler",
1242 target = "COMPILER",
1243 skip_all,
1244 fields(
1245 stage = stage,
1246 host = ?host,
1247 ),
1248 ),
1249 )]
1250 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1251 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1252 }
1253
1254 #[cfg_attr(
1266 feature = "tracing",
1267 instrument(
1268 level = "trace",
1269 name = "Builder::compiler_for",
1270 target = "COMPILER_FOR",
1271 skip_all,
1272 fields(
1273 stage = stage,
1274 host = ?host,
1275 target = ?target,
1276 ),
1277 ),
1278 )]
1279
1280 pub fn compiler_for(
1283 &self,
1284 stage: u32,
1285 host: TargetSelection,
1286 target: TargetSelection,
1287 ) -> Compiler {
1288 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1289 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1290 self.compiler(2, self.config.build)
1291 } else if self.build.force_use_stage1(stage, target) {
1292 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1293 self.compiler(1, self.config.build)
1294 } else {
1295 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1296 self.compiler(stage, host)
1297 };
1298
1299 if stage != resolved_compiler.stage {
1300 resolved_compiler.forced_compiler(true);
1301 }
1302
1303 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1304 resolved_compiler
1305 }
1306
1307 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1308 self.ensure(compile::Sysroot::new(compiler))
1309 }
1310
1311 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1313 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1314 }
1315
1316 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1319 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1320 }
1321
1322 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1323 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1324 }
1325
1326 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1332 if compiler.is_snapshot(self) {
1333 self.rustc_snapshot_libdir()
1334 } else {
1335 match self.config.libdir_relative() {
1336 Some(relative_libdir) if compiler.stage >= 1 => {
1337 self.sysroot(compiler).join(relative_libdir)
1338 }
1339 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1340 }
1341 }
1342 }
1343
1344 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1350 if compiler.is_snapshot(self) {
1351 libdir(self.config.build).as_ref()
1352 } else {
1353 match self.config.libdir_relative() {
1354 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1355 _ => libdir(compiler.host).as_ref(),
1356 }
1357 }
1358 }
1359
1360 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1365 match self.config.libdir_relative() {
1366 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1367 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1368 _ => Path::new("lib"),
1369 }
1370 }
1371
1372 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1373 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1374
1375 if self.config.llvm_from_ci {
1377 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1378 dylib_dirs.push(ci_llvm_lib);
1379 }
1380
1381 dylib_dirs
1382 }
1383
1384 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1387 if cfg!(windows) {
1391 return;
1392 }
1393
1394 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1395 }
1396
1397 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1399 if compiler.is_snapshot(self) {
1400 self.initial_rustc.clone()
1401 } else {
1402 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1403 }
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(&self, compiler: Compiler) -> PathBuf {
1416 self.ensure(tool::Rustdoc { compiler }).tool_path
1417 }
1418
1419 pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1420 if run_compiler.stage == 0 {
1421 let cargo_clippy = self
1422 .config
1423 .initial_cargo_clippy
1424 .clone()
1425 .unwrap_or_else(|| self.build.config.download_clippy());
1426
1427 let mut cmd = command(cargo_clippy);
1428 cmd.env("CARGO", &self.initial_cargo);
1429 return cmd;
1430 }
1431
1432 let _ = self.ensure(tool::Clippy { compiler: run_compiler, target: self.build.build });
1433 let cargo_clippy =
1434 self.ensure(tool::CargoClippy { compiler: run_compiler, target: self.build.build });
1435 let mut dylib_path = helpers::dylib_path();
1436 dylib_path.insert(0, self.sysroot(run_compiler).join("lib"));
1437
1438 let mut cmd = command(cargo_clippy.tool_path);
1439 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1440 cmd.env("CARGO", &self.initial_cargo);
1441 cmd
1442 }
1443
1444 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1445 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1446 let miri = self.ensure(tool::Miri { compiler: run_compiler, target: self.build.build });
1448 let cargo_miri =
1449 self.ensure(tool::CargoMiri { compiler: run_compiler, target: self.build.build });
1450 let mut cmd = command(cargo_miri.tool_path);
1452 cmd.env("MIRI", &miri.tool_path);
1453 cmd.env("CARGO", &self.initial_cargo);
1454 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1463 cmd
1464 }
1465
1466 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1467 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1468 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1469 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1470 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1473 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1474 .env("RUSTDOC_REAL", self.rustdoc(compiler))
1475 .env("RUSTC_BOOTSTRAP", "1");
1476
1477 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1478
1479 if self.config.deny_warnings {
1480 cmd.arg("-Dwarnings");
1481 }
1482 cmd.arg("-Znormalize-docs");
1483 cmd.args(linker_args(self, compiler.host, LldThreads::Yes, compiler.stage));
1484 cmd
1485 }
1486
1487 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1492 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1493 let llvm::LlvmResult { llvm_config, .. } = self.ensure(llvm::Llvm { target });
1494 if llvm_config.is_file() {
1495 return Some(llvm_config);
1496 }
1497 }
1498 None
1499 }
1500
1501 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1505 {
1506 let mut stack = self.stack.borrow_mut();
1507 for stack_step in stack.iter() {
1508 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1510 continue;
1511 }
1512 let mut out = String::new();
1513 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1514 for el in stack.iter().rev() {
1515 out += &format!("\t{el:?}\n");
1516 }
1517 panic!("{}", out);
1518 }
1519 if let Some(out) = self.cache.get(&step) {
1520 self.verbose_than(1, || println!("{}c {:?}", " ".repeat(stack.len()), step));
1521
1522 return out;
1523 }
1524 self.verbose_than(1, || println!("{}> {:?}", " ".repeat(stack.len()), step));
1525 stack.push(Box::new(step.clone()));
1526 }
1527
1528 #[cfg(feature = "build-metrics")]
1529 self.metrics.enter_step(&step, self);
1530
1531 let (out, dur) = {
1532 let start = Instant::now();
1533 let zero = Duration::new(0, 0);
1534 let parent = self.time_spent_on_dependencies.replace(zero);
1535 let out = step.clone().run(self);
1536 let dur = start.elapsed();
1537 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1538 (out, dur - deps)
1539 };
1540
1541 if self.config.print_step_timings && !self.config.dry_run() {
1542 let step_string = format!("{step:?}");
1543 let brace_index = step_string.find('{').unwrap_or(0);
1544 let type_string = type_name::<S>();
1545 println!(
1546 "[TIMING] {} {} -- {}.{:03}",
1547 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1548 &step_string[brace_index..],
1549 dur.as_secs(),
1550 dur.subsec_millis()
1551 );
1552 }
1553
1554 #[cfg(feature = "build-metrics")]
1555 self.metrics.exit_step(self);
1556
1557 {
1558 let mut stack = self.stack.borrow_mut();
1559 let cur_step = stack.pop().expect("step stack empty");
1560 assert_eq!(cur_step.downcast_ref(), Some(&step));
1561 }
1562 self.verbose_than(1, || println!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1563 self.cache.put(step, out.clone());
1564 out
1565 }
1566
1567 pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1571 &'a self,
1572 step: S,
1573 kind: Kind,
1574 ) -> S::Output {
1575 let desc = StepDescription::from::<S>(kind);
1576 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1577
1578 for pathset in &should_run.paths {
1580 if desc.is_excluded(self, pathset) {
1581 return None;
1582 }
1583 }
1584
1585 if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1587 }
1588
1589 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1591 let desc = StepDescription::from::<S>(kind);
1592 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1593
1594 for path in &self.paths {
1595 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1596 && !desc.is_excluded(
1597 self,
1598 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1599 )
1600 {
1601 return true;
1602 }
1603 }
1604
1605 false
1606 }
1607
1608 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1609 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1610 self.open_in_browser(path);
1611 } else {
1612 self.info(&format!("Doc path: {}", path.as_ref().display()));
1613 }
1614 }
1615
1616 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1617 let path = path.as_ref();
1618
1619 if self.config.dry_run() || !self.config.cmd.open() {
1620 self.info(&format!("Doc path: {}", path.display()));
1621 return;
1622 }
1623
1624 self.info(&format!("Opening doc {}", path.display()));
1625 if let Err(err) = opener::open(path) {
1626 self.info(&format!("{err}\n"));
1627 }
1628 }
1629}