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 ONLY_HOSTS: bool = false;
105
106 fn run(self, builder: &Builder<'_>) -> Self::Output;
120
121 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
123
124 fn make_run(_run: RunConfig<'_>) {
128 unimplemented!()
133 }
134
135 fn metadata(&self) -> Option<StepMetadata> {
137 None
138 }
139}
140
141#[allow(unused)]
143#[derive(Debug, PartialEq, Eq)]
144pub struct StepMetadata {
145 name: String,
146 kind: Kind,
147 target: TargetSelection,
148 built_by: Option<Compiler>,
149 stage: Option<u32>,
150 metadata: Option<String>,
152}
153
154impl StepMetadata {
155 pub fn build(name: &str, target: TargetSelection) -> Self {
156 Self::new(name, target, Kind::Build)
157 }
158
159 pub fn check(name: &str, target: TargetSelection) -> Self {
160 Self::new(name, target, Kind::Check)
161 }
162
163 pub fn clippy(name: &str, target: TargetSelection) -> Self {
164 Self::new(name, target, Kind::Clippy)
165 }
166
167 pub fn doc(name: &str, target: TargetSelection) -> Self {
168 Self::new(name, target, Kind::Doc)
169 }
170
171 pub fn dist(name: &str, target: TargetSelection) -> Self {
172 Self::new(name, target, Kind::Dist)
173 }
174
175 pub fn test(name: &str, target: TargetSelection) -> Self {
176 Self::new(name, target, Kind::Test)
177 }
178
179 fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
180 Self { name: name.to_string(), kind, target, built_by: None, stage: None, metadata: None }
181 }
182
183 pub fn built_by(mut self, compiler: Compiler) -> Self {
184 self.built_by = Some(compiler);
185 self
186 }
187
188 pub fn stage(mut self, stage: u32) -> Self {
189 self.stage = Some(stage);
190 self
191 }
192
193 pub fn with_metadata(mut self, metadata: String) -> Self {
194 self.metadata = Some(metadata);
195 self
196 }
197
198 pub fn get_stage(&self) -> Option<u32> {
199 self.stage.or(self
200 .built_by
201 .map(|compiler| if self.name == "std" { compiler.stage } else { compiler.stage + 1 }))
204 }
205
206 pub fn get_name(&self) -> &str {
207 &self.name
208 }
209
210 pub fn get_target(&self) -> TargetSelection {
211 self.target
212 }
213}
214
215pub struct RunConfig<'a> {
216 pub builder: &'a Builder<'a>,
217 pub target: TargetSelection,
218 pub paths: Vec<PathSet>,
219}
220
221impl RunConfig<'_> {
222 pub fn build_triple(&self) -> TargetSelection {
223 self.builder.build.host_target
224 }
225
226 #[track_caller]
228 pub fn cargo_crates_in_set(&self) -> Vec<String> {
229 let mut crates = Vec::new();
230 for krate in &self.paths {
231 let path = &krate.assert_single_path().path;
232
233 let crate_name = self
234 .builder
235 .crate_paths
236 .get(path)
237 .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
238
239 crates.push(crate_name.to_string());
240 }
241 crates
242 }
243
244 pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
251 let has_alias =
252 self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
253 if !has_alias {
254 return self.cargo_crates_in_set();
255 }
256
257 let crates = match alias {
258 Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
259 Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
260 };
261
262 crates.into_iter().map(|krate| krate.name.to_string()).collect()
263 }
264}
265
266#[derive(Debug, Copy, Clone)]
267pub enum Alias {
268 Library,
269 Compiler,
270}
271
272impl Alias {
273 fn as_str(self) -> &'static str {
274 match self {
275 Alias::Library => "library",
276 Alias::Compiler => "compiler",
277 }
278 }
279}
280
281pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
285 if crates.is_empty() {
286 return "".into();
287 }
288
289 let mut descr = String::from(" {");
290 descr.push_str(crates[0].as_ref());
291 for krate in &crates[1..] {
292 descr.push_str(", ");
293 descr.push_str(krate.as_ref());
294 }
295 descr.push('}');
296 descr
297}
298
299struct StepDescription {
300 default: bool,
301 only_hosts: bool,
302 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
303 make_run: fn(RunConfig<'_>),
304 name: &'static str,
305 kind: Kind,
306}
307
308#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
309pub struct TaskPath {
310 pub path: PathBuf,
311 pub kind: Option<Kind>,
312}
313
314impl Debug for TaskPath {
315 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316 if let Some(kind) = &self.kind {
317 write!(f, "{}::", kind.as_str())?;
318 }
319 write!(f, "{}", self.path.display())
320 }
321}
322
323#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
325pub enum PathSet {
326 Set(BTreeSet<TaskPath>),
337 Suite(TaskPath),
344}
345
346impl PathSet {
347 fn empty() -> PathSet {
348 PathSet::Set(BTreeSet::new())
349 }
350
351 fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
352 let mut set = BTreeSet::new();
353 set.insert(TaskPath { path: path.into(), kind: Some(kind) });
354 PathSet::Set(set)
355 }
356
357 fn has(&self, needle: &Path, module: Kind) -> bool {
358 match self {
359 PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
360 PathSet::Suite(suite) => Self::check(suite, needle, module),
361 }
362 }
363
364 fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
366 let check_path = || {
367 p.path.ends_with(needle) || p.path.starts_with(needle)
369 };
370 if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
371 }
372
373 fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
380 let mut check = |p| {
381 let mut result = false;
382 for n in needles.iter_mut() {
383 let matched = Self::check(p, &n.path, module);
384 if matched {
385 n.will_be_executed = true;
386 result = true;
387 }
388 }
389 result
390 };
391 match self {
392 PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
393 PathSet::Suite(suite) => {
394 if check(suite) {
395 self.clone()
396 } else {
397 PathSet::empty()
398 }
399 }
400 }
401 }
402
403 #[track_caller]
407 pub fn assert_single_path(&self) -> &TaskPath {
408 match self {
409 PathSet::Set(set) => {
410 assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
411 set.iter().next().unwrap()
412 }
413 PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
414 }
415 }
416}
417
418const PATH_REMAP: &[(&str, &[&str])] = &[
419 ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
422 (
424 "tests",
425 &[
426 "tests/assembly-llvm",
428 "tests/codegen-llvm",
429 "tests/codegen-units",
430 "tests/coverage",
431 "tests/coverage-run-rustdoc",
432 "tests/crashes",
433 "tests/debuginfo",
434 "tests/incremental",
435 "tests/mir-opt",
436 "tests/pretty",
437 "tests/run-make",
438 "tests/rustdoc",
439 "tests/rustdoc-gui",
440 "tests/rustdoc-js",
441 "tests/rustdoc-js-std",
442 "tests/rustdoc-json",
443 "tests/rustdoc-ui",
444 "tests/ui",
445 "tests/ui-fulldeps",
446 ],
448 ),
449];
450
451fn remap_paths(paths: &mut Vec<PathBuf>) {
452 let mut remove = vec![];
453 let mut add = vec![];
454 for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
455 {
456 for &(search, replace) in PATH_REMAP {
457 if path.trim_matches(std::path::is_separator) == search {
459 remove.push(i);
460 add.extend(replace.iter().map(PathBuf::from));
461 break;
462 }
463 }
464 }
465 remove.sort();
466 remove.dedup();
467 for idx in remove.into_iter().rev() {
468 paths.remove(idx);
469 }
470 paths.append(&mut add);
471}
472
473#[derive(Clone, PartialEq)]
474struct CLIStepPath {
475 path: PathBuf,
476 will_be_executed: bool,
477}
478
479#[cfg(test)]
480impl CLIStepPath {
481 fn will_be_executed(mut self, will_be_executed: bool) -> Self {
482 self.will_be_executed = will_be_executed;
483 self
484 }
485}
486
487impl Debug for CLIStepPath {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 write!(f, "{}", self.path.display())
490 }
491}
492
493impl From<PathBuf> for CLIStepPath {
494 fn from(path: PathBuf) -> Self {
495 Self { path, will_be_executed: false }
496 }
497}
498
499impl StepDescription {
500 fn from<S: Step>(kind: Kind) -> StepDescription {
501 StepDescription {
502 default: S::DEFAULT,
503 only_hosts: S::ONLY_HOSTS,
504 should_run: S::should_run,
505 make_run: S::make_run,
506 name: std::any::type_name::<S>(),
507 kind,
508 }
509 }
510
511 fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
512 pathsets.retain(|set| !self.is_excluded(builder, set));
513
514 if pathsets.is_empty() {
515 return;
516 }
517
518 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
520
521 for target in targets {
522 let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
523 (self.make_run)(run);
524 }
525 }
526
527 fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
528 if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
529 if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
530 println!("Skipping {pathset:?} because it is excluded");
531 }
532 return true;
533 }
534
535 if !builder.config.skip.is_empty()
536 && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
537 {
538 builder.verbose(|| {
539 println!(
540 "{:?} not skipped for {:?} -- not in {:?}",
541 pathset, self.name, builder.config.skip
542 )
543 });
544 }
545 false
546 }
547
548 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
549 let should_runs = v
550 .iter()
551 .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
552 .collect::<Vec<_>>();
553
554 if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
555 {
556 eprintln!(
557 "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
558 builder.kind.as_str()
559 );
560 crate::exit!(1);
561 }
562
563 for (desc, should_run) in v.iter().zip(&should_runs) {
565 assert!(
566 !should_run.paths.is_empty(),
567 "{:?} should have at least one pathset",
568 desc.name
569 );
570 }
571
572 if paths.is_empty() || builder.config.include_default_paths {
573 for (desc, should_run) in v.iter().zip(&should_runs) {
574 if desc.default && should_run.is_really_default() {
575 desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
576 }
577 }
578 }
579
580 let mut paths: Vec<PathBuf> = paths
582 .iter()
583 .map(|p| {
584 if !p.exists() {
586 return p.clone();
587 }
588
589 match std::path::absolute(p) {
591 Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
592 Err(e) => {
593 eprintln!("ERROR: {e:?}");
594 panic!("Due to the above error, failed to resolve path: {p:?}");
595 }
596 }
597 })
598 .collect();
599
600 remap_paths(&mut paths);
601
602 paths.retain(|path| {
605 for (desc, should_run) in v.iter().zip(&should_runs) {
606 if let Some(suite) = should_run.is_suite_path(path) {
607 desc.maybe_run(builder, vec![suite.clone()]);
608 return false;
609 }
610 }
611 true
612 });
613
614 if paths.is_empty() {
615 return;
616 }
617
618 let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
619 let mut path_lookup: Vec<(CLIStepPath, bool)> =
620 paths.clone().into_iter().map(|p| (p, false)).collect();
621
622 let mut steps_to_run = vec![];
626
627 for (desc, should_run) in v.iter().zip(&should_runs) {
628 let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
629
630 let mut closest_index = usize::MAX;
636
637 for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
639 if !*is_used && !paths.contains(path) {
640 closest_index = index;
641 *is_used = true;
642 break;
643 }
644 }
645
646 steps_to_run.push((closest_index, desc, pathsets));
647 }
648
649 steps_to_run.sort_by_key(|(index, _, _)| *index);
651
652 for (_index, desc, pathsets) in steps_to_run {
654 if !pathsets.is_empty() {
655 desc.maybe_run(builder, pathsets);
656 }
657 }
658
659 paths.retain(|p| !p.will_be_executed);
660
661 if !paths.is_empty() {
662 eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
663 eprintln!(
664 "HELP: run `x.py {} --help --verbose` to show a list of available paths",
665 builder.kind.as_str()
666 );
667 eprintln!(
668 "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
669 );
670 crate::exit!(1);
671 }
672 }
673}
674
675enum ReallyDefault<'a> {
676 Bool(bool),
677 Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
678}
679
680pub struct ShouldRun<'a> {
681 pub builder: &'a Builder<'a>,
682 kind: Kind,
683
684 paths: BTreeSet<PathSet>,
686
687 is_really_default: ReallyDefault<'a>,
690}
691
692impl<'a> ShouldRun<'a> {
693 fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
694 ShouldRun {
695 builder,
696 kind,
697 paths: BTreeSet::new(),
698 is_really_default: ReallyDefault::Bool(true), }
700 }
701
702 pub fn default_condition(mut self, cond: bool) -> Self {
703 self.is_really_default = ReallyDefault::Bool(cond);
704 self
705 }
706
707 pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
708 self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
709 self
710 }
711
712 pub fn is_really_default(&self) -> bool {
713 match &self.is_really_default {
714 ReallyDefault::Bool(val) => *val,
715 ReallyDefault::Lazy(lazy) => *lazy.deref(),
716 }
717 }
718
719 pub fn crate_or_deps(self, name: &str) -> Self {
724 let crates = self.builder.in_tree_crates(name, None);
725 self.crates(crates)
726 }
727
728 pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
734 for krate in crates {
735 let path = krate.local_path(self.builder);
736 self.paths.insert(PathSet::one(path, self.kind));
737 }
738 self
739 }
740
741 pub fn alias(mut self, alias: &str) -> Self {
743 assert!(
747 self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
748 "use `builder.path()` for real paths: {alias}"
749 );
750 self.paths.insert(PathSet::Set(
751 std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
752 ));
753 self
754 }
755
756 pub fn path(self, path: &str) -> Self {
760 self.paths(&[path])
761 }
762
763 pub fn paths(mut self, paths: &[&str]) -> Self {
773 let submodules_paths = self.builder.submodule_paths();
774
775 self.paths.insert(PathSet::Set(
776 paths
777 .iter()
778 .map(|p| {
779 if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
781 assert!(
782 self.builder.src.join(p).exists(),
783 "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
784 );
785 }
786
787 TaskPath { path: p.into(), kind: Some(self.kind) }
788 })
789 .collect(),
790 ));
791 self
792 }
793
794 fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
796 self.paths.iter().find(|pathset| match pathset {
797 PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
798 PathSet::Set(_) => false,
799 })
800 }
801
802 pub fn suite_path(mut self, suite: &str) -> Self {
803 self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
804 self
805 }
806
807 pub fn never(mut self) -> ShouldRun<'a> {
809 self.paths.insert(PathSet::empty());
810 self
811 }
812
813 fn pathset_for_paths_removing_matches(
823 &self,
824 paths: &mut [CLIStepPath],
825 kind: Kind,
826 ) -> Vec<PathSet> {
827 let mut sets = vec![];
828 for pathset in &self.paths {
829 let subset = pathset.intersection_removing_matches(paths, kind);
830 if subset != PathSet::empty() {
831 sets.push(subset);
832 }
833 }
834 sets
835 }
836}
837
838#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
839pub enum Kind {
840 #[value(alias = "b")]
841 Build,
842 #[value(alias = "c")]
843 Check,
844 Clippy,
845 Fix,
846 Format,
847 #[value(alias = "t")]
848 Test,
849 Miri,
850 MiriSetup,
851 MiriTest,
852 Bench,
853 #[value(alias = "d")]
854 Doc,
855 Clean,
856 Dist,
857 Install,
858 #[value(alias = "r")]
859 Run,
860 Setup,
861 Vendor,
862 Perf,
863}
864
865impl Kind {
866 pub fn as_str(&self) -> &'static str {
867 match self {
868 Kind::Build => "build",
869 Kind::Check => "check",
870 Kind::Clippy => "clippy",
871 Kind::Fix => "fix",
872 Kind::Format => "fmt",
873 Kind::Test => "test",
874 Kind::Miri => "miri",
875 Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
876 Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
877 Kind::Bench => "bench",
878 Kind::Doc => "doc",
879 Kind::Clean => "clean",
880 Kind::Dist => "dist",
881 Kind::Install => "install",
882 Kind::Run => "run",
883 Kind::Setup => "setup",
884 Kind::Vendor => "vendor",
885 Kind::Perf => "perf",
886 }
887 }
888
889 pub fn description(&self) -> String {
890 match self {
891 Kind::Test => "Testing",
892 Kind::Bench => "Benchmarking",
893 Kind::Doc => "Documenting",
894 Kind::Run => "Running",
895 Kind::Clippy => "Linting",
896 Kind::Perf => "Profiling & benchmarking",
897 _ => {
898 let title_letter = self.as_str()[0..1].to_ascii_uppercase();
899 return format!("{title_letter}{}ing", &self.as_str()[1..]);
900 }
901 }
902 .to_owned()
903 }
904}
905
906#[derive(Debug, Clone, Hash, PartialEq, Eq)]
907struct Libdir {
908 compiler: Compiler,
909 target: TargetSelection,
910}
911
912impl Step for Libdir {
913 type Output = PathBuf;
914
915 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
916 run.never()
917 }
918
919 fn run(self, builder: &Builder<'_>) -> PathBuf {
920 let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
921 let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
922
923 if !builder.config.dry_run() {
924 if !builder.download_rustc() {
927 let sysroot_target_libdir = sysroot.join(self.target).join("lib");
928 builder.verbose(|| {
929 eprintln!(
930 "Removing sysroot {} to avoid caching bugs",
931 sysroot_target_libdir.display()
932 )
933 });
934 let _ = fs::remove_dir_all(&sysroot_target_libdir);
935 t!(fs::create_dir_all(&sysroot_target_libdir));
936 }
937
938 if self.compiler.stage == 0 {
939 dist::maybe_install_llvm_target(
943 builder,
944 self.compiler.host,
945 &builder.sysroot(self.compiler),
946 );
947 }
948 }
949
950 sysroot
951 }
952}
953
954impl<'a> Builder<'a> {
955 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
956 macro_rules! describe {
957 ($($rule:ty),+ $(,)?) => {{
958 vec![$(StepDescription::from::<$rule>(kind)),+]
959 }};
960 }
961 match kind {
962 Kind::Build => describe!(
963 compile::Std,
964 compile::Rustc,
965 compile::Assemble,
966 compile::CraneliftCodegenBackend,
967 compile::GccCodegenBackend,
968 compile::StartupObjects,
969 tool::BuildManifest,
970 tool::Rustbook,
971 tool::ErrorIndex,
972 tool::UnstableBookGen,
973 tool::Tidy,
974 tool::Linkchecker,
975 tool::CargoTest,
976 tool::Compiletest,
977 tool::RemoteTestServer,
978 tool::RemoteTestClient,
979 tool::RustInstaller,
980 tool::FeaturesStatusDump,
981 tool::Cargo,
982 tool::RustAnalyzer,
983 tool::RustAnalyzerProcMacroSrv,
984 tool::Rustdoc,
985 tool::Clippy,
986 tool::CargoClippy,
987 llvm::Llvm,
988 gcc::Gcc,
989 llvm::Sanitizers,
990 tool::Rustfmt,
991 tool::Cargofmt,
992 tool::Miri,
993 tool::CargoMiri,
994 llvm::Lld,
995 llvm::Enzyme,
996 llvm::CrtBeginEnd,
997 tool::RustdocGUITest,
998 tool::OptimizedDist,
999 tool::CoverageDump,
1000 tool::LlvmBitcodeLinker,
1001 tool::RustcPerf,
1002 tool::WasmComponentLd,
1003 tool::LldWrapper
1004 ),
1005 Kind::Clippy => describe!(
1006 clippy::Std,
1007 clippy::Rustc,
1008 clippy::Bootstrap,
1009 clippy::BuildHelper,
1010 clippy::BuildManifest,
1011 clippy::CargoMiri,
1012 clippy::Clippy,
1013 clippy::CodegenGcc,
1014 clippy::CollectLicenseMetadata,
1015 clippy::Compiletest,
1016 clippy::CoverageDump,
1017 clippy::Jsondocck,
1018 clippy::Jsondoclint,
1019 clippy::LintDocs,
1020 clippy::LlvmBitcodeLinker,
1021 clippy::Miri,
1022 clippy::MiroptTestTools,
1023 clippy::OptDist,
1024 clippy::RemoteTestClient,
1025 clippy::RemoteTestServer,
1026 clippy::RustAnalyzer,
1027 clippy::Rustdoc,
1028 clippy::Rustfmt,
1029 clippy::RustInstaller,
1030 clippy::TestFloatParse,
1031 clippy::Tidy,
1032 clippy::CI,
1033 ),
1034 Kind::Check | Kind::Fix => describe!(
1035 check::Rustc,
1036 check::Rustdoc,
1037 check::CodegenBackend,
1038 check::Clippy,
1039 check::Miri,
1040 check::CargoMiri,
1041 check::MiroptTestTools,
1042 check::Rustfmt,
1043 check::RustAnalyzer,
1044 check::TestFloatParse,
1045 check::Bootstrap,
1046 check::RunMakeSupport,
1047 check::Compiletest,
1048 check::FeaturesStatusDump,
1049 check::CoverageDump,
1050 check::Linkchecker,
1051 check::Std,
1058 ),
1059 Kind::Test => describe!(
1060 crate::core::build_steps::toolstate::ToolStateCheck,
1061 test::Tidy,
1062 test::Bootstrap,
1063 test::Ui,
1064 test::Crashes,
1065 test::Coverage,
1066 test::MirOpt,
1067 test::CodegenLlvm,
1068 test::CodegenUnits,
1069 test::AssemblyLlvm,
1070 test::Incremental,
1071 test::Debuginfo,
1072 test::UiFullDeps,
1073 test::Rustdoc,
1074 test::CoverageRunRustdoc,
1075 test::Pretty,
1076 test::CodegenCranelift,
1077 test::CodegenGCC,
1078 test::Crate,
1079 test::CrateLibrustc,
1080 test::CrateRustdoc,
1081 test::CrateRustdocJsonTypes,
1082 test::CrateBootstrap,
1083 test::Linkcheck,
1084 test::TierCheck,
1085 test::Cargotest,
1086 test::Cargo,
1087 test::RustAnalyzer,
1088 test::ErrorIndex,
1089 test::Distcheck,
1090 test::Nomicon,
1091 test::Reference,
1092 test::RustdocBook,
1093 test::RustByExample,
1094 test::TheBook,
1095 test::UnstableBook,
1096 test::RustcBook,
1097 test::LintDocs,
1098 test::EmbeddedBook,
1099 test::EditionGuide,
1100 test::Rustfmt,
1101 test::Miri,
1102 test::CargoMiri,
1103 test::Clippy,
1104 test::CompiletestTest,
1105 test::CrateRunMakeSupport,
1106 test::CrateBuildHelper,
1107 test::RustdocJSStd,
1108 test::RustdocJSNotStd,
1109 test::RustdocGUI,
1110 test::RustdocTheme,
1111 test::RustdocUi,
1112 test::RustdocJson,
1113 test::HtmlCheck,
1114 test::RustInstaller,
1115 test::TestFloatParse,
1116 test::CollectLicenseMetadata,
1117 test::RunMake,
1119 ),
1120 Kind::Miri => describe!(test::Crate),
1121 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1122 Kind::Doc => describe!(
1123 doc::UnstableBook,
1124 doc::UnstableBookGen,
1125 doc::TheBook,
1126 doc::Standalone,
1127 doc::Std,
1128 doc::Rustc,
1129 doc::Rustdoc,
1130 doc::Rustfmt,
1131 doc::ErrorIndex,
1132 doc::Nomicon,
1133 doc::Reference,
1134 doc::RustdocBook,
1135 doc::RustByExample,
1136 doc::RustcBook,
1137 doc::Cargo,
1138 doc::CargoBook,
1139 doc::Clippy,
1140 doc::ClippyBook,
1141 doc::Miri,
1142 doc::EmbeddedBook,
1143 doc::EditionGuide,
1144 doc::StyleGuide,
1145 doc::Tidy,
1146 doc::Bootstrap,
1147 doc::Releases,
1148 doc::RunMakeSupport,
1149 doc::BuildHelper,
1150 doc::Compiletest,
1151 ),
1152 Kind::Dist => describe!(
1153 dist::Docs,
1154 dist::RustcDocs,
1155 dist::JsonDocs,
1156 dist::Mingw,
1157 dist::Rustc,
1158 dist::CraneliftCodegenBackend,
1159 dist::Std,
1160 dist::RustcDev,
1161 dist::Analysis,
1162 dist::Src,
1163 dist::Cargo,
1164 dist::RustAnalyzer,
1165 dist::Rustfmt,
1166 dist::Clippy,
1167 dist::Miri,
1168 dist::LlvmTools,
1169 dist::LlvmBitcodeLinker,
1170 dist::RustDev,
1171 dist::Bootstrap,
1172 dist::Extended,
1173 dist::PlainSourceTarball,
1178 dist::BuildManifest,
1179 dist::ReproducibleArtifacts,
1180 dist::Gcc
1181 ),
1182 Kind::Install => describe!(
1183 install::Docs,
1184 install::Std,
1185 install::Rustc,
1190 install::Cargo,
1191 install::RustAnalyzer,
1192 install::Rustfmt,
1193 install::Clippy,
1194 install::Miri,
1195 install::LlvmTools,
1196 install::Src,
1197 ),
1198 Kind::Run => describe!(
1199 run::BuildManifest,
1200 run::BumpStage0,
1201 run::ReplaceVersionPlaceholder,
1202 run::Miri,
1203 run::CollectLicenseMetadata,
1204 run::GenerateCopyright,
1205 run::GenerateWindowsSys,
1206 run::GenerateCompletions,
1207 run::UnicodeTableGenerator,
1208 run::FeaturesStatusDump,
1209 run::CyclicStep,
1210 run::CoverageDump,
1211 run::Rustfmt,
1212 ),
1213 Kind::Setup => {
1214 describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1215 }
1216 Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1217 Kind::Vendor => describe!(vendor::Vendor),
1218 Kind::Format | Kind::Perf => vec![],
1220 Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1221 }
1222 }
1223
1224 pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1225 let step_descriptions = Builder::get_step_descriptions(kind);
1226 if step_descriptions.is_empty() {
1227 return None;
1228 }
1229
1230 let builder = Self::new_internal(build, kind, vec![]);
1231 let builder = &builder;
1232 let mut should_run = ShouldRun::new(builder, Kind::Build);
1235 for desc in step_descriptions {
1236 should_run.kind = desc.kind;
1237 should_run = (desc.should_run)(should_run);
1238 }
1239 let mut help = String::from("Available paths:\n");
1240 let mut add_path = |path: &Path| {
1241 t!(write!(help, " ./x.py {} {}\n", kind.as_str(), path.display()));
1242 };
1243 for pathset in should_run.paths {
1244 match pathset {
1245 PathSet::Set(set) => {
1246 for path in set {
1247 add_path(&path.path);
1248 }
1249 }
1250 PathSet::Suite(path) => {
1251 add_path(&path.path.join("..."));
1252 }
1253 }
1254 }
1255 Some(help)
1256 }
1257
1258 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1259 Builder {
1260 build,
1261 top_stage: build.config.stage,
1262 kind,
1263 cache: Cache::new(),
1264 stack: RefCell::new(Vec::new()),
1265 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1266 paths,
1267 submodule_paths_cache: Default::default(),
1268 }
1269 }
1270
1271 pub fn new(build: &Build) -> Builder<'_> {
1272 let paths = &build.config.paths;
1273 let (kind, paths) = match build.config.cmd {
1274 Subcommand::Build => (Kind::Build, &paths[..]),
1275 Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1276 Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1277 Subcommand::Fix => (Kind::Fix, &paths[..]),
1278 Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1279 Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1280 Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1281 Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1282 Subcommand::Dist => (Kind::Dist, &paths[..]),
1283 Subcommand::Install => (Kind::Install, &paths[..]),
1284 Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1285 Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1286 Subcommand::Format { .. } => (Kind::Format, &[][..]),
1287 Subcommand::Setup { profile: ref path } => (
1288 Kind::Setup,
1289 path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1290 ),
1291 Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1292 Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1293 };
1294
1295 Self::new_internal(build, kind, paths.to_owned())
1296 }
1297
1298 pub fn execute_cli(&self) {
1299 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1300 }
1301
1302 pub fn default_doc(&self, paths: &[PathBuf]) {
1303 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1304 }
1305
1306 pub fn doc_rust_lang_org_channel(&self) -> String {
1307 let channel = match &*self.config.channel {
1308 "stable" => &self.version,
1309 "beta" => "beta",
1310 "nightly" | "dev" => "nightly",
1311 _ => "stable",
1313 };
1314
1315 format!("https://doc.rust-lang.org/{channel}")
1316 }
1317
1318 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1319 StepDescription::run(v, self, paths);
1320 }
1321
1322 pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1325 !target.triple.ends_with("-windows-gnu")
1326 }
1327
1328 #[cfg_attr(
1333 feature = "tracing",
1334 instrument(
1335 level = "trace",
1336 name = "Builder::compiler",
1337 target = "COMPILER",
1338 skip_all,
1339 fields(
1340 stage = stage,
1341 host = ?host,
1342 ),
1343 ),
1344 )]
1345 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1346 self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1347 }
1348
1349 #[cfg_attr(
1361 feature = "tracing",
1362 instrument(
1363 level = "trace",
1364 name = "Builder::compiler_for",
1365 target = "COMPILER_FOR",
1366 skip_all,
1367 fields(
1368 stage = stage,
1369 host = ?host,
1370 target = ?target,
1371 ),
1372 ),
1373 )]
1374 pub fn compiler_for(
1377 &self,
1378 stage: u32,
1379 host: TargetSelection,
1380 target: TargetSelection,
1381 ) -> Compiler {
1382 let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1383 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1384 self.compiler(2, self.config.host_target)
1385 } else if self.build.force_use_stage1(stage, target) {
1386 trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1387 self.compiler(1, self.config.host_target)
1388 } else {
1389 trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1390 self.compiler(stage, host)
1391 };
1392
1393 if stage != resolved_compiler.stage {
1394 resolved_compiler.forced_compiler(true);
1395 }
1396
1397 trace!(target: "COMPILER_FOR", ?resolved_compiler);
1398 resolved_compiler
1399 }
1400
1401 #[cfg_attr(
1406 feature = "tracing",
1407 instrument(
1408 level = "trace",
1409 name = "Builder::std",
1410 target = "STD",
1411 skip_all,
1412 fields(
1413 compiler = ?compiler,
1414 target = ?target,
1415 ),
1416 ),
1417 )]
1418 pub fn std(&self, compiler: Compiler, target: TargetSelection) {
1419 if compiler.stage == 0 {
1426 if target != compiler.host {
1427 panic!(
1428 r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1429You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1430",
1431 compiler.host
1432 )
1433 }
1434
1435 self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1437 } else {
1438 self.ensure(Std::new(compiler, target));
1441 }
1442 }
1443
1444 pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1445 self.ensure(compile::Sysroot::new(compiler))
1446 }
1447
1448 pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1450 self.ensure(Libdir { compiler, target }).join(target).join("bin")
1451 }
1452
1453 pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1456 self.ensure(Libdir { compiler, target }).join(target).join("lib")
1457 }
1458
1459 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1460 self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1461 }
1462
1463 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1469 if compiler.is_snapshot(self) {
1470 self.rustc_snapshot_libdir()
1471 } else {
1472 match self.config.libdir_relative() {
1473 Some(relative_libdir) if compiler.stage >= 1 => {
1474 self.sysroot(compiler).join(relative_libdir)
1475 }
1476 _ => self.sysroot(compiler).join(libdir(compiler.host)),
1477 }
1478 }
1479 }
1480
1481 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1487 if compiler.is_snapshot(self) {
1488 libdir(self.config.host_target).as_ref()
1489 } else {
1490 match self.config.libdir_relative() {
1491 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1492 _ => libdir(compiler.host).as_ref(),
1493 }
1494 }
1495 }
1496
1497 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1502 match self.config.libdir_relative() {
1503 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1504 _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1505 _ => Path::new("lib"),
1506 }
1507 }
1508
1509 pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1510 let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1511
1512 if self.config.llvm_from_ci {
1514 let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1515 dylib_dirs.push(ci_llvm_lib);
1516 }
1517
1518 dylib_dirs
1519 }
1520
1521 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1524 if cfg!(any(windows, target_os = "cygwin")) {
1528 return;
1529 }
1530
1531 add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1532 }
1533
1534 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1536 if compiler.is_snapshot(self) {
1537 self.initial_rustc.clone()
1538 } else {
1539 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1540 }
1541 }
1542
1543 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1545 fs::read_dir(self.sysroot_codegen_backends(compiler))
1546 .into_iter()
1547 .flatten()
1548 .filter_map(Result::ok)
1549 .map(|entry| entry.path())
1550 }
1551
1552 pub fn rustdoc_for_compiler(&self, target_compiler: Compiler) -> PathBuf {
1556 self.ensure(tool::Rustdoc { target_compiler })
1557 }
1558
1559 pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1560 assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1561
1562 let compilers =
1563 RustcPrivateCompilers::new(self, run_compiler.stage, self.build.host_target);
1564 assert_eq!(run_compiler, compilers.target_compiler());
1565
1566 let miri = self.ensure(tool::Miri::from_compilers(compilers));
1568 let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1569 let mut cmd = command(cargo_miri.tool_path);
1571 cmd.env("MIRI", &miri.tool_path);
1572 cmd.env("CARGO", &self.initial_cargo);
1573 add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1582 cmd
1583 }
1584
1585 pub fn cargo_clippy_cmd(&self, build_compiler: Compiler) -> BootstrapCommand {
1588 if build_compiler.stage == 0 {
1589 let cargo_clippy = self
1590 .config
1591 .initial_cargo_clippy
1592 .clone()
1593 .unwrap_or_else(|| self.build.config.download_clippy());
1594
1595 let mut cmd = command(cargo_clippy);
1596 cmd.env("CARGO", &self.initial_cargo);
1597 return cmd;
1598 }
1599
1600 let compilers = RustcPrivateCompilers::from_target_compiler(self, build_compiler);
1604
1605 let _ = self.ensure(tool::Clippy::from_compilers(compilers));
1606 let cargo_clippy = self.ensure(tool::CargoClippy::from_compilers(compilers));
1607 let mut dylib_path = helpers::dylib_path();
1608 dylib_path.insert(0, self.sysroot(build_compiler).join("lib"));
1609
1610 let mut cmd = command(cargo_clippy.tool_path);
1611 cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1612 cmd.env("CARGO", &self.initial_cargo);
1613 cmd
1614 }
1615
1616 pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1617 let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1618 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1619 .env("RUSTC_SYSROOT", self.sysroot(compiler))
1620 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1623 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1624 .env("RUSTDOC_REAL", self.rustdoc_for_compiler(compiler))
1625 .env("RUSTC_BOOTSTRAP", "1");
1626
1627 cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1628
1629 if self.config.deny_warnings {
1630 cmd.arg("-Dwarnings");
1631 }
1632 cmd.arg("-Znormalize-docs");
1633 cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1634 cmd
1635 }
1636
1637 pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1642 if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1643 let llvm::LlvmResult { llvm_config, .. } = self.ensure(llvm::Llvm { target });
1644 if llvm_config.is_file() {
1645 return Some(llvm_config);
1646 }
1647 }
1648 None
1649 }
1650
1651 pub fn require_and_update_all_submodules(&self) {
1654 for submodule in self.submodule_paths() {
1655 self.require_submodule(submodule, None);
1656 }
1657 }
1658
1659 pub fn submodule_paths(&self) -> &[String] {
1661 self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1662 }
1663
1664 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1668 {
1669 let mut stack = self.stack.borrow_mut();
1670 for stack_step in stack.iter() {
1671 if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1673 continue;
1674 }
1675 let mut out = String::new();
1676 out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1677 for el in stack.iter().rev() {
1678 out += &format!("\t{el:?}\n");
1679 }
1680 panic!("{}", out);
1681 }
1682 if let Some(out) = self.cache.get(&step) {
1683 self.verbose_than(1, || println!("{}c {:?}", " ".repeat(stack.len()), step));
1684
1685 #[cfg(feature = "tracing")]
1686 {
1687 if let Some(parent) = stack.last() {
1688 let mut graph = self.build.step_graph.borrow_mut();
1689 graph.register_cached_step(&step, parent, self.config.dry_run());
1690 }
1691 }
1692 return out;
1693 }
1694 self.verbose_than(1, || println!("{}> {:?}", " ".repeat(stack.len()), step));
1695
1696 #[cfg(feature = "tracing")]
1697 {
1698 let parent = stack.last();
1699 let mut graph = self.build.step_graph.borrow_mut();
1700 graph.register_step_execution(&step, parent, self.config.dry_run());
1701 }
1702
1703 stack.push(Box::new(step.clone()));
1704 }
1705
1706 #[cfg(feature = "build-metrics")]
1707 self.metrics.enter_step(&step, self);
1708
1709 let (out, dur) = {
1710 let start = Instant::now();
1711 let zero = Duration::new(0, 0);
1712 let parent = self.time_spent_on_dependencies.replace(zero);
1713 let out = step.clone().run(self);
1714 let dur = start.elapsed();
1715 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1716 (out, dur.saturating_sub(deps))
1717 };
1718
1719 if self.config.print_step_timings && !self.config.dry_run() {
1720 let step_string = format!("{step:?}");
1721 let brace_index = step_string.find('{').unwrap_or(0);
1722 let type_string = type_name::<S>();
1723 println!(
1724 "[TIMING] {} {} -- {}.{:03}",
1725 &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1726 &step_string[brace_index..],
1727 dur.as_secs(),
1728 dur.subsec_millis()
1729 );
1730 }
1731
1732 #[cfg(feature = "build-metrics")]
1733 self.metrics.exit_step(self);
1734
1735 {
1736 let mut stack = self.stack.borrow_mut();
1737 let cur_step = stack.pop().expect("step stack empty");
1738 assert_eq!(cur_step.downcast_ref(), Some(&step));
1739 }
1740 self.verbose_than(1, || println!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1741 self.cache.put(step, out.clone());
1742 out
1743 }
1744
1745 pub(crate) fn ensure_if_default<T, S: Step<Output = T>>(
1749 &'a self,
1750 step: S,
1751 kind: Kind,
1752 ) -> Option<S::Output> {
1753 let desc = StepDescription::from::<S>(kind);
1754 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1755
1756 for pathset in &should_run.paths {
1758 if desc.is_excluded(self, pathset) {
1759 return None;
1760 }
1761 }
1762
1763 if desc.default && should_run.is_really_default() { Some(self.ensure(step)) } else { None }
1765 }
1766
1767 pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1769 let desc = StepDescription::from::<S>(kind);
1770 let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1771
1772 for path in &self.paths {
1773 if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1774 && !desc.is_excluded(
1775 self,
1776 &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1777 )
1778 {
1779 return true;
1780 }
1781 }
1782
1783 false
1784 }
1785
1786 pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1787 if self.was_invoked_explicitly::<S>(Kind::Doc) {
1788 self.open_in_browser(path);
1789 } else {
1790 self.info(&format!("Doc path: {}", path.as_ref().display()));
1791 }
1792 }
1793
1794 pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1795 let path = path.as_ref();
1796
1797 if self.config.dry_run() || !self.config.cmd.open() {
1798 self.info(&format!("Doc path: {}", path.display()));
1799 return;
1800 }
1801
1802 self.info(&format!("Opening doc {}", path.display()));
1803 if let Err(err) = opener::open(path) {
1804 self.info(&format!("{err}\n"));
1805 }
1806 }
1807
1808 pub fn exec_ctx(&self) -> &ExecutionContext {
1809 &self.config.exec_ctx
1810 }
1811}
1812
1813impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1814 fn as_ref(&self) -> &ExecutionContext {
1815 self.exec_ctx()
1816 }
1817}