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: String,
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: &str, target: TargetSelection) -> Self {
155        Self::new(name, target, Kind::Build)
156    }
157
158    pub fn check(name: &str, target: TargetSelection) -> Self {
159        Self::new(name, target, Kind::Check)
160    }
161
162    pub fn doc(name: &str, target: TargetSelection) -> Self {
163        Self::new(name, target, Kind::Doc)
164    }
165
166    pub fn dist(name: &str, target: TargetSelection) -> Self {
167        Self::new(name, target, Kind::Dist)
168    }
169
170    pub fn test(name: &str, target: TargetSelection) -> Self {
171        Self::new(name, target, Kind::Test)
172    }
173
174    fn new(name: &str, target: TargetSelection, kind: Kind) -> Self {
175        Self { name: name.to_string(), 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-llvm",
415            "tests/codegen-llvm",
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                check::Linkchecker,
1037                // This has special staging logic, it may run on stage 1 while others run on stage 0.
1038                // It takes quite some time to build stage 1, so put this at the end.
1039                //
1040                // FIXME: This also helps bootstrap to not interfere with stage 0 builds. We should probably fix
1041                // that issue somewhere else, but we still want to keep `check::Std` at the end so that the
1042                // quicker steps run before this.
1043                check::Std,
1044            ),
1045            Kind::Test => describe!(
1046                crate::core::build_steps::toolstate::ToolStateCheck,
1047                test::Tidy,
1048                test::Bootstrap,
1049                test::Ui,
1050                test::Crashes,
1051                test::Coverage,
1052                test::MirOpt,
1053                test::CodegenLlvm,
1054                test::CodegenUnits,
1055                test::AssemblyLlvm,
1056                test::Incremental,
1057                test::Debuginfo,
1058                test::UiFullDeps,
1059                test::Rustdoc,
1060                test::CoverageRunRustdoc,
1061                test::Pretty,
1062                test::CodegenCranelift,
1063                test::CodegenGCC,
1064                test::Crate,
1065                test::CrateLibrustc,
1066                test::CrateRustdoc,
1067                test::CrateRustdocJsonTypes,
1068                test::CrateBootstrap,
1069                test::Linkcheck,
1070                test::TierCheck,
1071                test::Cargotest,
1072                test::Cargo,
1073                test::RustAnalyzer,
1074                test::ErrorIndex,
1075                test::Distcheck,
1076                test::Nomicon,
1077                test::Reference,
1078                test::RustdocBook,
1079                test::RustByExample,
1080                test::TheBook,
1081                test::UnstableBook,
1082                test::RustcBook,
1083                test::LintDocs,
1084                test::EmbeddedBook,
1085                test::EditionGuide,
1086                test::Rustfmt,
1087                test::Miri,
1088                test::CargoMiri,
1089                test::Clippy,
1090                test::CompiletestTest,
1091                test::CrateRunMakeSupport,
1092                test::CrateBuildHelper,
1093                test::RustdocJSStd,
1094                test::RustdocJSNotStd,
1095                test::RustdocGUI,
1096                test::RustdocTheme,
1097                test::RustdocUi,
1098                test::RustdocJson,
1099                test::HtmlCheck,
1100                test::RustInstaller,
1101                test::TestFloatParse,
1102                test::CollectLicenseMetadata,
1103                // Run run-make last, since these won't pass without make on Windows
1104                test::RunMake,
1105            ),
1106            Kind::Miri => describe!(test::Crate),
1107            Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
1108            Kind::Doc => describe!(
1109                doc::UnstableBook,
1110                doc::UnstableBookGen,
1111                doc::TheBook,
1112                doc::Standalone,
1113                doc::Std,
1114                doc::Rustc,
1115                doc::Rustdoc,
1116                doc::Rustfmt,
1117                doc::ErrorIndex,
1118                doc::Nomicon,
1119                doc::Reference,
1120                doc::RustdocBook,
1121                doc::RustByExample,
1122                doc::RustcBook,
1123                doc::Cargo,
1124                doc::CargoBook,
1125                doc::Clippy,
1126                doc::ClippyBook,
1127                doc::Miri,
1128                doc::EmbeddedBook,
1129                doc::EditionGuide,
1130                doc::StyleGuide,
1131                doc::Tidy,
1132                doc::Bootstrap,
1133                doc::Releases,
1134                doc::RunMakeSupport,
1135                doc::BuildHelper,
1136                doc::Compiletest,
1137            ),
1138            Kind::Dist => describe!(
1139                dist::Docs,
1140                dist::RustcDocs,
1141                dist::JsonDocs,
1142                dist::Mingw,
1143                dist::Rustc,
1144                dist::CodegenBackend,
1145                dist::Std,
1146                dist::RustcDev,
1147                dist::Analysis,
1148                dist::Src,
1149                dist::Cargo,
1150                dist::RustAnalyzer,
1151                dist::Rustfmt,
1152                dist::Clippy,
1153                dist::Miri,
1154                dist::LlvmTools,
1155                dist::LlvmBitcodeLinker,
1156                dist::RustDev,
1157                dist::Bootstrap,
1158                dist::Extended,
1159                // It seems that PlainSourceTarball somehow changes how some of the tools
1160                // perceive their dependencies (see #93033) which would invalidate fingerprints
1161                // and force us to rebuild tools after vendoring dependencies.
1162                // To work around this, create the Tarball after building all the tools.
1163                dist::PlainSourceTarball,
1164                dist::BuildManifest,
1165                dist::ReproducibleArtifacts,
1166                dist::Gcc
1167            ),
1168            Kind::Install => describe!(
1169                install::Docs,
1170                install::Std,
1171                // During the Rust compiler (rustc) installation process, we copy the entire sysroot binary
1172                // path (build/host/stage2/bin). Since the building tools also make their copy in the sysroot
1173                // binary path, we must install rustc before the tools. Otherwise, the rust-installer will
1174                // install the same binaries twice for each tool, leaving backup files (*.old) as a result.
1175                install::Rustc,
1176                install::Cargo,
1177                install::RustAnalyzer,
1178                install::Rustfmt,
1179                install::Clippy,
1180                install::Miri,
1181                install::LlvmTools,
1182                install::Src,
1183            ),
1184            Kind::Run => describe!(
1185                run::BuildManifest,
1186                run::BumpStage0,
1187                run::ReplaceVersionPlaceholder,
1188                run::Miri,
1189                run::CollectLicenseMetadata,
1190                run::GenerateCopyright,
1191                run::GenerateWindowsSys,
1192                run::GenerateCompletions,
1193                run::UnicodeTableGenerator,
1194                run::FeaturesStatusDump,
1195                run::CyclicStep,
1196                run::CoverageDump,
1197                run::Rustfmt,
1198            ),
1199            Kind::Setup => {
1200                describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
1201            }
1202            Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std),
1203            Kind::Vendor => describe!(vendor::Vendor),
1204            // special-cased in Build::build()
1205            Kind::Format | Kind::Perf => vec![],
1206            Kind::MiriTest | Kind::MiriSetup => unreachable!(),
1207        }
1208    }
1209
1210    pub fn get_help(build: &Build, kind: Kind) -> Option<String> {
1211        let step_descriptions = Builder::get_step_descriptions(kind);
1212        if step_descriptions.is_empty() {
1213            return None;
1214        }
1215
1216        let builder = Self::new_internal(build, kind, vec![]);
1217        let builder = &builder;
1218        // The "build" kind here is just a placeholder, it will be replaced with something else in
1219        // the following statement.
1220        let mut should_run = ShouldRun::new(builder, Kind::Build);
1221        for desc in step_descriptions {
1222            should_run.kind = desc.kind;
1223            should_run = (desc.should_run)(should_run);
1224        }
1225        let mut help = String::from("Available paths:\n");
1226        let mut add_path = |path: &Path| {
1227            t!(write!(help, "    ./x.py {} {}\n", kind.as_str(), path.display()));
1228        };
1229        for pathset in should_run.paths {
1230            match pathset {
1231                PathSet::Set(set) => {
1232                    for path in set {
1233                        add_path(&path.path);
1234                    }
1235                }
1236                PathSet::Suite(path) => {
1237                    add_path(&path.path.join("..."));
1238                }
1239            }
1240        }
1241        Some(help)
1242    }
1243
1244    fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
1245        Builder {
1246            build,
1247            top_stage: build.config.stage,
1248            kind,
1249            cache: Cache::new(),
1250            stack: RefCell::new(Vec::new()),
1251            time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
1252            paths,
1253            submodule_paths_cache: Default::default(),
1254        }
1255    }
1256
1257    pub fn new(build: &Build) -> Builder<'_> {
1258        let paths = &build.config.paths;
1259        let (kind, paths) = match build.config.cmd {
1260            Subcommand::Build => (Kind::Build, &paths[..]),
1261            Subcommand::Check { .. } => (Kind::Check, &paths[..]),
1262            Subcommand::Clippy { .. } => (Kind::Clippy, &paths[..]),
1263            Subcommand::Fix => (Kind::Fix, &paths[..]),
1264            Subcommand::Doc { .. } => (Kind::Doc, &paths[..]),
1265            Subcommand::Test { .. } => (Kind::Test, &paths[..]),
1266            Subcommand::Miri { .. } => (Kind::Miri, &paths[..]),
1267            Subcommand::Bench { .. } => (Kind::Bench, &paths[..]),
1268            Subcommand::Dist => (Kind::Dist, &paths[..]),
1269            Subcommand::Install => (Kind::Install, &paths[..]),
1270            Subcommand::Run { .. } => (Kind::Run, &paths[..]),
1271            Subcommand::Clean { .. } => (Kind::Clean, &paths[..]),
1272            Subcommand::Format { .. } => (Kind::Format, &[][..]),
1273            Subcommand::Setup { profile: ref path } => (
1274                Kind::Setup,
1275                path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)),
1276            ),
1277            Subcommand::Vendor { .. } => (Kind::Vendor, &paths[..]),
1278            Subcommand::Perf { .. } => (Kind::Perf, &paths[..]),
1279        };
1280
1281        Self::new_internal(build, kind, paths.to_owned())
1282    }
1283
1284    pub fn execute_cli(&self) {
1285        self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
1286    }
1287
1288    pub fn default_doc(&self, paths: &[PathBuf]) {
1289        self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
1290    }
1291
1292    pub fn doc_rust_lang_org_channel(&self) -> String {
1293        let channel = match &*self.config.channel {
1294            "stable" => &self.version,
1295            "beta" => "beta",
1296            "nightly" | "dev" => "nightly",
1297            // custom build of rustdoc maybe? link to the latest stable docs just in case
1298            _ => "stable",
1299        };
1300
1301        format!("https://doc.rust-lang.org/{channel}")
1302    }
1303
1304    fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
1305        StepDescription::run(v, self, paths);
1306    }
1307
1308    /// Returns if `std` should be statically linked into `rustc_driver`.
1309    /// It's currently not done on `windows-gnu` due to linker bugs.
1310    pub fn link_std_into_rustc_driver(&self, target: TargetSelection) -> bool {
1311        !target.triple.ends_with("-windows-gnu")
1312    }
1313
1314    /// Obtain a compiler at a given stage and for a given host (i.e., this is the target that the
1315    /// compiler will run on, *not* the target it will build code for). Explicitly does not take
1316    /// `Compiler` since all `Compiler` instances are meant to be obtained through this function,
1317    /// since it ensures that they are valid (i.e., built and assembled).
1318    #[cfg_attr(
1319        feature = "tracing",
1320        instrument(
1321            level = "trace",
1322            name = "Builder::compiler",
1323            target = "COMPILER",
1324            skip_all,
1325            fields(
1326                stage = stage,
1327                host = ?host,
1328            ),
1329        ),
1330    )]
1331    pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
1332        self.ensure(compile::Assemble { target_compiler: Compiler::new(stage, host) })
1333    }
1334
1335    /// Similar to `compiler`, except handles the full-bootstrap option to
1336    /// silently use the stage1 compiler instead of a stage2 compiler if one is
1337    /// requested.
1338    ///
1339    /// Note that this does *not* have the side effect of creating
1340    /// `compiler(stage, host)`, unlike `compiler` above which does have such
1341    /// a side effect. The returned compiler here can only be used to compile
1342    /// new artifacts, it can't be used to rely on the presence of a particular
1343    /// sysroot.
1344    ///
1345    /// See `force_use_stage1` and `force_use_stage2` for documentation on what each argument is.
1346    #[cfg_attr(
1347        feature = "tracing",
1348        instrument(
1349            level = "trace",
1350            name = "Builder::compiler_for",
1351            target = "COMPILER_FOR",
1352            skip_all,
1353            fields(
1354                stage = stage,
1355                host = ?host,
1356                target = ?target,
1357            ),
1358        ),
1359    )]
1360    /// FIXME: This function is unnecessary (and dangerous, see <https://github.com/rust-lang/rust/issues/137469>).
1361    /// We already have uplifting logic for the compiler, so remove this.
1362    pub fn compiler_for(
1363        &self,
1364        stage: u32,
1365        host: TargetSelection,
1366        target: TargetSelection,
1367    ) -> Compiler {
1368        let mut resolved_compiler = if self.build.force_use_stage2(stage) {
1369            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2");
1370            self.compiler(2, self.config.host_target)
1371        } else if self.build.force_use_stage1(stage, target) {
1372            trace!(target: "COMPILER_FOR", ?stage, "force_use_stage1");
1373            self.compiler(1, self.config.host_target)
1374        } else {
1375            trace!(target: "COMPILER_FOR", ?stage, ?host, "no force, fallback to `compiler()`");
1376            self.compiler(stage, host)
1377        };
1378
1379        if stage != resolved_compiler.stage {
1380            resolved_compiler.forced_compiler(true);
1381        }
1382
1383        trace!(target: "COMPILER_FOR", ?resolved_compiler);
1384        resolved_compiler
1385    }
1386
1387    /// Obtain a standard library for the given target that will be built by the passed compiler.
1388    /// The standard library will be linked to the sysroot of the passed compiler.
1389    ///
1390    /// Prefer using this method rather than manually invoking `Std::new`.
1391    #[cfg_attr(
1392        feature = "tracing",
1393        instrument(
1394            level = "trace",
1395            name = "Builder::std",
1396            target = "STD",
1397            skip_all,
1398            fields(
1399                compiler = ?compiler,
1400                target = ?target,
1401            ),
1402        ),
1403    )]
1404    pub fn std(&self, compiler: Compiler, target: TargetSelection) {
1405        // FIXME: make the `Std` step return some type-level "proof" that std was indeed built,
1406        // and then require passing that to all Cargo invocations that we do.
1407
1408        // The "stage 0" std is always precompiled and comes with the stage0 compiler, so we have
1409        // special logic for it, to avoid creating needless and confusing Std steps that don't
1410        // actually build anything.
1411        if compiler.stage == 0 {
1412            if target != compiler.host {
1413                panic!(
1414                    r"It is not possible to build the standard library for `{target}` using the stage0 compiler.
1415You have to build a stage1 compiler for `{}` first, and then use it to build a standard library for `{target}`.
1416",
1417                    compiler.host
1418                )
1419            }
1420
1421            // We still need to link the prebuilt standard library into the ephemeral stage0 sysroot
1422            self.ensure(StdLink::from_std(Std::new(compiler, target), compiler));
1423        } else {
1424            // This step both compiles the std and links it into the compiler's sysroot.
1425            // Yes, it's quite magical and side-effecty.. would be nice to refactor later.
1426            self.ensure(Std::new(compiler, target));
1427        }
1428    }
1429
1430    pub fn sysroot(&self, compiler: Compiler) -> PathBuf {
1431        self.ensure(compile::Sysroot::new(compiler))
1432    }
1433
1434    /// Returns the bindir for a compiler's sysroot.
1435    pub fn sysroot_target_bindir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1436        self.ensure(Libdir { compiler, target }).join(target).join("bin")
1437    }
1438
1439    /// Returns the libdir where the standard library and other artifacts are
1440    /// found for a compiler's sysroot.
1441    pub fn sysroot_target_libdir(&self, compiler: Compiler, target: TargetSelection) -> PathBuf {
1442        self.ensure(Libdir { compiler, target }).join(target).join("lib")
1443    }
1444
1445    pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
1446        self.sysroot_target_libdir(compiler, compiler.host).with_file_name("codegen-backends")
1447    }
1448
1449    /// Returns the compiler's libdir where it stores the dynamic libraries that
1450    /// it itself links against.
1451    ///
1452    /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
1453    /// Windows.
1454    pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
1455        if compiler.is_snapshot(self) {
1456            self.rustc_snapshot_libdir()
1457        } else {
1458            match self.config.libdir_relative() {
1459                Some(relative_libdir) if compiler.stage >= 1 => {
1460                    self.sysroot(compiler).join(relative_libdir)
1461                }
1462                _ => self.sysroot(compiler).join(libdir(compiler.host)),
1463            }
1464        }
1465    }
1466
1467    /// Returns the compiler's relative libdir where it stores the dynamic libraries that
1468    /// it itself links against.
1469    ///
1470    /// For example this returns `lib` on Unix and `bin` on
1471    /// Windows.
1472    pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
1473        if compiler.is_snapshot(self) {
1474            libdir(self.config.host_target).as_ref()
1475        } else {
1476            match self.config.libdir_relative() {
1477                Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1478                _ => libdir(compiler.host).as_ref(),
1479            }
1480        }
1481    }
1482
1483    /// Returns the compiler's relative libdir where the standard library and other artifacts are
1484    /// found for a compiler's sysroot.
1485    ///
1486    /// For example this returns `lib` on Unix and Windows.
1487    pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
1488        match self.config.libdir_relative() {
1489            Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
1490            _ if compiler.stage == 0 => &self.build.initial_relative_libdir,
1491            _ => Path::new("lib"),
1492        }
1493    }
1494
1495    pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
1496        let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
1497
1498        // Ensure that the downloaded LLVM libraries can be found.
1499        if self.config.llvm_from_ci {
1500            let ci_llvm_lib = self.out.join(compiler.host).join("ci-llvm").join("lib");
1501            dylib_dirs.push(ci_llvm_lib);
1502        }
1503
1504        dylib_dirs
1505    }
1506
1507    /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
1508    /// library lookup path.
1509    pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut BootstrapCommand) {
1510        // Windows doesn't need dylib path munging because the dlls for the
1511        // compiler live next to the compiler and the system will find them
1512        // automatically.
1513        if cfg!(any(windows, target_os = "cygwin")) {
1514            return;
1515        }
1516
1517        add_dylib_path(self.rustc_lib_paths(compiler), cmd);
1518    }
1519
1520    /// Gets a path to the compiler specified.
1521    pub fn rustc(&self, compiler: Compiler) -> PathBuf {
1522        if compiler.is_snapshot(self) {
1523            self.initial_rustc.clone()
1524        } else {
1525            self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
1526        }
1527    }
1528
1529    /// Gets the paths to all of the compiler's codegen backends.
1530    fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
1531        fs::read_dir(self.sysroot_codegen_backends(compiler))
1532            .into_iter()
1533            .flatten()
1534            .filter_map(Result::ok)
1535            .map(|entry| entry.path())
1536    }
1537
1538    pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
1539        self.ensure(tool::Rustdoc { compiler }).tool_path
1540    }
1541
1542    pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand {
1543        if run_compiler.stage == 0 {
1544            let cargo_clippy = self
1545                .config
1546                .initial_cargo_clippy
1547                .clone()
1548                .unwrap_or_else(|| self.build.config.download_clippy());
1549
1550            let mut cmd = command(cargo_clippy);
1551            cmd.env("CARGO", &self.initial_cargo);
1552            return cmd;
1553        }
1554
1555        let _ =
1556            self.ensure(tool::Clippy { compiler: run_compiler, target: self.build.host_target });
1557        let cargo_clippy = self
1558            .ensure(tool::CargoClippy { compiler: run_compiler, target: self.build.host_target });
1559        let mut dylib_path = helpers::dylib_path();
1560        dylib_path.insert(0, self.sysroot(run_compiler).join("lib"));
1561
1562        let mut cmd = command(cargo_clippy.tool_path);
1563        cmd.env(helpers::dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1564        cmd.env("CARGO", &self.initial_cargo);
1565        cmd
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        // Prepare the tools
1571        let miri =
1572            self.ensure(tool::Miri { compiler: run_compiler, target: self.build.host_target });
1573        let cargo_miri =
1574            self.ensure(tool::CargoMiri { compiler: run_compiler, target: self.build.host_target });
1575        // Invoke cargo-miri, make sure it can find miri and cargo.
1576        let mut cmd = command(cargo_miri.tool_path);
1577        cmd.env("MIRI", &miri.tool_path);
1578        cmd.env("CARGO", &self.initial_cargo);
1579        // Need to add the `run_compiler` libs. Those are the libs produces *by* `build_compiler`
1580        // in `tool::ToolBuild` step, so they match the Miri we just built. However this means they
1581        // are actually living one stage up, i.e. we are running `stage0-tools-bin/miri` with the
1582        // libraries in `stage1/lib`. This is an unfortunate off-by-1 caused (possibly) by the fact
1583        // that Miri doesn't have an "assemble" step like rustc does that would cross the stage boundary.
1584        // We can't use `add_rustc_lib_path` as that's a NOP on Windows but we do need these libraries
1585        // added to the PATH due to the stage mismatch.
1586        // Also see https://github.com/rust-lang/rust/pull/123192#issuecomment-2028901503.
1587        add_dylib_path(self.rustc_lib_paths(run_compiler), &mut cmd);
1588        cmd
1589    }
1590
1591    pub fn rustdoc_cmd(&self, compiler: Compiler) -> BootstrapCommand {
1592        let mut cmd = command(self.bootstrap_out.join("rustdoc"));
1593        cmd.env("RUSTC_STAGE", compiler.stage.to_string())
1594            .env("RUSTC_SYSROOT", self.sysroot(compiler))
1595            // Note that this is *not* the sysroot_libdir because rustdoc must be linked
1596            // equivalently to rustc.
1597            .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
1598            .env("CFG_RELEASE_CHANNEL", &self.config.channel)
1599            .env("RUSTDOC_REAL", self.rustdoc(compiler))
1600            .env("RUSTC_BOOTSTRAP", "1");
1601
1602        cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
1603
1604        if self.config.deny_warnings {
1605            cmd.arg("-Dwarnings");
1606        }
1607        cmd.arg("-Znormalize-docs");
1608        cmd.args(linker_args(self, compiler.host, LldThreads::Yes, compiler.stage));
1609        cmd
1610    }
1611
1612    /// Return the path to `llvm-config` for the target, if it exists.
1613    ///
1614    /// Note that this returns `None` if LLVM is disabled, or if we're in a
1615    /// check build or dry-run, where there's no need to build all of LLVM.
1616    ///
1617    /// FIXME(@kobzol)
1618    /// **WARNING**: This actually returns the **HOST** LLVM config, not LLVM config for the given
1619    /// *target*.
1620    pub fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
1621        if self.config.llvm_enabled(target) && self.kind != Kind::Check && !self.config.dry_run() {
1622            let llvm::LlvmResult { host_llvm_config, .. } = self.ensure(llvm::Llvm { target });
1623            if host_llvm_config.is_file() {
1624                return Some(host_llvm_config);
1625            }
1626        }
1627        None
1628    }
1629
1630    /// Updates all submodules, and exits with an error if submodule
1631    /// management is disabled and the submodule does not exist.
1632    pub fn require_and_update_all_submodules(&self) {
1633        for submodule in self.submodule_paths() {
1634            self.require_submodule(submodule, None);
1635        }
1636    }
1637
1638    /// Get all submodules from the src directory.
1639    pub fn submodule_paths(&self) -> &[String] {
1640        self.submodule_paths_cache.get_or_init(|| build_helper::util::parse_gitmodules(&self.src))
1641    }
1642
1643    /// Ensure that a given step is built, returning its output. This will
1644    /// cache the step, so it is safe (and good!) to call this as often as
1645    /// needed to ensure that all dependencies are built.
1646    pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1647        {
1648            let mut stack = self.stack.borrow_mut();
1649            for stack_step in stack.iter() {
1650                // should skip
1651                if stack_step.downcast_ref::<S>().is_none_or(|stack_step| *stack_step != step) {
1652                    continue;
1653                }
1654                let mut out = String::new();
1655                out += &format!("\n\nCycle in build detected when adding {step:?}\n");
1656                for el in stack.iter().rev() {
1657                    out += &format!("\t{el:?}\n");
1658                }
1659                panic!("{}", out);
1660            }
1661            if let Some(out) = self.cache.get(&step) {
1662                self.verbose_than(1, || println!("{}c {:?}", "  ".repeat(stack.len()), step));
1663
1664                return out;
1665            }
1666            self.verbose_than(1, || println!("{}> {:?}", "  ".repeat(stack.len()), step));
1667            stack.push(Box::new(step.clone()));
1668        }
1669
1670        #[cfg(feature = "build-metrics")]
1671        self.metrics.enter_step(&step, self);
1672
1673        let (out, dur) = {
1674            let start = Instant::now();
1675            let zero = Duration::new(0, 0);
1676            let parent = self.time_spent_on_dependencies.replace(zero);
1677            let out = step.clone().run(self);
1678            let dur = start.elapsed();
1679            let deps = self.time_spent_on_dependencies.replace(parent + dur);
1680            (out, dur.saturating_sub(deps))
1681        };
1682
1683        if self.config.print_step_timings && !self.config.dry_run() {
1684            let step_string = format!("{step:?}");
1685            let brace_index = step_string.find('{').unwrap_or(0);
1686            let type_string = type_name::<S>();
1687            println!(
1688                "[TIMING] {} {} -- {}.{:03}",
1689                &type_string.strip_prefix("bootstrap::").unwrap_or(type_string),
1690                &step_string[brace_index..],
1691                dur.as_secs(),
1692                dur.subsec_millis()
1693            );
1694        }
1695
1696        #[cfg(feature = "build-metrics")]
1697        self.metrics.exit_step(self);
1698
1699        {
1700            let mut stack = self.stack.borrow_mut();
1701            let cur_step = stack.pop().expect("step stack empty");
1702            assert_eq!(cur_step.downcast_ref(), Some(&step));
1703        }
1704        self.verbose_than(1, || println!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1705        self.cache.put(step, out.clone());
1706        out
1707    }
1708
1709    /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1710    /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1711    /// needed to ensure that all dependencies are build.
1712    pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1713        &'a self,
1714        step: S,
1715        kind: Kind,
1716    ) -> S::Output {
1717        let desc = StepDescription::from::<S>(kind);
1718        let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1719
1720        // Avoid running steps contained in --skip
1721        for pathset in &should_run.paths {
1722            if desc.is_excluded(self, pathset) {
1723                return None;
1724            }
1725        }
1726
1727        // Only execute if it's supposed to run as default
1728        if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1729    }
1730
1731    /// Checks if any of the "should_run" paths is in the `Builder` paths.
1732    pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1733        let desc = StepDescription::from::<S>(kind);
1734        let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1735
1736        for path in &self.paths {
1737            if should_run.paths.iter().any(|s| s.has(path, desc.kind))
1738                && !desc.is_excluded(
1739                    self,
1740                    &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1741                )
1742            {
1743                return true;
1744            }
1745        }
1746
1747        false
1748    }
1749
1750    pub(crate) fn maybe_open_in_browser<S: Step>(&self, path: impl AsRef<Path>) {
1751        if self.was_invoked_explicitly::<S>(Kind::Doc) {
1752            self.open_in_browser(path);
1753        } else {
1754            self.info(&format!("Doc path: {}", path.as_ref().display()));
1755        }
1756    }
1757
1758    pub(crate) fn open_in_browser(&self, path: impl AsRef<Path>) {
1759        let path = path.as_ref();
1760
1761        if self.config.dry_run() || !self.config.cmd.open() {
1762            self.info(&format!("Doc path: {}", path.display()));
1763            return;
1764        }
1765
1766        self.info(&format!("Opening doc {}", path.display()));
1767        if let Err(err) = opener::open(path) {
1768            self.info(&format!("{err}\n"));
1769        }
1770    }
1771
1772    pub fn exec_ctx(&self) -> &ExecutionContext {
1773        &self.config.exec_ctx
1774    }
1775}
1776
1777impl<'a> AsRef<ExecutionContext> for Builder<'a> {
1778    fn as_ref(&self) -> &ExecutionContext {
1779        self.exec_ctx()
1780    }
1781}