bootstrap/core/builder/
mod.rs

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
35/// Builds and performs different [`Self::kind`]s of stuff and actions, taking
36/// into account build configuration from e.g. bootstrap.toml.
37pub struct Builder<'a> {
38    /// Build configuration from e.g. bootstrap.toml.
39    pub build: &'a Build,
40
41    /// The stage to use. Either implicitly determined based on subcommand, or
42    /// explicitly specified with `--stage N`. Normally this is the stage we
43    /// use, but sometimes we want to run steps with a lower stage than this.
44    pub top_stage: u32,
45
46    /// What to build or what action to perform.
47    pub kind: Kind,
48
49    /// A cache of outputs of [`Step`]s so we can avoid running steps we already
50    /// ran.
51    cache: Cache,
52
53    /// A stack of [`Step`]s to run before we can run this builder. The output
54    /// of steps is cached in [`Self::cache`].
55    stack: RefCell<Vec<Box<dyn AnyDebug>>>,
56
57    /// The total amount of time we spent running [`Step`]s in [`Self::stack`].
58    time_spent_on_dependencies: Cell<Duration>,
59
60    /// The paths passed on the command line. Used by steps to figure out what
61    /// to do. For example: with `./x check foo bar` we get `paths=["foo",
62    /// "bar"]`.
63    pub paths: Vec<PathBuf>,
64
65    /// Cached list of submodules from self.build.src.
66    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
77/// This trait is similar to `Any`, except that it also exposes the underlying
78/// type's [`Debug`] implementation.
79///
80/// (Trying to debug-print `dyn Any` results in the unhelpful `"Any { .. }"`.)
81pub trait AnyDebug: Any + Debug {}
82impl<T: Any + Debug> AnyDebug for T {}
83impl dyn AnyDebug {
84    /// Equivalent to `<dyn Any>::downcast_ref`.
85    fn downcast_ref<T: Any>(&self) -> Option<&T> {
86        (self as &dyn Any).downcast_ref()
87    }
88
89    // Feel free to add other `dyn Any` methods as necessary.
90}
91
92pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
93    /// Result type of `Step::run`.
94    type Output: Clone;
95
96    /// Whether this step is run by default as part of its respective phase, as defined by the `describe`
97    /// macro in [`Builder::get_step_descriptions`].
98    ///
99    /// Note: Even if set to `true`, it can still be overridden with [`ShouldRun::default_condition`]
100    /// by `Step::should_run`.
101    const DEFAULT: bool = false;
102
103    /// If true, then this rule should be skipped if --target was specified, but --host was not
104    const ONLY_HOSTS: bool = false;
105
106    /// Primary function to implement `Step` logic.
107    ///
108    /// This function can be triggered in two ways:
109    /// 1. Directly from [`Builder::execute_cli`].
110    /// 2. Indirectly by being called from other `Step`s using [`Builder::ensure`].
111    ///
112    /// When called with [`Builder::execute_cli`] (as done by `Build::build`), this function is executed twice:
113    /// - First in "dry-run" mode to validate certain things (like cyclic Step invocations,
114    ///   directory creation, etc) super quickly.
115    /// - Then it's called again to run the actual, very expensive process.
116    ///
117    /// When triggered indirectly from other `Step`s, it may still run twice (as dry-run and real mode)
118    /// depending on the `Step::run` implementation of the caller.
119    fn run(self, builder: &Builder<'_>) -> Self::Output;
120
121    /// Determines if this `Step` should be run when given specific paths (e.g., `x build $path`).
122    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
123
124    /// Called directly by the bootstrap `Step` handler when not triggered indirectly by other `Step`s using [`Builder::ensure`].
125    /// For example, `./x.py test bootstrap` runs this for `test::Bootstrap`. Similarly, `./x.py test` runs it for every step
126    /// that is listed by the `describe` macro in [`Builder::get_step_descriptions`].
127    fn make_run(_run: RunConfig<'_>) {
128        // It is reasonable to not have an implementation of make_run for rules
129        // who do not want to get called from the root context. This means that
130        // they are likely dependencies (e.g., sysroot creation) or similar, and
131        // as such calling them from ./x.py isn't logical.
132        unimplemented!()
133    }
134
135    /// Returns metadata of the step, for tests
136    fn metadata(&self) -> Option<StepMetadata> {
137        None
138    }
139}
140
141/// Metadata that describes an executed step, mostly for testing and tracing.
142#[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    /// Additional opaque string printed in the metadata
151    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            // For std, its stage corresponds to the stage of the compiler that builds it.
202            // For everything else, a stage N things gets built by a stage N-1 compiler.
203            .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    /// Return a list of crate names selected by `run.paths`.
227    #[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    /// Given an `alias` selected by the `Step` and the paths passed on the command line,
245    /// return a list of the crates that should be built.
246    ///
247    /// Normally, people will pass *just* `library` if they pass it.
248    /// But it's possible (although strange) to pass something like `library std core`.
249    /// Build all crates anyway, as if they hadn't passed the other args.
250    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
281/// A description of the crates in this set, suitable for passing to `builder.info`.
282///
283/// `crates` should be generated by [`RunConfig::cargo_crates_in_set`].
284pub 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/// Collection of paths used to match a task rule.
324#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
325pub enum PathSet {
326    /// A collection of individual paths or aliases.
327    ///
328    /// These are generally matched as a path suffix. For example, a
329    /// command-line value of `std` will match if `library/std` is in the
330    /// set.
331    ///
332    /// NOTE: the paths within a set should always be aliases of one another.
333    /// For example, `src/librustdoc` and `src/tools/rustdoc` should be in the same set,
334    /// but `library/core` and `library/std` generally should not, unless there's no way (for that Step)
335    /// to build them separately.
336    Set(BTreeSet<TaskPath>),
337    /// A "suite" of paths.
338    ///
339    /// These can match as a path suffix (like `Set`), or as a prefix. For
340    /// example, a command-line value of `tests/ui/abi/variadic-ffi.rs`
341    /// will match `tests/ui`. A command-line value of `ui` would also
342    /// match `tests/ui`.
343    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    // internal use only
365    fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
366        let check_path = || {
367            // This order is important for retro-compatibility, as `starts_with` was introduced later.
368            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    /// Return all `TaskPath`s in `Self` that contain any of the `needles`, removing the
374    /// matched needles.
375    ///
376    /// This is used for `StepDescription::krate`, which passes all matching crates at once to
377    /// `Step::make_run`, rather than calling it many times with a single crate.
378    /// See `tests.rs` for examples.
379    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    /// A convenience wrapper for Steps which know they have no aliases and all their sets contain only a single path.
404    ///
405    /// This can be used with [`ShouldRun::crate_or_deps`], [`ShouldRun::path`], or [`ShouldRun::alias`].
406    #[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    // bootstrap.toml uses `rust-analyzer-proc-macro-srv`, but the
420    // actual path is `proc-macro-srv-cli`
421    ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
422    // Make `x test tests` function the same as `x t tests/*`
423    (
424        "tests",
425        &[
426            // tidy-alphabetical-start
427            "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            // tidy-alphabetical-end
447        ],
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            // Remove leading and trailing slashes so `tests/` and `tests` are equivalent
458            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        // Determine the targets participating in this rule.
519        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        // sanity checks on rules
564        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        // Attempt to resolve paths to be relative to the builder source directory.
581        let mut paths: Vec<PathBuf> = paths
582            .iter()
583            .map(|p| {
584                // If the path does not exist, it may represent the name of a Step, such as `tidy` in `x test tidy`
585                if !p.exists() {
586                    return p.clone();
587                }
588
589                // Make the path absolute, strip the prefix, and convert to a PathBuf.
590                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        // Handle all test suite paths.
603        // (This is separate from the loop below to avoid having to handle multiple paths in `is_suite_path` somehow.)
604        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        // List of `(usize, &StepDescription, Vec<PathSet>)` where `usize` is the closest index of a path
623        // compared to the given CLI paths. So we can respect to the CLI order by using this value to sort
624        // the steps.
625        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            // This value is used for sorting the step execution order.
631            // By default, `usize::MAX` is used as the index for steps to assign them the lowest priority.
632            //
633            // If we resolve the step's path from the given CLI input, this value will be updated with
634            // the step's actual index.
635            let mut closest_index = usize::MAX;
636
637            // Find the closest index from the original list of paths given by the CLI input.
638            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        // Sort the steps before running them to respect the CLI order.
650        steps_to_run.sort_by_key(|(index, _, _)| *index);
651
652        // Handle all PathSets.
653        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    // use a BTreeSet to maintain sort order
685    paths: BTreeSet<PathSet>,
686
687    // If this is a default rule, this is an additional constraint placed on
688    // its run. Generally something like compiler docs being enabled.
689    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), // by default no additional conditions
699        }
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    /// Indicates it should run if the command-line selects the given crate or
720    /// any of its (local) dependencies.
721    ///
722    /// `make_run` will be called a single time with all matching command-line paths.
723    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    /// Indicates it should run if the command-line selects any of the given crates.
729    ///
730    /// `make_run` will be called a single time with all matching command-line paths.
731    ///
732    /// Prefer [`ShouldRun::crate_or_deps`] to this function where possible.
733    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    // single alias, which does not correspond to any on-disk path
742    pub fn alias(mut self, alias: &str) -> Self {
743        // exceptional case for `Kind::Setup` because its `library`
744        // and `compiler` options would otherwise naively match with
745        // `compiler` and `library` folders respectively.
746        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    /// single, non-aliased path
757    ///
758    /// Must be an on-disk path; use `alias` for names that do not correspond to on-disk paths.
759    pub fn path(self, path: &str) -> Self {
760        self.paths(&[path])
761    }
762
763    /// Multiple aliases for the same job.
764    ///
765    /// This differs from [`path`] in that multiple calls to path will end up calling `make_run`
766    /// multiple times, whereas a single call to `paths` will only ever generate a single call to
767    /// `make_run`.
768    ///
769    /// This is analogous to `all_krates`, although `all_krates` is gone now. Prefer [`path`] where possible.
770    ///
771    /// [`path`]: ShouldRun::path
772    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                    // assert only if `p` isn't submodule
780                    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    /// Handles individual files (not directories) within a test suite.
795    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    // allows being more explicit about why should_run in Step returns the value passed to it
808    pub fn never(mut self) -> ShouldRun<'a> {
809        self.paths.insert(PathSet::empty());
810        self
811    }
812
813    /// Given a set of requested paths, return the subset which match the Step for this `ShouldRun`,
814    /// removing the matches from `paths`.
815    ///
816    /// NOTE: this returns multiple PathSets to allow for the possibility of multiple units of work
817    /// within the same step. For example, `test::Crate` allows testing multiple crates in the same
818    /// cargo invocation, which are put into separate sets because they aren't aliases.
819    ///
820    /// The reason we return PathSet instead of PathBuf is to allow for aliases that mean the same thing
821    /// (for now, just `all_krates` and `paths`, but we may want to add an `aliases` function in the future?)
822    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            // Avoid deleting the `rustlib/` directory we just copied (in `impl Step for
925            // Sysroot`).
926            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                // The stage 0 compiler for the build triple is always pre-built. Ensure that
940                // `libLLVM.so` ends up in the target libdir, so that ui-fulldeps tests can use
941                // it when run.
942                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                // This has special staging logic, it may run on stage 1 while others run on stage 0.
1052                // It takes quite some time to build stage 1, so put this at the end.
1053                //
1054                // FIXME: This also helps bootstrap to not interfere with stage 0 builds. We should probably fix
1055                // that issue somewhere else, but we still want to keep `check::Std` at the end so that the
1056                // quicker steps run before this.
1057                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                // Run run-make last, since these won't pass without make on Windows
1118                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                // It seems that PlainSourceTarball somehow changes how some of the tools
1174                // perceive their dependencies (see #93033) which would invalidate fingerprints
1175                // and force us to rebuild tools after vendoring dependencies.
1176                // To work around this, create the Tarball after building all the tools.
1177                dist::PlainSourceTarball,
1178                dist::BuildManifest,
1179                dist::ReproducibleArtifacts,
1180                dist::Gcc
1181            ),
1182            Kind::Install => describe!(
1183                install::Docs,
1184                install::Std,
1185                // During the Rust compiler (rustc) installation process, we copy the entire sysroot binary
1186                // path (build/host/stage2/bin). Since the building tools also make their copy in the sysroot
1187                // binary path, we must install rustc before the tools. Otherwise, the rust-installer will
1188                // install the same binaries twice for each tool, leaving backup files (*.old) as a result.
1189                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            // special-cased in Build::build()
1219            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        // The "build" kind here is just a placeholder, it will be replaced with something else in
1233        // the following statement.
1234        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            // custom build of rustdoc maybe? link to the latest stable docs just in case
1312            _ => "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    /// Returns if `std` should be statically linked into `rustc_driver`.
1323    /// It's currently not done on `windows-gnu` due to linker bugs.
1324    pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1325        !target.triple.ends_with("-windows-gnu")
1326    }
1327
1328    /// Obtain a compiler at a given stage and for a given host (i.e., this is the target that the
1329    /// compiler will run on, *not* the target it will build code for). Explicitly does not take
1330    /// `Compiler` since all `Compiler` instances are meant to be obtained through this function,
1331    /// since it ensures that they are valid (i.e., built and assembled).
1332    #[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    /// Similar to `compiler`, except handles the full-bootstrap option to
1350    /// silently use the stage1 compiler instead of a stage2 compiler if one is
1351    /// requested.
1352    ///
1353    /// Note that this does *not* have the side effect of creating
1354    /// `compiler(stage, host)`, unlike `compiler` above which does have such
1355    /// a side effect. The returned compiler here can only be used to compile
1356    /// new artifacts, it can't be used to rely on the presence of a particular
1357    /// sysroot.
1358    ///
1359    /// See `force_use_stage1` and `force_use_stage2` for documentation on what each argument is.
1360    #[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    /// FIXME: This function is unnecessary (and dangerous, see <https://github.com/rust-lang/rust/issues/137469>).
1375    /// We already have uplifting logic for the compiler, so remove this.
1376    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    /// Obtain a standard library for the given target that will be built by the passed compiler.
1402    /// The standard library will be linked to the sysroot of the passed compiler.
1403    ///
1404    /// Prefer using this method rather than manually invoking `Std::new`.
1405    #[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        // FIXME: make the `Std` step return some type-level "proof" that std was indeed built,
1420        // and then require passing that to all Cargo invocations that we do.
1421
1422        // The "stage 0" std is always precompiled and comes with the stage0 compiler, so we have
1423        // special logic for it, to avoid creating needless and confusing Std steps that don't
1424        // actually build anything.
1425        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            // We still need to link the prebuilt standard library into the ephemeral stage0 sysroot
1436            self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1437        } else {
1438            // This step both compiles the std and links it into the compiler's sysroot.
1439            // Yes, it's quite magical and side-effecty.. would be nice to refactor later.
1440            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    /// Returns the bindir for a compiler's sysroot.
1449    pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1450        self.ensure(Libdir { compiler, target }).join(target).join("bin")
1451    }
1452
1453    /// Returns the libdir where the standard library and other artifacts are
1454    /// found for a compiler's sysroot.
1455    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    /// Returns the compiler's libdir where it stores the dynamic libraries that
1464    /// it itself links against.
1465    ///
1466    /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1467    /// Windows.
1468    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    /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1482    /// it itself links against.
1483    ///
1484    /// For example this returns `lib` on Unix and `bin` on
1485    /// Windows.
1486    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    /// Returns the compiler's relative libdir where the standard library and other artifacts are
1498    /// found for a compiler's sysroot.
1499    ///
1500    /// For example this returns `lib` on Unix and Windows.
1501    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        // Ensure that the downloaded LLVM libraries can be found.
1513        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    /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1522    /// library lookup path.
1523    pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1524        // Windows doesn't need dylib path munging because the dlls for the
1525        // compiler live next to the compiler and the system will find them
1526        // automatically.
1527        if cfg!(any(windows, target_os = "cygwin")) {
1528            return;
1529        }
1530
1531        add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1532    }
1533
1534    /// Gets a path to the compiler specified.
1535    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    /// Gets the paths to all of the compiler's codegen backends.
1544    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    /// Returns a path to `Rustdoc` that "belongs" to the `target_compiler`.
1553    /// It can be either a stage0 rustdoc or a locally built rustdoc that *links* to
1554    /// `target_compiler`.
1555    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        // Prepare the tools
1567        let miri = self.ensure(tool::Miri::from_compilers(compilers));
1568        let cargo_miri = self.ensure(tool::CargoMiri::from_compilers(compilers));
1569        // Invoke cargo-miri, make sure it can find miri and cargo.
1570        let mut cmd = command(cargo_miri.tool_path);
1571        cmd.env("MIRI", &miri.tool_path);
1572        cmd.env("CARGO", &self.initial_cargo);
1573        // Need to add the `run_compiler` libs. Those are the libs produces *by* `build_compiler`
1574        // in `tool::ToolBuild` step, so they match the Miri we just built. However this means they
1575        // are actually living one stage up, i.e. we are running `stage1-tools-bin/miri` with the
1576        // libraries in `stage1/lib`. This is an unfortunate off-by-1 caused (possibly) by the fact
1577        // that Miri doesn't have an "assemble" step like rustc does that would cross the stage boundary.
1578        // We can't use `add_rustc_lib_path` as that's a NOP on Windows but we do need these libraries
1579        // added to the PATH due to the stage mismatch.
1580        // Also see https://github.com/rust-lang/rust/pull/123192#issuecomment-2028901503.
1581        add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1582        cmd
1583    }
1584
1585    /// Create a Cargo command for running Clippy.
1586    /// The used Clippy is (or in the case of stage 0, already was) built using `build_compiler`.
1587    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        // If we're linting something with build_compiler stage N, we want to build Clippy stage N
1601        // and use that to lint it. That is why we use the `build_compiler` as the target compiler
1602        // for RustcPrivateCompilers. We will use build compiler stage N-1 to build Clippy stage N.
1603        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            // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1621            // equivalently to rustc.
1622            .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    /// Return the path to `llvm-config` for the target, if it exists.
1638    ///
1639    /// Note that this returns `None` if LLVM is disabled, or if we're in a
1640    /// check build or dry-run, where there's no need to build all of LLVM.
1641    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    /// Updates all submodules, and exits with an error if submodule
1652    /// management is disabled and the submodule does not exist.
1653    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    /// Get all submodules from the src directory.
1660    pub fn submodule_paths(&self) -> &[String] {
1661        self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1662    }
1663
1664    /// Ensure that a given step is built, returning its output. This will
1665    /// cache the step, so it is safe (and good!) to call this as often as
1666    /// needed to ensure that all dependencies are built.
1667    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                // should skip
1672                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    /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1746    /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1747    /// needed to ensure that all dependencies are build.
1748    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        // Avoid running steps contained in --skip
1757        for pathset in &should_run.paths {
1758            if desc.is_excluded(self, pathset) {
1759                return None;
1760            }
1761        }
1762
1763        // Only execute if it's supposed to run as default
1764        if desc.default && should_run.is_really_default() { Some(self.ensure(step)) } else { None }
1765    }
1766
1767    /// Checks if any of the "should_run" paths is in the `Builder` paths.
1768    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}