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