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::cache::Cache;
26use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
27use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
28use crate::{Build, Crate, trace};
29
30mod cargo;
31
32#[cfg(test)]
33mod tests;
34
35pub struct Builder<'a> {
38 pub build: &'a Build,
40
41 pub top_stage: u32,
45
46 pub kind: Kind,
48
49 cache: Cache,
52
53 stack: RefCell<Vec<Box<dyn AnyDebug>>>,
56
57 time_spent_on_dependencies: Cell<Duration>,
59
60 pub paths: Vec<PathBuf>,
64
65 submodule_paths_cache: OnceLock<Vec<String>>,
67}
68
69impl Deref for Builder<'_> {
70 type Target = Build;
71
72 fn deref(&self) -> &Self::Target {
73 self.build
74 }
75}
76
77pub trait AnyDebug: Any + Debug {}
82impl<T: Any + Debug> AnyDebug for T {}
83impl dyn AnyDebug {
84 fn downcast_ref<T: Any>(&self) -> Option<&T> {
86 (self as &dyn Any).downcast_ref()
87 }
88
89 }
91
92pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
93 type Output: Clone;
95
96 const DEFAULT: bool = false;
102
103 const IS_HOST: bool = false;
110
111 fn run(self, builder: &Builder<'_>) -> Self::Output;
125
126 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
128
129 fn make_run(_run: RunConfig<'_>) {
133 unimplemented!()
138 }
139
140 fn metadata(&self) -> Option<StepMetadata> {
142 None
143 }
144}
145
146#[allow(unused)]
148#[derive(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 fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
185 Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
186 }
187
188 pub fn built_by(mut self, compiler: Compiler) -> Self {
189 self.built_by = Some(compiler);
190 self
191 }
192
193 pub fn stage(mut self, stage: u32) -> Self {
194 self.stage = Some(stage);
195 self
196 }
197
198 pub fn with_metadata(mut self, metadata: String) -> Self {
199 self.metadata = Some(metadata);
200 self
201 }
202
203 pub fn get_stage(&self) -> Option<u32> {
204 self.stage.or(self
205 .built_by
206 .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
209 }
210
211 pub fn get_name(&self) -> &str {
212 &self.name
213 }
214
215 pub fn get_target(&self) -> TargetSelection {
216 self.target
217 }
218}
219
220pub struct RunConfig<'a> {
221 pub builder: &'a Builder<'a>,
222 pub target: TargetSelection,
223 pub paths: Vec<PathSet>,
224}
225
226impl RunConfig<'_> {
227 pub fn build_triple(&self) -> TargetSelection {
228 self.builder.build.host_target
229 }
230
231 #[track_caller]
233 pub fn cargo_crates_in_set(&self) -> Vec<String> {
234 let mut crates = Vec::new();
235 for krate in &self.paths {
236 let path = &krate.assert_single_path().path;
237
238 let crate_name = self
239 .builder
240 .crate_paths
241 .get(path)
242 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
243
244 crates.push(crate_name.to_string());
245 }
246 crates
247 }
248
249 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
256 let has_alias =
257 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
258 if !has_alias {
259 return self.cargo_crates_in_set();
260 }
261
262 let crates = match alias {
263 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
264 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
265 };
266
267 crates.into_iter().map(|krate| krate.name.to_string()).collect()
268 }
269}
270
271#[derive(Debug, Copy, Clone)]
272pub enum Alias {
273 Library,
274 Compiler,
275}
276
277impl Alias {
278 fn as_str(self) -> &'static str {
279 match self {
280 Alias::Library => "library",
281 Alias::Compiler => "compiler",
282 }
283 }
284}
285
286pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
290 if crates.is_empty() {
291 return "".into();
292 }
293
294 let mut descr = String::from(" {");
295 descr.push_str(crates[0].as_ref());
296 for krate in &crates[1..] {
297 descr.push_str(", ");
298 descr.push_str(krate.as_ref());
299 }
300 descr.push('}');
301 descr
302}
303
304struct StepDescription {
305 default: bool,
306 is_host: bool,
307 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
308 make_run: fn(RunConfig<'_>),
309 name: &'static str,
310 kind: Kind,
311}
312
313#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
314pub struct TaskPath {
315 pub path: PathBuf,
316 pub kind: Option<Kind>,
317}
318
319impl Debug for TaskPath {
320 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
321 if let Some(kind) = &self.kind {
322 write!(f, "{}::", kind.as_str())?;
323 }
324 write!(f, "{}", self.path.display())
325 }
326}
327
328#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
330pub enum PathSet {
331 Set(BTreeSet<TaskPath>),
342 Suite(TaskPath),
349}
350
351impl PathSet {
352 fn empty() -> PathSet {
353 PathSet::Set(BTreeSet::new())
354 }
355
356 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
357 let mut set = BTreeSet::new();
358 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
359 PathSet::Set(set)
360 }
361
362 fn has(&self, needle: &Path, module: Kind) -> bool {
363 match self {
364 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
365 PathSet::Suite(suite) => Self::check(suite, needle, module),
366 }
367 }
368
369 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
371 let check_path = || {
372 p.path.ends_with(needle) || p.path.starts_with(needle)
374 };
375 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
376 }
377
378 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
385 let mut check = |p| {
386 let mut result = false;
387 for n in needles.iter_mut() {
388 let matched = Self::check(p, &n.path, module);
389 if matched {
390 n.will_be_executed = true;
391 result = true;
392 }
393 }
394 result
395 };
396 match self {
397 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
398 PathSet::Suite(suite) => {
399 if check(suite) {
400 self.clone()
401 } else {
402 PathSet::empty()
403 }
404 }
405 }
406 }
407
408 #[track_caller]
412 pub fn assert_single_path(&self) -> &TaskPath {
413 match self {
414 PathSet::Set(set) => {
415 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
416 set.iter().next().unwrap()
417 }
418 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
419 }
420 }
421}
422
423const PATH_REMAP: &[(&str, &[&str])] = &[
424 ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
427 (
429 "tests",
430 &[
431 "tests/assembly-llvm",
433 "tests/codegen-llvm",
434 "tests/codegen-units",
435 "tests/coverage",
436 "tests/coverage-run-rustdoc",
437 "tests/crashes",
438 "tests/debuginfo",
439 "tests/incremental",
440 "tests/mir-opt",
441 "tests/pretty",
442 "tests/run-make",
443 "tests/rustdoc",
444 "tests/rustdoc-gui",
445 "tests/rustdoc-js",
446 "tests/rustdoc-js-std",
447 "tests/rustdoc-json",
448 "tests/rustdoc-ui",
449 "tests/ui",
450 "tests/ui-fulldeps",
451 ],
453 ),
454];
455
456fn remap_paths(paths: &mut Vec<PathBuf>) {
457 let mut remove = vec![];
458 let mut add = vec![];
459 for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
460 {
461 for &(search, replace) in PATH_REMAP {
462 if path.trim_matches(std::path::is_separator) == search {
464 remove.push(i);
465 add.extend(replace.iter().map(PathBuf::from));
466 break;
467 }
468 }
469 }
470 remove.sort();
471 remove.dedup();
472 for idx in remove.into_iter().rev() {
473 paths.remove(idx);
474 }
475 paths.append(&mut add);
476}
477
478#[derive(Clone, PartialEq)]
479struct CLIStepPath {
480 path: PathBuf,
481 will_be_executed: bool,
482}
483
484#[cfg(test)]
485impl CLIStepPath {
486 fn will_be_executed(mut self, will_be_executed: bool) -> Self {
487 self.will_be_executed = will_be_executed;
488 self
489 }
490}
491
492impl Debug for CLIStepPath {
493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494 write!(f, "{}", self.path.display())
495 }
496}
497
498impl From<PathBuf> for CLIStepPath {
499 fn from(path: PathBuf) -> Self {
500 Self { path, will_be_executed: false }
501 }
502}
503
504impl StepDescription {
505 fn from<S: Step>(kind: Kind) -> StepDescription {
506 StepDescription {
507 default: S::DEFAULT,
508 is_host: S::IS_HOST,
509 should_run: S::should_run,
510 make_run: S::make_run,
511 name: std::any::type_name::<S>(),
512 kind,
513 }
514 }
515
516 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
517 pathsets.retain(|set| !self.is_excluded(builder, set));
518
519 if pathsets.is_empty() {
520 return;
521 }
522
523 let targets = if self.is_host { &builder.hosts } else { &builder.targets };
525
526 for target in targets {
527 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
528 (self.make_run)(run);
529 }
530 }
531
532 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
533 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
534 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
535 println!("Skipping {pathset:?} because it is excluded");
536 }
537 return true;
538 }
539
540 if !builder.config.skip.is_empty()
541 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
542 {
543 builder.verbose(|| {
544 println!(
545 "{:?} not skipped for {:?} -- not in {:?}",
546 pathset, self.name, builder.config.skip
547 )
548 });
549 }
550 false
551 }
552
553 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
554 let should_runs = v
555 .iter()
556 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
557 .collect::<Vec<_>>();
558
559 if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
560 {
561 eprintln!(
562 "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
563 builder.kind.as_str()
564 );
565 crate::exit!(1);
566 }
567
568 for (desc, should_run) in v.iter().zip(&should_runs) {
570 assert!(
571 !should_run.paths.is_empty(),
572 "{:?} should have at least one pathset",
573 desc.name
574 );
575 }
576
577 if paths.is_empty() || builder.config.include_default_paths {
578 for (desc, should_run) in v.iter().zip(&should_runs) {
579 if desc.default && should_run.is_really_default() {
580 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
581 }
582 }
583 }
584
585 let mut paths: Vec<PathBuf> = paths
587 .iter()
588 .map(|p| {
589 if !p.exists() {
591 return p.clone();
592 }
593
594 match std::path::absolute(p) {
596 Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
597 Err(e) => {
598 eprintln!("ERROR: {e:?}");
599 panic!("Due to the above error, failed to resolve path: {p:?}");
600 }
601 }
602 })
603 .collect();
604
605 remap_paths(&mut paths);
606
607 paths.retain(|path| {
610 for (desc, should_run) in v.iter().zip(&should_runs) {
611 if let Some(suite) = should_run.is_suite_path(path) {
612 desc.maybe_run(builder, vec![suite.clone()]);
613 return false;
614 }
615 }
616 true
617 });
618
619 if paths.is_empty() {
620 return;
621 }
622
623 let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
624 let mut path_lookup: Vec<(CLIStepPath, bool)> =
625 paths.clone().into_iter().map(|p| (p, false)).collect();
626
627 let mut steps_to_run = vec![];
631
632 for (desc, should_run) in v.iter().zip(&should_runs) {
633 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
634
635 let mut closest_index = usize::MAX;
641
642 for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
644 if !*is_used && !paths.contains(path) {
645 closest_index = index;
646 *is_used = true;
647 break;
648 }
649 }
650
651 steps_to_run.push((closest_index, desc, pathsets));
652 }
653
654 steps_to_run.sort_by_key(|(index, _, _)| *index);
656
657 for (_index, desc, pathsets) in steps_to_run {
659 if !pathsets.is_empty() {
660 desc.maybe_run(builder, pathsets);
661 }
662 }
663
664 paths.retain(|p| !p.will_be_executed);
665
666 if !paths.is_empty() {
667 eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
668 eprintln!(
669 "HELP: run `x.py {} --help --verbose` to show a list of available paths",
670 builder.kind.as_str()
671 );
672 eprintln!(
673 "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
674 );
675 crate::exit!(1);
676 }
677 }
678}
679
680enum ReallyDefault<'a> {
681 Bool(bool),
682 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
683}
684
685pub struct ShouldRun<'a> {
686 pub builder: &'a Builder<'a>,
687 kind: Kind,
688
689 paths: BTreeSet<PathSet>,
691
692 is_really_default: ReallyDefault<'a>,
695}
696
697impl<'a> ShouldRun<'a> {
698 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
699 ShouldRun {
700 builder,
701 kind,
702 paths: BTreeSet::new(),
703 is_really_default: ReallyDefault::Bool(true), }
705 }
706
707 pub fn default_condition(mut self, cond: bool) -> Self {
708 self.is_really_default = ReallyDefault::Bool(cond);
709 self
710 }
711
712 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
713 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
714 self
715 }
716
717 pub fn is_really_default(&self) -> bool {
718 match &self.is_really_default {
719 ReallyDefault::Bool(val) => *val,
720 ReallyDefault::Lazy(lazy) => *lazy.deref(),
721 }
722 }
723
724 pub fn crate_or_deps(self, name: &str) -> Self {
729 let crates = self.builder.in_tree_crates(name, None);
730 self.crates(crates)
731 }
732
733 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
739 for krate in crates {
740 let path = krate.local_path(self.builder);
741 self.paths.insert(PathSet::one(path, self.kind));
742 }
743 self
744 }
745
746 pub fn alias(mut self, alias: &str) -> Self {
748 assert!(
752 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
753 "use `builder.path()` for real paths: {alias}"
754 );
755 self.paths.insert(PathSet::Set(
756 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
757 ));
758 self
759 }
760
761 pub fn path(self, path: &str) -> Self {
765 self.paths(&[path])
766 }
767
768 pub fn paths(mut self, paths: &[&str]) -> Self {
778 let submodules_paths = self.builder.submodule_paths();
779
780 self.paths.insert(PathSet::Set(
781 paths
782 .iter()
783 .map(|p| {
784 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
786 assert!(
787 self.builder.src.join(p).exists(),
788 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
789 );
790 }
791
792 TaskPath { path: p.into(), kind: Some(self.kind) }
793 })
794 .collect(),
795 ));
796 self
797 }
798
799 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
801 self.paths.iter().find(|pathset| match pathset {
802 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
803 PathSet::Set(_) => false,
804 })
805 }
806
807 pub fn suite_path(mut self, suite: &str) -> Self {
808 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
809 self
810 }
811
812 pub fn never(mut self) -> ShouldRun<'a> {
814 self.paths.insert(PathSet::empty());
815 self
816 }
817
818 fn pathset_for_paths_removing_matches(
828 &self,
829 paths: &mut [CLIStepPath],
830 kind: Kind,
831 ) -> Vec<PathSet> {
832 let mut sets = vec![];
833 for pathset in &self.paths {
834 let subset = pathset.intersection_removing_matches(paths, kind);
835 if subset != PathSet::empty() {
836 sets.push(subset);
837 }
838 }
839 sets
840 }
841}
842
843#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
844pub enum Kind {
845 #[value(alias = "b")]
846 Build,
847 #[value(alias = "c")]
848 Check,
849 Clippy,
850 Fix,
851 Format,
852 #[value(alias = "t")]
853 Test,
854 Miri,
855 MiriSetup,
856 MiriTest,
857 Bench,
858 #[value(alias = "d")]
859 Doc,
860 Clean,
861 Dist,
862 Install,
863 #[value(alias = "r")]
864 Run,
865 Setup,
866 Vendor,
867 Perf,
868}
869
870impl Kind {
871 pub fn as_str(&self) -> &'static str {
872 match self {
873 Kind::Build => "build",
874 Kind::Check => "check",
875 Kind::Clippy => "clippy",
876 Kind::Fix => "fix",
877 Kind::Format => "fmt",
878 Kind::Test => "test",
879 Kind::Miri => "miri",
880 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
881 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
882 Kind::Bench => "bench",
883 Kind::Doc => "doc",
884 Kind::Clean => "clean",
885 Kind::Dist => "dist",
886 Kind::Install => "install",
887 Kind::Run => "run",
888 Kind::Setup => "setup",
889 Kind::Vendor => "vendor",
890 Kind::Perf => "perf",
891 }
892 }
893
894 pub fn description(&self) -> String {
895 match self {
896 Kind::Test => "Testing",
897 Kind::Bench => "Benchmarking",
898 Kind::Doc => "Documenting",
899 Kind::Run => "Running",
900 Kind::Clippy => "Linting",
901 Kind::Perf => "Profiling & benchmarking",
902 _ => {
903 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
904 return format!("{title_letter}{}ing", &self.as_str()[1..]);
905 }
906 }
907 .to_owned()
908 }
909}
910
911#[derive(Debug, Clone, Hash, PartialEq, Eq)]
912struct Libdir {
913 compiler: Compiler,
914 target: TargetSelection,
915}
916
917impl Step for Libdir {
918 type Output = PathBuf;
919
920 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
921 run.never()
922 }
923
924 fn run(self, builder: &Builder<'_>) -> PathBuf {
925 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
926 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
927
928 if !builder.config.dry_run() {
929 if !builder.download_rustc() {
932 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
933 builder.verbose(|| {
934 eprintln!(
935 "Removing sysroot {} to avoid caching bugs",
936 sysroot_target_libdir.display()
937 )
938 });
939 let _ = fs::remove_dir_all(&sysroot_target_libdir);
940 t!(fs::create_dir_all(&sysroot_target_libdir));
941 }
942
943 if self.compiler.stage == 0 {
944 dist::maybe_install_llvm_target(
948 builder,
949 self.compiler.host,
950 &builder.sysroot(self.compiler),
951 );
952 }
953 }
954
955 sysroot
956 }
957}
958
959#[cfg(feature = "tracing")]
960pub const STEP_SPAN_TARGET: &str = "STEP";
961
962impl<'a> Builder<'a> {
963 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
964 macro_rules! describe {
965 ($($rule:ty),+ $(,)?) => {{
966 vec![$(StepDescription::from::<$rule>(kind)),+]
967 }};
968 }
969 match kind {
970 Kind::Build => describe!(
971 compile::Std,
972 compile::Rustc,
973 compile::Assemble,
974 compile::CraneliftCodegenBackend,
975 compile::GccCodegenBackend,
976 compile::StartupObjects,
977 tool::BuildManifest,
978 tool::Rustbook,
979 tool::ErrorIndex,
980 tool::UnstableBookGen,
981 tool::Tidy,
982 tool::Linkchecker,
983 tool::CargoTest,
984 tool::Compiletest,
985 tool::RemoteTestServer,
986 tool::RemoteTestClient,
987 tool::RustInstaller,
988 tool::FeaturesStatusDump,
989 tool::Cargo,
990 tool::RustAnalyzer,
991 tool::RustAnalyzerProcMacroSrv,
992 tool::Rustdoc,
993 tool::Clippy,
994 tool::CargoClippy,
995 llvm::Llvm,
996 gcc::Gcc,
997 llvm::Sanitizers,
998 tool::Rustfmt,
999 tool::Cargofmt,
1000 tool::Miri,
1001 tool::CargoMiri,
1002 llvm::Lld,
1003 llvm::Enzyme,
1004 llvm::CrtBeginEnd,
1005 tool::RustdocGUITest,
1006 tool::OptimizedDist,
1007 tool::CoverageDump,
1008 tool::LlvmBitcodeLinker,
1009 tool::RustcPerf,
1010 tool::WasmComponentLd,
1011 tool::LldWrapper
1012 ),
1013 Kind::Clippy => describe!(
1014 clippy::Std,
1015 clippy::Rustc,
1016 clippy::Bootstrap,
1017 clippy::BuildHelper,
1018 clippy::BuildManifest,
1019 clippy::CargoMiri,
1020 clippy::Clippy,
1021 clippy::CodegenGcc,
1022 clippy::CollectLicenseMetadata,
1023 clippy::Compiletest,
1024 clippy::CoverageDump,
1025 clippy::Jsondocck,
1026 clippy::Jsondoclint,
1027 clippy::LintDocs,
1028 clippy::LlvmBitcodeLinker,
1029 clippy::Miri,
1030 clippy::MiroptTestTools,
1031 clippy::OptDist,
1032 clippy::RemoteTestClient,
1033 clippy::RemoteTestServer,
1034 clippy::RustAnalyzer,
1035 clippy::Rustdoc,
1036 clippy::Rustfmt,
1037 clippy::RustInstaller,
1038 clippy::TestFloatParse,
1039 clippy::Tidy,
1040 clippy::CI,
1041 ),
1042 Kind::Check | Kind::Fix => describe!(
1043 check::Rustc,
1044 check::Rustdoc,
1045 check::CraneliftCodegenBackend,
1046 check::GccCodegenBackend,
1047 check::Clippy,
1048 check::Miri,
1049 check::CargoMiri,
1050 check::MiroptTestTools,
1051 check::Rustfmt,
1052 check::RustAnalyzer,
1053 check::TestFloatParse,
1054 check::Bootstrap,
1055 check::RunMakeSupport,
1056 check::Compiletest,
1057 check::FeaturesStatusDump,
1058 check::CoverageDump,
1059 check::Linkchecker,
1060 check::Std,
1067 ),
1068 Kind::Test => describe!(
1069 crate::core::build_steps::toolstate::ToolStateCheck,
1070 test::Tidy,
1071 test::Bootstrap,
1072 test::Ui,
1073 test::Crashes,
1074 test::Coverage,
1075 test::MirOpt,
1076 test::CodegenLlvm,
1077 test::CodegenUnits,
1078 test::AssemblyLlvm,
1079 test::Incremental,
1080 test::Debuginfo,
1081 test::UiFullDeps,
1082 test::Rustdoc,
1083 test::CoverageRunRustdoc,
1084 test::Pretty,
1085 test::CodegenCranelift,
1086 test::CodegenGCC,
1087 test::Crate,
1088 test::CrateLibrustc,
1089 test::CrateRustdoc,
1090 test::CrateRustdocJsonTypes,
1091 test::CrateBootstrap,
1092 test::Linkcheck,
1093 test::TierCheck,
1094 test::Cargotest,
1095 test::Cargo,
1096 test::RustAnalyzer,
1097 test::ErrorIndex,
1098 test::Distcheck,
1099 test::Nomicon,
1100 test::Reference,
1101 test::RustdocBook,
1102 test::RustByExample,
1103 test::TheBook,
1104 test::UnstableBook,
1105 test::RustcBook,
1106 test::LintDocs,
1107 test::EmbeddedBook,
1108 test::EditionGuide,
1109 test::Rustfmt,
1110 test::Miri,
1111 test::CargoMiri,
1112 test::Clippy,
1113 test::CompiletestTest,
1114 test::CrateRunMakeSupport,
1115 test::CrateBuildHelper,
1116 test::RustdocJSStd,
1117 test::RustdocJSNotStd,
1118 test::RustdocGUI,
1119 test::RustdocTheme,
1120 test::RustdocUi,
1121 test::RustdocJson,
1122 test::HtmlCheck,
1123 test::RustInstaller,
1124 test::TestFloatParse,
1125 test::CollectLicenseMetadata,
1126 test::RunMake,
1128 ),
1129 Kind::Miri => describe!(test::Crate),
1130 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1131 Kind::Doc => describe!(
1132 doc::UnstableBook,
1133 doc::UnstableBookGen,
1134 doc::TheBook,
1135 doc::Standalone,
1136 doc::Std,
1137 doc::Rustc,
1138 doc::Rustdoc,
1139 doc::Rustfmt,
1140 doc::ErrorIndex,
1141 doc::Nomicon,
1142 doc::Reference,
1143 doc::RustdocBook,
1144 doc::RustByExample,
1145 doc::RustcBook,
1146 doc::Cargo,
1147 doc::CargoBook,
1148 doc::Clippy,
1149 doc::ClippyBook,
1150 doc::Miri,
1151 doc::EmbeddedBook,
1152 doc::EditionGuide,
1153 doc::StyleGuide,
1154 doc::Tidy,
1155 doc::Bootstrap,
1156 doc::Releases,
1157 doc::RunMakeSupport,
1158 doc::BuildHelper,
1159 doc::Compiletest,
1160 ),
1161 Kind::Dist => describe!(
1162 dist::Docs,
1163 dist::RustcDocs,
1164 dist::JsonDocs,
1165 dist::Mingw,
1166 dist::Rustc,
1167 dist::CraneliftCodegenBackend,
1168 dist::Std,
1169 dist::RustcDev,
1170 dist::Analysis,
1171 dist::Src,
1172 dist::Cargo,
1173 dist::RustAnalyzer,
1174 dist::Rustfmt,
1175 dist::Clippy,
1176 dist::Miri,
1177 dist::LlvmTools,
1178 dist::LlvmBitcodeLinker,
1179 dist::RustDev,
1180 dist::Bootstrap,
1181 dist::Extended,
1182 dist::PlainSourceTarball,
1187 dist::BuildManifest,
1188 dist::ReproducibleArtifacts,
1189 dist::Gcc
1190 ),
1191 Kind::Install => describe!(
1192 install::Docs,
1193 install::Std,
1194 install::Rustc,
1199 install::Cargo,
1200 install::RustAnalyzer,
1201 install::Rustfmt,
1202 install::Clippy,
1203 install::Miri,
1204 install::LlvmTools,
1205 install::Src,
1206 ),
1207 Kind::Run => describe!(
1208 run::BuildManifest,
1209 run::BumpStage0,
1210 run::ReplaceVersionPlaceholder,
1211 run::Miri,
1212 run::CollectLicenseMetadata,
1213 run::GenerateCopyright,
1214 run::GenerateWindowsSys,
1215 run::GenerateCompletions,
1216 run::UnicodeTableGenerator,
1217 run::FeaturesStatusDump,
1218 run::CyclicStep,
1219 run::CoverageDump,
1220 run::Rustfmt,
1221 ),
1222 Kind::Setup => {
1223 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1224 }
1225 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1226 Kind::Vendor => describe!(vendor::Vendor),
1227 Kind::Format | Kind::Perf => vec![],
1229 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1230 }
1231 }
1232
1233 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1234 let step_descriptions = Builder::get_step_descriptions(kind);
1235 if step_descriptions.is_empty() {
1236 return None;
1237 }
1238
1239 let builder = Self::new_internal(build, kind, vec![]);
1240 let builder = &builder;
1241 let mut should_run = ShouldRun::new(builder, Kind::Build);
1244 for desc in step_descriptions {
1245 should_run.kind = desc.kind;
1246 should_run = (desc.should_run)(should_run);
1247 }
1248 let mut help = String::from("Available paths:\n");
1249 let mut add_path = |path: &Path| {
1250 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1251 };
1252 for pathset in should_run.paths {
1253 match pathset {
1254 PathSet::Set(set) => {
1255 for path in set {
1256 add_path(&path.path);
1257 }
1258 }
1259 PathSet::Suite(path) => {
1260 add_path(&path.path.join("..."));
1261 }
1262 }
1263 }
1264 Some(help)
1265 }
1266
1267 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1268 Builder {
1269 build,
1270 top_stage: build.config.stage,
1271 kind,
1272 cache: Cache::new(),
1273 stack: RefCell::new(Vec::new()),
1274 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1275 paths,
1276 submodule_paths_cache: Default::default(),
1277 }
1278 }
1279
1280 pub fn new(build: &Build) -> Builder<'_> {
1281 let paths = &build.config.paths;
1282 let (kind, paths) = match build.config.cmd {
1283 Subcommand::Build { .. } => (Kind::Build, &paths[..]),
1284 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1285 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1286 Subcommand::Fix => (Kind::Fix, &paths[..]),
1287 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1288 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1289 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1290 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1291 Subcommand::Dist => (Kind::Dist, &paths[..]),
1292 Subcommand::Install => (Kind::Install, &paths[..]),
1293 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1294 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1295 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1296 Subcommand::Setup { profile: ref path } => (
1297 Kind::Setup,
1298 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1299 ),
1300 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1301 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1302 };
1303
1304 Self::new_internal(build, kind, paths.to_owned())
1305 }
1306
1307 pub fn execute_cli(&self) {
1308 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1309 }
1310
1311 pub fn default_doc(&self, paths: &[PathBuf]) {
1312 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1313 }
1314
1315 pub fn doc_rust_lang_org_channel(&self) -> String {
1316 let channel = match &*self.config.channel {
1317 "stable" => &self.version,
1318 "beta" => "beta",
1319 "nightly" | "dev" => "nightly",
1320 _ => "stable",
1322 };
1323
1324 format!("https://doc.rust-lang.org/{channel}")
1325 }
1326
1327 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1328 StepDescription::run(v, self, paths);
1329 }
1330
1331 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1334 !target.triple.ends_with("-windows-gnu")
1335 }
1336
1337 #[cfg_attr(
1342 feature = "tracing",
1343 instrument(
1344 level = "trace",
1345 name = "Builder::compiler",
1346 target = "COMPILER",
1347 skip_all,
1348 fields(
1349 stage = stage,
1350 host = ?host,
1351 ),
1352 ),
1353 )]
1354 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1355 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1356 }
1357
1358 #[cfg_attr(
1370 feature = "tracing",
1371 instrument(
1372 level = "trace",
1373 name = "Builder::compiler_for",
1374 target = "COMPILER_FOR",
1375 skip_all,
1376 fields(
1377 stage = stage,
1378 host = ?host,
1379 target = ?target,
1380 ),
1381 ),
1382 )]
1383 pub fn compiler_for(
1386 &self,
1387 stage: u32,
1388 host: TargetSelection,
1389 target: TargetSelection,
1390 ) -> Compiler {
1391 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1392 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1393 self.compiler(2, self.config.host_target)
1394 } else if self.build.force_use_stage1(stage, target) {
1395 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1396 self.compiler(1, self.config.host_target)
1397 } else {
1398 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1399 self.compiler(stage, host)
1400 };
1401
1402 if stage != resolved_compiler.stage {
1403 resolved_compiler.forced_compiler(true);
1404 }
1405
1406 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1407 resolved_compiler
1408 }
1409
1410 #[cfg_attr(
1415 feature = "tracing",
1416 instrument(
1417 level = "trace",
1418 name = "Builder::std",
1419 target = "STD",
1420 skip_all,
1421 fields(
1422 compiler = ?compiler,
1423 target = ?target,
1424 ),
1425 ),
1426 )]
1427 pub fn std(&self, compiler: Compiler, target: TargetSelection) {
1428 if compiler.stage == 0 {
1435 if target != compiler.host {
1436 panic!(
1437 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1438You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1439",
1440 compiler.host
1441 )
1442 }
1443
1444 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1446 } else {
1447 self.ensure(Std::new(compiler, target));
1450 }
1451 }
1452
1453 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1454 self.ensure(compile::Sysroot::new(compiler))
1455 }
1456
1457 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1459 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1460 }
1461
1462 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1465 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1466 }
1467
1468 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1469 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1470 }
1471
1472 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1478 if compiler.is_snapshot(self) {
1479 self.rustc_snapshot_libdir()
1480 } else {
1481 match self.config.libdir_relative() {
1482 Some(relative_libdir) if compiler.stage >= 1 => {
1483 self.sysroot(compiler).join(relative_libdir)
1484 }
1485 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1486 }
1487 }
1488 }
1489
1490 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1496 if compiler.is_snapshot(self) {
1497 libdir(self.config.host_target).as_ref()
1498 } else {
1499 match self.config.libdir_relative() {
1500 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1501 _ => libdir(compiler.host).as_ref(),
1502 }
1503 }
1504 }
1505
1506 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1511 match self.config.libdir_relative() {
1512 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1513 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1514 _ => Path::new("lib"),
1515 }
1516 }
1517
1518 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1519 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1520
1521 if self.config.llvm_from_ci {
1523 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1524 dylib_dirs.push(ci_llvm_lib);
1525 }
1526
1527 dylib_dirs
1528 }
1529
1530 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1533 if cfg!(any(windows, target_os = "cygwin")) {
1537 return;
1538 }
1539
1540 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1541 }
1542
1543 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1545 if compiler.is_snapshot(self) {
1546 self.initial_rustc.clone()
1547 } else {
1548 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1549 }
1550 }
1551
1552 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1554 fs::read_dir(self.sysroot_codegen_backends(compiler))
1555 .into_iter()
1556 .flatten()
1557 .filter_map(Result::ok)
1558 .map(|entry| entry.path())
1559 }
1560
1561 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1565 self.ensure(tool::Rustdoc { target_compiler })
1566 }
1567
1568 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1569 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1570
1571 let compilers =
1572 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1573 assert_eq!(run_compiler, compilers.target_compiler());
1574
1575 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1577 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1578 let mut cmd = command(cargo_miri.tool_path);
1580 cmd.env("MIRI", &miri.tool_path);
1581 cmd.env("CARGO", &self.initial_cargo);
1582 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1591 cmd
1592 }
1593
1594 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1597 if build_compiler.stage == 0 {
1598 let cargo_clippy = self
1599 .config
1600 .initial_cargo_clippy
1601 .clone()
1602 .unwrap_or_else(|| self.build.config.download_clippy());
1603
1604 let mut cmd = command(cargo_clippy);
1605 cmd.env("CARGO", &self.initial_cargo);
1606 return cmd;
1607 }
1608
1609 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1613
1614 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1615 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1616 let mut dylib_path = helpers::dylib_path();
1617 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1618
1619 let mut cmd = command(cargo_clippy.tool_path);
1620 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1621 cmd.env("CARGO", &self.initial_cargo);
1622 cmd
1623 }
1624
1625 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1626 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1627 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1628 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1629 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1632 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1633 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1634 .env("RUSTC_BOOTSTRAP", "1");
1635
1636 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1637
1638 if self.config.deny_warnings {
1639 cmd.arg("-Dwarnings");
1640 }
1641 cmd.arg("-Znormalize-docs");
1642 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1643 cmd
1644 }
1645
1646 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1651 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1652 let llvm::LlvmResult { llvm_config, .. } = self.ensure(llvm::Llvm { target });
1653 if llvm_config.is_file() {
1654 return Some(llvm_config);
1655 }
1656 }
1657 None
1658 }
1659
1660 pub fn require_and_update_all_submodules(&self) {
1663 for submodule in self.submodule_paths() {
1664 self.require_submodule(submodule, None);
1665 }
1666 }
1667
1668 pub fn submodule_paths(&self) -> &[String] {
1670 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1671 }
1672
1673 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1677 {
1678 let mut stack = self.stack.borrow_mut();
1679 for stack_step in stack.iter() {
1680 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1682 continue;
1683 }
1684 let mut out = String::new();
1685 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1686 for el in stack.iter().rev() {
1687 out += &format!("\t{el:?}\n");
1688 }
1689 panic!("{}", out);
1690 }
1691 if let Some(out) = self.cache.get(&step) {
1692 #[cfg(feature = "tracing")]
1693 {
1694 if let Some(parent) = stack.last() {
1695 let mut graph = self.build.step_graph.borrow_mut();
1696 graph.register_cached_step(&step, parent, self.config.dry_run());
1697 }
1698 }
1699 return out;
1700 }
1701
1702 #[cfg(feature = "tracing")]
1703 {
1704 let parent = stack.last();
1705 let mut graph = self.build.step_graph.borrow_mut();
1706 graph.register_step_execution(&step, parent, self.config.dry_run());
1707 }
1708
1709 stack.push(Box::new(step.clone()));
1710 }
1711
1712 #[cfg(feature = "build-metrics")]
1713 self.metrics.enter_step(&step, self);
1714
1715 if self.config.print_step_timings && !self.config.dry_run() {
1716 println!("[TIMING:start] {}", pretty_print_step(&step));
1717 }
1718
1719 let (out, dur) = {
1720 let start = Instant::now();
1721 let zero = Duration::new(0, 0);
1722 let parent = self.time_spent_on_dependencies.replace(zero);
1723
1724 #[cfg(feature = "tracing")]
1725 let _span = {
1726 let span = tracing::info_span!(
1728 target: STEP_SPAN_TARGET,
1729 "step",
1732 step_name = pretty_step_name::<S>(),
1733 args = step_debug_args(&step)
1734 );
1735 span.entered()
1736 };
1737
1738 let out = step.clone().run(self);
1739 let dur = start.elapsed();
1740 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1741 (out, dur.saturating_sub(deps))
1742 };
1743
1744 if self.config.print_step_timings && !self.config.dry_run() {
1745 println!(
1746 "[TIMING:end] {} -- {}.{:03}",
1747 pretty_print_step(&step),
1748 dur.as_secs(),
1749 dur.subsec_millis()
1750 );
1751 }
1752
1753 #[cfg(feature = "build-metrics")]
1754 self.metrics.exit_step(self);
1755
1756 {
1757 let mut stack = self.stack.borrow_mut();
1758 let cur_step = stack.pop().expect("step stack empty");
1759 assert_eq!(cur_step.downcast_ref(), Some(&step));
1760 }
1761 self.cache.put(step, out.clone());
1762 out
1763 }
1764
1765 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1769 &'a self,
1770 step: S,
1771 kind: Kind,
1772 ) -> Option<S::Output> {
1773 let desc = StepDescription::from::<S>(kind);
1774 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1775
1776 for pathset in &should_run.paths {
1778 if desc.is_excluded(self, pathset) {
1779 return None;
1780 }
1781 }
1782
1783 if desc.default && should_run.is_really_default() { Some(self.ensure(step)) } else { None }
1785 }
1786
1787 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1789 let desc = StepDescription::from::<S>(kind);
1790 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1791
1792 for path in &self.paths {
1793 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1794 && !desc.is_excluded(
1795 self,
1796 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1797 )
1798 {
1799 return true;
1800 }
1801 }
1802
1803 false
1804 }
1805
1806 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1807 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1808 self.open_in_browser(path);
1809 } else {
1810 self.info(&format!("Doc path: {}", path.as_ref().display()));
1811 }
1812 }
1813
1814 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1815 let path = path.as_ref();
1816
1817 if self.config.dry_run() || !self.config.cmd.open() {
1818 self.info(&format!("Doc path: {}", path.display()));
1819 return;
1820 }
1821
1822 self.info(&format!("Opening doc {}", path.display()));
1823 if let Err(err) = opener::open(path) {
1824 self.info(&format!("{err}\n"));
1825 }
1826 }
1827
1828 pub fn exec_ctx(&self) -> &ExecutionContext {
1829 &self.config.exec_ctx
1830 }
1831}
1832
1833pub fn pretty_step_name<S: Step>() -> String {
1835 let path = type_name::<S>().rsplit("::").take(2).collect::<Vec<_>>();
1837 path.into_iter().rev().collect::<Vec<_>>().join("::")
1838}
1839
1840fn step_debug_args<S: Step>(step: &S) -> String {
1842 let step_dbg_repr = format!("{step:?}");
1843 let brace_start = step_dbg_repr.find('{').unwrap_or(0);
1844 let brace_end = step_dbg_repr.rfind('}').unwrap_or(step_dbg_repr.len());
1845 step_dbg_repr[brace_start + 1..brace_end - 1].trim().to_string()
1846}
1847
1848fn pretty_print_step<S: Step>(step: &S) -> String {
1849 format!("{} {{ {} }}", pretty_step_name::<S>(), step_debug_args(step))
1850}
1851
1852impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1853 fn as_ref(&self) -> &ExecutionContext {
1854 self.exec_ctx()
1855 }
1856}