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, 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::config::flags::Subcommand;
24use crate::core::config::{DryRun, TargetSelection};
25use crate::utils::build_stamp::BuildStamp;
26use crate::utils::cache::Cache;
27use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
28use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
29use crate::{Build, Crate, trace};
30
31mod cargo;
32
33#[cfg(test)]
34mod tests;
35
36pub struct Builder<'a> {
39 pub build: &'a Build,
41
42 pub top_stage: u32,
46
47 pub kind: Kind,
49
50 cache: Cache,
53
54 stack: RefCell<Vec<Box<dyn AnyDebug>>>,
57
58 time_spent_on_dependencies: Cell<Duration>,
60
61 pub paths: Vec<PathBuf>,
65
66 submodule_paths_cache: OnceLock<Vec<String>>,
68}
69
70impl Deref for Builder<'_> {
71 type Target = Build;
72
73 fn deref(&self) -> &Self::Target {
74 self.build
75 }
76}
77
78pub trait AnyDebug: Any + Debug {}
83impl<T: Any + Debug> AnyDebug for T {}
84impl dyn AnyDebug {
85 fn downcast_ref<T: Any>(&self) -> Option<&T> {
87 (self as &dyn Any).downcast_ref()
88 }
89
90 }
92
93pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
94 type Output: Clone;
96
97 const DEFAULT: bool = false;
103
104 const IS_HOST: bool = false;
111
112 fn run(self, builder: &Builder<'_>) -> Self::Output;
126
127 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
129
130 fn make_run(_run: RunConfig<'_>) {
134 unimplemented!()
139 }
140
141 fn metadata(&self) -> Option<StepMetadata> {
143 None
144 }
145}
146
147#[derive(Clone, Debug, PartialEq, Eq)]
149pub struct StepMetadata {
150 name: String,
151 kind: Kind,
152 target: TargetSelection,
153 built_by: Option<Compiler>,
154 stage: Option<u32>,
155 metadata: Option<String>,
157}
158
159impl StepMetadata {
160 pub fn build(name: &str, target: TargetSelection) -> Self {
161 Self::new(name, target, Kind::Build)
162 }
163
164 pub fn check(name: &str, target: TargetSelection) -> Self {
165 Self::new(name, target, Kind::Check)
166 }
167
168 pub fn clippy(name: &str, target: TargetSelection) -> Self {
169 Self::new(name, target, Kind::Clippy)
170 }
171
172 pub fn doc(name: &str, target: TargetSelection) -> Self {
173 Self::new(name, target, Kind::Doc)
174 }
175
176 pub fn dist(name: &str, target: TargetSelection) -> Self {
177 Self::new(name, target, Kind::Dist)
178 }
179
180 pub fn test(name: &str, target: TargetSelection) -> Self {
181 Self::new(name, target, Kind::Test)
182 }
183
184 pub fn run(name: &str, target: TargetSelection) -> Self {
185 Self::new(name, target, Kind::Run)
186 }
187
188 fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
189 Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
190 }
191
192 pub fn built_by(mut self, compiler: Compiler) -> Self {
193 self.built_by = Some(compiler);
194 self
195 }
196
197 pub fn stage(mut self, stage: u32) -> Self {
198 self.stage = Some(stage);
199 self
200 }
201
202 pub fn with_metadata(mut self, metadata: String) -> Self {
203 self.metadata = Some(metadata);
204 self
205 }
206
207 pub fn get_stage(&self) -> Option<u32> {
208 self.stage.or(self
209 .built_by
210 .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
213 }
214
215 pub fn get_name(&self) -> &str {
216 &self.name
217 }
218
219 pub fn get_target(&self) -> TargetSelection {
220 self.target
221 }
222}
223
224pub struct RunConfig<'a> {
225 pub builder: &'a Builder<'a>,
226 pub target: TargetSelection,
227 pub paths: Vec<PathSet>,
228}
229
230impl RunConfig<'_> {
231 pub fn build_triple(&self) -> TargetSelection {
232 self.builder.build.host_target
233 }
234
235 #[track_caller]
237 pub fn cargo_crates_in_set(&self) -> Vec<String> {
238 let mut crates = Vec::new();
239 for krate in &self.paths {
240 let path = &krate.assert_single_path().path;
241
242 let crate_name = self
243 .builder
244 .crate_paths
245 .get(path)
246 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
247
248 crates.push(crate_name.to_string());
249 }
250 crates
251 }
252
253 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
260 let has_alias =
261 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
262 if !has_alias {
263 return self.cargo_crates_in_set();
264 }
265
266 let crates = match alias {
267 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
268 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
269 };
270
271 crates.into_iter().map(|krate| krate.name.to_string()).collect()
272 }
273}
274
275#[derive(Debug, Copy, Clone)]
276pub enum Alias {
277 Library,
278 Compiler,
279}
280
281impl Alias {
282 fn as_str(self) -> &'static str {
283 match self {
284 Alias::Library => "library",
285 Alias::Compiler => "compiler",
286 }
287 }
288}
289
290pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
294 if crates.is_empty() {
295 return "".into();
296 }
297
298 let mut descr = String::from("{");
299 descr.push_str(crates[0].as_ref());
300 for krate in &crates[1..] {
301 descr.push_str(", ");
302 descr.push_str(krate.as_ref());
303 }
304 descr.push('}');
305 descr
306}
307
308struct StepDescription {
309 default: bool,
310 is_host: bool,
311 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
312 make_run: fn(RunConfig<'_>),
313 name: &'static str,
314 kind: Kind,
315}
316
317#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
318pub struct TaskPath {
319 pub path: PathBuf,
320 pub kind: Option<Kind>,
321}
322
323impl Debug for TaskPath {
324 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325 if let Some(kind) = &self.kind {
326 write!(f, "{}::", kind.as_str())?;
327 }
328 write!(f, "{}", self.path.display())
329 }
330}
331
332#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
334pub enum PathSet {
335 Set(BTreeSet<TaskPath>),
346 Suite(TaskPath),
353}
354
355impl PathSet {
356 fn empty() -> PathSet {
357 PathSet::Set(BTreeSet::new())
358 }
359
360 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
361 let mut set = BTreeSet::new();
362 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
363 PathSet::Set(set)
364 }
365
366 fn has(&self, needle: &Path, module: Kind) -> bool {
367 match self {
368 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
369 PathSet::Suite(suite) => Self::check(suite, needle, module),
370 }
371 }
372
373 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
375 let check_path = || {
376 p.path.ends_with(needle) || p.path.starts_with(needle)
378 };
379 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
380 }
381
382 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
389 let mut check = |p| {
390 let mut result = false;
391 for n in needles.iter_mut() {
392 let matched = Self::check(p, &n.path, module);
393 if matched {
394 n.will_be_executed = true;
395 result = true;
396 }
397 }
398 result
399 };
400 match self {
401 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
402 PathSet::Suite(suite) => {
403 if check(suite) {
404 self.clone()
405 } else {
406 PathSet::empty()
407 }
408 }
409 }
410 }
411
412 #[track_caller]
416 pub fn assert_single_path(&self) -> &TaskPath {
417 match self {
418 PathSet::Set(set) => {
419 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
420 set.iter().next().unwrap()
421 }
422 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
423 }
424 }
425}
426
427const PATH_REMAP: &[(&str, &[&str])] = &[
428 ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
431 (
433 "tests",
434 &[
435 "tests/assembly-llvm",
437 "tests/codegen-llvm",
438 "tests/codegen-units",
439 "tests/coverage",
440 "tests/coverage-run-rustdoc",
441 "tests/crashes",
442 "tests/debuginfo",
443 "tests/incremental",
444 "tests/mir-opt",
445 "tests/pretty",
446 "tests/run-make",
447 "tests/run-make-cargo",
448 "tests/rustdoc",
449 "tests/rustdoc-gui",
450 "tests/rustdoc-js",
451 "tests/rustdoc-js-std",
452 "tests/rustdoc-json",
453 "tests/rustdoc-ui",
454 "tests/ui",
455 "tests/ui-fulldeps",
456 ],
458 ),
459];
460
461fn remap_paths(paths: &mut Vec<PathBuf>) {
462 let mut remove = vec![];
463 let mut add = vec![];
464 for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
465 {
466 for &(search, replace) in PATH_REMAP {
467 if path.trim_matches(std::path::is_separator) == search {
469 remove.push(i);
470 add.extend(replace.iter().map(PathBuf::from));
471 break;
472 }
473 }
474 }
475 remove.sort();
476 remove.dedup();
477 for idx in remove.into_iter().rev() {
478 paths.remove(idx);
479 }
480 paths.append(&mut add);
481}
482
483#[derive(Clone, PartialEq)]
484struct CLIStepPath {
485 path: PathBuf,
486 will_be_executed: bool,
487}
488
489#[cfg(test)]
490impl CLIStepPath {
491 fn will_be_executed(mut self, will_be_executed: bool) -> Self {
492 self.will_be_executed = will_be_executed;
493 self
494 }
495}
496
497impl Debug for CLIStepPath {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 write!(f, "{}", self.path.display())
500 }
501}
502
503impl From<PathBuf> for CLIStepPath {
504 fn from(path: PathBuf) -> Self {
505 Self { path, will_be_executed: false }
506 }
507}
508
509impl StepDescription {
510 fn from<S: Step>(kind: Kind) -> StepDescription {
511 StepDescription {
512 default: S::DEFAULT,
513 is_host: S::IS_HOST,
514 should_run: S::should_run,
515 make_run: S::make_run,
516 name: std::any::type_name::<S>(),
517 kind,
518 }
519 }
520
521 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
522 pathsets.retain(|set| !self.is_excluded(builder, set));
523
524 if pathsets.is_empty() {
525 return;
526 }
527
528 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
530
531 for target in targets {
532 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
533 (self.make_run)(run);
534 }
535 }
536
537 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
538 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
539 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
540 println!("Skipping {pathset:?} because it is excluded");
541 }
542 return true;
543 }
544
545 if !builder.config.skip.is_empty()
546 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
547 {
548 builder.verbose(|| {
549 println!(
550 "{:?} not skipped for {:?} -- not in {:?}",
551 pathset, self.name, builder.config.skip
552 )
553 });
554 }
555 false
556 }
557
558 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
559 let should_runs = v
560 .iter()
561 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
562 .collect::<Vec<_>>();
563
564 if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
565 {
566 eprintln!(
567 "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
568 builder.kind.as_str()
569 );
570 crate::exit!(1);
571 }
572
573 for (desc, should_run) in v.iter().zip(&should_runs) {
575 assert!(
576 !should_run.paths.is_empty(),
577 "{:?} should have at least one pathset",
578 desc.name
579 );
580 }
581
582 if paths.is_empty() || builder.config.include_default_paths {
583 for (desc, should_run) in v.iter().zip(&should_runs) {
584 if desc.default && should_run.is_really_default() {
585 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
586 }
587 }
588 }
589
590 let mut paths: Vec<PathBuf> = paths
592 .iter()
593 .map(|p| {
594 if !p.exists() {
596 return p.clone();
597 }
598
599 match std::path::absolute(p) {
601 Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
602 Err(e) => {
603 eprintln!("ERROR: {e:?}");
604 panic!("Due to the above error, failed to resolve path: {p:?}");
605 }
606 }
607 })
608 .collect();
609
610 remap_paths(&mut paths);
611
612 paths.retain(|path| {
615 for (desc, should_run) in v.iter().zip(&should_runs) {
616 if let Some(suite) = should_run.is_suite_path(path) {
617 desc.maybe_run(builder, vec![suite.clone()]);
618 return false;
619 }
620 }
621 true
622 });
623
624 if paths.is_empty() {
625 return;
626 }
627
628 let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
629 let mut path_lookup: Vec<(CLIStepPath, bool)> =
630 paths.clone().into_iter().map(|p| (p, false)).collect();
631
632 let mut steps_to_run = vec![];
636
637 for (desc, should_run) in v.iter().zip(&should_runs) {
638 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
639
640 let mut closest_index = usize::MAX;
646
647 for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
649 if !*is_used && !paths.contains(path) {
650 closest_index = index;
651 *is_used = true;
652 break;
653 }
654 }
655
656 steps_to_run.push((closest_index, desc, pathsets));
657 }
658
659 steps_to_run.sort_by_key(|(index, _, _)| *index);
661
662 for (_index, desc, pathsets) in steps_to_run {
664 if !pathsets.is_empty() {
665 desc.maybe_run(builder, pathsets);
666 }
667 }
668
669 paths.retain(|p| !p.will_be_executed);
670
671 if !paths.is_empty() {
672 eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
673 eprintln!(
674 "HELP: run `x.py {} --help --verbose` to show a list of available paths",
675 builder.kind.as_str()
676 );
677 eprintln!(
678 "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
679 );
680 crate::exit!(1);
681 }
682 }
683}
684
685enum ReallyDefault<'a> {
686 Bool(bool),
687 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
688}
689
690pub struct ShouldRun<'a> {
691 pub builder: &'a Builder<'a>,
692 kind: Kind,
693
694 paths: BTreeSet<PathSet>,
696
697 is_really_default: ReallyDefault<'a>,
700}
701
702impl<'a> ShouldRun<'a> {
703 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
704 ShouldRun {
705 builder,
706 kind,
707 paths: BTreeSet::new(),
708 is_really_default: ReallyDefault::Bool(true), }
710 }
711
712 pub fn default_condition(mut self, cond: bool) -> Self {
713 self.is_really_default = ReallyDefault::Bool(cond);
714 self
715 }
716
717 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
718 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
719 self
720 }
721
722 pub fn is_really_default(&self) -> bool {
723 match &self.is_really_default {
724 ReallyDefault::Bool(val) => *val,
725 ReallyDefault::Lazy(lazy) => *lazy.deref(),
726 }
727 }
728
729 pub fn crate_or_deps(self, name: &str) -> Self {
734 let crates = self.builder.in_tree_crates(name, None);
735 self.crates(crates)
736 }
737
738 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
744 for krate in crates {
745 let path = krate.local_path(self.builder);
746 self.paths.insert(PathSet::one(path, self.kind));
747 }
748 self
749 }
750
751 pub fn alias(mut self, alias: &str) -> Self {
753 assert!(
757 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
758 "use `builder.path()` for real paths: {alias}"
759 );
760 self.paths.insert(PathSet::Set(
761 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
762 ));
763 self
764 }
765
766 pub fn path(self, path: &str) -> Self {
770 self.paths(&[path])
771 }
772
773 pub fn paths(mut self, paths: &[&str]) -> Self {
783 let submodules_paths = self.builder.submodule_paths();
784
785 self.paths.insert(PathSet::Set(
786 paths
787 .iter()
788 .map(|p| {
789 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
791 assert!(
792 self.builder.src.join(p).exists(),
793 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
794 );
795 }
796
797 TaskPath { path: p.into(), kind: Some(self.kind) }
798 })
799 .collect(),
800 ));
801 self
802 }
803
804 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
806 self.paths.iter().find(|pathset| match pathset {
807 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
808 PathSet::Set(_) => false,
809 })
810 }
811
812 pub fn suite_path(mut self, suite: &str) -> Self {
813 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
814 self
815 }
816
817 pub fn never(mut self) -> ShouldRun<'a> {
819 self.paths.insert(PathSet::empty());
820 self
821 }
822
823 fn pathset_for_paths_removing_matches(
833 &self,
834 paths: &mut [CLIStepPath],
835 kind: Kind,
836 ) -> Vec<PathSet> {
837 let mut sets = vec![];
838 for pathset in &self.paths {
839 let subset = pathset.intersection_removing_matches(paths, kind);
840 if subset != PathSet::empty() {
841 sets.push(subset);
842 }
843 }
844 sets
845 }
846}
847
848#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
849pub enum Kind {
850 #[value(alias = "b")]
851 Build,
852 #[value(alias = "c")]
853 Check,
854 Clippy,
855 Fix,
856 Format,
857 #[value(alias = "t")]
858 Test,
859 Miri,
860 MiriSetup,
861 MiriTest,
862 Bench,
863 #[value(alias = "d")]
864 Doc,
865 Clean,
866 Dist,
867 Install,
868 #[value(alias = "r")]
869 Run,
870 Setup,
871 Vendor,
872 Perf,
873}
874
875impl Kind {
876 pub fn as_str(&self) -> &'static str {
877 match self {
878 Kind::Build => "build",
879 Kind::Check => "check",
880 Kind::Clippy => "clippy",
881 Kind::Fix => "fix",
882 Kind::Format => "fmt",
883 Kind::Test => "test",
884 Kind::Miri => "miri",
885 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
886 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
887 Kind::Bench => "bench",
888 Kind::Doc => "doc",
889 Kind::Clean => "clean",
890 Kind::Dist => "dist",
891 Kind::Install => "install",
892 Kind::Run => "run",
893 Kind::Setup => "setup",
894 Kind::Vendor => "vendor",
895 Kind::Perf => "perf",
896 }
897 }
898
899 pub fn description(&self) -> String {
900 match self {
901 Kind::Test => "Testing",
902 Kind::Bench => "Benchmarking",
903 Kind::Doc => "Documenting",
904 Kind::Run => "Running",
905 Kind::Clippy => "Linting",
906 Kind::Perf => "Profiling & benchmarking",
907 _ => {
908 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
909 return format!("{title_letter}{}ing", &self.as_str()[1..]);
910 }
911 }
912 .to_owned()
913 }
914}
915
916#[derive(Debug, Clone, Hash, PartialEq, Eq)]
917struct Libdir {
918 compiler: Compiler,
919 target: TargetSelection,
920}
921
922impl Step for Libdir {
923 type Output = PathBuf;
924
925 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
926 run.never()
927 }
928
929 fn run(self, builder: &Builder<'_>) -> PathBuf {
930 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
931 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
932
933 if !builder.config.dry_run() {
934 if !builder.download_rustc() {
937 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
938 builder.verbose(|| {
939 eprintln!(
940 "Removing sysroot {} to avoid caching bugs",
941 sysroot_target_libdir.display()
942 )
943 });
944 let _ = fs::remove_dir_all(&sysroot_target_libdir);
945 t!(fs::create_dir_all(&sysroot_target_libdir));
946 }
947
948 if self.compiler.stage == 0 {
949 dist::maybe_install_llvm_target(
953 builder,
954 self.compiler.host,
955 &builder.sysroot(self.compiler),
956 );
957 }
958 }
959
960 sysroot
961 }
962}
963
964#[cfg(feature = "tracing")]
965pub const STEP_SPAN_TARGET: &str = "STEP";
966
967impl<'a> Builder<'a> {
968 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
969 macro_rules! describe {
970 ($($rule:ty),+ $(,)?) => {{
971 vec![$(StepDescription::from::<$rule>(kind)),+]
972 }};
973 }
974 match kind {
975 Kind::Build => describe!(
976 compile::Std,
977 compile::Rustc,
978 compile::Assemble,
979 compile::CraneliftCodegenBackend,
980 compile::GccCodegenBackend,
981 compile::StartupObjects,
982 tool::BuildManifest,
983 tool::Rustbook,
984 tool::ErrorIndex,
985 tool::UnstableBookGen,
986 tool::Tidy,
987 tool::Linkchecker,
988 tool::CargoTest,
989 tool::Compiletest,
990 tool::RemoteTestServer,
991 tool::RemoteTestClient,
992 tool::RustInstaller,
993 tool::FeaturesStatusDump,
994 tool::Cargo,
995 tool::RustAnalyzer,
996 tool::RustAnalyzerProcMacroSrv,
997 tool::Rustdoc,
998 tool::Clippy,
999 tool::CargoClippy,
1000 llvm::Llvm,
1001 gcc::Gcc,
1002 llvm::Sanitizers,
1003 tool::Rustfmt,
1004 tool::Cargofmt,
1005 tool::Miri,
1006 tool::CargoMiri,
1007 llvm::Lld,
1008 llvm::Enzyme,
1009 llvm::CrtBeginEnd,
1010 tool::RustdocGUITest,
1011 tool::OptimizedDist,
1012 tool::CoverageDump,
1013 tool::LlvmBitcodeLinker,
1014 tool::RustcPerf,
1015 tool::WasmComponentLd,
1016 tool::LldWrapper
1017 ),
1018 Kind::Clippy => describe!(
1019 clippy::Std,
1020 clippy::Rustc,
1021 clippy::Bootstrap,
1022 clippy::BuildHelper,
1023 clippy::BuildManifest,
1024 clippy::CargoMiri,
1025 clippy::Clippy,
1026 clippy::CodegenGcc,
1027 clippy::CollectLicenseMetadata,
1028 clippy::Compiletest,
1029 clippy::CoverageDump,
1030 clippy::Jsondocck,
1031 clippy::Jsondoclint,
1032 clippy::LintDocs,
1033 clippy::LlvmBitcodeLinker,
1034 clippy::Miri,
1035 clippy::MiroptTestTools,
1036 clippy::OptDist,
1037 clippy::RemoteTestClient,
1038 clippy::RemoteTestServer,
1039 clippy::RustAnalyzer,
1040 clippy::Rustdoc,
1041 clippy::Rustfmt,
1042 clippy::RustInstaller,
1043 clippy::TestFloatParse,
1044 clippy::Tidy,
1045 clippy::CI,
1046 ),
1047 Kind::Check | Kind::Fix => describe!(
1048 check::Rustc,
1049 check::Rustdoc,
1050 check::CraneliftCodegenBackend,
1051 check::GccCodegenBackend,
1052 check::Clippy,
1053 check::Miri,
1054 check::CargoMiri,
1055 check::MiroptTestTools,
1056 check::Rustfmt,
1057 check::RustAnalyzer,
1058 check::TestFloatParse,
1059 check::Bootstrap,
1060 check::RunMakeSupport,
1061 check::Compiletest,
1062 check::FeaturesStatusDump,
1063 check::CoverageDump,
1064 check::Linkchecker,
1065 check::BumpStage0,
1066 check::Std,
1073 ),
1074 Kind::Test => describe!(
1075 crate::core::build_steps::toolstate::ToolStateCheck,
1076 test::Tidy,
1077 test::Bootstrap,
1078 test::Ui,
1079 test::Crashes,
1080 test::Coverage,
1081 test::MirOpt,
1082 test::CodegenLlvm,
1083 test::CodegenUnits,
1084 test::AssemblyLlvm,
1085 test::Incremental,
1086 test::Debuginfo,
1087 test::UiFullDeps,
1088 test::Rustdoc,
1089 test::CoverageRunRustdoc,
1090 test::Pretty,
1091 test::CodegenCranelift,
1092 test::CodegenGCC,
1093 test::Crate,
1094 test::CrateLibrustc,
1095 test::CrateRustdoc,
1096 test::CrateRustdocJsonTypes,
1097 test::CrateBootstrap,
1098 test::Linkcheck,
1099 test::TierCheck,
1100 test::Cargotest,
1101 test::Cargo,
1102 test::RustAnalyzer,
1103 test::ErrorIndex,
1104 test::Distcheck,
1105 test::Nomicon,
1106 test::Reference,
1107 test::RustdocBook,
1108 test::RustByExample,
1109 test::TheBook,
1110 test::UnstableBook,
1111 test::RustcBook,
1112 test::LintDocs,
1113 test::EmbeddedBook,
1114 test::EditionGuide,
1115 test::Rustfmt,
1116 test::Miri,
1117 test::CargoMiri,
1118 test::Clippy,
1119 test::CompiletestTest,
1120 test::CrateRunMakeSupport,
1121 test::CrateBuildHelper,
1122 test::RustdocJSStd,
1123 test::RustdocJSNotStd,
1124 test::RustdocGUI,
1125 test::RustdocTheme,
1126 test::RustdocUi,
1127 test::RustdocJson,
1128 test::HtmlCheck,
1129 test::RustInstaller,
1130 test::TestFloatParse,
1131 test::CollectLicenseMetadata,
1132 test::RunMake,
1133 test::RunMakeCargo,
1134 ),
1135 Kind::Miri => describe!(test::Crate),
1136 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1137 Kind::Doc => describe!(
1138 doc::UnstableBook,
1139 doc::UnstableBookGen,
1140 doc::TheBook,
1141 doc::Standalone,
1142 doc::Std,
1143 doc::Rustc,
1144 doc::Rustdoc,
1145 doc::Rustfmt,
1146 doc::ErrorIndex,
1147 doc::Nomicon,
1148 doc::Reference,
1149 doc::RustdocBook,
1150 doc::RustByExample,
1151 doc::RustcBook,
1152 doc::Cargo,
1153 doc::CargoBook,
1154 doc::Clippy,
1155 doc::ClippyBook,
1156 doc::Miri,
1157 doc::EmbeddedBook,
1158 doc::EditionGuide,
1159 doc::StyleGuide,
1160 doc::Tidy,
1161 doc::Bootstrap,
1162 doc::Releases,
1163 doc::RunMakeSupport,
1164 doc::BuildHelper,
1165 doc::Compiletest,
1166 ),
1167 Kind::Dist => describe!(
1168 dist::Docs,
1169 dist::RustcDocs,
1170 dist::JsonDocs,
1171 dist::Mingw,
1172 dist::Rustc,
1173 dist::CraneliftCodegenBackend,
1174 dist::Std,
1175 dist::RustcDev,
1176 dist::Analysis,
1177 dist::Src,
1178 dist::Cargo,
1179 dist::RustAnalyzer,
1180 dist::Rustfmt,
1181 dist::Clippy,
1182 dist::Miri,
1183 dist::LlvmTools,
1184 dist::LlvmBitcodeLinker,
1185 dist::RustDev,
1186 dist::Bootstrap,
1187 dist::Extended,
1188 dist::PlainSourceTarball,
1193 dist::BuildManifest,
1194 dist::ReproducibleArtifacts,
1195 dist::Gcc
1196 ),
1197 Kind::Install => describe!(
1198 install::Docs,
1199 install::Std,
1200 install::Rustc,
1205 install::Cargo,
1206 install::RustAnalyzer,
1207 install::Rustfmt,
1208 install::Clippy,
1209 install::Miri,
1210 install::LlvmTools,
1211 install::Src,
1212 ),
1213 Kind::Run => describe!(
1214 run::BuildManifest,
1215 run::BumpStage0,
1216 run::ReplaceVersionPlaceholder,
1217 run::Miri,
1218 run::CollectLicenseMetadata,
1219 run::GenerateCopyright,
1220 run::GenerateWindowsSys,
1221 run::GenerateCompletions,
1222 run::UnicodeTableGenerator,
1223 run::FeaturesStatusDump,
1224 run::CyclicStep,
1225 run::CoverageDump,
1226 run::Rustfmt,
1227 ),
1228 Kind::Setup => {
1229 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1230 }
1231 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1232 Kind::Vendor => describe!(vendor::Vendor),
1233 Kind::Format | Kind::Perf => vec![],
1235 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1236 }
1237 }
1238
1239 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1240 let step_descriptions = Builder::get_step_descriptions(kind);
1241 if step_descriptions.is_empty() {
1242 return None;
1243 }
1244
1245 let builder = Self::new_internal(build, kind, vec![]);
1246 let builder = &builder;
1247 let mut should_run = ShouldRun::new(builder, Kind::Build);
1250 for desc in step_descriptions {
1251 should_run.kind = desc.kind;
1252 should_run = (desc.should_run)(should_run);
1253 }
1254 let mut help = String::from("Available paths:\n");
1255 let mut add_path = |path: &Path| {
1256 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1257 };
1258 for pathset in should_run.paths {
1259 match pathset {
1260 PathSet::Set(set) => {
1261 for path in set {
1262 add_path(&path.path);
1263 }
1264 }
1265 PathSet::Suite(path) => {
1266 add_path(&path.path.join("..."));
1267 }
1268 }
1269 }
1270 Some(help)
1271 }
1272
1273 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1274 Builder {
1275 build,
1276 top_stage: build.config.stage,
1277 kind,
1278 cache: Cache::new(),
1279 stack: RefCell::new(Vec::new()),
1280 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1281 paths,
1282 submodule_paths_cache: Default::default(),
1283 }
1284 }
1285
1286 pub fn new(build: &Build) -> Builder<'_> {
1287 let paths = &build.config.paths;
1288 let (kind, paths) = match build.config.cmd {
1289 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1290 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1291 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1292 Subcommand::Fix => (Kind::Fix, &paths[..]),
1293 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1294 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1295 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1296 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1297 Subcommand::Dist => (Kind::Dist, &paths[..]),
1298 Subcommand::Install => (Kind::Install, &paths[..]),
1299 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1300 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1301 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1302 Subcommand::Setup { profile: ref path } => (
1303 Kind::Setup,
1304 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1305 ),
1306 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1307 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1308 };
1309
1310 Self::new_internal(build, kind, paths.to_owned())
1311 }
1312
1313 pub fn execute_cli(&self) {
1314 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1315 }
1316
1317 pub fn run_default_doc_steps(&self) {
1319 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), &[]);
1320 }
1321
1322 pub fn doc_rust_lang_org_channel(&self) -> String {
1323 let channel = match &*self.config.channel {
1324 "stable" => &self.version,
1325 "beta" => "beta",
1326 "nightly" | "dev" => "nightly",
1327 _ => "stable",
1329 };
1330
1331 format!("https://doc.rust-lang.org/{channel}")
1332 }
1333
1334 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1335 StepDescription::run(v, self, paths);
1336 }
1337
1338 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1341 !target.triple.ends_with("-windows-gnu")
1342 }
1343
1344 #[cfg_attr(
1349 feature = "tracing",
1350 instrument(
1351 level = "trace",
1352 name = "Builder::compiler",
1353 target = "COMPILER",
1354 skip_all,
1355 fields(
1356 stage = stage,
1357 host = ?host,
1358 ),
1359 ),
1360 )]
1361 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1362 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1363 }
1364
1365 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1382 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1383 self.compiler(1, self.host_target)
1384 } else {
1385 self.compiler(stage, self.host_target)
1386 }
1387 }
1388
1389 #[cfg_attr(
1401 feature = "tracing",
1402 instrument(
1403 level = "trace",
1404 name = "Builder::compiler_for",
1405 target = "COMPILER_FOR",
1406 skip_all,
1407 fields(
1408 stage = stage,
1409 host = ?host,
1410 target = ?target,
1411 ),
1412 ),
1413 )]
1414 pub fn compiler_for(
1417 &self,
1418 stage: u32,
1419 host: TargetSelection,
1420 target: TargetSelection,
1421 ) -> Compiler {
1422 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1423 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1424 self.compiler(2, self.config.host_target)
1425 } else if self.build.force_use_stage1(stage, target) {
1426 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1427 self.compiler(1, self.config.host_target)
1428 } else {
1429 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1430 self.compiler(stage, host)
1431 };
1432
1433 if stage != resolved_compiler.stage {
1434 resolved_compiler.forced_compiler(true);
1435 }
1436
1437 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1438 resolved_compiler
1439 }
1440
1441 #[cfg_attr(
1448 feature = "tracing",
1449 instrument(
1450 level = "trace",
1451 name = "Builder::std",
1452 target = "STD",
1453 skip_all,
1454 fields(
1455 compiler = ?compiler,
1456 target = ?target,
1457 ),
1458 ),
1459 )]
1460 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1461 if compiler.stage == 0 {
1471 if target != compiler.host {
1472 if self.local_rebuild {
1473 self.ensure(Std::new(compiler, target))
1474 } else {
1475 panic!(
1476 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1477You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1478Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1479",
1480 compiler.host
1481 )
1482 }
1483 } else {
1484 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1486 None
1487 }
1488 } else {
1489 self.ensure(Std::new(compiler, target))
1492 }
1493 }
1494
1495 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1496 self.ensure(compile::Sysroot::new(compiler))
1497 }
1498
1499 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1501 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1502 }
1503
1504 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1507 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1508 }
1509
1510 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1511 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1512 }
1513
1514 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1520 if compiler.is_snapshot(self) {
1521 self.rustc_snapshot_libdir()
1522 } else {
1523 match self.config.libdir_relative() {
1524 Some(relative_libdir) if compiler.stage >= 1 => {
1525 self.sysroot(compiler).join(relative_libdir)
1526 }
1527 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1528 }
1529 }
1530 }
1531
1532 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1538 if compiler.is_snapshot(self) {
1539 libdir(self.config.host_target).as_ref()
1540 } else {
1541 match self.config.libdir_relative() {
1542 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1543 _ => libdir(compiler.host).as_ref(),
1544 }
1545 }
1546 }
1547
1548 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1553 match self.config.libdir_relative() {
1554 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1555 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1556 _ => Path::new("lib"),
1557 }
1558 }
1559
1560 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1561 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1562
1563 if self.config.llvm_from_ci {
1565 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1566 dylib_dirs.push(ci_llvm_lib);
1567 }
1568
1569 dylib_dirs
1570 }
1571
1572 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1575 if cfg!(any(windows, target_os = "cygwin")) {
1579 return;
1580 }
1581
1582 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1583 }
1584
1585 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1587 if compiler.is_snapshot(self) {
1588 self.initial_rustc.clone()
1589 } else {
1590 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1591 }
1592 }
1593
1594 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1596 fs::read_dir(self.sysroot_codegen_backends(compiler))
1597 .into_iter()
1598 .flatten()
1599 .filter_map(Result::ok)
1600 .map(|entry| entry.path())
1601 }
1602
1603 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1607 self.ensure(tool::Rustdoc { target_compiler })
1608 }
1609
1610 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1611 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1612
1613 let compilers =
1614 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1615 assert_eq!(run_compiler, compilers.target_compiler());
1616
1617 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1619 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1620 let mut cmd = command(cargo_miri.tool_path);
1622 cmd.env("MIRI", &miri.tool_path);
1623 cmd.env("CARGO", &self.initial_cargo);
1624 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1633 cmd
1634 }
1635
1636 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1639 if build_compiler.stage == 0 {
1640 let cargo_clippy = self
1641 .config
1642 .initial_cargo_clippy
1643 .clone()
1644 .unwrap_or_else(|| self.build.config.download_clippy());
1645
1646 let mut cmd = command(cargo_clippy);
1647 cmd.env("CARGO", &self.initial_cargo);
1648 return cmd;
1649 }
1650
1651 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1655
1656 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1657 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1658 let mut dylib_path = helpers::dylib_path();
1659 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1660
1661 let mut cmd = command(cargo_clippy.tool_path);
1662 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1663 cmd.env("CARGO", &self.initial_cargo);
1664 cmd
1665 }
1666
1667 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1668 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1669 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1670 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1671 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1674 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1675 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1676 .env("RUSTC_BOOTSTRAP", "1");
1677
1678 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1679
1680 if self.config.deny_warnings {
1681 cmd.arg("-Dwarnings");
1682 }
1683 cmd.arg("-Znormalize-docs");
1684 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1685 cmd
1686 }
1687
1688 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1697 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1698 let llvm::LlvmResult { host_llvm_config, .. } = self.ensure(llvm::Llvm { target });
1699 if host_llvm_config.is_file() {
1700 return Some(host_llvm_config);
1701 }
1702 }
1703 None
1704 }
1705
1706 pub fn require_and_update_all_submodules(&self) {
1709 for submodule in self.submodule_paths() {
1710 self.require_submodule(submodule, None);
1711 }
1712 }
1713
1714 pub fn submodule_paths(&self) -> &[String] {
1716 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1717 }
1718
1719 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1723 {
1724 let mut stack = self.stack.borrow_mut();
1725 for stack_step in stack.iter() {
1726 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1728 continue;
1729 }
1730 let mut out = String::new();
1731 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1732 for el in stack.iter().rev() {
1733 out += &format!("\t{el:?}\n");
1734 }
1735 panic!("{}", out);
1736 }
1737 if let Some(out) = self.cache.get(&step) {
1738 #[cfg(feature = "tracing")]
1739 {
1740 if let Some(parent) = stack.last() {
1741 let mut graph = self.build.step_graph.borrow_mut();
1742 graph.register_cached_step(&step, parent, self.config.dry_run());
1743 }
1744 }
1745 return out;
1746 }
1747
1748 #[cfg(feature = "tracing")]
1749 {
1750 let parent = stack.last();
1751 let mut graph = self.build.step_graph.borrow_mut();
1752 graph.register_step_execution(&step, parent, self.config.dry_run());
1753 }
1754
1755 stack.push(Box::new(step.clone()));
1756 }
1757
1758 #[cfg(feature = "build-metrics")]
1759 self.metrics.enter_step(&step, self);
1760
1761 if self.config.print_step_timings && !self.config.dry_run() {
1762 println!("[TIMING:start] {}", pretty_print_step(&step));
1763 }
1764
1765 let (out, dur) = {
1766 let start = Instant::now();
1767 let zero = Duration::new(0, 0);
1768 let parent = self.time_spent_on_dependencies.replace(zero);
1769
1770 #[cfg(feature = "tracing")]
1771 let _span = {
1772 let span = tracing::info_span!(
1774 target: STEP_SPAN_TARGET,
1775 "step",
1778 step_name = pretty_step_name::<S>(),
1779 args = step_debug_args(&step)
1780 );
1781 span.entered()
1782 };
1783
1784 let out = step.clone().run(self);
1785 let dur = start.elapsed();
1786 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1787 (out, dur.saturating_sub(deps))
1788 };
1789
1790 if self.config.print_step_timings && !self.config.dry_run() {
1791 println!(
1792 "[TIMING:end] {} -- {}.{:03}",
1793 pretty_print_step(&step),
1794 dur.as_secs(),
1795 dur.subsec_millis()
1796 );
1797 }
1798
1799 #[cfg(feature = "build-metrics")]
1800 self.metrics.exit_step(self);
1801
1802 {
1803 let mut stack = self.stack.borrow_mut();
1804 let cur_step = stack.pop().expect("step stack empty");
1805 assert_eq!(cur_step.downcast_ref(), Some(&step));
1806 }
1807 self.cache.put(step, out.clone());
1808 out
1809 }
1810
1811 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1815 &'a self,
1816 step: S,
1817 kind: Kind,
1818 ) -> Option<S::Output> {
1819 let desc = StepDescription::from::<S>(kind);
1820 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1821
1822 for pathset in &should_run.paths {
1824 if desc.is_excluded(self, pathset) {
1825 return None;
1826 }
1827 }
1828
1829 if desc.default && should_run.is_really_default() { Some(self.ensure(step)) } else { None }
1831 }
1832
1833 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1835 let desc = StepDescription::from::<S>(kind);
1836 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1837
1838 for path in &self.paths {
1839 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1840 && !desc.is_excluded(
1841 self,
1842 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1843 )
1844 {
1845 return true;
1846 }
1847 }
1848
1849 false
1850 }
1851
1852 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1853 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1854 self.open_in_browser(path);
1855 } else {
1856 self.info(&format!("Doc path: {}", path.as_ref().display()));
1857 }
1858 }
1859
1860 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1861 let path = path.as_ref();
1862
1863 if self.config.dry_run() || !self.config.cmd.open() {
1864 self.info(&format!("Doc path: {}", path.display()));
1865 return;
1866 }
1867
1868 self.info(&format!("Opening doc {}", path.display()));
1869 if let Err(err) = opener::open(path) {
1870 self.info(&format!("{err}\n"));
1871 }
1872 }
1873
1874 pub fn exec_ctx(&self) -> &ExecutionContext {
1875 &self.config.exec_ctx
1876 }
1877}
1878
1879pub fn pretty_step_name<S: Step>() -> String {
1881 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1883 path.into_iter().rev().collect::<Vec<_>>().join("::")
1884}
1885
1886fn step_debug_args<S: Step>(step: &S) -> String {
1888 let step_dbg_repr = format!("{step:?}");
1889
1890 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1892 (Some(brace_start), Some(brace_end)) => {
1893 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1894 }
1895 _ => String::new(),
1896 }
1897}
1898
1899fn pretty_print_step<S: Step>(step: &S) -> String {
1900 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1901}
1902
1903impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1904 fn as_ref(&self) -> &ExecutionContext {
1905 self.exec_ctx()
1906 }
1907}