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