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