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