bootstrap/core/builder/
mod.rs

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