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::{
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
34/// Builds and performs different [`Self::kind`]s of stuff and actions, taking
35/// into account build configuration from e.g. bootstrap.toml.
36pub struct Builder<'a> {
37    /// Build configuration from e.g. bootstrap.toml.
38    pub build: &'a Build,
39
40    /// The stage to use. Either implicitly determined based on subcommand, or
41    /// explicitly specified with `--stage N`. Normally this is the stage we
42    /// use, but sometimes we want to run steps with a lower stage than this.
43    pub top_stage: u32,
44
45    /// What to build or what action to perform.
46    pub kind: Kind,
47
48    /// A cache of outputs of [`Step`]s so we can avoid running steps we already
49    /// ran.
50    cache: Cache,
51
52    /// A stack of [`Step`]s to run before we can run this builder. The output
53    /// of steps is cached in [`Self::cache`].
54    stack: RefCell<Vec<Box<dyn AnyDebug>>>,
55
56    /// The total amount of time we spent running [`Step`]s in [`Self::stack`].
57    time_spent_on_dependencies: Cell<Duration>,
58
59    /// The paths passed on the command line. Used by steps to figure out what
60    /// to do. For example: with `./x check foo bar` we get `paths=["foo",
61    /// "bar"]`.
62    pub paths: Vec<PathBuf>,
63
64    /// Cached list of submodules from self.build.src.
65    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
76/// This trait is similar to `Any`, except that it also exposes the underlying
77/// type's [`Debug`] implementation.
78///
79/// (Trying to debug-print `dyn Any` results in the unhelpful `"Any { .. }"`.)
80trait AnyDebug: Any + Debug {}
81impl<T: Any + Debug> AnyDebug for T {}
82impl dyn AnyDebug {
83    /// Equivalent to `<dyn Any>::downcast_ref`.
84    fn downcast_ref<T: Any>(&self) -> Option<&T> {
85        (self as &dyn Any).downcast_ref()
86    }
87
88    // Feel free to add other `dyn Any` methods as necessary.
89}
90
91pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
92    /// Result type of `Step::run`.
93    type Output: Clone;
94
95    /// Whether this step is run by default as part of its respective phase, as defined by the `describe`
96    /// macro in [`Builder::get_step_descriptions`].
97    ///
98    /// Note: Even if set to `true`, it can still be overridden with [`ShouldRun::default_condition`]
99    /// by `Step::should_run`.
100    const DEFAULT: bool = false;
101
102    /// If true, then this rule should be skipped if --target was specified, but --host was not
103    const ONLY_HOSTS: bool = false;
104
105    /// Primary function to implement `Step` logic.
106    ///
107    /// This function can be triggered in two ways:
108    /// 1. Directly from [`Builder::execute_cli`].
109    /// 2. Indirectly by being called from other `Step`s using [`Builder::ensure`].
110    ///
111    /// When called with [`Builder::execute_cli`] (as done by `Build::build`), this function is executed twice:
112    /// - First in "dry-run" mode to validate certain things (like cyclic Step invocations,
113    ///   directory creation, etc) super quickly.
114    /// - Then it's called again to run the actual, very expensive process.
115    ///
116    /// When triggered indirectly from other `Step`s, it may still run twice (as dry-run and real mode)
117    /// depending on the `Step::run` implementation of the caller.
118    fn run(self, builder: &Builder<'_>) -> Self::Output;
119
120    /// Determines if this `Step` should be run when given specific paths (e.g., `x build $path`).
121    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
122
123    /// Called directly by the bootstrap `Step` handler when not triggered indirectly by other `Step`s using [`Builder::ensure`].
124    /// For example, `./x.py test bootstrap` runs this for `test::Bootstrap`. Similarly, `./x.py test` runs it for every step
125    /// that is listed by the `describe` macro in [`Builder::get_step_descriptions`].
126    fn make_run(_run: RunConfig<'_>) {
127        // It is reasonable to not have an implementation of make_run for rules
128        // who do not want to get called from the root context. This means that
129        // they are likely dependencies (e.g., sysroot creation) or similar, and
130        // as such calling them from ./x.py isn't logical.
131        unimplemented!()
132    }
133
134    /// Returns metadata of the step, for tests
135    fn metadata(&self) -> Option<StepMetadata> {
136        None
137    }
138}
139
140/// Metadata that describes an executed step, mostly for testing and tracing.
141#[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 doc(name: &'static str, target: TargetSelection) -> Self {
157        Self::new(name, target, Kind::Doc)
158    }
159
160    pub fn dist(name: &'static str, target: TargetSelection) -> Self {
161        Self::new(name, target, Kind::Dist)
162    }
163
164    pub fn test(name: &'static str, target: TargetSelection) -> Self {
165        Self::new(name, target, Kind::Test)
166    }
167
168    fn new(name: &'static str, target: TargetSelection, kind: Kind) -> Self {
169        Self { name, kind, target, built_by: None, stage: None }
170    }
171
172    pub fn built_by(mut self, compiler: Compiler) -> Self {
173        self.built_by = Some(compiler);
174        self
175    }
176
177    pub fn stage(mut self, stage: u32) -> Self {
178        self.stage = Some(stage);
179        self
180    }
181}
182
183pub struct RunConfig<'a> {
184    pub builder: &'a Builder<'a>,
185    pub target: TargetSelection,
186    pub paths: Vec<PathSet>,
187}
188
189impl RunConfig<'_> {
190    pub fn build_triple(&self) -> TargetSelection {
191        self.builder.build.host_target
192    }
193
194    /// Return a list of crate names selected by `run.paths`.
195    #[track_caller]
196    pub fn cargo_crates_in_set(&self) -> Vec<String> {
197        let mut crates = Vec::new();
198        for krate in &self.paths {
199            let path = &krate.assert_single_path().path;
200
201            let crate_name = self
202                .builder
203                .crate_paths
204                .get(path)
205                .unwrap_or_else(|| panic!("missing crate for path {}", path.display()));
206
207            crates.push(crate_name.to_string());
208        }
209        crates
210    }
211
212    /// Given an `alias` selected by the `Step` and the paths passed on the command line,
213    /// return a list of the crates that should be built.
214    ///
215    /// Normally, people will pass *just* `library` if they pass it.
216    /// But it's possible (although strange) to pass something like `library std core`.
217    /// Build all crates anyway, as if they hadn't passed the other args.
218    pub fn make_run_crates(&self, alias: Alias) -> Vec<String> {
219        let has_alias =
220            self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str()));
221        if !has_alias {
222            return self.cargo_crates_in_set();
223        }
224
225        let crates = match alias {
226            Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)),
227            Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)),
228        };
229
230        crates.into_iter().map(|krate| krate.name.to_string()).collect()
231    }
232}
233
234#[derive(Debug, Copy, Clone)]
235pub enum Alias {
236    Library,
237    Compiler,
238}
239
240impl Alias {
241    fn as_str(self) -> &'static str {
242        match self {
243            Alias::Library => "library",
244            Alias::Compiler => "compiler",
245        }
246    }
247}
248
249/// A description of the crates in this set, suitable for passing to `builder.info`.
250///
251/// `crates` should be generated by [`RunConfig::cargo_crates_in_set`].
252pub fn crate_description(crates: &[impl AsRef<str>]) -> String {
253    if crates.is_empty() {
254        return "".into();
255    }
256
257    let mut descr = String::from(" {");
258    descr.push_str(crates[0].as_ref());
259    for krate in &crates[1..] {
260        descr.push_str(", ");
261        descr.push_str(krate.as_ref());
262    }
263    descr.push('}');
264    descr
265}
266
267struct StepDescription {
268    default: bool,
269    only_hosts: bool,
270    should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
271    make_run: fn(RunConfig<'_>),
272    name: &'static str,
273    kind: Kind,
274}
275
276#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
277pub struct TaskPath {
278    pub path: PathBuf,
279    pub kind: Option<Kind>,
280}
281
282impl Debug for TaskPath {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        if let Some(kind) = &self.kind {
285            write!(f, "{}::", kind.as_str())?;
286        }
287        write!(f, "{}", self.path.display())
288    }
289}
290
291/// Collection of paths used to match a task rule.
292#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
293pub enum PathSet {
294    /// A collection of individual paths or aliases.
295    ///
296    /// These are generally matched as a path suffix. For example, a
297    /// command-line value of `std` will match if `library/std` is in the
298    /// set.
299    ///
300    /// NOTE: the paths within a set should always be aliases of one another.
301    /// For example, `src/librustdoc` and `src/tools/rustdoc` should be in the same set,
302    /// but `library/core` and `library/std` generally should not, unless there's no way (for that Step)
303    /// to build them separately.
304    Set(BTreeSet<TaskPath>),
305    /// A "suite" of paths.
306    ///
307    /// These can match as a path suffix (like `Set`), or as a prefix. For
308    /// example, a command-line value of `tests/ui/abi/variadic-ffi.rs`
309    /// will match `tests/ui`. A command-line value of `ui` would also
310    /// match `tests/ui`.
311    Suite(TaskPath),
312}
313
314impl PathSet {
315    fn empty() -> PathSet {
316        PathSet::Set(BTreeSet::new())
317    }
318
319    fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
320        let mut set = BTreeSet::new();
321        set.insert(TaskPath { path: path.into(), kind: Some(kind) });
322        PathSet::Set(set)
323    }
324
325    fn has(&self, needle: &Path, module: Kind) -> bool {
326        match self {
327            PathSet::Set(set) => set.iter().any(|p| Self::check(p, needle, module)),
328            PathSet::Suite(suite) => Self::check(suite, needle, module),
329        }
330    }
331
332    // internal use only
333    fn check(p: &TaskPath, needle: &Path, module: Kind) -> bool {
334        let check_path = || {
335            // This order is important for retro-compatibility, as `starts_with` was introduced later.
336            p.path.ends_with(needle) || p.path.starts_with(needle)
337        };
338        if let Some(p_kind) = &p.kind { check_path() && *p_kind == module } else { check_path() }
339    }
340
341    /// Return all `TaskPath`s in `Self` that contain any of the `needles`, removing the
342    /// matched needles.
343    ///
344    /// This is used for `StepDescription::krate`, which passes all matching crates at once to
345    /// `Step::make_run`, rather than calling it many times with a single crate.
346    /// See `tests.rs` for examples.
347    fn intersection_removing_matches(&self, needles: &mut [CLIStepPath], module: Kind) -> PathSet {
348        let mut check = |p| {
349            let mut result = false;
350            for n in needles.iter_mut() {
351                let matched = Self::check(p, &n.path, module);
352                if matched {
353                    n.will_be_executed = true;
354                    result = true;
355                }
356            }
357            result
358        };
359        match self {
360            PathSet::Set(set) => PathSet::Set(set.iter().filter(|&p| check(p)).cloned().collect()),
361            PathSet::Suite(suite) => {
362                if check(suite) {
363                    self.clone()
364                } else {
365                    PathSet::empty()
366                }
367            }
368        }
369    }
370
371    /// A convenience wrapper for Steps which know they have no aliases and all their sets contain only a single path.
372    ///
373    /// This can be used with [`ShouldRun::crate_or_deps`], [`ShouldRun::path`], or [`ShouldRun::alias`].
374    #[track_caller]
375    pub fn assert_single_path(&self) -> &TaskPath {
376        match self {
377            PathSet::Set(set) => {
378                assert_eq!(set.len(), 1, "called assert_single_path on multiple paths");
379                set.iter().next().unwrap()
380            }
381            PathSet::Suite(_) => unreachable!("called assert_single_path on a Suite path"),
382        }
383    }
384}
385
386const PATH_REMAP: &[(&str, &[&str])] = &[
387    // bootstrap.toml uses `rust-analyzer-proc-macro-srv`, but the
388    // actual path is `proc-macro-srv-cli`
389    ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]),
390    // Make `x test tests` function the same as `x t tests/*`
391    (
392        "tests",
393        &[
394            // tidy-alphabetical-start
395            "tests/assembly",
396            "tests/codegen",
397            "tests/codegen-units",
398            "tests/coverage",
399            "tests/coverage-run-rustdoc",
400            "tests/crashes",
401            "tests/debuginfo",
402            "tests/incremental",
403            "tests/mir-opt",
404            "tests/pretty",
405            "tests/run-make",
406            "tests/rustdoc",
407            "tests/rustdoc-gui",
408            "tests/rustdoc-js",
409            "tests/rustdoc-js-std",
410            "tests/rustdoc-json",
411            "tests/rustdoc-ui",
412            "tests/ui",
413            "tests/ui-fulldeps",
414            // tidy-alphabetical-end
415        ],
416    ),
417];
418
419fn remap_paths(paths: &mut Vec<PathBuf>) {
420    let mut remove = vec![];
421    let mut add = vec![];
422    for (i, path) in paths.iter().enumerate().filter_map(|(i, path)| path.to_str().map(|s| (i, s)))
423    {
424        for &(search, replace) in PATH_REMAP {
425            // Remove leading and trailing slashes so `tests/` and `tests` are equivalent
426            if path.trim_matches(std::path::is_separator) == search {
427                remove.push(i);
428                add.extend(replace.iter().map(PathBuf::from));
429                break;
430            }
431        }
432    }
433    remove.sort();
434    remove.dedup();
435    for idx in remove.into_iter().rev() {
436        paths.remove(idx);
437    }
438    paths.append(&mut add);
439}
440
441#[derive(Clone, PartialEq)]
442struct CLIStepPath {
443    path: PathBuf,
444    will_be_executed: bool,
445}
446
447#[cfg(test)]
448impl CLIStepPath {
449    fn will_be_executed(mut self, will_be_executed: bool) -> Self {
450        self.will_be_executed = will_be_executed;
451        self
452    }
453}
454
455impl Debug for CLIStepPath {
456    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457        write!(f, "{}", self.path.display())
458    }
459}
460
461impl From<PathBuf> for CLIStepPath {
462    fn from(path: PathBuf) -> Self {
463        Self { path, will_be_executed: false }
464    }
465}
466
467impl StepDescription {
468    fn from<S: Step>(kind: Kind) -> StepDescription {
469        StepDescription {
470            default: S::DEFAULT,
471            only_hosts: S::ONLY_HOSTS,
472            should_run: S::should_run,
473            make_run: S::make_run,
474            name: std::any::type_name::<S>(),
475            kind,
476        }
477    }
478
479    fn maybe_run(&self, builder: &Builder<'_>, mut pathsets: Vec<PathSet>) {
480        pathsets.retain(|set| !self.is_excluded(builder, set));
481
482        if pathsets.is_empty() {
483            return;
484        }
485
486        // Determine the targets participating in this rule.
487        let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
488
489        for target in targets {
490            let run = RunConfig { builder, paths: pathsets.clone(), target: *target };
491            (self.make_run)(run);
492        }
493    }
494
495    fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
496        if builder.config.skip.iter().any(|e| pathset.has(e, builder.kind)) {
497            if !matches!(builder.config.get_dry_run(), DryRun::SelfCheck) {
498                println!("Skipping {pathset:?} because it is excluded");
499            }
500            return true;
501        }
502
503        if !builder.config.skip.is_empty()
504            && !matches!(builder.config.get_dry_run(), DryRun::SelfCheck)
505        {
506            builder.verbose(|| {
507                println!(
508                    "{:?} not skipped for {:?} -- not in {:?}",
509                    pathset, self.name, builder.config.skip
510                )
511            });
512        }
513        false
514    }
515
516    fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
517        let should_runs = v
518            .iter()
519            .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
520            .collect::<Vec<_>>();
521
522        if builder.download_rustc() && (builder.kind == Kind::Dist || builder.kind == Kind::Install)
523        {
524            eprintln!(
525                "ERROR: '{}' subcommand is incompatible with `rust.download-rustc`.",
526                builder.kind.as_str()
527            );
528            crate::exit!(1);
529        }
530
531        // sanity checks on rules
532        for (desc, should_run) in v.iter().zip(&should_runs) {
533            assert!(
534                !should_run.paths.is_empty(),
535                "{:?} should have at least one pathset",
536                desc.name
537            );
538        }
539
540        if paths.is_empty() || builder.config.include_default_paths {
541            for (desc, should_run) in v.iter().zip(&should_runs) {
542                if desc.default && should_run.is_really_default() {
543                    desc.maybe_run(builder, should_run.paths.iter().cloned().collect());
544                }
545            }
546        }
547
548        // Attempt to resolve paths to be relative to the builder source directory.
549        let mut paths: Vec<PathBuf> = paths
550            .iter()
551            .map(|p| {
552                // If the path does not exist, it may represent the name of a Step, such as `tidy` in `x test tidy`
553                if !p.exists() {
554                    return p.clone();
555                }
556
557                // Make the path absolute, strip the prefix, and convert to a PathBuf.
558                match std::path::absolute(p) {
559                    Ok(p) => p.strip_prefix(&builder.src).unwrap_or(&p).to_path_buf(),
560                    Err(e) => {
561                        eprintln!("ERROR: {e:?}");
562                        panic!("Due to the above error, failed to resolve path: {p:?}");
563                    }
564                }
565            })
566            .collect();
567
568        remap_paths(&mut paths);
569
570        // Handle all test suite paths.
571        // (This is separate from the loop below to avoid having to handle multiple paths in `is_suite_path` somehow.)
572        paths.retain(|path| {
573            for (desc, should_run) in v.iter().zip(&should_runs) {
574                if let Some(suite) = should_run.is_suite_path(path) {
575                    desc.maybe_run(builder, vec![suite.clone()]);
576                    return false;
577                }
578            }
579            true
580        });
581
582        if paths.is_empty() {
583            return;
584        }
585
586        let mut paths: Vec<CLIStepPath> = paths.into_iter().map(|p| p.into()).collect();
587        let mut path_lookup: Vec<(CLIStepPath, bool)> =
588            paths.clone().into_iter().map(|p| (p, false)).collect();
589
590        // List of `(usize, &StepDescription, Vec<PathSet>)` where `usize` is the closest index of a path
591        // compared to the given CLI paths. So we can respect to the CLI order by using this value to sort
592        // the steps.
593        let mut steps_to_run = vec![];
594
595        for (desc, should_run) in v.iter().zip(&should_runs) {
596            let pathsets = should_run.pathset_for_paths_removing_matches(&mut paths, desc.kind);
597
598            // This value is used for sorting the step execution order.
599            // By default, `usize::MAX` is used as the index for steps to assign them the lowest priority.
600            //
601            // If we resolve the step's path from the given CLI input, this value will be updated with
602            // the step's actual index.
603            let mut closest_index = usize::MAX;
604
605            // Find the closest index from the original list of paths given by the CLI input.
606            for (index, (path, is_used)) in path_lookup.iter_mut().enumerate() {
607                if !*is_used && !paths.contains(path) {
608                    closest_index = index;
609                    *is_used = true;
610                    break;
611                }
612            }
613
614            steps_to_run.push((closest_index, desc, pathsets));
615        }
616
617        // Sort the steps before running them to respect the CLI order.
618        steps_to_run.sort_by_key(|(index, _, _)| *index);
619
620        // Handle all PathSets.
621        for (_index, desc, pathsets) in steps_to_run {
622            if !pathsets.is_empty() {
623                desc.maybe_run(builder, pathsets);
624            }
625        }
626
627        paths.retain(|p| !p.will_be_executed);
628
629        if !paths.is_empty() {
630            eprintln!("ERROR: no `{}` rules matched {:?}", builder.kind.as_str(), paths);
631            eprintln!(
632                "HELP: run `x.py {} --help --verbose` to show a list of available paths",
633                builder.kind.as_str()
634            );
635            eprintln!(
636                "NOTE: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`"
637            );
638            crate::exit!(1);
639        }
640    }
641}
642
643enum ReallyDefault<'a> {
644    Bool(bool),
645    Lazy(LazyLock<bool, Box<dyn Fn() -> bool + 'a>>),
646}
647
648pub struct ShouldRun<'a> {
649    pub builder: &'a Builder<'a>,
650    kind: Kind,
651
652    // use a BTreeSet to maintain sort order
653    paths: BTreeSet<PathSet>,
654
655    // If this is a default rule, this is an additional constraint placed on
656    // its run. Generally something like compiler docs being enabled.
657    is_really_default: ReallyDefault<'a>,
658}
659
660impl<'a> ShouldRun<'a> {
661    fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
662        ShouldRun {
663            builder,
664            kind,
665            paths: BTreeSet::new(),
666            is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
667        }
668    }
669
670    pub fn default_condition(mut self, cond: bool) -> Self {
671        self.is_really_default = ReallyDefault::Bool(cond);
672        self
673    }
674
675    pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
676        self.is_really_default = ReallyDefault::Lazy(LazyLock::new(lazy_cond));
677        self
678    }
679
680    pub fn is_really_default(&self) -> bool {
681        match &self.is_really_default {
682            ReallyDefault::Bool(val) => *val,
683            ReallyDefault::Lazy(lazy) => *lazy.deref(),
684        }
685    }
686
687    /// Indicates it should run if the command-line selects the given crate or
688    /// any of its (local) dependencies.
689    ///
690    /// `make_run` will be called a single time with all matching command-line paths.
691    pub fn crate_or_deps(self, name: &str) -> Self {
692        let crates = self.builder.in_tree_crates(name, None);
693        self.crates(crates)
694    }
695
696    /// Indicates it should run if the command-line selects any of the given crates.
697    ///
698    /// `make_run` will be called a single time with all matching command-line paths.
699    ///
700    /// Prefer [`ShouldRun::crate_or_deps`] to this function where possible.
701    pub(crate) fn crates(mut self, crates: Vec<&Crate>) -> Self {
702        for krate in crates {
703            let path = krate.local_path(self.builder);
704            self.paths.insert(PathSet::one(path, self.kind));
705        }
706        self
707    }
708
709    // single alias, which does not correspond to any on-disk path
710    pub fn alias(mut self, alias: &str) -> Self {
711        // exceptional case for `Kind::Setup` because its `library`
712        // and `compiler` options would otherwise naively match with
713        // `compiler` and `library` folders respectively.
714        assert!(
715            self.kind == Kind::Setup || !self.builder.src.join(alias).exists(),
716            "use `builder.path()` for real paths: {alias}"
717        );
718        self.paths.insert(PathSet::Set(
719            std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
720        ));
721        self
722    }
723
724    /// single, non-aliased path
725    ///
726    /// Must be an on-disk path; use `alias` for names that do not correspond to on-disk paths.
727    pub fn path(self, path: &str) -> Self {
728        self.paths(&[path])
729    }
730
731    /// Multiple aliases for the same job.
732    ///
733    /// This differs from [`path`] in that multiple calls to path will end up calling `make_run`
734    /// multiple times, whereas a single call to `paths` will only ever generate a single call to
735    /// `make_run`.
736    ///
737    /// This is analogous to `all_krates`, although `all_krates` is gone now. Prefer [`path`] where possible.
738    ///
739    /// [`path`]: ShouldRun::path
740    pub fn paths(mut self, paths: &[&str]) -> Self {
741        let submodules_paths = self.builder.submodule_paths();
742
743        self.paths.insert(PathSet::Set(
744            paths
745                .iter()
746                .map(|p| {
747                    // assert only if `p` isn't submodule
748                    if !submodules_paths.iter().any(|sm_p| p.contains(sm_p)) {
749                        assert!(
750                            self.builder.src.join(p).exists(),
751                            "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {p}"
752                        );
753                    }
754
755                    TaskPath { path: p.into(), kind: Some(self.kind) }
756                })
757                .collect(),
758        ));
759        self
760    }
761
762    /// Handles individual files (not directories) within a test suite.
763    fn is_suite_path(&self, requested_path: &Path) -> Option<&PathSet> {
764        self.paths.iter().find(|pathset| match pathset {
765            PathSet::Suite(suite) => requested_path.starts_with(&suite.path),
766            PathSet::Set(_) => false,
767        })
768    }
769
770    pub fn suite_path(mut self, suite: &str) -> Self {
771        self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
772        self
773    }
774
775    // allows being more explicit about why should_run in Step returns the value passed to it
776    pub fn never(mut self) -> ShouldRun<'a> {
777        self.paths.insert(PathSet::empty());
778        self
779    }
780
781    /// Given a set of requested paths, return the subset which match the Step for this `ShouldRun`,
782    /// removing the matches from `paths`.
783    ///
784    /// NOTE: this returns multiple PathSets to allow for the possibility of multiple units of work
785    /// within the same step. For example, `test::Crate` allows testing multiple crates in the same
786    /// cargo invocation, which are put into separate sets because they aren't aliases.
787    ///
788    /// The reason we return PathSet instead of PathBuf is to allow for aliases that mean the same thing
789    /// (for now, just `all_krates` and `paths`, but we may want to add an `aliases` function in the future?)
790    fn pathset_for_paths_removing_matches(
791        &self,
792        paths: &mut [CLIStepPath],
793        kind: Kind,
794    ) -> Vec<PathSet> {
795        let mut sets = vec![];
796        for pathset in &self.paths {
797            let subset = pathset.intersection_removing_matches(paths, kind);
798            if subset != PathSet::empty() {
799                sets.push(subset);
800            }
801        }
802        sets
803    }
804}
805
806#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)]
807pub enum Kind {
808    #[value(alias = "b")]
809    Build,
810    #[value(alias = "c")]
811    Check,
812    Clippy,
813    Fix,
814    Format,
815    #[value(alias = "t")]
816    Test,
817    Miri,
818    MiriSetup,
819    MiriTest,
820    Bench,
821    #[value(alias = "d")]
822    Doc,
823    Clean,
824    Dist,
825    Install,
826    #[value(alias = "r")]
827    Run,
828    Setup,
829    Suggest,
830    Vendor,
831    Perf,
832}
833
834impl Kind {
835    pub fn as_str(&self) -> &'static str {
836        match self {
837            Kind::Build => "build",
838            Kind::Check => "check",
839            Kind::Clippy => "clippy",
840            Kind::Fix => "fix",
841            Kind::Format => "fmt",
842            Kind::Test => "test",
843            Kind::Miri => "miri",
844            Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."),
845            Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."),
846            Kind::Bench => "bench",
847            Kind::Doc => "doc",
848            Kind::Clean => "clean",
849            Kind::Dist => "dist",
850            Kind::Install => "install",
851            Kind::Run => "run",
852            Kind::Setup => "setup",
853            Kind::Suggest => "suggest",
854            Kind::Vendor => "vendor",
855            Kind::Perf => "perf",
856        }
857    }
858
859    pub fn description(&self) -> String {
860        match self {
861            Kind::Test => "Testing",
862            Kind::Bench => "Benchmarking",
863            Kind::Doc => "Documenting",
864            Kind::Run => "Running",
865            Kind::Suggest => "Suggesting",
866            Kind::Clippy => "Linting",
867            Kind::Perf => "Profiling & benchmarking",
868            _ => {
869                let title_letter = self.as_str()[0..1].to_ascii_uppercase();
870                return format!("{title_letter}{}ing", &self.as_str()[1..]);
871            }
872        }
873        .to_owned()
874    }
875}
876
877#[derive(Debug, Clone, Hash, PartialEq, Eq)]
878struct Libdir {
879    compiler: Compiler,
880    target: TargetSelection,
881}
882
883impl Step for Libdir {
884    type Output = PathBuf;
885
886    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
887        run.never()
888    }
889
890    fn run(self, builder: &Builder<'_>) -> PathBuf {
891        let relative_sysroot_libdir = builder.sysroot_libdir_relative(self.compiler);
892        let sysroot = builder.sysroot(self.compiler).join(relative_sysroot_libdir).join("rustlib");
893
894        if !builder.config.dry_run() {
895            // Avoid deleting the `rustlib/` directory we just copied (in `impl Step for
896            // Sysroot`).
897            if !builder.download_rustc() {
898                let sysroot_target_libdir = sysroot.join(self.target).join("lib");
899                builder.verbose(|| {
900                    eprintln!(
901                        "Removing sysroot {} to avoid caching bugs",
902                        sysroot_target_libdir.display()
903                    )
904                });
905                let _ = fs::remove_dir_all(&sysroot_target_libdir);
906                t!(fs::create_dir_all(&sysroot_target_libdir));
907            }
908
909            if self.compiler.stage == 0 {
910                // The stage 0 compiler for the build triple is always pre-built. Ensure that
911                // `libLLVM.so` ends up in the target libdir, so that ui-fulldeps tests can use
912                // it when run.
913                dist::maybe_install_llvm_target(
914                    builder,
915                    self.compiler.host,
916                    &builder.sysroot(self.compiler),
917                );
918            }
919        }
920
921        sysroot
922    }
923}
924
925impl<'a> Builder<'a> {
926    fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
927        macro_rules! describe {
928            ($($rule:ty),+ $(,)?) => {{
929                vec![$(StepDescription::from::<$rule>(kind)),+]
930            }};
931        }
932        match kind {
933            Kind::Build => describe!(
934                compile::Std,
935                compile::Rustc,
936                compile::Assemble,
937                compile::CodegenBackend,
938                compile::StartupObjects,
939                tool::BuildManifest,
940                tool::Rustbook,
941                tool::ErrorIndex,
942                tool::UnstableBookGen,
943                tool::Tidy,
944                tool::Linkchecker,
945                tool::CargoTest,
946                tool::Compiletest,
947                tool::RemoteTestServer,
948                tool::RemoteTestClient,
949                tool::RustInstaller,
950                tool::Cargo,
951                tool::RustAnalyzer,
952                tool::RustAnalyzerProcMacroSrv,
953                tool::Rustdoc,
954                tool::Clippy,
955                tool::CargoClippy,
956                llvm::Llvm,
957                gcc::Gcc,
958                llvm::Sanitizers,
959                tool::Rustfmt,
960                tool::Cargofmt,
961                tool::Miri,
962                tool::CargoMiri,
963                llvm::Lld,
964                llvm::Enzyme,
965                llvm::CrtBeginEnd,
966                tool::RustdocGUITest,
967                tool::OptimizedDist,
968                tool::CoverageDump,
969                tool::LlvmBitcodeLinker,
970                tool::RustcPerf,
971            ),
972            Kind::Clippy => describe!(
973                clippy::Std,
974                clippy::Rustc,
975                clippy::Bootstrap,
976                clippy::BuildHelper,
977                clippy::BuildManifest,
978                clippy::CargoMiri,
979                clippy::Clippy,
980                clippy::CodegenGcc,
981                clippy::CollectLicenseMetadata,
982                clippy::Compiletest,
983                clippy::CoverageDump,
984                clippy::Jsondocck,
985                clippy::Jsondoclint,
986                clippy::LintDocs,
987                clippy::LlvmBitcodeLinker,
988                clippy::Miri,
989                clippy::MiroptTestTools,
990                clippy::OptDist,
991                clippy::RemoteTestClient,
992                clippy::RemoteTestServer,
993                clippy::RustAnalyzer,
994                clippy::Rustdoc,
995                clippy::Rustfmt,
996                clippy::RustInstaller,
997                clippy::TestFloatParse,
998                clippy::Tidy,
999                clippy::CI,
1000            ),
1001            Kind::Check | Kind::Fix => describe!(
1002                check::Rustc,
1003                check::Rustdoc,
1004                check::CodegenBackend,
1005                check::Clippy,
1006                check::Miri,
1007                check::CargoMiri,
1008                check::MiroptTestTools,
1009                check::Rustfmt,
1010                check::RustAnalyzer,
1011                check::TestFloatParse,
1012                check::Bootstrap,
1013                check::RunMakeSupport,
1014                check::Compiletest,
1015                check::FeaturesStatusDump,
1016                check::CoverageDump,
1017                // This has special staging logic, it may run on stage 1 while others run on stage 0.
1018                // It takes quite some time to build stage 1, so put this at the end.
1019                //
1020                // FIXME: This also helps bootstrap to not interfere with stage 0 builds. We should probably fix
1021                // that issue somewhere else, but we still want to keep `check::Std` at the end so that the
1022                // quicker steps run before this.
1023                check::Std,
1024            ),
1025            Kind::Test => describe!(
1026                crate::core::build_steps::toolstate::ToolStateCheck,
1027                test::Tidy,
1028                test::Ui,
1029                test::Crashes,
1030                test::Coverage,
1031                test::MirOpt,
1032                test::Codegen,
1033                test::CodegenUnits,
1034                test::Assembly,
1035                test::Incremental,
1036                test::Debuginfo,
1037                test::UiFullDeps,
1038                test::Rustdoc,
1039                test::CoverageRunRustdoc,
1040                test::Pretty,
1041                test::CodegenCranelift,
1042                test::CodegenGCC,
1043                test::Crate,
1044                test::CrateLibrustc,
1045                test::CrateRustdoc,
1046                test::CrateRustdocJsonTypes,
1047                test::CrateBootstrap,
1048                test::Linkcheck,
1049                test::TierCheck,
1050                test::Cargotest,
1051                test::Cargo,
1052                test::RustAnalyzer,
1053                test::ErrorIndex,
1054                test::Distcheck,
1055                test::Nomicon,
1056                test::Reference,
1057                test::RustdocBook,
1058                test::RustByExample,
1059                test::TheBook,
1060                test::UnstableBook,
1061                test::RustcBook,
1062                test::LintDocs,
1063                test::EmbeddedBook,
1064                test::EditionGuide,
1065                test::Rustfmt,
1066                test::Miri,
1067                test::CargoMiri,
1068                test::Clippy,
1069                test::CompiletestTest,
1070                test::CrateRunMakeSupport,
1071                test::CrateBuildHelper,
1072                test::RustdocJSStd,
1073                test::RustdocJSNotStd,
1074                test::RustdocGUI,
1075                test::RustdocTheme,
1076                test::RustdocUi,
1077                test::RustdocJson,
1078                test::HtmlCheck,
1079                test::RustInstaller,
1080                test::TestFloatParse,
1081                test::CollectLicenseMetadata,
1082                // Run bootstrap close to the end as it's unlikely to fail
1083                test::Bootstrap,
1084                // Run run-make last, since these won't pass without make on Windows
1085                test::RunMake,
1086            ),
1087            Kind::Miri => describe!(test::Crate),
1088            Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1089            Kind::Doc => describe!(
1090                doc::UnstableBook,
1091                doc::UnstableBookGen,
1092                doc::TheBook,
1093                doc::Standalone,
1094                doc::Std,
1095                doc::Rustc,
1096                doc::Rustdoc,
1097                doc::Rustfmt,
1098                doc::ErrorIndex,
1099                doc::Nomicon,
1100                doc::Reference,
1101                doc::RustdocBook,
1102                doc::RustByExample,
1103                doc::RustcBook,
1104                doc::Cargo,
1105                doc::CargoBook,
1106                doc::Clippy,
1107                doc::ClippyBook,
1108                doc::Miri,
1109                doc::EmbeddedBook,
1110                doc::EditionGuide,
1111                doc::StyleGuide,
1112                doc::Tidy,
1113                doc::Bootstrap,
1114                doc::Releases,
1115                doc::RunMakeSupport,
1116                doc::BuildHelper,
1117                doc::Compiletest,
1118            ),
1119            Kind::Dist => describe!(
1120                dist::Docs,
1121                dist::RustcDocs,
1122                dist::JsonDocs,
1123                dist::Mingw,
1124                dist::Rustc,
1125                dist::CodegenBackend,
1126                dist::Std,
1127                dist::RustcDev,
1128                dist::Analysis,
1129                dist::Src,
1130                dist::Cargo,
1131                dist::RustAnalyzer,
1132                dist::Rustfmt,
1133                dist::Clippy,
1134                dist::Miri,
1135                dist::LlvmTools,
1136                dist::LlvmBitcodeLinker,
1137                dist::RustDev,
1138                dist::Bootstrap,
1139                dist::Extended,
1140                // It seems that PlainSourceTarball somehow changes how some of the tools
1141                // perceive their dependencies (see #93033) which would invalidate fingerprints
1142                // and force us to rebuild tools after vendoring dependencies.
1143                // To work around this, create the Tarball after building all the tools.
1144                dist::PlainSourceTarball,
1145                dist::BuildManifest,
1146                dist::ReproducibleArtifacts,
1147                dist::Gcc
1148            ),
1149            Kind::Install => describe!(
1150                install::Docs,
1151                install::Std,
1152                // During the Rust compiler (rustc) installation process, we copy the entire sysroot binary
1153                // path (build/host/stage2/bin). Since the building tools also make their copy in the sysroot
1154                // binary path, we must install rustc before the tools. Otherwise, the rust-installer will
1155                // install the same binaries twice for each tool, leaving backup files (*.old) as a result.
1156                install::Rustc,
1157                install::Cargo,
1158                install::RustAnalyzer,
1159                install::Rustfmt,
1160                install::Clippy,
1161                install::Miri,
1162                install::LlvmTools,
1163                install::Src,
1164            ),
1165            Kind::Run => describe!(
1166                run::BuildManifest,
1167                run::BumpStage0,
1168                run::ReplaceVersionPlaceholder,
1169                run::Miri,
1170                run::CollectLicenseMetadata,
1171                run::GenerateCopyright,
1172                run::GenerateWindowsSys,
1173                run::GenerateCompletions,
1174                run::UnicodeTableGenerator,
1175                run::FeaturesStatusDump,
1176                run::CyclicStep,
1177                run::CoverageDump,
1178                run::Rustfmt,
1179            ),
1180            Kind::Setup => {
1181                describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1182            }
1183            Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1184            Kind::Vendor => describe!(vendor::Vendor),
1185            // special-cased in Build::build()
1186            Kind::Format | Kind::Suggest | Kind::Perf => vec![],
1187            Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1188        }
1189    }
1190
1191    pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1192        let step_descriptions = Builder::get_step_descriptions(kind);
1193        if step_descriptions.is_empty() {
1194            return None;
1195        }
1196
1197        let builder = Self::new_internal(build, kind, vec![]);
1198        let builder = &builder;
1199        // The "build" kind here is just a placeholder, it will be replaced with something else in
1200        // the following statement.
1201        let mut should_run = ShouldRun::new(builder, Kind::Build);
1202        for desc in step_descriptions {
1203            should_run.kind = desc.kind;
1204            should_run = (desc.should_run)(should_run);
1205        }
1206        let mut help = String::from("Available paths:\n");
1207        let mut add_path = |path: &Path| {
1208            t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
1209        };
1210        for pathset in should_run.paths {
1211            match pathset {
1212                PathSet::Set(set) => {
1213                    for path in set {
1214                        add_path(&path.path);
1215                    }
1216                }
1217                PathSet::Suite(path) => {
1218                    add_path(&path.path.join("..."));
1219                }
1220            }
1221        }
1222        Some(help)
1223    }
1224
1225    fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1226        Builder {
1227            build,
1228            top_stage: build.config.stage,
1229            kind,
1230            cache: Cache::new(),
1231            stack: RefCell::new(Vec::new()),
1232            time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1233            paths,
1234            submodule_paths_cache: Default::default(),
1235        }
1236    }
1237
1238    pub fn new(build: &Build) -> Builder<'_> {
1239        let paths = &build.config.paths;
1240        let (kind, paths) = match build.config.cmd {
1241            Subcommand::Build => (Kind::Build, &paths[..]),
1242            Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1243            Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1244            Subcommand::Fix => (Kind::Fix, &paths[..]),
1245            Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1246            Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1247            Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1248            Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1249            Subcommand::Dist => (Kind::Dist, &paths[..]),
1250            Subcommand::Install => (Kind::Install, &paths[..]),
1251            Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1252            Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1253            Subcommand::Format { .. } => (Kind::Format, &[][..]),
1254            Subcommand::Suggest { .. } => (Kind::Suggest, &[][..]),
1255            Subcommand::Setup { profile: ref path } => (
1256                Kind::Setup,
1257                path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1258            ),
1259            Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1260            Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1261        };
1262
1263        Self::new_internal(build, kind, paths.to_owned())
1264    }
1265
1266    pub fn execute_cli(&self) {
1267        self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1268    }
1269
1270    pub fn default_doc(&self, paths: &[PathBuf]) {
1271        self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1272    }
1273
1274    pub fn doc_rust_lang_org_channel(&self) -> String {
1275        let channel = match &*self.config.channel {
1276            "stable" => &self.version,
1277            "beta" => "beta",
1278            "nightly" | "dev" => "nightly",
1279            // custom build of rustdoc maybe? link to the latest stable docs just in case
1280            _ => "stable",
1281        };
1282
1283        format!("https://doc.rust-lang.org/{channel}")
1284    }
1285
1286    fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1287        StepDescription::run(v, self, paths);
1288    }
1289
1290    /// Returns if `std` should be statically linked into `rustc_driver`.
1291    /// It's currently not done on `windows-gnu` due to linker bugs.
1292    pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1293        !target.triple.ends_with("-windows-gnu")
1294    }
1295
1296    /// Obtain a compiler at a given stage and for a given host (i.e., this is the target that the
1297    /// compiler will run on, *not* the target it will build code for). Explicitly does not take
1298    /// `Compiler` since all `Compiler` instances are meant to be obtained through this function,
1299    /// since it ensures that they are valid (i.e., built and assembled).
1300    #[cfg_attr(
1301        feature = "tracing",
1302        instrument(
1303            level = "trace",
1304            name = "Builder::compiler",
1305            target = "COMPILER",
1306            skip_all,
1307            fields(
1308                stage = stage,
1309                host = ?host,
1310            ),
1311        ),
1312    )]
1313    pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1314        self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1315    }
1316
1317    /// Similar to `compiler`, except handles the full-bootstrap option to
1318    /// silently use the stage1 compiler instead of a stage2 compiler if one is
1319    /// requested.
1320    ///
1321    /// Note that this does *not* have the side effect of creating
1322    /// `compiler(stage, host)`, unlike `compiler` above which does have such
1323    /// a side effect. The returned compiler here can only be used to compile
1324    /// new artifacts, it can't be used to rely on the presence of a particular
1325    /// sysroot.
1326    ///
1327    /// See `force_use_stage1` and `force_use_stage2` for documentation on what each argument is.
1328    #[cfg_attr(
1329        feature = "tracing",
1330        instrument(
1331            level = "trace",
1332            name = "Builder::compiler_for",
1333            target = "COMPILER_FOR",
1334            skip_all,
1335            fields(
1336                stage = stage,
1337                host = ?host,
1338                target = ?target,
1339            ),
1340        ),
1341    )]
1342    /// FIXME: This function is unnecessary (and dangerous, see <https://github.com/rust-lang/rust/issues/137469>).
1343    /// We already have uplifting logic for the compiler, so remove this.
1344    pub fn compiler_for(
1345        &self,
1346        stage: u32,
1347        host: TargetSelection,
1348        target: TargetSelection,
1349    ) -> Compiler {
1350        let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1351            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1352            self.compiler(2, self.config.host_target)
1353        } else if self.build.force_use_stage1(stage, target) {
1354            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1355            self.compiler(1, self.config.host_target)
1356        } else {
1357            trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1358            self.compiler(stage, host)
1359        };
1360
1361        if stage != resolved_compiler.stage {
1362            resolved_compiler.forced_compiler(true);
1363        }
1364
1365        trace!(target: "COMPILER_FOR", ?resolved_compiler);
1366        resolved_compiler
1367    }
1368
1369    /// Obtain a standard library for the given target that will be built by the passed compiler.
1370    /// The standard library will be linked to the sysroot of the passed compiler.
1371    ///
1372    /// Prefer using this method rather than manually invoking `Std::new`.
1373    #[cfg_attr(
1374        feature = "tracing",
1375        instrument(
1376            level = "trace",
1377            name = "Builder::std",
1378            target = "STD",
1379            skip_all,
1380            fields(
1381                compiler = ?compiler,
1382                target = ?target,
1383            ),
1384        ),
1385    )]
1386    pub fn std(&self, compiler: Compiler, target: TargetSelection) {
1387        // FIXME: make the `Std` step return some type-level "proof" that std was indeed built,
1388        // and then require passing that to all Cargo invocations that we do.
1389
1390        // The "stage 0" std is always precompiled and comes with the stage0 compiler, so we have
1391        // special logic for it, to avoid creating needless and confusing Std steps that don't
1392        // actually build anything.
1393        if compiler.stage == 0 {
1394            if target != compiler.host {
1395                panic!(
1396                    r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1397You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1398",
1399                    compiler.host
1400                )
1401            }
1402
1403            // We still need to link the prebuilt standard library into the ephemeral stage0 sysroot
1404            self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1405        } else {
1406            // This step both compiles the std and links it into the compiler's sysroot.
1407            // Yes, it's quite magical and side-effecty.. would be nice to refactor later.
1408            self.ensure(Std::new(compiler, target));
1409        }
1410    }
1411
1412    pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1413        self.ensure(compile::Sysroot::new(compiler))
1414    }
1415
1416    /// Returns the bindir for a compiler's sysroot.
1417    pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1418        self.ensure(Libdir { compiler, target }).join(target).join("bin")
1419    }
1420
1421    /// Returns the libdir where the standard library and other artifacts are
1422    /// found for a compiler's sysroot.
1423    pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1424        self.ensure(Libdir { compiler, target }).join(target).join("lib")
1425    }
1426
1427    pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1428        self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1429    }
1430
1431    /// Returns the compiler's libdir where it stores the dynamic libraries that
1432    /// it itself links against.
1433    ///
1434    /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1435    /// Windows.
1436    pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1437        if compiler.is_snapshot(self) {
1438            self.rustc_snapshot_libdir()
1439        } else {
1440            match self.config.libdir_relative() {
1441                Some(relative_libdir) if compiler.stage >= 1 => {
1442                    self.sysroot(compiler).join(relative_libdir)
1443                }
1444                _ => self.sysroot(compiler).join(libdir(compiler.host)),
1445            }
1446        }
1447    }
1448
1449    /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1450    /// it itself links against.
1451    ///
1452    /// For example this returns `lib` on Unix and `bin` on
1453    /// Windows.
1454    pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1455        if compiler.is_snapshot(self) {
1456            libdir(self.config.host_target).as_ref()
1457        } else {
1458            match self.config.libdir_relative() {
1459                Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1460                _ => libdir(compiler.host).as_ref(),
1461            }
1462        }
1463    }
1464
1465    /// Returns the compiler's relative libdir where the standard library and other artifacts are
1466    /// found for a compiler's sysroot.
1467    ///
1468    /// For example this returns `lib` on Unix and Windows.
1469    pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1470        match self.config.libdir_relative() {
1471            Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1472            _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1473            _ => Path::new("lib"),
1474        }
1475    }
1476
1477    pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1478        let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1479
1480        // Ensure that the downloaded LLVM libraries can be found.
1481        if self.config.llvm_from_ci {
1482            let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1483            dylib_dirs.push(ci_llvm_lib);
1484        }
1485
1486        dylib_dirs
1487    }
1488
1489    /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1490    /// library lookup path.
1491    pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1492        // Windows doesn't need dylib path munging because the dlls for the
1493        // compiler live next to the compiler and the system will find them
1494        // automatically.
1495        if cfg!(any(windows, target_os = "cygwin")) {
1496            return;
1497        }
1498
1499        add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1500    }
1501
1502    /// Gets a path to the compiler specified.
1503    pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1504        if compiler.is_snapshot(self) {
1505            self.initial_rustc.clone()
1506        } else {
1507            self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1508        }
1509    }
1510
1511    /// Gets the paths to all of the compiler's codegen backends.
1512    fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1513        fs::read_dir(self.sysroot_codegen_backends(compiler))
1514            .into_iter()
1515            .flatten()
1516            .filter_map(Result::ok)
1517            .map(|entry| entry.path())
1518    }
1519
1520    pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1521        self.ensure(tool::Rustdoc { compiler }).tool_path
1522    }
1523
1524    pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1525        if run_compiler.stage == 0 {
1526            let cargo_clippy = self
1527                .config
1528                .initial_cargo_clippy
1529                .clone()
1530                .unwrap_or_else(|| self.build.config.download_clippy());
1531
1532            let mut cmd = command(cargo_clippy);
1533            cmd.env("CARGO", &self.initial_cargo);
1534            return cmd;
1535        }
1536
1537        let _ =
1538            self.ensure(tool::Clippy { compiler: run_compiler, target: self.build.host_target });
1539        let cargo_clippy = self
1540            .ensure(tool::CargoClippy { compiler: run_compiler, target: self.build.host_target });
1541        let mut dylib_path = helpers::dylib_path();
1542        dylib_path.insert(0, self.sysroot(run_compiler).join("lib"));
1543
1544        let mut cmd = command(cargo_clippy.tool_path);
1545        cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1546        cmd.env("CARGO", &self.initial_cargo);
1547        cmd
1548    }
1549
1550    pub fn cargo_miri_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1551        assert!(run_compiler.stage > 0, "miri can not be invoked at stage 0");
1552        // Prepare the tools
1553        let miri =
1554            self.ensure(tool::Miri { compiler: run_compiler, target: self.build.host_target });
1555        let cargo_miri =
1556            self.ensure(tool::CargoMiri { compiler: run_compiler, target: self.build.host_target });
1557        // Invoke cargo-miri, make sure it can find miri and cargo.
1558        let mut cmd = command(cargo_miri.tool_path);
1559        cmd.env("MIRI", &miri.tool_path);
1560        cmd.env("CARGO", &self.initial_cargo);
1561        // Need to add the `run_compiler` libs. Those are the libs produces *by* `build_compiler`
1562        // in `tool::ToolBuild` step, so they match the Miri we just built. However this means they
1563        // are actually living one stage up, i.e. we are running `stage0-tools-bin/miri` with the
1564        // libraries in `stage1/lib`. This is an unfortunate off-by-1 caused (possibly) by the fact
1565        // that Miri doesn't have an "assemble" step like rustc does that would cross the stage boundary.
1566        // We can't use `add_rustc_lib_path` as that's a NOP on Windows but we do need these libraries
1567        // added to the PATH due to the stage mismatch.
1568        // Also see https://github.com/rust-lang/rust/pull/123192#issuecomment-2028901503.
1569        add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1570        cmd
1571    }
1572
1573    pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1574        let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1575        cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1576            .env("RUSTC_SYSROOT", self.sysroot(compiler))
1577            // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1578            // equivalently to rustc.
1579            .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1580            .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1581            .env("RUSTDOC_REAL", self.rustdoc(compiler))
1582            .env("RUSTC_BOOTSTRAP", "1");
1583
1584        cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1585
1586        if self.config.deny_warnings {
1587            cmd.arg("-Dwarnings");
1588        }
1589        cmd.arg("-Znormalize-docs");
1590        cmd.args(linker_args(self, compiler.host, LldThreads::Yes));
1591        cmd
1592    }
1593
1594    /// Return the path to `llvm-config` for the target, if it exists.
1595    ///
1596    /// Note that this returns `None` if LLVM is disabled, or if we're in a
1597    /// check build or dry-run, where there's no need to build all of LLVM.
1598    pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1599        if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1600            let llvm::LlvmResult { llvm_config, .. } = self.ensure(llvm::Llvm { target });
1601            if llvm_config.is_file() {
1602                return Some(llvm_config);
1603            }
1604        }
1605        None
1606    }
1607
1608    /// Updates all submodules, and exits with an error if submodule
1609    /// management is disabled and the submodule does not exist.
1610    pub fn require_and_update_all_submodules(&self) {
1611        for submodule in self.submodule_paths() {
1612            self.require_submodule(submodule, None);
1613        }
1614    }
1615
1616    /// Get all submodules from the src directory.
1617    pub fn submodule_paths(&self) -> &[String] {
1618        self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1619    }
1620
1621    /// Ensure that a given step is built, returning its output. This will
1622    /// cache the step, so it is safe (and good!) to call this as often as
1623    /// needed to ensure that all dependencies are built.
1624    pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1625        {
1626            let mut stack = self.stack.borrow_mut();
1627            for stack_step in stack.iter() {
1628                // should skip
1629                if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1630                    continue;
1631                }
1632                let mut out = String::new();
1633                out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1634                for el in stack.iter().rev() {
1635                    out += &format!("\t{el:?}\n");
1636                }
1637                panic!("{}", out);
1638            }
1639            if let Some(out) = self.cache.get(&step) {
1640                self.verbose_than(1, || println!("{}c {:?}", "  ".repeat(stack.len()), step));
1641
1642                return out;
1643            }
1644            self.verbose_than(1, || println!("{}> {:?}", "  ".repeat(stack.len()), step));
1645            stack.push(Box::new(step.clone()));
1646        }
1647
1648        #[cfg(feature = "build-metrics")]
1649        self.metrics.enter_step(&step, self);
1650
1651        let (out, dur) = {
1652            let start = Instant::now();
1653            let zero = Duration::new(0, 0);
1654            let parent = self.time_spent_on_dependencies.replace(zero);
1655            let out = step.clone().run(self);
1656            let dur = start.elapsed();
1657            let deps = self.time_spent_on_dependencies.replace(parent + dur);
1658            (out, dur.saturating_sub(deps))
1659        };
1660
1661        if self.config.print_step_timings && !self.config.dry_run() {
1662            let step_string = format!("{step:?}");
1663            let brace_index = step_string.find('{').unwrap_or(0);
1664            let type_string = type_name::<S>();
1665            println!(
1666                "[TIMING] {} {} -- {}.{:03}",
1667                &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1668                &step_string[brace_index..],
1669                dur.as_secs(),
1670                dur.subsec_millis()
1671            );
1672        }
1673
1674        #[cfg(feature = "build-metrics")]
1675        self.metrics.exit_step(self);
1676
1677        {
1678            let mut stack = self.stack.borrow_mut();
1679            let cur_step = stack.pop().expect("step stack empty");
1680            assert_eq!(cur_step.downcast_ref(), Some(&step));
1681        }
1682        self.verbose_than(1, || println!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1683        self.cache.put(step, out.clone());
1684        out
1685    }
1686
1687    /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1688    /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1689    /// needed to ensure that all dependencies are build.
1690    pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1691        &'a self,
1692        step: S,
1693        kind: Kind,
1694    ) -> S::Output {
1695        let desc = StepDescription::from::<S>(kind);
1696        let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1697
1698        // Avoid running steps contained in --skip
1699        for pathset in &should_run.paths {
1700            if desc.is_excluded(self, pathset) {
1701                return None;
1702            }
1703        }
1704
1705        // Only execute if it's supposed to run as default
1706        if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1707    }
1708
1709    /// Checks if any of the "should_run" paths is in the `Builder` paths.
1710    pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1711        let desc = StepDescription::from::<S>(kind);
1712        let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1713
1714        for path in &self.paths {
1715            if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1716                && !desc.is_excluded(
1717                    self,
1718                    &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1719                )
1720            {
1721                return true;
1722            }
1723        }
1724
1725        false
1726    }
1727
1728    pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1729        if self.was_invoked_explicitly::<S>(Kind::Doc) {
1730            self.open_in_browser(path);
1731        } else {
1732            self.info(&format!("Doc path: {}", path.as_ref().display()));
1733        }
1734    }
1735
1736    pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1737        let path = path.as_ref();
1738
1739        if self.config.dry_run() || !self.config.cmd.open() {
1740            self.info(&format!("Doc path: {}", path.display()));
1741            return;
1742        }
1743
1744        self.info(&format!("Opening doc {}", path.display()));
1745        if let Err(err) = opener::open(path) {
1746            self.info(&format!("{err}\n"));
1747        }
1748    }
1749
1750    pub fn exec_ctx(&self) -> &ExecutionContext {
1751        &self.config.exec_ctx
1752    }
1753}
1754
1755impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1756    fn as_ref(&self) -> &ExecutionContext {
1757        self.exec_ctx()
1758    }
1759}