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