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/rustdoc",
448 "tests/rustdoc-gui",
449 "tests/rustdoc-js",
450 "tests/rustdoc-js-std",
451 "tests/rustdoc-json",
452 "tests/rustdoc-ui",
453 "tests/ui",
454 "tests/ui-fulldeps",
455 ],
457 ),
458];
459
460fn remap_paths(paths: &mut Vec<PathBuf>) {
461 let mut remove = vec![];
462 let mut add = vec![];
463 for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
464 {
465 for &(search, replace) in PATH_REMAP {
466 if path.trim_matches(std::path::is_separator) == search {
468 remove.push(i);
469 add.extend(replace.iter().map(PathBuf::from));
470 break;
471 }
472 }
473 }
474 remove.sort();
475 remove.dedup();
476 for idx in remove.into_iter().rev() {
477 paths.remove(idx);
478 }
479 paths.append(&mut add);
480}
481
482#[derive(Clone, PartialEq)]
483struct CLIStepPath {
484 path: PathBuf,
485 will_be_executed: bool,
486}
487
488#[cfg(test)]
489impl CLIStepPath {
490 fn will_be_executed(mut self, will_be_executed: bool) -> Self {
491 self.will_be_executed = will_be_executed;
492 self
493 }
494}
495
496impl Debug for CLIStepPath {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 write!(f, "{}", self.path.display())
499 }
500}
501
502impl From<PathBuf> for CLIStepPath {
503 fn from(path: PathBuf) -> Self {
504 Self { path, will_be_executed: false }
505 }
506}
507
508impl StepDescription {
509 fn from<S: Step>(kind: Kind) -> StepDescription {
510 StepDescription {
511 default: S::DEFAULT,
512 is_host: S::IS_HOST,
513 should_run: S::should_run,
514 make_run: S::make_run,
515 name: std::any::type_name::<S>(),
516 kind,
517 }
518 }
519
520 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
521 pathsets.retain(|set| !self.is_excluded(builder, set));
522
523 if pathsets.is_empty() {
524 return;
525 }
526
527 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
529
530 for target in targets {
531 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
532 (self.make_run)(run);
533 }
534 }
535
536 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
537 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
538 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
539 println!("Skipping {pathset:?} because it is excluded");
540 }
541 return true;
542 }
543
544 if !builder.config.skip.is_empty()
545 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
546 {
547 builder.verbose(|| {
548 println!(
549 "{:?} not skipped for {:?} -- not in {:?}",
550 pathset, self.name, builder.config.skip
551 )
552 });
553 }
554 false
555 }
556
557 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
558 let should_runs = v
559 .iter()
560 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
561 .collect::<Vec<_>>();
562
563 if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
564 {
565 eprintln!(
566 "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
567 builder.kind.as_str()
568 );
569 crate::exit!(1);
570 }
571
572 for (desc, should_run) in v.iter().zip(&should_runs) {
574 assert!(
575 !should_run.paths.is_empty(),
576 "{:?} should have at least one pathset",
577 desc.name
578 );
579 }
580
581 if paths.is_empty() || builder.config.include_default_paths {
582 for (desc, should_run) in v.iter().zip(&should_runs) {
583 if desc.default && should_run.is_really_default() {
584 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
585 }
586 }
587 }
588
589 let mut paths: Vec<PathBuf> = paths
591 .iter()
592 .map(|p| {
593 if !p.exists() {
595 return p.clone();
596 }
597
598 match std::path::absolute(p) {
600 Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
601 Err(e) => {
602 eprintln!("ERROR: {e:?}");
603 panic!("Due to the above error, failed to resolve path: {p:?}");
604 }
605 }
606 })
607 .collect();
608
609 remap_paths(&mut paths);
610
611 paths.retain(|path| {
614 for (desc, should_run) in v.iter().zip(&should_runs) {
615 if let Some(suite) = should_run.is_suite_path(path) {
616 desc.maybe_run(builder, vec![suite.clone()]);
617 return false;
618 }
619 }
620 true
621 });
622
623 if paths.is_empty() {
624 return;
625 }
626
627 let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
628 let mut path_lookup: Vec<(CLIStepPath, bool)> =
629 paths.clone().into_iter().map(|p| (p, false)).collect();
630
631 let mut steps_to_run = vec![];
635
636 for (desc, should_run) in v.iter().zip(&should_runs) {
637 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
638
639 let mut closest_index = usize::MAX;
645
646 for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
648 if !*is_used && !paths.contains(path) {
649 closest_index = index;
650 *is_used = true;
651 break;
652 }
653 }
654
655 steps_to_run.push((closest_index, desc, pathsets));
656 }
657
658 steps_to_run.sort_by_key(|(index, _, _)| *index);
660
661 for (_index, desc, pathsets) in steps_to_run {
663 if !pathsets.is_empty() {
664 desc.maybe_run(builder, pathsets);
665 }
666 }
667
668 paths.retain(|p| !p.will_be_executed);
669
670 if !paths.is_empty() {
671 eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
672 eprintln!(
673 "HELP: run `x.py {} --help --verbose` to show a list of available paths",
674 builder.kind.as_str()
675 );
676 eprintln!(
677 "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
678 );
679 crate::exit!(1);
680 }
681 }
682}
683
684enum ReallyDefault<'a> {
685 Bool(bool),
686 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
687}
688
689pub struct ShouldRun<'a> {
690 pub builder: &'a Builder<'a>,
691 kind: Kind,
692
693 paths: BTreeSet<PathSet>,
695
696 is_really_default: ReallyDefault<'a>,
699}
700
701impl<'a> ShouldRun<'a> {
702 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
703 ShouldRun {
704 builder,
705 kind,
706 paths: BTreeSet::new(),
707 is_really_default: ReallyDefault::Bool(true), }
709 }
710
711 pub fn default_condition(mut self, cond: bool) -> Self {
712 self.is_really_default = ReallyDefault::Bool(cond);
713 self
714 }
715
716 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
717 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
718 self
719 }
720
721 pub fn is_really_default(&self) -> bool {
722 match &self.is_really_default {
723 ReallyDefault::Bool(val) => *val,
724 ReallyDefault::Lazy(lazy) => *lazy.deref(),
725 }
726 }
727
728 pub fn crate_or_deps(self, name: &str) -> Self {
733 let crates = self.builder.in_tree_crates(name, None);
734 self.crates(crates)
735 }
736
737 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
743 for krate in crates {
744 let path = krate.local_path(self.builder);
745 self.paths.insert(PathSet::one(path, self.kind));
746 }
747 self
748 }
749
750 pub fn alias(mut self, alias: &str) -> Self {
752 assert!(
756 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
757 "use `builder.path()` for real paths: {alias}"
758 );
759 self.paths.insert(PathSet::Set(
760 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
761 ));
762 self
763 }
764
765 pub fn path(self, path: &str) -> Self {
769 self.paths(&[path])
770 }
771
772 pub fn paths(mut self, paths: &[&str]) -> Self {
782 let submodules_paths = self.builder.submodule_paths();
783
784 self.paths.insert(PathSet::Set(
785 paths
786 .iter()
787 .map(|p| {
788 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
790 assert!(
791 self.builder.src.join(p).exists(),
792 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
793 );
794 }
795
796 TaskPath { path: p.into(), kind: Some(self.kind) }
797 })
798 .collect(),
799 ));
800 self
801 }
802
803 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
805 self.paths.iter().find(|pathset| match pathset {
806 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
807 PathSet::Set(_) => false,
808 })
809 }
810
811 pub fn suite_path(mut self, suite: &str) -> Self {
812 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
813 self
814 }
815
816 pub fn never(mut self) -> ShouldRun<'a> {
818 self.paths.insert(PathSet::empty());
819 self
820 }
821
822 fn pathset_for_paths_removing_matches(
832 &self,
833 paths: &mut [CLIStepPath],
834 kind: Kind,
835 ) -> Vec<PathSet> {
836 let mut sets = vec![];
837 for pathset in &self.paths {
838 let subset = pathset.intersection_removing_matches(paths, kind);
839 if subset != PathSet::empty() {
840 sets.push(subset);
841 }
842 }
843 sets
844 }
845}
846
847#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
848pub enum Kind {
849 #[value(alias = "b")]
850 Build,
851 #[value(alias = "c")]
852 Check,
853 Clippy,
854 Fix,
855 Format,
856 #[value(alias = "t")]
857 Test,
858 Miri,
859 MiriSetup,
860 MiriTest,
861 Bench,
862 #[value(alias = "d")]
863 Doc,
864 Clean,
865 Dist,
866 Install,
867 #[value(alias = "r")]
868 Run,
869 Setup,
870 Vendor,
871 Perf,
872}
873
874impl Kind {
875 pub fn as_str(&self) -> &'static str {
876 match self {
877 Kind::Build => "build",
878 Kind::Check => "check",
879 Kind::Clippy => "clippy",
880 Kind::Fix => "fix",
881 Kind::Format => "fmt",
882 Kind::Test => "test",
883 Kind::Miri => "miri",
884 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
885 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
886 Kind::Bench => "bench",
887 Kind::Doc => "doc",
888 Kind::Clean => "clean",
889 Kind::Dist => "dist",
890 Kind::Install => "install",
891 Kind::Run => "run",
892 Kind::Setup => "setup",
893 Kind::Vendor => "vendor",
894 Kind::Perf => "perf",
895 }
896 }
897
898 pub fn description(&self) -> String {
899 match self {
900 Kind::Test => "Testing",
901 Kind::Bench => "Benchmarking",
902 Kind::Doc => "Documenting",
903 Kind::Run => "Running",
904 Kind::Clippy => "Linting",
905 Kind::Perf => "Profiling & benchmarking",
906 _ => {
907 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
908 return format!("{title_letter}{}ing", &self.as_str()[1..]);
909 }
910 }
911 .to_owned()
912 }
913}
914
915#[derive(Debug, Clone, Hash, PartialEq, Eq)]
916struct Libdir {
917 compiler: Compiler,
918 target: TargetSelection,
919}
920
921impl Step for Libdir {
922 type Output = PathBuf;
923
924 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
925 run.never()
926 }
927
928 fn run(self, builder: &Builder<'_>) -> PathBuf {
929 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
930 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
931
932 if !builder.config.dry_run() {
933 if !builder.download_rustc() {
936 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
937 builder.verbose(|| {
938 eprintln!(
939 "Removing sysroot {} to avoid caching bugs",
940 sysroot_target_libdir.display()
941 )
942 });
943 let _ = fs::remove_dir_all(&sysroot_target_libdir);
944 t!(fs::create_dir_all(&sysroot_target_libdir));
945 }
946
947 if self.compiler.stage == 0 {
948 dist::maybe_install_llvm_target(
952 builder,
953 self.compiler.host,
954 &builder.sysroot(self.compiler),
955 );
956 }
957 }
958
959 sysroot
960 }
961}
962
963#[cfg(feature = "tracing")]
964pub const STEP_SPAN_TARGET: &str = "STEP";
965
966impl<'a> Builder<'a> {
967 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
968 macro_rules! describe {
969 ($($rule:ty),+ $(,)?) => {{
970 vec![$(StepDescription::from::<$rule>(kind)),+]
971 }};
972 }
973 match kind {
974 Kind::Build => describe!(
975 compile::Std,
976 compile::Rustc,
977 compile::Assemble,
978 compile::CraneliftCodegenBackend,
979 compile::GccCodegenBackend,
980 compile::StartupObjects,
981 tool::BuildManifest,
982 tool::Rustbook,
983 tool::ErrorIndex,
984 tool::UnstableBookGen,
985 tool::Tidy,
986 tool::Linkchecker,
987 tool::CargoTest,
988 tool::Compiletest,
989 tool::RemoteTestServer,
990 tool::RemoteTestClient,
991 tool::RustInstaller,
992 tool::FeaturesStatusDump,
993 tool::Cargo,
994 tool::RustAnalyzer,
995 tool::RustAnalyzerProcMacroSrv,
996 tool::Rustdoc,
997 tool::Clippy,
998 tool::CargoClippy,
999 llvm::Llvm,
1000 gcc::Gcc,
1001 llvm::Sanitizers,
1002 tool::Rustfmt,
1003 tool::Cargofmt,
1004 tool::Miri,
1005 tool::CargoMiri,
1006 llvm::Lld,
1007 llvm::Enzyme,
1008 llvm::CrtBeginEnd,
1009 tool::RustdocGUITest,
1010 tool::OptimizedDist,
1011 tool::CoverageDump,
1012 tool::LlvmBitcodeLinker,
1013 tool::RustcPerf,
1014 tool::WasmComponentLd,
1015 tool::LldWrapper
1016 ),
1017 Kind::Clippy => describe!(
1018 clippy::Std,
1019 clippy::Rustc,
1020 clippy::Bootstrap,
1021 clippy::BuildHelper,
1022 clippy::BuildManifest,
1023 clippy::CargoMiri,
1024 clippy::Clippy,
1025 clippy::CodegenGcc,
1026 clippy::CollectLicenseMetadata,
1027 clippy::Compiletest,
1028 clippy::CoverageDump,
1029 clippy::Jsondocck,
1030 clippy::Jsondoclint,
1031 clippy::LintDocs,
1032 clippy::LlvmBitcodeLinker,
1033 clippy::Miri,
1034 clippy::MiroptTestTools,
1035 clippy::OptDist,
1036 clippy::RemoteTestClient,
1037 clippy::RemoteTestServer,
1038 clippy::RustAnalyzer,
1039 clippy::Rustdoc,
1040 clippy::Rustfmt,
1041 clippy::RustInstaller,
1042 clippy::TestFloatParse,
1043 clippy::Tidy,
1044 clippy::CI,
1045 ),
1046 Kind::Check | Kind::Fix => describe!(
1047 check::Rustc,
1048 check::Rustdoc,
1049 check::CraneliftCodegenBackend,
1050 check::GccCodegenBackend,
1051 check::Clippy,
1052 check::Miri,
1053 check::CargoMiri,
1054 check::MiroptTestTools,
1055 check::Rustfmt,
1056 check::RustAnalyzer,
1057 check::TestFloatParse,
1058 check::Bootstrap,
1059 check::RunMakeSupport,
1060 check::Compiletest,
1061 check::FeaturesStatusDump,
1062 check::CoverageDump,
1063 check::Linkchecker,
1064 check::Std,
1071 ),
1072 Kind::Test => describe!(
1073 crate::core::build_steps::toolstate::ToolStateCheck,
1074 test::Tidy,
1075 test::Bootstrap,
1076 test::Ui,
1077 test::Crashes,
1078 test::Coverage,
1079 test::MirOpt,
1080 test::CodegenLlvm,
1081 test::CodegenUnits,
1082 test::AssemblyLlvm,
1083 test::Incremental,
1084 test::Debuginfo,
1085 test::UiFullDeps,
1086 test::Rustdoc,
1087 test::CoverageRunRustdoc,
1088 test::Pretty,
1089 test::CodegenCranelift,
1090 test::CodegenGCC,
1091 test::Crate,
1092 test::CrateLibrustc,
1093 test::CrateRustdoc,
1094 test::CrateRustdocJsonTypes,
1095 test::CrateBootstrap,
1096 test::Linkcheck,
1097 test::TierCheck,
1098 test::Cargotest,
1099 test::Cargo,
1100 test::RustAnalyzer,
1101 test::ErrorIndex,
1102 test::Distcheck,
1103 test::Nomicon,
1104 test::Reference,
1105 test::RustdocBook,
1106 test::RustByExample,
1107 test::TheBook,
1108 test::UnstableBook,
1109 test::RustcBook,
1110 test::LintDocs,
1111 test::EmbeddedBook,
1112 test::EditionGuide,
1113 test::Rustfmt,
1114 test::Miri,
1115 test::CargoMiri,
1116 test::Clippy,
1117 test::CompiletestTest,
1118 test::CrateRunMakeSupport,
1119 test::CrateBuildHelper,
1120 test::RustdocJSStd,
1121 test::RustdocJSNotStd,
1122 test::RustdocGUI,
1123 test::RustdocTheme,
1124 test::RustdocUi,
1125 test::RustdocJson,
1126 test::HtmlCheck,
1127 test::RustInstaller,
1128 test::TestFloatParse,
1129 test::CollectLicenseMetadata,
1130 test::RunMake,
1132 ),
1133 Kind::Miri => describe!(test::Crate),
1134 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1135 Kind::Doc => describe!(
1136 doc::UnstableBook,
1137 doc::UnstableBookGen,
1138 doc::TheBook,
1139 doc::Standalone,
1140 doc::Std,
1141 doc::Rustc,
1142 doc::Rustdoc,
1143 doc::Rustfmt,
1144 doc::ErrorIndex,
1145 doc::Nomicon,
1146 doc::Reference,
1147 doc::RustdocBook,
1148 doc::RustByExample,
1149 doc::RustcBook,
1150 doc::Cargo,
1151 doc::CargoBook,
1152 doc::Clippy,
1153 doc::ClippyBook,
1154 doc::Miri,
1155 doc::EmbeddedBook,
1156 doc::EditionGuide,
1157 doc::StyleGuide,
1158 doc::Tidy,
1159 doc::Bootstrap,
1160 doc::Releases,
1161 doc::RunMakeSupport,
1162 doc::BuildHelper,
1163 doc::Compiletest,
1164 ),
1165 Kind::Dist => describe!(
1166 dist::Docs,
1167 dist::RustcDocs,
1168 dist::JsonDocs,
1169 dist::Mingw,
1170 dist::Rustc,
1171 dist::CraneliftCodegenBackend,
1172 dist::Std,
1173 dist::RustcDev,
1174 dist::Analysis,
1175 dist::Src,
1176 dist::Cargo,
1177 dist::RustAnalyzer,
1178 dist::Rustfmt,
1179 dist::Clippy,
1180 dist::Miri,
1181 dist::LlvmTools,
1182 dist::LlvmBitcodeLinker,
1183 dist::RustDev,
1184 dist::Bootstrap,
1185 dist::Extended,
1186 dist::PlainSourceTarball,
1191 dist::BuildManifest,
1192 dist::ReproducibleArtifacts,
1193 dist::Gcc
1194 ),
1195 Kind::Install => describe!(
1196 install::Docs,
1197 install::Std,
1198 install::Rustc,
1203 install::Cargo,
1204 install::RustAnalyzer,
1205 install::Rustfmt,
1206 install::Clippy,
1207 install::Miri,
1208 install::LlvmTools,
1209 install::Src,
1210 ),
1211 Kind::Run => describe!(
1212 run::BuildManifest,
1213 run::BumpStage0,
1214 run::ReplaceVersionPlaceholder,
1215 run::Miri,
1216 run::CollectLicenseMetadata,
1217 run::GenerateCopyright,
1218 run::GenerateWindowsSys,
1219 run::GenerateCompletions,
1220 run::UnicodeTableGenerator,
1221 run::FeaturesStatusDump,
1222 run::CyclicStep,
1223 run::CoverageDump,
1224 run::Rustfmt,
1225 ),
1226 Kind::Setup => {
1227 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1228 }
1229 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1230 Kind::Vendor => describe!(vendor::Vendor),
1231 Kind::Format | Kind::Perf => vec![],
1233 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1234 }
1235 }
1236
1237 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1238 let step_descriptions = Builder::get_step_descriptions(kind);
1239 if step_descriptions.is_empty() {
1240 return None;
1241 }
1242
1243 let builder = Self::new_internal(build, kind, vec![]);
1244 let builder = &builder;
1245 let mut should_run = ShouldRun::new(builder, Kind::Build);
1248 for desc in step_descriptions {
1249 should_run.kind = desc.kind;
1250 should_run = (desc.should_run)(should_run);
1251 }
1252 let mut help = String::from("Available paths:\n");
1253 let mut add_path = |path: &Path| {
1254 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1255 };
1256 for pathset in should_run.paths {
1257 match pathset {
1258 PathSet::Set(set) => {
1259 for path in set {
1260 add_path(&path.path);
1261 }
1262 }
1263 PathSet::Suite(path) => {
1264 add_path(&path.path.join("..."));
1265 }
1266 }
1267 }
1268 Some(help)
1269 }
1270
1271 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1272 Builder {
1273 build,
1274 top_stage: build.config.stage,
1275 kind,
1276 cache: Cache::new(),
1277 stack: RefCell::new(Vec::new()),
1278 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1279 paths,
1280 submodule_paths_cache: Default::default(),
1281 }
1282 }
1283
1284 pub fn new(build: &Build) -> Builder<'_> {
1285 let paths = &build.config.paths;
1286 let (kind, paths) = match build.config.cmd {
1287 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1288 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1289 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1290 Subcommand::Fix => (Kind::Fix, &paths[..]),
1291 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1292 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1293 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1294 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1295 Subcommand::Dist => (Kind::Dist, &paths[..]),
1296 Subcommand::Install => (Kind::Install, &paths[..]),
1297 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1298 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1299 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1300 Subcommand::Setup { profile: ref path } => (
1301 Kind::Setup,
1302 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1303 ),
1304 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1305 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1306 };
1307
1308 Self::new_internal(build, kind, paths.to_owned())
1309 }
1310
1311 pub fn execute_cli(&self) {
1312 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1313 }
1314
1315 pub fn run_default_doc_steps(&self) {
1317 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), &[]);
1318 }
1319
1320 pub fn doc_rust_lang_org_channel(&self) -> String {
1321 let channel = match &*self.config.channel {
1322 "stable" => &self.version,
1323 "beta" => "beta",
1324 "nightly" | "dev" => "nightly",
1325 _ => "stable",
1327 };
1328
1329 format!("https://doc.rust-lang.org/{channel}")
1330 }
1331
1332 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1333 StepDescription::run(v, self, paths);
1334 }
1335
1336 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1339 !target.triple.ends_with("-windows-gnu")
1340 }
1341
1342 #[cfg_attr(
1347 feature = "tracing",
1348 instrument(
1349 level = "trace",
1350 name = "Builder::compiler",
1351 target = "COMPILER",
1352 skip_all,
1353 fields(
1354 stage = stage,
1355 host = ?host,
1356 ),
1357 ),
1358 )]
1359 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1360 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1361 }
1362
1363 pub fn compiler_for_std(&self, stage: u32) -> Compiler {
1380 if compile::Std::should_be_uplifted_from_stage_1(self, stage) {
1381 self.compiler(1, self.host_target)
1382 } else {
1383 self.compiler(stage, self.host_target)
1384 }
1385 }
1386
1387 #[cfg_attr(
1399 feature = "tracing",
1400 instrument(
1401 level = "trace",
1402 name = "Builder::compiler_for",
1403 target = "COMPILER_FOR",
1404 skip_all,
1405 fields(
1406 stage = stage,
1407 host = ?host,
1408 target = ?target,
1409 ),
1410 ),
1411 )]
1412 pub fn compiler_for(
1415 &self,
1416 stage: u32,
1417 host: TargetSelection,
1418 target: TargetSelection,
1419 ) -> Compiler {
1420 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1421 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1422 self.compiler(2, self.config.host_target)
1423 } else if self.build.force_use_stage1(stage, target) {
1424 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1425 self.compiler(1, self.config.host_target)
1426 } else {
1427 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1428 self.compiler(stage, host)
1429 };
1430
1431 if stage != resolved_compiler.stage {
1432 resolved_compiler.forced_compiler(true);
1433 }
1434
1435 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1436 resolved_compiler
1437 }
1438
1439 #[cfg_attr(
1446 feature = "tracing",
1447 instrument(
1448 level = "trace",
1449 name = "Builder::std",
1450 target = "STD",
1451 skip_all,
1452 fields(
1453 compiler = ?compiler,
1454 target = ?target,
1455 ),
1456 ),
1457 )]
1458 pub fn std(&self, compiler: Compiler, target: TargetSelection) -> Option<BuildStamp> {
1459 if compiler.stage == 0 {
1469 if target != compiler.host {
1470 if self.local_rebuild {
1471 self.ensure(Std::new(compiler, target))
1472 } else {
1473 panic!(
1474 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1475You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1476Alternatively, you can set `build.local-rebuild=true` and use a stage0 compiler built from in-tree sources.
1477",
1478 compiler.host
1479 )
1480 }
1481 } else {
1482 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1484 None
1485 }
1486 } else {
1487 self.ensure(Std::new(compiler, target))
1490 }
1491 }
1492
1493 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1494 self.ensure(compile::Sysroot::new(compiler))
1495 }
1496
1497 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1499 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1500 }
1501
1502 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1505 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1506 }
1507
1508 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1509 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1510 }
1511
1512 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1518 if compiler.is_snapshot(self) {
1519 self.rustc_snapshot_libdir()
1520 } else {
1521 match self.config.libdir_relative() {
1522 Some(relative_libdir) if compiler.stage >= 1 => {
1523 self.sysroot(compiler).join(relative_libdir)
1524 }
1525 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1526 }
1527 }
1528 }
1529
1530 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1536 if compiler.is_snapshot(self) {
1537 libdir(self.config.host_target).as_ref()
1538 } else {
1539 match self.config.libdir_relative() {
1540 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1541 _ => libdir(compiler.host).as_ref(),
1542 }
1543 }
1544 }
1545
1546 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1551 match self.config.libdir_relative() {
1552 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1553 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1554 _ => Path::new("lib"),
1555 }
1556 }
1557
1558 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1559 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1560
1561 if self.config.llvm_from_ci {
1563 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1564 dylib_dirs.push(ci_llvm_lib);
1565 }
1566
1567 dylib_dirs
1568 }
1569
1570 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1573 if cfg!(any(windows, target_os = "cygwin")) {
1577 return;
1578 }
1579
1580 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1581 }
1582
1583 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1585 if compiler.is_snapshot(self) {
1586 self.initial_rustc.clone()
1587 } else {
1588 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1589 }
1590 }
1591
1592 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1594 fs::read_dir(self.sysroot_codegen_backends(compiler))
1595 .into_iter()
1596 .flatten()
1597 .filter_map(Result::ok)
1598 .map(|entry| entry.path())
1599 }
1600
1601 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1605 self.ensure(tool::Rustdoc { target_compiler })
1606 }
1607
1608 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1609 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1610
1611 let compilers =
1612 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1613 assert_eq!(run_compiler, compilers.target_compiler());
1614
1615 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1617 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1618 let mut cmd = command(cargo_miri.tool_path);
1620 cmd.env("MIRI", &miri.tool_path);
1621 cmd.env("CARGO", &self.initial_cargo);
1622 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1631 cmd
1632 }
1633
1634 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1637 if build_compiler.stage == 0 {
1638 let cargo_clippy = self
1639 .config
1640 .initial_cargo_clippy
1641 .clone()
1642 .unwrap_or_else(|| self.build.config.download_clippy());
1643
1644 let mut cmd = command(cargo_clippy);
1645 cmd.env("CARGO", &self.initial_cargo);
1646 return cmd;
1647 }
1648
1649 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1653
1654 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1655 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1656 let mut dylib_path = helpers::dylib_path();
1657 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1658
1659 let mut cmd = command(cargo_clippy.tool_path);
1660 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1661 cmd.env("CARGO", &self.initial_cargo);
1662 cmd
1663 }
1664
1665 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1666 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1667 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1668 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1669 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1672 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1673 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1674 .env("RUSTC_BOOTSTRAP", "1");
1675
1676 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1677
1678 if self.config.deny_warnings {
1679 cmd.arg("-Dwarnings");
1680 }
1681 cmd.arg("-Znormalize-docs");
1682 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1683 cmd
1684 }
1685
1686 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1695 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1696 let llvm::LlvmResult { host_llvm_config, .. } = self.ensure(llvm::Llvm { target });
1697 if host_llvm_config.is_file() {
1698 return Some(host_llvm_config);
1699 }
1700 }
1701 None
1702 }
1703
1704 pub fn require_and_update_all_submodules(&self) {
1707 for submodule in self.submodule_paths() {
1708 self.require_submodule(submodule, None);
1709 }
1710 }
1711
1712 pub fn submodule_paths(&self) -> &[String] {
1714 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1715 }
1716
1717 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1721 {
1722 let mut stack = self.stack.borrow_mut();
1723 for stack_step in stack.iter() {
1724 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1726 continue;
1727 }
1728 let mut out = String::new();
1729 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1730 for el in stack.iter().rev() {
1731 out += &format!("\t{el:?}\n");
1732 }
1733 panic!("{}", out);
1734 }
1735 if let Some(out) = self.cache.get(&step) {
1736 #[cfg(feature = "tracing")]
1737 {
1738 if let Some(parent) = stack.last() {
1739 let mut graph = self.build.step_graph.borrow_mut();
1740 graph.register_cached_step(&step, parent, self.config.dry_run());
1741 }
1742 }
1743 return out;
1744 }
1745
1746 #[cfg(feature = "tracing")]
1747 {
1748 let parent = stack.last();
1749 let mut graph = self.build.step_graph.borrow_mut();
1750 graph.register_step_execution(&step, parent, self.config.dry_run());
1751 }
1752
1753 stack.push(Box::new(step.clone()));
1754 }
1755
1756 #[cfg(feature = "build-metrics")]
1757 self.metrics.enter_step(&step, self);
1758
1759 if self.config.print_step_timings && !self.config.dry_run() {
1760 println!("[TIMING:start] {}", pretty_print_step(&step));
1761 }
1762
1763 let (out, dur) = {
1764 let start = Instant::now();
1765 let zero = Duration::new(0, 0);
1766 let parent = self.time_spent_on_dependencies.replace(zero);
1767
1768 #[cfg(feature = "tracing")]
1769 let _span = {
1770 let span = tracing::info_span!(
1772 target: STEP_SPAN_TARGET,
1773 "step",
1776 step_name = pretty_step_name::<S>(),
1777 args = step_debug_args(&step)
1778 );
1779 span.entered()
1780 };
1781
1782 let out = step.clone().run(self);
1783 let dur = start.elapsed();
1784 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1785 (out, dur.saturating_sub(deps))
1786 };
1787
1788 if self.config.print_step_timings && !self.config.dry_run() {
1789 println!(
1790 "[TIMING:end] {} -- {}.{:03}",
1791 pretty_print_step(&step),
1792 dur.as_secs(),
1793 dur.subsec_millis()
1794 );
1795 }
1796
1797 #[cfg(feature = "build-metrics")]
1798 self.metrics.exit_step(self);
1799
1800 {
1801 let mut stack = self.stack.borrow_mut();
1802 let cur_step = stack.pop().expect("step stack empty");
1803 assert_eq!(cur_step.downcast_ref(), Some(&step));
1804 }
1805 self.cache.put(step, out.clone());
1806 out
1807 }
1808
1809 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1813 &'a self,
1814 step: S,
1815 kind: Kind,
1816 ) -> Option<S::Output> {
1817 let desc = StepDescription::from::<S>(kind);
1818 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1819
1820 for pathset in &should_run.paths {
1822 if desc.is_excluded(self, pathset) {
1823 return None;
1824 }
1825 }
1826
1827 if desc.default && should_run.is_really_default() { Some(self.ensure(step)) } else { None }
1829 }
1830
1831 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1833 let desc = StepDescription::from::<S>(kind);
1834 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1835
1836 for path in &self.paths {
1837 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1838 && !desc.is_excluded(
1839 self,
1840 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1841 )
1842 {
1843 return true;
1844 }
1845 }
1846
1847 false
1848 }
1849
1850 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1851 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1852 self.open_in_browser(path);
1853 } else {
1854 self.info(&format!("Doc path: {}", path.as_ref().display()));
1855 }
1856 }
1857
1858 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1859 let path = path.as_ref();
1860
1861 if self.config.dry_run() || !self.config.cmd.open() {
1862 self.info(&format!("Doc path: {}", path.display()));
1863 return;
1864 }
1865
1866 self.info(&format!("Opening doc {}", path.display()));
1867 if let Err(err) = opener::open(path) {
1868 self.info(&format!("{err}\n"));
1869 }
1870 }
1871
1872 pub fn exec_ctx(&self) -> &ExecutionContext {
1873 &self.config.exec_ctx
1874 }
1875}
1876
1877pub fn pretty_step_name<S: Step>() -> String {
1879 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1881 path.into_iter().rev().collect::<Vec<_>>().join("::")
1882}
1883
1884fn step_debug_args<S: Step>(step: &S) -> String {
1886 let step_dbg_repr = format!("{step:?}");
1887
1888 match (step_dbg_repr.find('{'), step_dbg_repr.rfind('}')) {
1890 (Some(brace_start), Some(brace_end)) => {
1891 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1892 }
1893 _ => String::new(),
1894 }
1895}
1896
1897fn pretty_print_step<S: Step>(step: &S) -> String {
1898 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1899}
1900
1901impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1902 fn as_ref(&self) -> &ExecutionContext {
1903 self.exec_ctx()
1904 }
1905}