bootstrap/core/build_steps/
test.rs

1//! Build-and-run steps for `./x.py test` test fixtures
2//!
3//! `./x.py test` (aka [`Kind::Test`]) is currently allowed to reach build steps in other modules.
4//! However, this contains ~all test parts we expect people to be able to build and run locally.
5
6// (This file should be split up, but having tidy block all changes is not helpful.)
7// ignore-tidy-filelength
8
9use std::collections::HashSet;
10use std::env::split_paths;
11use std::ffi::{OsStr, OsString};
12use std::path::{Path, PathBuf};
13use std::{env, fs, iter};
14
15use build_helper::exit;
16
17use crate::core::build_steps::compile::{Std, run_cargo};
18use crate::core::build_steps::doc::{DocumentationFormat, prepare_doc_compiler};
19use crate::core::build_steps::gcc::{Gcc, GccTargetPair, add_cg_gcc_cargo_flags};
20use crate::core::build_steps::llvm::get_llvm_version;
21use crate::core::build_steps::run::{get_completion_paths, get_help_path};
22use crate::core::build_steps::synthetic_targets::MirOptPanicAbortSyntheticTarget;
23use crate::core::build_steps::test::compiletest::CompiletestMode;
24use crate::core::build_steps::tool::{
25    self, RustcPrivateCompilers, SourceType, TEST_FLOAT_PARSE_ALLOW_FEATURES, Tool,
26    ToolTargetBuildMode, get_tool_target_compiler,
27};
28use crate::core::build_steps::toolstate::ToolState;
29use crate::core::build_steps::{compile, dist, llvm};
30use crate::core::builder::{
31    self, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, StepMetadata,
32    crate_description,
33};
34use crate::core::config::TargetSelection;
35use crate::core::config::flags::{Subcommand, get_completion, top_level_help};
36use crate::core::{android, debuggers};
37use crate::utils::build_stamp::{self, BuildStamp};
38use crate::utils::exec::{BootstrapCommand, command};
39use crate::utils::helpers::{
40    self, LldThreads, add_dylib_path, add_rustdoc_cargo_linker_args, dylib_path, dylib_path_var,
41    linker_args, linker_flags, t, target_supports_cranelift_backend, up_to_date,
42};
43use crate::utils::render_tests::{add_flags_and_try_run_tests, try_run_tests};
44use crate::{CLang, CodegenBackendKind, DocTests, GitRepo, Mode, PathSet, envify};
45
46mod compiletest;
47
48/// Runs `cargo test` on various internal tools used by bootstrap.
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct CrateBootstrap {
51    path: PathBuf,
52    host: TargetSelection,
53}
54
55impl Step for CrateBootstrap {
56    type Output = ();
57    const IS_HOST: bool = true;
58
59    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
60        // This step is responsible for several different tool paths.
61        //
62        // By default, it will test all of them, but requesting specific tools on the command-line
63        // (e.g. `./x test src/tools/coverage-dump`) will test only the specified tools.
64        run.path("src/tools/jsondoclint")
65            .path("src/tools/replace-version-placeholder")
66            .path("src/tools/coverage-dump")
67            // We want `./x test tidy` to _run_ the tidy tool, not its tests.
68            // So we need a separate alias to test the tidy tool itself.
69            .alias("tidyselftest")
70    }
71
72    fn is_default_step(_builder: &Builder<'_>) -> bool {
73        true
74    }
75
76    fn make_run(run: RunConfig<'_>) {
77        // Create and ensure a separate instance of this step for each path
78        // that was selected on the command-line (or selected by default).
79        for path in run.paths {
80            let path = path.assert_single_path().path.clone();
81            run.builder.ensure(CrateBootstrap { host: run.target, path });
82        }
83    }
84
85    fn run(self, builder: &Builder<'_>) {
86        let bootstrap_host = builder.config.host_target;
87        let compiler = builder.compiler(0, bootstrap_host);
88        let mut path = self.path.to_str().unwrap();
89
90        // Map alias `tidyselftest` back to the actual crate path of tidy.
91        if path == "tidyselftest" {
92            path = "src/tools/tidy";
93        }
94
95        let cargo = tool::prepare_tool_cargo(
96            builder,
97            compiler,
98            Mode::ToolBootstrap,
99            bootstrap_host,
100            Kind::Test,
101            path,
102            SourceType::InTree,
103            &[],
104        );
105
106        let crate_name = path.rsplit_once('/').unwrap().1;
107        run_cargo_test(cargo, &[], &[], crate_name, bootstrap_host, builder);
108    }
109
110    fn metadata(&self) -> Option<StepMetadata> {
111        Some(
112            StepMetadata::test("crate-bootstrap", self.host)
113                .with_metadata(self.path.as_path().to_string_lossy().to_string()),
114        )
115    }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub struct Linkcheck {
120    host: TargetSelection,
121}
122
123impl Step for Linkcheck {
124    type Output = ();
125    const IS_HOST: bool = true;
126
127    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
128        run.path("src/tools/linkchecker")
129    }
130
131    fn is_default_step(builder: &Builder<'_>) -> bool {
132        builder.config.docs
133    }
134
135    fn make_run(run: RunConfig<'_>) {
136        run.builder.ensure(Linkcheck { host: run.target });
137    }
138
139    /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
140    ///
141    /// This tool in `src/tools` will verify the validity of all our links in the
142    /// documentation to ensure we don't have a bunch of dead ones.
143    fn run(self, builder: &Builder<'_>) {
144        let host = self.host;
145        let hosts = &builder.hosts;
146        let targets = &builder.targets;
147
148        // if we have different hosts and targets, some things may be built for
149        // the host (e.g. rustc) and others for the target (e.g. std). The
150        // documentation built for each will contain broken links to
151        // docs built for the other platform (e.g. rustc linking to cargo)
152        if (hosts != targets) && !hosts.is_empty() && !targets.is_empty() {
153            panic!(
154                "Linkcheck currently does not support builds with different hosts and targets.
155You can skip linkcheck with --skip src/tools/linkchecker"
156            );
157        }
158
159        builder.info(&format!("Linkcheck ({host})"));
160
161        // Test the linkchecker itself.
162        let bootstrap_host = builder.config.host_target;
163        let compiler = builder.compiler(0, bootstrap_host);
164
165        let cargo = tool::prepare_tool_cargo(
166            builder,
167            compiler,
168            Mode::ToolBootstrap,
169            bootstrap_host,
170            Kind::Test,
171            "src/tools/linkchecker",
172            SourceType::InTree,
173            &[],
174        );
175        run_cargo_test(cargo, &[], &[], "linkchecker self tests", bootstrap_host, builder);
176
177        if builder.doc_tests == DocTests::No {
178            return;
179        }
180
181        // Build all the default documentation.
182        builder.run_default_doc_steps();
183
184        // Build the linkchecker before calling `msg`, since GHA doesn't support nested groups.
185        let linkchecker = builder.tool_cmd(Tool::Linkchecker);
186
187        // Run the linkchecker.
188        let _guard = builder.msg_test("Linkcheck", bootstrap_host, 1);
189        let _time = helpers::timeit(builder);
190        linkchecker.delay_failure().arg(builder.out.join(host).join("doc")).run(builder);
191    }
192
193    fn metadata(&self) -> Option<StepMetadata> {
194        Some(StepMetadata::test("link-check", self.host))
195    }
196}
197
198fn check_if_tidy_is_installed(builder: &Builder<'_>) -> bool {
199    command("tidy")
200        .allow_failure()
201        .arg("--version")
202        // Cache the output to avoid running this command more than once (per builder).
203        .cached()
204        .run_capture_stdout(builder)
205        .is_success()
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Hash)]
209pub struct HtmlCheck {
210    target: TargetSelection,
211}
212
213impl Step for HtmlCheck {
214    type Output = ();
215    const IS_HOST: bool = true;
216
217    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
218        run.path("src/tools/html-checker")
219    }
220
221    fn is_default_step(builder: &Builder<'_>) -> bool {
222        check_if_tidy_is_installed(builder)
223    }
224
225    fn make_run(run: RunConfig<'_>) {
226        run.builder.ensure(HtmlCheck { target: run.target });
227    }
228
229    fn run(self, builder: &Builder<'_>) {
230        if !check_if_tidy_is_installed(builder) {
231            eprintln!("not running HTML-check tool because `tidy` is missing");
232            eprintln!(
233                "You need the HTML tidy tool https://www.html-tidy.org/, this tool is *not* part of the rust project and needs to be installed separately, for example via your package manager."
234            );
235            panic!("Cannot run html-check tests");
236        }
237        // Ensure that a few different kinds of documentation are available.
238        builder.run_default_doc_steps();
239        builder.ensure(crate::core::build_steps::doc::Rustc::for_stage(
240            builder,
241            builder.top_stage,
242            self.target,
243        ));
244
245        builder
246            .tool_cmd(Tool::HtmlChecker)
247            .delay_failure()
248            .arg(builder.doc_out(self.target))
249            .run(builder);
250    }
251
252    fn metadata(&self) -> Option<StepMetadata> {
253        Some(StepMetadata::test("html-check", self.target))
254    }
255}
256
257/// Builds cargo and then runs the `src/tools/cargotest` tool, which checks out
258/// some representative crate repositories and runs `cargo test` on them, in
259/// order to test cargo.
260#[derive(Debug, Clone, PartialEq, Eq, Hash)]
261pub struct Cargotest {
262    build_compiler: Compiler,
263    host: TargetSelection,
264}
265
266impl Step for Cargotest {
267    type Output = ();
268    const IS_HOST: bool = true;
269
270    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
271        run.path("src/tools/cargotest")
272    }
273
274    fn make_run(run: RunConfig<'_>) {
275        if run.builder.top_stage == 0 {
276            eprintln!(
277                "ERROR: running cargotest with stage 0 is currently unsupported. Use at least stage 1."
278            );
279            exit!(1);
280        }
281        // We want to build cargo stage N (where N == top_stage), and rustc stage N,
282        // and test both of these together.
283        // So we need to get a build compiler stage N-1 to build the stage N components.
284        run.builder.ensure(Cargotest {
285            build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.target),
286            host: run.target,
287        });
288    }
289
290    /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
291    ///
292    /// This tool in `src/tools` will check out a few Rust projects and run `cargo
293    /// test` to ensure that we don't regress the test suites there.
294    fn run(self, builder: &Builder<'_>) {
295        // cargotest's staging has several pieces:
296        // consider ./x test cargotest --stage=2.
297        //
298        // The test goal is to exercise a (stage 2 cargo, stage 2 rustc) pair through a stage 2
299        // cargotest tool.
300        // To produce the stage 2 cargo and cargotest, we need to do so with the stage 1 rustc and std.
301        // Importantly, the stage 2 rustc being tested (`tested_compiler`) via stage 2 cargotest is
302        // the rustc built by an earlier stage 1 rustc (the build_compiler). These are two different
303        // compilers!
304        let cargo =
305            builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host));
306        let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host);
307        builder.std(tested_compiler, self.host);
308
309        // Note that this is a short, cryptic, and not scoped directory name. This
310        // is currently to minimize the length of path on Windows where we otherwise
311        // quickly run into path name limit constraints.
312        let out_dir = builder.out.join("ct");
313        t!(fs::create_dir_all(&out_dir));
314
315        let _time = helpers::timeit(builder);
316        let mut cmd = builder.tool_cmd(Tool::CargoTest);
317        cmd.arg(&cargo.tool_path)
318            .arg(&out_dir)
319            .args(builder.config.test_args())
320            .env("RUSTC", builder.rustc(tested_compiler))
321            .env("RUSTDOC", builder.rustdoc_for_compiler(tested_compiler));
322        add_rustdoc_cargo_linker_args(&mut cmd, builder, tested_compiler.host, LldThreads::No);
323        cmd.delay_failure().run(builder);
324    }
325
326    fn metadata(&self) -> Option<StepMetadata> {
327        Some(StepMetadata::test("cargotest", self.host).stage(self.build_compiler.stage + 1))
328    }
329}
330
331/// Runs `cargo test` for cargo itself.
332/// We label these tests as "cargo self-tests".
333#[derive(Debug, Clone, PartialEq, Eq, Hash)]
334pub struct Cargo {
335    build_compiler: Compiler,
336    host: TargetSelection,
337}
338
339impl Cargo {
340    const CRATE_PATH: &str = "src/tools/cargo";
341}
342
343impl Step for Cargo {
344    type Output = ();
345    const IS_HOST: bool = true;
346
347    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
348        run.path(Self::CRATE_PATH)
349    }
350
351    fn make_run(run: RunConfig<'_>) {
352        run.builder.ensure(Cargo {
353            build_compiler: get_tool_target_compiler(
354                run.builder,
355                ToolTargetBuildMode::Build(run.target),
356            ),
357            host: run.target,
358        });
359    }
360
361    /// Runs `cargo test` for `cargo` packaged with Rust.
362    fn run(self, builder: &Builder<'_>) {
363        // When we do a "stage 1 cargo self-test", it means that we test the stage 1 rustc
364        // using stage 1 cargo. So we actually build cargo using the stage 0 compiler, and then
365        // run its tests against the stage 1 compiler (called `tested_compiler` below).
366        builder.ensure(tool::Cargo::from_build_compiler(self.build_compiler, self.host));
367
368        let tested_compiler = builder.compiler(self.build_compiler.stage + 1, self.host);
369        builder.std(tested_compiler, self.host);
370        // We also need to build rustdoc for cargo tests
371        // It will be located in the bindir of `tested_compiler`, so we don't need to explicitly
372        // pass its path to Cargo.
373        builder.rustdoc_for_compiler(tested_compiler);
374
375        let cargo = tool::prepare_tool_cargo(
376            builder,
377            self.build_compiler,
378            Mode::ToolTarget,
379            self.host,
380            Kind::Test,
381            Self::CRATE_PATH,
382            SourceType::Submodule,
383            &[],
384        );
385
386        // NOTE: can't use `run_cargo_test` because we need to overwrite `PATH`
387        let mut cargo = prepare_cargo_test(cargo, &[], &[], self.host, builder);
388
389        // Don't run cross-compile tests, we may not have cross-compiled libstd libs
390        // available.
391        cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
392        // Forcibly disable tests using nightly features since any changes to
393        // those features won't be able to land.
394        cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
395
396        // Configure PATH to find the right rustc. NB. we have to use PATH
397        // and not RUSTC because the Cargo test suite has tests that will
398        // fail if rustc is not spelled `rustc`.
399        cargo.env("PATH", bin_path_for_cargo(builder, tested_compiler));
400
401        // The `cargo` command configured above has dylib dir path set to the `build_compiler`'s
402        // libdir. That causes issues in cargo test, because the programs that cargo compiles are
403        // incorrectly picking that libdir, even though they should be picking the
404        // `tested_compiler`'s libdir. We thus have to override the precedence here.
405        let mut existing_dylib_paths = cargo
406            .get_envs()
407            .find(|(k, _)| *k == OsStr::new(dylib_path_var()))
408            .and_then(|(_, v)| v)
409            .map(|value| split_paths(value).collect::<Vec<PathBuf>>())
410            .unwrap_or_default();
411        existing_dylib_paths.insert(0, builder.rustc_libdir(tested_compiler));
412        add_dylib_path(existing_dylib_paths, &mut cargo);
413
414        // Cargo's test suite uses `CARGO_RUSTC_CURRENT_DIR` to determine the path that `file!` is
415        // relative to. Cargo no longer sets this env var, so we have to do that. This has to be the
416        // same value as `-Zroot-dir`.
417        cargo.env("CARGO_RUSTC_CURRENT_DIR", builder.src.display().to_string());
418
419        #[cfg(feature = "build-metrics")]
420        builder.metrics.begin_test_suite(
421            build_helper::metrics::TestSuiteMetadata::CargoPackage {
422                crates: vec!["cargo".into()],
423                target: self.host.triple.to_string(),
424                host: self.host.triple.to_string(),
425                stage: self.build_compiler.stage + 1,
426            },
427            builder,
428        );
429
430        let _time = helpers::timeit(builder);
431        add_flags_and_try_run_tests(builder, &mut cargo);
432    }
433
434    fn metadata(&self) -> Option<StepMetadata> {
435        Some(StepMetadata::test("cargo", self.host).built_by(self.build_compiler))
436    }
437}
438
439#[derive(Debug, Clone, PartialEq, Eq, Hash)]
440pub struct RustAnalyzer {
441    compilers: RustcPrivateCompilers,
442}
443
444impl Step for RustAnalyzer {
445    type Output = ();
446    const IS_HOST: bool = true;
447
448    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
449        run.path("src/tools/rust-analyzer")
450    }
451
452    fn is_default_step(_builder: &Builder<'_>) -> bool {
453        true
454    }
455
456    fn make_run(run: RunConfig<'_>) {
457        run.builder.ensure(Self {
458            compilers: RustcPrivateCompilers::new(
459                run.builder,
460                run.builder.top_stage,
461                run.builder.host_target,
462            ),
463        });
464    }
465
466    /// Runs `cargo test` for rust-analyzer
467    fn run(self, builder: &Builder<'_>) {
468        let build_compiler = self.compilers.build_compiler();
469        let target = self.compilers.target();
470
471        // NOTE: rust-analyzer repo currently (as of 2025-12-11) does not run tests against 32-bit
472        // targets, so we also don't run them in rust-lang/rust CI (because that will just mean that
473        // subtree syncs will keep getting 32-bit-specific failures that are not observed in
474        // rust-analyzer repo CI).
475        //
476        // Some 32-bit specific failures include e.g. target pointer width specific hashes.
477
478        // FIXME: eventually, we should probably reduce the amount of target tuple substring
479        // matching in bootstrap.
480        if target.starts_with("i686") {
481            return;
482        }
483
484        let mut cargo = tool::prepare_tool_cargo(
485            builder,
486            build_compiler,
487            Mode::ToolRustcPrivate,
488            target,
489            Kind::Test,
490            "src/tools/rust-analyzer",
491            SourceType::InTree,
492            &["in-rust-tree".to_owned()],
493        );
494        cargo.allow_features(tool::RustAnalyzer::ALLOW_FEATURES);
495
496        // N.B. it turns out _setting_ `CARGO_WORKSPACE_DIR` actually somehow breaks `expect-test`,
497        // even though previously we actually needed to set that hack to allow `expect-test` to
498        // correctly discover the r-a workspace instead of the outer r-l/r workspace.
499
500        // FIXME: RA's test suite tries to write to the source directory, that can't work in Rust CI
501        // without properly wiring up the writable test dir.
502        cargo.env("SKIP_SLOW_TESTS", "1");
503
504        // NOTE: we need to skip `src/tools/rust-analyzer/xtask` as they seem to exercise rustup /
505        // stable rustfmt.
506        //
507        // NOTE: you can only skip a specific workspace package via `--exclude=...` if you *also*
508        // specify `--workspace`.
509        cargo.arg("--workspace");
510        cargo.arg("--exclude=xtask");
511
512        let mut skip_tests = vec![];
513
514        // NOTE: the following test skips is a bit cheeky in that it assumes there are no
515        // identically named tests across different r-a packages, where we want to run the
516        // identically named test in one package but not another. If we want to support that use
517        // case, we'd have to run the r-a tests in two batches (with one excluding the package that
518        // we *don't* want to run the test for, and the other batch including).
519
520        // Across all platforms.
521        skip_tests.extend_from_slice(&[
522            // FIXME: this test wants to find a `rustc`. We need to provide it with a path to staged
523            // in-tree `rustc`, but setting `RUSTC` env var requires some reworking of bootstrap.
524            "tests::smoke_test_real_sysroot_cargo",
525            // NOTE: part of `smol-str` test suite; this tries to access a stable rustfmt from the
526            // environment, which is not something we want to do.
527            "check_code_formatting",
528        ]);
529
530        let skip_tests = skip_tests.iter().map(|name| format!("--skip={name}")).collect::<Vec<_>>();
531        let skip_tests = skip_tests.iter().map(|s| s.as_str()).collect::<Vec<_>>();
532
533        cargo.add_rustc_lib_path(builder);
534        run_cargo_test(cargo, skip_tests.as_slice(), &[], "rust-analyzer", target, builder);
535    }
536
537    fn metadata(&self) -> Option<StepMetadata> {
538        Some(
539            StepMetadata::test("rust-analyzer", self.compilers.target())
540                .built_by(self.compilers.build_compiler()),
541        )
542    }
543}
544
545/// Runs `cargo test` for rustfmt.
546#[derive(Debug, Clone, PartialEq, Eq, Hash)]
547pub struct Rustfmt {
548    compilers: RustcPrivateCompilers,
549}
550
551impl Step for Rustfmt {
552    type Output = ();
553    const IS_HOST: bool = true;
554
555    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
556        run.path("src/tools/rustfmt")
557    }
558
559    fn make_run(run: RunConfig<'_>) {
560        run.builder.ensure(Rustfmt {
561            compilers: RustcPrivateCompilers::new(
562                run.builder,
563                run.builder.top_stage,
564                run.builder.host_target,
565            ),
566        });
567    }
568
569    /// Runs `cargo test` for rustfmt.
570    fn run(self, builder: &Builder<'_>) {
571        let build_compiler = self.compilers.build_compiler();
572        let target = self.compilers.target();
573
574        let mut cargo = tool::prepare_tool_cargo(
575            builder,
576            build_compiler,
577            Mode::ToolRustcPrivate,
578            target,
579            Kind::Test,
580            "src/tools/rustfmt",
581            SourceType::InTree,
582            &[],
583        );
584
585        let dir = testdir(builder, target);
586        t!(fs::create_dir_all(&dir));
587        cargo.env("RUSTFMT_TEST_DIR", dir);
588
589        cargo.add_rustc_lib_path(builder);
590
591        run_cargo_test(cargo, &[], &[], "rustfmt", target, builder);
592    }
593
594    fn metadata(&self) -> Option<StepMetadata> {
595        Some(
596            StepMetadata::test("rustfmt", self.compilers.target())
597                .built_by(self.compilers.build_compiler()),
598        )
599    }
600}
601
602#[derive(Debug, Clone, PartialEq, Eq, Hash)]
603pub struct Miri {
604    target: TargetSelection,
605}
606
607impl Miri {
608    /// Run `cargo miri setup` for the given target, return where the Miri sysroot was put.
609    pub fn build_miri_sysroot(
610        builder: &Builder<'_>,
611        compiler: Compiler,
612        target: TargetSelection,
613    ) -> PathBuf {
614        let miri_sysroot = builder.out.join(compiler.host).join("miri-sysroot");
615        let mut cargo = builder::Cargo::new(
616            builder,
617            compiler,
618            Mode::Std,
619            SourceType::Submodule,
620            target,
621            Kind::MiriSetup,
622        );
623
624        // Tell `cargo miri setup` where to find the sources.
625        cargo.env("MIRI_LIB_SRC", builder.src.join("library"));
626        // Tell it where to put the sysroot.
627        cargo.env("MIRI_SYSROOT", &miri_sysroot);
628
629        let mut cargo = BootstrapCommand::from(cargo);
630        let _guard =
631            builder.msg(Kind::Build, "miri sysroot", Mode::ToolRustcPrivate, compiler, target);
632        cargo.run(builder);
633
634        // # Determine where Miri put its sysroot.
635        // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
636        // (We do this separately from the above so that when the setup actually
637        // happens we get some output.)
638        // We re-use the `cargo` from above.
639        cargo.arg("--print-sysroot");
640
641        builder.do_if_verbose(|| println!("running: {cargo:?}"));
642        let stdout = cargo.run_capture_stdout(builder).stdout();
643        // Output is "<sysroot>\n".
644        let sysroot = stdout.trim_end();
645        builder.do_if_verbose(|| println!("`cargo miri setup --print-sysroot` said: {sysroot:?}"));
646        PathBuf::from(sysroot)
647    }
648}
649
650impl Step for Miri {
651    type Output = ();
652
653    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
654        run.path("src/tools/miri")
655    }
656
657    fn make_run(run: RunConfig<'_>) {
658        run.builder.ensure(Miri { target: run.target });
659    }
660
661    /// Runs `cargo test` for miri.
662    fn run(self, builder: &Builder<'_>) {
663        let host = builder.build.host_target;
664        let target = self.target;
665        let stage = builder.top_stage;
666        if stage == 0 {
667            eprintln!("miri cannot be tested at stage 0");
668            std::process::exit(1);
669        }
670
671        // This compiler runs on the host, we'll just use it for the target.
672        let compilers = RustcPrivateCompilers::new(builder, stage, host);
673
674        // Build our tools.
675        let miri = builder.ensure(tool::Miri::from_compilers(compilers));
676        // the ui tests also assume cargo-miri has been built
677        builder.ensure(tool::CargoMiri::from_compilers(compilers));
678
679        let target_compiler = compilers.target_compiler();
680
681        // We also need sysroots, for Miri and for the host (the latter for build scripts).
682        // This is for the tests so everything is done with the target compiler.
683        let miri_sysroot = Miri::build_miri_sysroot(builder, target_compiler, target);
684        builder.std(target_compiler, host);
685        let host_sysroot = builder.sysroot(target_compiler);
686
687        // Miri has its own "target dir" for ui test dependencies. Make sure it gets cleared when
688        // the sysroot gets rebuilt, to avoid "found possibly newer version of crate `std`" errors.
689        if !builder.config.dry_run() {
690            // This has to match `CARGO_TARGET_TMPDIR` in Miri's `ui.rs`.
691            // This means we need `host` here as that's the target `ui.rs` is built for.
692            let ui_test_dep_dir = builder
693                .stage_out(miri.build_compiler, Mode::ToolStd)
694                .join(host)
695                .join("tmp")
696                .join("miri_ui");
697            // The mtime of `miri_sysroot` changes when the sysroot gets rebuilt (also see
698            // <https://github.com/RalfJung/rustc-build-sysroot/commit/10ebcf60b80fe2c3dc765af0ff19fdc0da4b7466>).
699            // We can hence use that directly as a signal to clear the ui test dir.
700            build_stamp::clear_if_dirty(builder, &ui_test_dep_dir, &miri_sysroot);
701        }
702
703        // Run `cargo test`.
704        // This is with the Miri crate, so it uses the host compiler.
705        let mut cargo = tool::prepare_tool_cargo(
706            builder,
707            miri.build_compiler,
708            Mode::ToolRustcPrivate,
709            host,
710            Kind::Test,
711            "src/tools/miri",
712            SourceType::InTree,
713            &[],
714        );
715
716        cargo.add_rustc_lib_path(builder);
717
718        // We can NOT use `run_cargo_test` since Miri's integration tests do not use the usual test
719        // harness and therefore do not understand the flags added by `add_flags_and_try_run_test`.
720        let mut cargo = prepare_cargo_test(cargo, &[], &[], host, builder);
721
722        // miri tests need to know about the stage sysroot
723        cargo.env("MIRI_SYSROOT", &miri_sysroot);
724        cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);
725
726        // Set the target.
727        cargo.env("MIRI_TEST_TARGET", target.rustc_target_arg());
728
729        {
730            let _guard = builder.msg_test("miri", target, target_compiler.stage);
731            let _time = helpers::timeit(builder);
732            cargo.run(builder);
733        }
734
735        // Run it again for mir-opt-level 4 to catch some miscompilations.
736        if builder.config.test_args().is_empty() {
737            cargo.env("MIRIFLAGS", "-O -Zmir-opt-level=4 -Cdebug-assertions=yes");
738            // Optimizations can change backtraces
739            cargo.env("MIRI_SKIP_UI_CHECKS", "1");
740            // `MIRI_SKIP_UI_CHECKS` and `RUSTC_BLESS` are incompatible
741            cargo.env_remove("RUSTC_BLESS");
742            // Optimizations can change error locations and remove UB so don't run `fail` tests.
743            cargo.args(["tests/pass", "tests/panic"]);
744
745            {
746                let _guard =
747                    builder.msg_test("miri (mir-opt-level 4)", target, target_compiler.stage);
748                let _time = helpers::timeit(builder);
749                cargo.run(builder);
750            }
751        }
752    }
753}
754
755/// Runs `cargo miri test` to demonstrate that `src/tools/miri/cargo-miri`
756/// works and that libtest works under miri.
757#[derive(Debug, Clone, PartialEq, Eq, Hash)]
758pub struct CargoMiri {
759    target: TargetSelection,
760}
761
762impl Step for CargoMiri {
763    type Output = ();
764
765    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
766        run.path("src/tools/miri/cargo-miri")
767    }
768
769    fn make_run(run: RunConfig<'_>) {
770        run.builder.ensure(CargoMiri { target: run.target });
771    }
772
773    /// Tests `cargo miri test`.
774    fn run(self, builder: &Builder<'_>) {
775        let host = builder.build.host_target;
776        let target = self.target;
777        let stage = builder.top_stage;
778        if stage == 0 {
779            eprintln!("cargo-miri cannot be tested at stage 0");
780            std::process::exit(1);
781        }
782
783        // This compiler runs on the host, we'll just use it for the target.
784        let build_compiler = builder.compiler(stage, host);
785
786        // Run `cargo miri test`.
787        // This is just a smoke test (Miri's own CI invokes this in a bunch of different ways and ensures
788        // that we get the desired output), but that is sufficient to make sure that the libtest harness
789        // itself executes properly under Miri, and that all the logic in `cargo-miri` does not explode.
790        let mut cargo = tool::prepare_tool_cargo(
791            builder,
792            build_compiler,
793            Mode::ToolStd, // it's unclear what to use here, we're not building anything just doing a smoke test!
794            target,
795            Kind::MiriTest,
796            "src/tools/miri/test-cargo-miri",
797            SourceType::Submodule,
798            &[],
799        );
800
801        // We're not using `prepare_cargo_test` so we have to do this ourselves.
802        // (We're not using that as the test-cargo-miri crate is not known to bootstrap.)
803        match builder.doc_tests {
804            DocTests::Yes => {}
805            DocTests::No => {
806                cargo.args(["--lib", "--bins", "--examples", "--tests", "--benches"]);
807            }
808            DocTests::Only => {
809                cargo.arg("--doc");
810            }
811        }
812        cargo.arg("--").args(builder.config.test_args());
813
814        // Finally, run everything.
815        let mut cargo = BootstrapCommand::from(cargo);
816        {
817            let _guard = builder.msg_test("cargo-miri", target, stage);
818            let _time = helpers::timeit(builder);
819            cargo.run(builder);
820        }
821    }
822}
823
824#[derive(Debug, Clone, PartialEq, Eq, Hash)]
825pub struct CompiletestTest {
826    host: TargetSelection,
827}
828
829impl Step for CompiletestTest {
830    type Output = ();
831
832    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
833        run.path("src/tools/compiletest")
834    }
835
836    fn make_run(run: RunConfig<'_>) {
837        run.builder.ensure(CompiletestTest { host: run.target });
838    }
839
840    /// Runs `cargo test` for compiletest.
841    fn run(self, builder: &Builder<'_>) {
842        let host = self.host;
843
844        // Now that compiletest uses only stable Rust, building it always uses
845        // the stage 0 compiler. However, some of its unit tests need to be able
846        // to query information from an in-tree compiler, so we treat `--stage`
847        // as selecting the stage of that secondary compiler.
848
849        if builder.top_stage == 0 && !builder.config.compiletest_allow_stage0 {
850            eprintln!("\
851ERROR: `--stage 0` causes compiletest to query information from the stage0 (precompiled) compiler, instead of the in-tree compiler, which can cause some tests to fail inappropriately
852NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `--set build.compiletest-allow-stage0=true`."
853            );
854            crate::exit!(1);
855        }
856
857        let bootstrap_compiler = builder.compiler(0, host);
858        let staged_compiler = builder.compiler(builder.top_stage, host);
859
860        let mut cargo = tool::prepare_tool_cargo(
861            builder,
862            bootstrap_compiler,
863            Mode::ToolBootstrap,
864            host,
865            Kind::Test,
866            "src/tools/compiletest",
867            SourceType::InTree,
868            &[],
869        );
870
871        // Used for `compiletest` self-tests to have the path to the *staged* compiler. Getting this
872        // right is important, as `compiletest` is intended to only support one target spec JSON
873        // format, namely that of the staged compiler.
874        cargo.env("TEST_RUSTC", builder.rustc(staged_compiler));
875
876        run_cargo_test(cargo, &[], &[], "compiletest self test", host, builder);
877    }
878}
879
880#[derive(Debug, Clone, PartialEq, Eq, Hash)]
881pub struct Clippy {
882    compilers: RustcPrivateCompilers,
883}
884
885impl Step for Clippy {
886    type Output = ();
887    const IS_HOST: bool = true;
888
889    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
890        run.suite_path("src/tools/clippy/tests").path("src/tools/clippy")
891    }
892
893    fn is_default_step(_builder: &Builder<'_>) -> bool {
894        false
895    }
896
897    fn make_run(run: RunConfig<'_>) {
898        run.builder.ensure(Clippy {
899            compilers: RustcPrivateCompilers::new(
900                run.builder,
901                run.builder.top_stage,
902                run.builder.host_target,
903            ),
904        });
905    }
906
907    /// Runs `cargo test` for clippy.
908    fn run(self, builder: &Builder<'_>) {
909        let target = self.compilers.target();
910
911        // We need to carefully distinguish the compiler that builds clippy, and the compiler
912        // that is linked into the clippy being tested. `target_compiler` is the latter,
913        // and it must also be used by clippy's test runner to build tests and their dependencies.
914        let target_compiler = self.compilers.target_compiler();
915        let build_compiler = self.compilers.build_compiler();
916
917        let mut cargo = tool::prepare_tool_cargo(
918            builder,
919            build_compiler,
920            Mode::ToolRustcPrivate,
921            target,
922            Kind::Test,
923            "src/tools/clippy",
924            SourceType::InTree,
925            &[],
926        );
927
928        cargo.env("RUSTC_TEST_SUITE", builder.rustc(build_compiler));
929        cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(build_compiler));
930        let host_libs =
931            builder.stage_out(build_compiler, Mode::ToolRustcPrivate).join(builder.cargo_dir());
932        cargo.env("HOST_LIBS", host_libs);
933
934        // Build the standard library that the tests can use.
935        builder.std(target_compiler, target);
936        cargo.env("TEST_SYSROOT", builder.sysroot(target_compiler));
937        cargo.env("TEST_RUSTC", builder.rustc(target_compiler));
938        cargo.env("TEST_RUSTC_LIB", builder.rustc_libdir(target_compiler));
939
940        // Collect paths of tests to run
941        'partially_test: {
942            let paths = &builder.config.paths[..];
943            let mut test_names = Vec::new();
944            for path in paths {
945                if let Some(path) =
946                    helpers::is_valid_test_suite_arg(path, "src/tools/clippy/tests", builder)
947                {
948                    test_names.push(path);
949                } else if path.ends_with("src/tools/clippy") {
950                    // When src/tools/clippy is called directly, all tests should be run.
951                    break 'partially_test;
952                }
953            }
954            cargo.env("TESTNAME", test_names.join(","));
955        }
956
957        cargo.add_rustc_lib_path(builder);
958        let cargo = prepare_cargo_test(cargo, &[], &[], target, builder);
959
960        let _guard = builder.msg_test("clippy", target, target_compiler.stage);
961
962        // Clippy reports errors if it blessed the outputs
963        if cargo.allow_failure().run(builder) {
964            // The tests succeeded; nothing to do.
965            return;
966        }
967
968        if !builder.config.cmd.bless() {
969            crate::exit!(1);
970        }
971    }
972
973    fn metadata(&self) -> Option<StepMetadata> {
974        Some(
975            StepMetadata::test("clippy", self.compilers.target())
976                .built_by(self.compilers.build_compiler()),
977        )
978    }
979}
980
981fn bin_path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
982    let path = builder.sysroot(compiler).join("bin");
983    let old_path = env::var_os("PATH").unwrap_or_default();
984    env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
985}
986
987/// Run the rustdoc-themes tool to test a given compiler.
988#[derive(Debug, Clone, Hash, PartialEq, Eq)]
989pub struct RustdocTheme {
990    /// The compiler (more accurately, its rustdoc) that we test.
991    test_compiler: Compiler,
992}
993
994impl Step for RustdocTheme {
995    type Output = ();
996    const IS_HOST: bool = true;
997
998    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
999        run.path("src/tools/rustdoc-themes")
1000    }
1001
1002    fn is_default_step(_builder: &Builder<'_>) -> bool {
1003        true
1004    }
1005
1006    fn make_run(run: RunConfig<'_>) {
1007        let test_compiler = run.builder.compiler(run.builder.top_stage, run.target);
1008
1009        run.builder.ensure(RustdocTheme { test_compiler });
1010    }
1011
1012    fn run(self, builder: &Builder<'_>) {
1013        let rustdoc = builder.bootstrap_out.join("rustdoc");
1014        let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
1015        cmd.arg(rustdoc.to_str().unwrap())
1016            .arg(builder.src.join("src/librustdoc/html/static/css/rustdoc.css").to_str().unwrap())
1017            .env("RUSTC_STAGE", self.test_compiler.stage.to_string())
1018            .env("RUSTC_SYSROOT", builder.sysroot(self.test_compiler))
1019            .env(
1020                "RUSTDOC_LIBDIR",
1021                builder.sysroot_target_libdir(self.test_compiler, self.test_compiler.host),
1022            )
1023            .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1024            .env("RUSTDOC_REAL", builder.rustdoc_for_compiler(self.test_compiler))
1025            .env("RUSTC_BOOTSTRAP", "1");
1026        cmd.args(linker_args(builder, self.test_compiler.host, LldThreads::No));
1027
1028        cmd.delay_failure().run(builder);
1029    }
1030
1031    fn metadata(&self) -> Option<StepMetadata> {
1032        Some(
1033            StepMetadata::test("rustdoc-theme", self.test_compiler.host)
1034                .stage(self.test_compiler.stage),
1035        )
1036    }
1037}
1038
1039/// Test rustdoc JS for the standard library.
1040#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1041pub struct RustdocJSStd {
1042    /// Compiler that will build the standary library.
1043    build_compiler: Compiler,
1044    target: TargetSelection,
1045}
1046
1047impl Step for RustdocJSStd {
1048    type Output = ();
1049    const IS_HOST: bool = true;
1050
1051    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1052        run.suite_path("tests/rustdoc-js-std")
1053    }
1054
1055    fn is_default_step(builder: &Builder<'_>) -> bool {
1056        builder.config.nodejs.is_some()
1057    }
1058
1059    fn make_run(run: RunConfig<'_>) {
1060        run.builder.ensure(RustdocJSStd {
1061            build_compiler: run.builder.compiler(run.builder.top_stage, run.builder.host_target),
1062            target: run.target,
1063        });
1064    }
1065
1066    fn run(self, builder: &Builder<'_>) {
1067        let nodejs =
1068            builder.config.nodejs.as_ref().expect("need nodejs to run rustdoc-js-std tests");
1069        let mut command = command(nodejs);
1070        command
1071            .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
1072            .arg("--crate-name")
1073            .arg("std")
1074            .arg("--resource-suffix")
1075            .arg(&builder.version)
1076            .arg("--doc-folder")
1077            .arg(builder.doc_out(self.target))
1078            .arg("--test-folder")
1079            .arg(builder.src.join("tests/rustdoc-js-std"));
1080        for path in &builder.paths {
1081            if let Some(p) = helpers::is_valid_test_suite_arg(path, "tests/rustdoc-js-std", builder)
1082            {
1083                if !p.ends_with(".js") {
1084                    eprintln!("A non-js file was given: `{}`", path.display());
1085                    panic!("Cannot run rustdoc-js-std tests");
1086                }
1087                command.arg("--test-file").arg(path);
1088            }
1089        }
1090        builder.ensure(crate::core::build_steps::doc::Std::from_build_compiler(
1091            self.build_compiler,
1092            self.target,
1093            DocumentationFormat::Html,
1094        ));
1095        let _guard = builder.msg_test("rustdoc-js-std", self.target, self.build_compiler.stage);
1096        command.run(builder);
1097    }
1098
1099    fn metadata(&self) -> Option<StepMetadata> {
1100        Some(StepMetadata::test("rustdoc-js-std", self.target).stage(self.build_compiler.stage))
1101    }
1102}
1103
1104#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1105pub struct RustdocJSNotStd {
1106    pub target: TargetSelection,
1107    pub compiler: Compiler,
1108}
1109
1110impl Step for RustdocJSNotStd {
1111    type Output = ();
1112    const IS_HOST: bool = true;
1113
1114    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1115        run.suite_path("tests/rustdoc-js")
1116    }
1117
1118    fn is_default_step(builder: &Builder<'_>) -> bool {
1119        builder.config.nodejs.is_some()
1120    }
1121
1122    fn make_run(run: RunConfig<'_>) {
1123        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1124        run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
1125    }
1126
1127    fn run(self, builder: &Builder<'_>) {
1128        builder.ensure(Compiletest {
1129            test_compiler: self.compiler,
1130            target: self.target,
1131            mode: CompiletestMode::RustdocJs,
1132            suite: "rustdoc-js",
1133            path: "tests/rustdoc-js",
1134            compare_mode: None,
1135        });
1136    }
1137}
1138
1139fn get_browser_ui_test_version_inner(
1140    builder: &Builder<'_>,
1141    yarn: &Path,
1142    global: bool,
1143) -> Option<String> {
1144    let mut command = command(yarn);
1145    command
1146        .arg("--cwd")
1147        .arg(&builder.build.out)
1148        .arg("list")
1149        .arg("--parseable")
1150        .arg("--long")
1151        .arg("--depth=0");
1152    if global {
1153        command.arg("--global");
1154    }
1155    // Cache the command output so that `test::RustdocGUI` only performs these
1156    // command-line probes once.
1157    let lines = command.allow_failure().cached().run_capture(builder).stdout();
1158    lines
1159        .lines()
1160        .find_map(|l| l.split(':').nth(1)?.strip_prefix("browser-ui-test@"))
1161        .map(|v| v.to_owned())
1162}
1163
1164fn get_browser_ui_test_version(builder: &Builder<'_>) -> Option<String> {
1165    let yarn = builder.config.yarn.as_deref()?;
1166    get_browser_ui_test_version_inner(builder, yarn, false)
1167        .or_else(|| get_browser_ui_test_version_inner(builder, yarn, true))
1168}
1169
1170/// Run GUI tests on a given rustdoc.
1171#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1172pub struct RustdocGUI {
1173    /// The compiler whose rustdoc we are testing.
1174    test_compiler: Compiler,
1175    target: TargetSelection,
1176}
1177
1178impl Step for RustdocGUI {
1179    type Output = ();
1180    const IS_HOST: bool = true;
1181
1182    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1183        run.suite_path("tests/rustdoc-gui")
1184    }
1185
1186    fn is_default_step(builder: &Builder<'_>) -> bool {
1187        builder.config.nodejs.is_some()
1188            && builder.doc_tests != DocTests::Only
1189            && get_browser_ui_test_version(builder).is_some()
1190    }
1191
1192    fn make_run(run: RunConfig<'_>) {
1193        let test_compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1194        run.builder.ensure(RustdocGUI { test_compiler, target: run.target });
1195    }
1196
1197    fn run(self, builder: &Builder<'_>) {
1198        builder.std(self.test_compiler, self.target);
1199
1200        let mut cmd = builder.tool_cmd(Tool::RustdocGUITest);
1201
1202        let out_dir = builder.test_out(self.target).join("rustdoc-gui");
1203        build_stamp::clear_if_dirty(
1204            builder,
1205            &out_dir,
1206            &builder.rustdoc_for_compiler(self.test_compiler),
1207        );
1208
1209        if let Some(src) = builder.config.src.to_str() {
1210            cmd.arg("--rust-src").arg(src);
1211        }
1212
1213        if let Some(out_dir) = out_dir.to_str() {
1214            cmd.arg("--out-dir").arg(out_dir);
1215        }
1216
1217        if let Some(initial_cargo) = builder.config.initial_cargo.to_str() {
1218            cmd.arg("--initial-cargo").arg(initial_cargo);
1219        }
1220
1221        cmd.arg("--jobs").arg(builder.jobs().to_string());
1222
1223        cmd.env("RUSTDOC", builder.rustdoc_for_compiler(self.test_compiler))
1224            .env("RUSTC", builder.rustc(self.test_compiler));
1225
1226        add_rustdoc_cargo_linker_args(&mut cmd, builder, self.test_compiler.host, LldThreads::No);
1227
1228        for path in &builder.paths {
1229            if let Some(p) = helpers::is_valid_test_suite_arg(path, "tests/rustdoc-gui", builder) {
1230                if !p.ends_with(".goml") {
1231                    eprintln!("A non-goml file was given: `{}`", path.display());
1232                    panic!("Cannot run rustdoc-gui tests");
1233                }
1234                if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
1235                    cmd.arg("--goml-file").arg(name);
1236                }
1237            }
1238        }
1239
1240        for test_arg in builder.config.test_args() {
1241            cmd.arg("--test-arg").arg(test_arg);
1242        }
1243
1244        if let Some(ref nodejs) = builder.config.nodejs {
1245            cmd.arg("--nodejs").arg(nodejs);
1246        }
1247
1248        if let Some(ref yarn) = builder.config.yarn {
1249            cmd.arg("--yarn").arg(yarn);
1250        }
1251
1252        let _time = helpers::timeit(builder);
1253        let _guard = builder.msg_test("rustdoc-gui", self.target, self.test_compiler.stage);
1254        try_run_tests(builder, &mut cmd, true);
1255    }
1256
1257    fn metadata(&self) -> Option<StepMetadata> {
1258        Some(StepMetadata::test("rustdoc-gui", self.target).stage(self.test_compiler.stage))
1259    }
1260}
1261
1262/// Runs `src/tools/tidy` and `cargo fmt --check` to detect various style
1263/// problems in the repository.
1264///
1265/// (To run the tidy tool's internal tests, use the alias "tidyselftest" instead.)
1266#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1267pub struct Tidy;
1268
1269impl Step for Tidy {
1270    type Output = ();
1271    const IS_HOST: bool = true;
1272
1273    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1274        run.path("src/tools/tidy")
1275    }
1276
1277    fn is_default_step(builder: &Builder<'_>) -> bool {
1278        builder.doc_tests != DocTests::Only
1279    }
1280
1281    fn make_run(run: RunConfig<'_>) {
1282        run.builder.ensure(Tidy);
1283    }
1284
1285    /// Runs the `tidy` tool.
1286    ///
1287    /// This tool in `src/tools` checks up on various bits and pieces of style and
1288    /// otherwise just implements a few lint-like checks that are specific to the
1289    /// compiler itself.
1290    ///
1291    /// Once tidy passes, this step also runs `fmt --check` if tests are being run
1292    /// for the `dev` or `nightly` channels.
1293    fn run(self, builder: &Builder<'_>) {
1294        let mut cmd = builder.tool_cmd(Tool::Tidy);
1295        cmd.arg(&builder.src);
1296        cmd.arg(&builder.initial_cargo);
1297        cmd.arg(&builder.out);
1298        // Tidy is heavily IO constrained. Still respect `-j`, but use a higher limit if `jobs` hasn't been configured.
1299        let jobs = builder.config.jobs.unwrap_or_else(|| {
1300            8 * std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1301        });
1302        cmd.arg(jobs.to_string());
1303        // pass the path to the yarn command used for installing js deps.
1304        if let Some(yarn) = &builder.config.yarn {
1305            cmd.arg(yarn);
1306        } else {
1307            cmd.arg("yarn");
1308        }
1309        if builder.is_verbose() {
1310            cmd.arg("--verbose");
1311        }
1312        if builder.config.cmd.bless() {
1313            cmd.arg("--bless");
1314        }
1315        if let Some(s) =
1316            builder.config.cmd.extra_checks().or(builder.config.tidy_extra_checks.as_deref())
1317        {
1318            cmd.arg(format!("--extra-checks={s}"));
1319        }
1320        let mut args = std::env::args_os();
1321        if args.any(|arg| arg == OsStr::new("--")) {
1322            cmd.arg("--");
1323            cmd.args(args);
1324        }
1325
1326        if builder.config.channel == "dev" || builder.config.channel == "nightly" {
1327            if !builder.config.json_output {
1328                builder.info("fmt check");
1329                if builder.config.initial_rustfmt.is_none() {
1330                    let inferred_rustfmt_dir = builder.initial_sysroot.join("bin");
1331                    eprintln!(
1332                        "\
1333ERROR: no `rustfmt` binary found in {PATH}
1334INFO: `rust.channel` is currently set to \"{CHAN}\"
1335HELP: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `bootstrap.toml` file
1336HELP: to skip test's attempt to check tidiness, pass `--skip src/tools/tidy` to `x.py test`",
1337                        PATH = inferred_rustfmt_dir.display(),
1338                        CHAN = builder.config.channel,
1339                    );
1340                    crate::exit!(1);
1341                }
1342                let all = false;
1343                crate::core::build_steps::format::format(
1344                    builder,
1345                    !builder.config.cmd.bless(),
1346                    all,
1347                    &[],
1348                );
1349            } else {
1350                eprintln!(
1351                    "WARNING: `--json-output` is not supported on rustfmt, formatting will be skipped"
1352                );
1353            }
1354        }
1355
1356        builder.info("tidy check");
1357        cmd.delay_failure().run(builder);
1358
1359        builder.info("x.py completions check");
1360        let completion_paths = get_completion_paths(builder);
1361        if builder.config.cmd.bless() {
1362            builder.ensure(crate::core::build_steps::run::GenerateCompletions);
1363        } else if completion_paths
1364            .into_iter()
1365            .any(|(shell, path)| get_completion(shell, &path).is_some())
1366        {
1367            eprintln!(
1368                "x.py completions were changed; run `x.py run generate-completions` to update them"
1369            );
1370            crate::exit!(1);
1371        }
1372
1373        builder.info("x.py help check");
1374        if builder.config.cmd.bless() {
1375            builder.ensure(crate::core::build_steps::run::GenerateHelp);
1376        } else {
1377            let help_path = get_help_path(builder);
1378            let cur_help = std::fs::read_to_string(&help_path).unwrap_or_else(|err| {
1379                eprintln!("couldn't read {}: {}", help_path.display(), err);
1380                crate::exit!(1);
1381            });
1382            let new_help = top_level_help();
1383
1384            if new_help != cur_help {
1385                eprintln!("x.py help was changed; run `x.py run generate-help` to update it");
1386                crate::exit!(1);
1387            }
1388        }
1389    }
1390
1391    fn metadata(&self) -> Option<StepMetadata> {
1392        Some(StepMetadata::test("tidy", TargetSelection::default()))
1393    }
1394}
1395
1396/// Runs `cargo test` on the `src/tools/run-make-support` crate.
1397/// That crate is used by run-make tests.
1398#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1399pub struct CrateRunMakeSupport {
1400    host: TargetSelection,
1401}
1402
1403impl Step for CrateRunMakeSupport {
1404    type Output = ();
1405    const IS_HOST: bool = true;
1406
1407    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1408        run.path("src/tools/run-make-support")
1409    }
1410
1411    fn make_run(run: RunConfig<'_>) {
1412        run.builder.ensure(CrateRunMakeSupport { host: run.target });
1413    }
1414
1415    /// Runs `cargo test` for run-make-support.
1416    fn run(self, builder: &Builder<'_>) {
1417        let host = self.host;
1418        let compiler = builder.compiler(0, host);
1419
1420        let mut cargo = tool::prepare_tool_cargo(
1421            builder,
1422            compiler,
1423            Mode::ToolBootstrap,
1424            host,
1425            Kind::Test,
1426            "src/tools/run-make-support",
1427            SourceType::InTree,
1428            &[],
1429        );
1430        cargo.allow_features("test");
1431        run_cargo_test(cargo, &[], &[], "run-make-support self test", host, builder);
1432    }
1433}
1434
1435#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1436pub struct CrateBuildHelper {
1437    host: TargetSelection,
1438}
1439
1440impl Step for CrateBuildHelper {
1441    type Output = ();
1442    const IS_HOST: bool = true;
1443
1444    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1445        run.path("src/build_helper")
1446    }
1447
1448    fn make_run(run: RunConfig<'_>) {
1449        run.builder.ensure(CrateBuildHelper { host: run.target });
1450    }
1451
1452    /// Runs `cargo test` for build_helper.
1453    fn run(self, builder: &Builder<'_>) {
1454        let host = self.host;
1455        let compiler = builder.compiler(0, host);
1456
1457        let mut cargo = tool::prepare_tool_cargo(
1458            builder,
1459            compiler,
1460            Mode::ToolBootstrap,
1461            host,
1462            Kind::Test,
1463            "src/build_helper",
1464            SourceType::InTree,
1465            &[],
1466        );
1467        cargo.allow_features("test");
1468        run_cargo_test(cargo, &[], &[], "build_helper self test", host, builder);
1469    }
1470}
1471
1472fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
1473    builder.out.join(host).join("test")
1474}
1475
1476/// Declares a test step that invokes compiletest on a particular test suite.
1477macro_rules! test {
1478    (
1479        $( #[$attr:meta] )* // allow docstrings and attributes
1480        $name:ident {
1481            path: $path:expr,
1482            mode: $mode:expr,
1483            suite: $suite:expr,
1484            default: $default:expr
1485            $( , IS_HOST: $IS_HOST:expr )? // default: false
1486            $( , compare_mode: $compare_mode:expr )? // default: None
1487            $( , )? // optional trailing comma
1488        }
1489    ) => {
1490        $( #[$attr] )*
1491        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1492        pub struct $name {
1493            test_compiler: Compiler,
1494            target: TargetSelection,
1495        }
1496
1497        impl Step for $name {
1498            type Output = ();
1499            const IS_HOST: bool = (const {
1500                #[allow(unused_assignments, unused_mut)]
1501                let mut value = false;
1502                $( value = $IS_HOST; )?
1503                value
1504            });
1505
1506            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1507                run.suite_path($path)
1508            }
1509
1510            fn is_default_step(_builder: &Builder<'_>) -> bool {
1511                const { $default }
1512            }
1513
1514            fn make_run(run: RunConfig<'_>) {
1515                let test_compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1516
1517                run.builder.ensure($name { test_compiler, target: run.target });
1518            }
1519
1520            fn run(self, builder: &Builder<'_>) {
1521                builder.ensure(Compiletest {
1522                    test_compiler: self.test_compiler,
1523                    target: self.target,
1524                    mode: const { $mode },
1525                    suite: $suite,
1526                    path: $path,
1527                    compare_mode: (const {
1528                        #[allow(unused_assignments, unused_mut)]
1529                        let mut value = None;
1530                        $( value = $compare_mode; )?
1531                        value
1532                    }),
1533                })
1534            }
1535        }
1536    };
1537}
1538
1539test!(Ui { path: "tests/ui", mode: CompiletestMode::Ui, suite: "ui", default: true });
1540
1541test!(Crashes {
1542    path: "tests/crashes",
1543    mode: CompiletestMode::Crashes,
1544    suite: "crashes",
1545    default: true,
1546});
1547
1548test!(CodegenLlvm {
1549    path: "tests/codegen-llvm",
1550    mode: CompiletestMode::Codegen,
1551    suite: "codegen-llvm",
1552    default: true
1553});
1554
1555test!(CodegenUnits {
1556    path: "tests/codegen-units",
1557    mode: CompiletestMode::CodegenUnits,
1558    suite: "codegen-units",
1559    default: true,
1560});
1561
1562test!(Incremental {
1563    path: "tests/incremental",
1564    mode: CompiletestMode::Incremental,
1565    suite: "incremental",
1566    default: true,
1567});
1568
1569test!(Debuginfo {
1570    path: "tests/debuginfo",
1571    mode: CompiletestMode::Debuginfo,
1572    suite: "debuginfo",
1573    default: true,
1574    compare_mode: Some("split-dwarf"),
1575});
1576
1577test!(UiFullDeps {
1578    path: "tests/ui-fulldeps",
1579    mode: CompiletestMode::Ui,
1580    suite: "ui-fulldeps",
1581    default: true,
1582    IS_HOST: true,
1583});
1584
1585test!(Rustdoc {
1586    path: "tests/rustdoc",
1587    mode: CompiletestMode::Rustdoc,
1588    suite: "rustdoc",
1589    default: true,
1590    IS_HOST: true,
1591});
1592test!(RustdocUi {
1593    path: "tests/rustdoc-ui",
1594    mode: CompiletestMode::Ui,
1595    suite: "rustdoc-ui",
1596    default: true,
1597    IS_HOST: true,
1598});
1599
1600test!(RustdocJson {
1601    path: "tests/rustdoc-json",
1602    mode: CompiletestMode::RustdocJson,
1603    suite: "rustdoc-json",
1604    default: true,
1605    IS_HOST: true,
1606});
1607
1608test!(Pretty {
1609    path: "tests/pretty",
1610    mode: CompiletestMode::Pretty,
1611    suite: "pretty",
1612    default: true,
1613    IS_HOST: true,
1614});
1615
1616test!(RunMake {
1617    path: "tests/run-make",
1618    mode: CompiletestMode::RunMake,
1619    suite: "run-make",
1620    default: true,
1621});
1622test!(RunMakeCargo {
1623    path: "tests/run-make-cargo",
1624    mode: CompiletestMode::RunMake,
1625    suite: "run-make-cargo",
1626    default: true
1627});
1628
1629test!(AssemblyLlvm {
1630    path: "tests/assembly-llvm",
1631    mode: CompiletestMode::Assembly,
1632    suite: "assembly-llvm",
1633    default: true
1634});
1635
1636/// Runs the coverage test suite at `tests/coverage` in some or all of the
1637/// coverage test modes.
1638#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1639pub struct Coverage {
1640    pub compiler: Compiler,
1641    pub target: TargetSelection,
1642    pub(crate) mode: CompiletestMode,
1643}
1644
1645impl Coverage {
1646    const PATH: &'static str = "tests/coverage";
1647    const SUITE: &'static str = "coverage";
1648    const ALL_MODES: &[CompiletestMode] =
1649        &[CompiletestMode::CoverageMap, CompiletestMode::CoverageRun];
1650}
1651
1652impl Step for Coverage {
1653    type Output = ();
1654    /// Compiletest will automatically skip the "coverage-run" tests if necessary.
1655    const IS_HOST: bool = false;
1656
1657    fn should_run(mut run: ShouldRun<'_>) -> ShouldRun<'_> {
1658        // Support various invocation styles, including:
1659        // - `./x test coverage`
1660        // - `./x test tests/coverage/trivial.rs`
1661        // - `./x test coverage-map`
1662        // - `./x test coverage-run -- tests/coverage/trivial.rs`
1663        run = run.suite_path(Self::PATH);
1664        for mode in Self::ALL_MODES {
1665            run = run.alias(mode.as_str());
1666        }
1667        run
1668    }
1669
1670    fn is_default_step(_builder: &Builder<'_>) -> bool {
1671        true
1672    }
1673
1674    fn make_run(run: RunConfig<'_>) {
1675        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1676        let target = run.target;
1677
1678        // List of (coverage) test modes that the coverage test suite will be
1679        // run in. It's OK for this to contain duplicates, because the call to
1680        // `Builder::ensure` below will take care of deduplication.
1681        let mut modes = vec![];
1682
1683        // From the pathsets that were selected on the command-line (or by default),
1684        // determine which modes to run in.
1685        for path in &run.paths {
1686            match path {
1687                PathSet::Set(_) => {
1688                    for &mode in Self::ALL_MODES {
1689                        if path.assert_single_path().path == Path::new(mode.as_str()) {
1690                            modes.push(mode);
1691                            break;
1692                        }
1693                    }
1694                }
1695                PathSet::Suite(_) => {
1696                    modes.extend_from_slice(Self::ALL_MODES);
1697                    break;
1698                }
1699            }
1700        }
1701
1702        // Skip any modes that were explicitly skipped/excluded on the command-line.
1703        // FIXME(Zalathar): Integrate this into central skip handling somehow?
1704        modes.retain(|mode| {
1705            !run.builder.config.skip.iter().any(|skip| skip == Path::new(mode.as_str()))
1706        });
1707
1708        // FIXME(Zalathar): Make these commands skip all coverage tests, as expected:
1709        // - `./x test --skip=tests`
1710        // - `./x test --skip=tests/coverage`
1711        // - `./x test --skip=coverage`
1712        // Skip handling currently doesn't have a way to know that skipping the coverage
1713        // suite should also skip the `coverage-map` and `coverage-run` aliases.
1714
1715        for mode in modes {
1716            run.builder.ensure(Coverage { compiler, target, mode });
1717        }
1718    }
1719
1720    fn run(self, builder: &Builder<'_>) {
1721        let Self { compiler, target, mode } = self;
1722        // Like other compiletest suite test steps, delegate to an internal
1723        // compiletest task to actually run the tests.
1724        builder.ensure(Compiletest {
1725            test_compiler: compiler,
1726            target,
1727            mode,
1728            suite: Self::SUITE,
1729            path: Self::PATH,
1730            compare_mode: None,
1731        });
1732    }
1733}
1734
1735test!(CoverageRunRustdoc {
1736    path: "tests/coverage-run-rustdoc",
1737    mode: CompiletestMode::CoverageRun,
1738    suite: "coverage-run-rustdoc",
1739    default: true,
1740    IS_HOST: true,
1741});
1742
1743// For the mir-opt suite we do not use macros, as we need custom behavior when blessing.
1744#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1745pub struct MirOpt {
1746    pub compiler: Compiler,
1747    pub target: TargetSelection,
1748}
1749
1750impl Step for MirOpt {
1751    type Output = ();
1752
1753    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1754        run.suite_path("tests/mir-opt")
1755    }
1756
1757    fn is_default_step(_builder: &Builder<'_>) -> bool {
1758        true
1759    }
1760
1761    fn make_run(run: RunConfig<'_>) {
1762        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1763        run.builder.ensure(MirOpt { compiler, target: run.target });
1764    }
1765
1766    fn run(self, builder: &Builder<'_>) {
1767        let run = |target| {
1768            builder.ensure(Compiletest {
1769                test_compiler: self.compiler,
1770                target,
1771                mode: CompiletestMode::MirOpt,
1772                suite: "mir-opt",
1773                path: "tests/mir-opt",
1774                compare_mode: None,
1775            })
1776        };
1777
1778        run(self.target);
1779
1780        // Run more targets with `--bless`. But we always run the host target first, since some
1781        // tests use very specific `only` clauses that are not covered by the target set below.
1782        if builder.config.cmd.bless() {
1783            // All that we really need to do is cover all combinations of 32/64-bit and unwind/abort,
1784            // but while we're at it we might as well flex our cross-compilation support. This
1785            // selection covers all our tier 1 operating systems and architectures using only tier
1786            // 1 targets.
1787
1788            for target in ["aarch64-unknown-linux-gnu", "i686-pc-windows-msvc"] {
1789                run(TargetSelection::from_user(target));
1790            }
1791
1792            for target in ["x86_64-apple-darwin", "i686-unknown-linux-musl"] {
1793                let target = TargetSelection::from_user(target);
1794                let panic_abort_target = builder.ensure(MirOptPanicAbortSyntheticTarget {
1795                    compiler: self.compiler,
1796                    base: target,
1797                });
1798                run(panic_abort_target);
1799            }
1800        }
1801    }
1802}
1803
1804/// Executes the `compiletest` tool to run a suite of tests.
1805///
1806/// Compiles all tests with `test_compiler` for `target` with the specified
1807/// compiletest `mode` and `suite` arguments. For example `mode` can be
1808/// "mir-opt" and `suite` can be something like "debuginfo".
1809#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1810struct Compiletest {
1811    /// The compiler that we're testing.
1812    test_compiler: Compiler,
1813    target: TargetSelection,
1814    mode: CompiletestMode,
1815    suite: &'static str,
1816    path: &'static str,
1817    compare_mode: Option<&'static str>,
1818}
1819
1820impl Step for Compiletest {
1821    type Output = ();
1822
1823    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1824        run.never()
1825    }
1826
1827    fn run(self, builder: &Builder<'_>) {
1828        if builder.doc_tests == DocTests::Only {
1829            return;
1830        }
1831
1832        if builder.top_stage == 0 && !builder.config.compiletest_allow_stage0 {
1833            eprintln!("\
1834ERROR: `--stage 0` runs compiletest on the stage0 (precompiled) compiler, not your local changes, and will almost always cause tests to fail
1835HELP: to test the compiler or standard library, omit the stage or explicitly use `--stage 1` instead
1836NOTE: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `--set build.compiletest-allow-stage0=true`."
1837            );
1838            crate::exit!(1);
1839        }
1840
1841        let mut test_compiler = self.test_compiler;
1842        let target = self.target;
1843        let mode = self.mode;
1844        let suite = self.suite;
1845
1846        // Path for test suite
1847        let suite_path = self.path;
1848
1849        // Skip codegen tests if they aren't enabled in configuration.
1850        if !builder.config.codegen_tests && mode == CompiletestMode::Codegen {
1851            return;
1852        }
1853
1854        // Support stage 1 ui-fulldeps. This is somewhat complicated: ui-fulldeps tests for the most
1855        // part test the *API* of the compiler, not how it compiles a given file. As a result, we
1856        // can run them against the stage 1 sources as long as we build them with the stage 0
1857        // bootstrap compiler.
1858        // NOTE: Only stage 1 is special cased because we need the rustc_private artifacts to match the
1859        // running compiler in stage 2 when plugins run.
1860        let query_compiler;
1861        let (stage, stage_id) = if suite == "ui-fulldeps" && test_compiler.stage == 1 {
1862            // Even when using the stage 0 compiler, we also need to provide the stage 1 compiler
1863            // so that compiletest can query it for target information.
1864            query_compiler = Some(test_compiler);
1865            // At stage 0 (stage - 1) we are using the stage0 compiler. Using `self.target` can lead
1866            // finding an incorrect compiler path on cross-targets, as the stage 0 is always equal to
1867            // `build.build` in the configuration.
1868            let build = builder.build.host_target;
1869            test_compiler = builder.compiler(test_compiler.stage - 1, build);
1870            let test_stage = test_compiler.stage + 1;
1871            (test_stage, format!("stage{test_stage}-{build}"))
1872        } else {
1873            query_compiler = None;
1874            let stage = test_compiler.stage;
1875            (stage, format!("stage{stage}-{target}"))
1876        };
1877
1878        if suite.ends_with("fulldeps") {
1879            builder.ensure(compile::Rustc::new(test_compiler, target));
1880        }
1881
1882        if suite == "debuginfo" {
1883            builder.ensure(dist::DebuggerScripts {
1884                sysroot: builder.sysroot(test_compiler).to_path_buf(),
1885                target,
1886            });
1887        }
1888        if mode == CompiletestMode::RunMake {
1889            builder.tool_exe(Tool::RunMakeSupport);
1890        }
1891
1892        // ensure that `libproc_macro` is available on the host.
1893        if suite == "mir-opt" {
1894            builder.ensure(
1895                compile::Std::new(test_compiler, test_compiler.host).is_for_mir_opt_tests(true),
1896            );
1897        } else {
1898            builder.std(test_compiler, test_compiler.host);
1899        }
1900
1901        let mut cmd = builder.tool_cmd(Tool::Compiletest);
1902
1903        if suite == "mir-opt" {
1904            builder.ensure(compile::Std::new(test_compiler, target).is_for_mir_opt_tests(true));
1905        } else {
1906            builder.std(test_compiler, target);
1907        }
1908
1909        builder.ensure(RemoteCopyLibs { build_compiler: test_compiler, target });
1910
1911        // compiletest currently has... a lot of arguments, so let's just pass all
1912        // of them!
1913
1914        cmd.arg("--stage").arg(stage.to_string());
1915        cmd.arg("--stage-id").arg(stage_id);
1916
1917        cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(test_compiler));
1918        cmd.arg("--run-lib-path").arg(builder.sysroot_target_libdir(test_compiler, target));
1919        cmd.arg("--rustc-path").arg(builder.rustc(test_compiler));
1920        if let Some(query_compiler) = query_compiler {
1921            cmd.arg("--query-rustc-path").arg(builder.rustc(query_compiler));
1922        }
1923
1924        // Minicore auxiliary lib for `no_core` tests that need `core` stubs in cross-compilation
1925        // scenarios.
1926        cmd.arg("--minicore-path")
1927            .arg(builder.src.join("tests").join("auxiliary").join("minicore.rs"));
1928
1929        let is_rustdoc = suite == "rustdoc-ui" || suite == "rustdoc-js";
1930
1931        // There are (potentially) 2 `cargo`s to consider:
1932        //
1933        // - A "bootstrap" cargo, which is the same cargo used to build bootstrap itself, and is
1934        //   used to build the `run-make` test recipes and the `run-make-support` test library. All
1935        //   of these may not use unstable rustc/cargo features.
1936        // - An in-tree cargo, which should be considered as under test. The `run-make-cargo` test
1937        //   suite is intended to support the use case of testing the "toolchain" (that is, at the
1938        //   minimum the interaction between in-tree cargo + rustc) together.
1939        //
1940        // For build time and iteration purposes, we partition `run-make` tests which needs an
1941        // in-tree cargo (a smaller subset) versus `run-make` tests that do not into two test
1942        // suites, `run-make` and `run-make-cargo`. That way, contributors who do not need to run
1943        // the `run-make` tests that need in-tree cargo do not need to spend time building in-tree
1944        // cargo.
1945        if mode == CompiletestMode::RunMake {
1946            // We need to pass the compiler that was used to compile run-make-support,
1947            // because we have to use the same compiler to compile rmake.rs recipes.
1948            let stage0_rustc_path = builder.compiler(0, test_compiler.host);
1949            cmd.arg("--stage0-rustc-path").arg(builder.rustc(stage0_rustc_path));
1950
1951            if suite == "run-make-cargo" {
1952                let cargo_path = if test_compiler.stage == 0 {
1953                    // If we're using `--stage 0`, we should provide the bootstrap cargo.
1954                    builder.initial_cargo.clone()
1955                } else {
1956                    builder
1957                        .ensure(tool::Cargo::from_build_compiler(
1958                            builder.compiler(test_compiler.stage - 1, test_compiler.host),
1959                            test_compiler.host,
1960                        ))
1961                        .tool_path
1962                };
1963
1964                cmd.arg("--cargo-path").arg(cargo_path);
1965            }
1966        }
1967
1968        // Avoid depending on rustdoc when we don't need it.
1969        if matches!(
1970            mode,
1971            CompiletestMode::RunMake
1972                | CompiletestMode::Rustdoc
1973                | CompiletestMode::RustdocJs
1974                | CompiletestMode::RustdocJson
1975        ) || matches!(suite, "rustdoc-ui" | "coverage-run-rustdoc")
1976        {
1977            cmd.arg("--rustdoc-path").arg(builder.rustdoc_for_compiler(test_compiler));
1978        }
1979
1980        if mode == CompiletestMode::RustdocJson {
1981            // Use the stage0 compiler for jsondocck
1982            let json_compiler = builder.compiler(0, builder.host_target);
1983            cmd.arg("--jsondocck-path")
1984                .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }).tool_path);
1985            cmd.arg("--jsondoclint-path").arg(
1986                builder.ensure(tool::JsonDocLint { compiler: json_compiler, target }).tool_path,
1987            );
1988        }
1989
1990        if matches!(mode, CompiletestMode::CoverageMap | CompiletestMode::CoverageRun) {
1991            let coverage_dump = builder.tool_exe(Tool::CoverageDump);
1992            cmd.arg("--coverage-dump-path").arg(coverage_dump);
1993        }
1994
1995        cmd.arg("--src-root").arg(&builder.src);
1996        cmd.arg("--src-test-suite-root").arg(builder.src.join("tests").join(suite));
1997
1998        // N.B. it's important to distinguish between the *root* build directory, the *host* build
1999        // directory immediately under the root build directory, and the test-suite-specific build
2000        // directory.
2001        cmd.arg("--build-root").arg(&builder.out);
2002        cmd.arg("--build-test-suite-root").arg(testdir(builder, test_compiler.host).join(suite));
2003
2004        // When top stage is 0, that means that we're testing an externally provided compiler.
2005        // In that case we need to use its specific sysroot for tests to pass.
2006        // Note: DO NOT check if test_compiler.stage is 0, because the test compiler can be stage 0
2007        // even if the top stage is 1 (when we run the ui-fulldeps suite).
2008        let sysroot = if builder.top_stage == 0 {
2009            builder.initial_sysroot.clone()
2010        } else {
2011            builder.sysroot(test_compiler)
2012        };
2013
2014        cmd.arg("--sysroot-base").arg(sysroot);
2015
2016        cmd.arg("--suite").arg(suite);
2017        cmd.arg("--mode").arg(mode.as_str());
2018        cmd.arg("--target").arg(target.rustc_target_arg());
2019        cmd.arg("--host").arg(&*test_compiler.host.triple);
2020        cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.host_target));
2021
2022        if let Some(codegen_backend) = builder.config.cmd.test_codegen_backend() {
2023            if !builder
2024                .config
2025                .enabled_codegen_backends(test_compiler.host)
2026                .contains(codegen_backend)
2027            {
2028                eprintln!(
2029                    "\
2030ERROR: No configured backend named `{name}`
2031HELP: You can add it into `bootstrap.toml` in `rust.codegen-backends = [{name:?}]`",
2032                    name = codegen_backend.name(),
2033                );
2034                crate::exit!(1);
2035            }
2036
2037            if let CodegenBackendKind::Gcc = codegen_backend
2038                && builder.config.rustc_debug_assertions
2039            {
2040                eprintln!(
2041                    r#"WARNING: Running tests with the GCC codegen backend while rustc debug assertions are enabled. This might lead to test failures.
2042Please disable assertions with `rust.debug-assertions = false`.
2043        "#
2044                );
2045            }
2046
2047            // Tells compiletest that we want to use this codegen in particular and to override
2048            // the default one.
2049            cmd.arg("--override-codegen-backend").arg(codegen_backend.name());
2050            // Tells compiletest which codegen backend to use.
2051            // It is used to e.g. ignore tests that don't support that codegen backend.
2052            cmd.arg("--default-codegen-backend").arg(codegen_backend.name());
2053        } else {
2054            // Tells compiletest which codegen backend to use.
2055            // It is used to e.g. ignore tests that don't support that codegen backend.
2056            cmd.arg("--default-codegen-backend")
2057                .arg(builder.config.default_codegen_backend(test_compiler.host).name());
2058        }
2059        if builder.config.cmd.bypass_ignore_backends() {
2060            cmd.arg("--bypass-ignore-backends");
2061        }
2062
2063        if builder.build.config.llvm_enzyme {
2064            cmd.arg("--has-enzyme");
2065        }
2066
2067        if builder.config.cmd.bless() {
2068            cmd.arg("--bless");
2069        }
2070
2071        if builder.config.cmd.force_rerun() {
2072            cmd.arg("--force-rerun");
2073        }
2074
2075        if builder.config.cmd.no_capture() {
2076            cmd.arg("--no-capture");
2077        }
2078
2079        let compare_mode =
2080            builder.config.cmd.compare_mode().or_else(|| {
2081                if builder.config.test_compare_mode { self.compare_mode } else { None }
2082            });
2083
2084        if let Some(ref pass) = builder.config.cmd.pass() {
2085            cmd.arg("--pass");
2086            cmd.arg(pass);
2087        }
2088
2089        if let Some(ref run) = builder.config.cmd.run() {
2090            cmd.arg("--run");
2091            cmd.arg(run);
2092        }
2093
2094        if let Some(ref nodejs) = builder.config.nodejs {
2095            cmd.arg("--nodejs").arg(nodejs);
2096        } else if mode == CompiletestMode::RustdocJs {
2097            panic!("need nodejs to run rustdoc-js suite");
2098        }
2099        if builder.config.rust_optimize_tests {
2100            cmd.arg("--optimize-tests");
2101        }
2102        if builder.config.rust_randomize_layout {
2103            cmd.arg("--rust-randomized-layout");
2104        }
2105        if builder.config.cmd.only_modified() {
2106            cmd.arg("--only-modified");
2107        }
2108        if let Some(compiletest_diff_tool) = &builder.config.compiletest_diff_tool {
2109            cmd.arg("--compiletest-diff-tool").arg(compiletest_diff_tool);
2110        }
2111
2112        let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
2113        flags.push(format!(
2114            "-Cdebuginfo={}",
2115            if mode == CompiletestMode::Codegen {
2116                // codegen tests typically check LLVM IR and are sensitive to additional debuginfo.
2117                // So do not apply `rust.debuginfo-level-tests` for codegen tests.
2118                if builder.config.rust_debuginfo_level_tests
2119                    != crate::core::config::DebuginfoLevel::None
2120                {
2121                    println!(
2122                        "NOTE: ignoring `rust.debuginfo-level-tests={}` for codegen tests",
2123                        builder.config.rust_debuginfo_level_tests
2124                    );
2125                }
2126                crate::core::config::DebuginfoLevel::None
2127            } else {
2128                builder.config.rust_debuginfo_level_tests
2129            }
2130        ));
2131        flags.extend(builder.config.cmd.compiletest_rustc_args().iter().map(|s| s.to_string()));
2132
2133        if suite != "mir-opt" {
2134            if let Some(linker) = builder.linker(target) {
2135                cmd.arg("--target-linker").arg(linker);
2136            }
2137            if let Some(linker) = builder.linker(test_compiler.host) {
2138                cmd.arg("--host-linker").arg(linker);
2139            }
2140        }
2141
2142        // FIXME(136096): on macOS, we get linker warnings about duplicate `-lm` flags.
2143        if suite == "ui-fulldeps" && target.ends_with("darwin") {
2144            flags.push("-Alinker_messages".into());
2145        }
2146
2147        let mut hostflags = flags.clone();
2148        hostflags.extend(linker_flags(builder, test_compiler.host, LldThreads::No));
2149
2150        let mut targetflags = flags;
2151
2152        // Provide `rust_test_helpers` for both host and target.
2153        if suite == "ui" || suite == "incremental" {
2154            builder.ensure(TestHelpers { target: test_compiler.host });
2155            builder.ensure(TestHelpers { target });
2156            hostflags.push(format!(
2157                "-Lnative={}",
2158                builder.test_helpers_out(test_compiler.host).display()
2159            ));
2160            targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
2161        }
2162
2163        for flag in hostflags {
2164            cmd.arg("--host-rustcflags").arg(flag);
2165        }
2166        for flag in targetflags {
2167            cmd.arg("--target-rustcflags").arg(flag);
2168        }
2169
2170        cmd.arg("--python").arg(
2171            builder.config.python.as_ref().expect("python is required for running rustdoc tests"),
2172        );
2173
2174        // Discover and set some flags related to running tests on Android targets.
2175        let android = android::discover_android(builder, target);
2176        if let Some(android::Android { adb_path, adb_test_dir, android_cross_path }) = &android {
2177            cmd.arg("--adb-path").arg(adb_path);
2178            cmd.arg("--adb-test-dir").arg(adb_test_dir);
2179            cmd.arg("--android-cross-path").arg(android_cross_path);
2180        }
2181
2182        if mode == CompiletestMode::Debuginfo {
2183            if let Some(debuggers::Cdb { cdb }) = debuggers::discover_cdb(target) {
2184                cmd.arg("--cdb").arg(cdb);
2185            }
2186
2187            if let Some(debuggers::Gdb { gdb }) = debuggers::discover_gdb(builder, android.as_ref())
2188            {
2189                cmd.arg("--gdb").arg(gdb.as_ref());
2190            }
2191
2192            if let Some(debuggers::Lldb { lldb_exe, lldb_version }) =
2193                debuggers::discover_lldb(builder)
2194            {
2195                cmd.arg("--lldb").arg(lldb_exe);
2196                cmd.arg("--lldb-version").arg(lldb_version);
2197            }
2198        }
2199
2200        if helpers::forcing_clang_based_tests() {
2201            let clang_exe = builder.llvm_out(target).join("bin").join("clang");
2202            cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
2203        }
2204
2205        for exclude in &builder.config.skip {
2206            cmd.arg("--skip");
2207            cmd.arg(exclude);
2208        }
2209
2210        // Get paths from cmd args
2211        let mut paths = match &builder.config.cmd {
2212            Subcommand::Test { .. } => &builder.config.paths[..],
2213            _ => &[],
2214        };
2215
2216        // in rustdoc-js mode, allow filters to be rs files or js files.
2217        // use a late-initialized Vec to avoid cloning for other modes.
2218        let mut paths_v;
2219        if mode == CompiletestMode::RustdocJs {
2220            paths_v = paths.to_vec();
2221            for p in &mut paths_v {
2222                if let Some(ext) = p.extension()
2223                    && ext == "js"
2224                {
2225                    p.set_extension("rs");
2226                }
2227            }
2228            paths = &paths_v;
2229        }
2230        // Get test-args by striping suite path
2231        let mut test_args: Vec<&str> = paths
2232            .iter()
2233            .filter_map(|p| helpers::is_valid_test_suite_arg(p, suite_path, builder))
2234            .collect();
2235
2236        test_args.append(&mut builder.config.test_args());
2237
2238        // On Windows, replace forward slashes in test-args by backslashes
2239        // so the correct filters are passed to libtest
2240        if cfg!(windows) {
2241            let test_args_win: Vec<String> =
2242                test_args.iter().map(|s| s.replace('/', "\\")).collect();
2243            cmd.args(&test_args_win);
2244        } else {
2245            cmd.args(&test_args);
2246        }
2247
2248        if builder.is_verbose() {
2249            cmd.arg("--verbose");
2250        }
2251
2252        if builder.config.rustc_debug_assertions {
2253            cmd.arg("--with-rustc-debug-assertions");
2254        }
2255
2256        if builder.config.std_debug_assertions {
2257            cmd.arg("--with-std-debug-assertions");
2258        }
2259
2260        let mut llvm_components_passed = false;
2261        let mut copts_passed = false;
2262        if builder.config.llvm_enabled(test_compiler.host) {
2263            let llvm::LlvmResult { host_llvm_config, .. } =
2264                builder.ensure(llvm::Llvm { target: builder.config.host_target });
2265            if !builder.config.dry_run() {
2266                let llvm_version = get_llvm_version(builder, &host_llvm_config);
2267                let llvm_components = command(&host_llvm_config)
2268                    .cached()
2269                    .arg("--components")
2270                    .run_capture_stdout(builder)
2271                    .stdout();
2272                // Remove trailing newline from llvm-config output.
2273                cmd.arg("--llvm-version")
2274                    .arg(llvm_version.trim())
2275                    .arg("--llvm-components")
2276                    .arg(llvm_components.trim());
2277                llvm_components_passed = true;
2278            }
2279            if !builder.config.is_rust_llvm(target) {
2280                cmd.arg("--system-llvm");
2281            }
2282
2283            // Tests that use compiler libraries may inherit the `-lLLVM` link
2284            // requirement, but the `-L` library path is not propagated across
2285            // separate compilations. We can add LLVM's library path to the
2286            // rustc args as a workaround.
2287            if !builder.config.dry_run() && suite.ends_with("fulldeps") {
2288                let llvm_libdir = command(&host_llvm_config)
2289                    .cached()
2290                    .arg("--libdir")
2291                    .run_capture_stdout(builder)
2292                    .stdout();
2293                let link_llvm = if target.is_msvc() {
2294                    format!("-Clink-arg=-LIBPATH:{llvm_libdir}")
2295                } else {
2296                    format!("-Clink-arg=-L{llvm_libdir}")
2297                };
2298                cmd.arg("--host-rustcflags").arg(link_llvm);
2299            }
2300
2301            if !builder.config.dry_run()
2302                && matches!(mode, CompiletestMode::RunMake | CompiletestMode::CoverageRun)
2303            {
2304                // The llvm/bin directory contains many useful cross-platform
2305                // tools. Pass the path to run-make tests so they can use them.
2306                // (The coverage-run tests also need these tools to process
2307                // coverage reports.)
2308                let llvm_bin_path = host_llvm_config
2309                    .parent()
2310                    .expect("Expected llvm-config to be contained in directory");
2311                assert!(llvm_bin_path.is_dir());
2312                cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
2313            }
2314
2315            if !builder.config.dry_run() && mode == CompiletestMode::RunMake {
2316                // If LLD is available, add it to the PATH
2317                if builder.config.lld_enabled {
2318                    let lld_install_root =
2319                        builder.ensure(llvm::Lld { target: builder.config.host_target });
2320
2321                    let lld_bin_path = lld_install_root.join("bin");
2322
2323                    let old_path = env::var_os("PATH").unwrap_or_default();
2324                    let new_path = env::join_paths(
2325                        std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
2326                    )
2327                    .expect("Could not add LLD bin path to PATH");
2328                    cmd.env("PATH", new_path);
2329                }
2330            }
2331        }
2332
2333        // Only pass correct values for these flags for the `run-make` suite as it
2334        // requires that a C++ compiler was configured which isn't always the case.
2335        if !builder.config.dry_run() && mode == CompiletestMode::RunMake {
2336            let mut cflags = builder.cc_handled_clags(target, CLang::C);
2337            cflags.extend(builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C));
2338            let mut cxxflags = builder.cc_handled_clags(target, CLang::Cxx);
2339            cxxflags.extend(builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx));
2340            cmd.arg("--cc")
2341                .arg(builder.cc(target))
2342                .arg("--cxx")
2343                .arg(builder.cxx(target).unwrap())
2344                .arg("--cflags")
2345                .arg(cflags.join(" "))
2346                .arg("--cxxflags")
2347                .arg(cxxflags.join(" "));
2348            copts_passed = true;
2349            if let Some(ar) = builder.ar(target) {
2350                cmd.arg("--ar").arg(ar);
2351            }
2352        }
2353
2354        if !llvm_components_passed {
2355            cmd.arg("--llvm-components").arg("");
2356        }
2357        if !copts_passed {
2358            cmd.arg("--cc")
2359                .arg("")
2360                .arg("--cxx")
2361                .arg("")
2362                .arg("--cflags")
2363                .arg("")
2364                .arg("--cxxflags")
2365                .arg("");
2366        }
2367
2368        if builder.remote_tested(target) {
2369            cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
2370        } else if let Some(tool) = builder.runner(target) {
2371            cmd.arg("--runner").arg(tool);
2372        }
2373
2374        if suite != "mir-opt" {
2375            // Running a C compiler on MSVC requires a few env vars to be set, to be
2376            // sure to set them here.
2377            //
2378            // Note that if we encounter `PATH` we make sure to append to our own `PATH`
2379            // rather than stomp over it.
2380            if !builder.config.dry_run() && target.is_msvc() {
2381                for (k, v) in builder.cc[&target].env() {
2382                    if k != "PATH" {
2383                        cmd.env(k, v);
2384                    }
2385                }
2386            }
2387        }
2388
2389        // Special setup to enable running with sanitizers on MSVC.
2390        if !builder.config.dry_run()
2391            && target.contains("msvc")
2392            && builder.config.sanitizers_enabled(target)
2393        {
2394            // Ignore interception failures: not all dlls in the process will have been built with
2395            // address sanitizer enabled (e.g., ntdll.dll).
2396            cmd.env("ASAN_WIN_CONTINUE_ON_INTERCEPTION_FAILURE", "1");
2397            // Add the address sanitizer runtime to the PATH - it is located next to cl.exe.
2398            let asan_runtime_path = builder.cc[&target].path().parent().unwrap().to_path_buf();
2399            let old_path = cmd
2400                .get_envs()
2401                .find_map(|(k, v)| (k == "PATH").then_some(v))
2402                .flatten()
2403                .map_or_else(|| env::var_os("PATH").unwrap_or_default(), |v| v.to_owned());
2404            let new_path = env::join_paths(
2405                env::split_paths(&old_path).chain(std::iter::once(asan_runtime_path)),
2406            )
2407            .expect("Could not add ASAN runtime path to PATH");
2408            cmd.env("PATH", new_path);
2409        }
2410
2411        // Some UI tests trigger behavior in rustc where it reads $CARGO and changes behavior if it exists.
2412        // To make the tests work that rely on it not being set, make sure it is not set.
2413        cmd.env_remove("CARGO");
2414
2415        cmd.env("RUSTC_BOOTSTRAP", "1");
2416        // Override the rustc version used in symbol hashes to reduce the amount of normalization
2417        // needed when diffing test output.
2418        cmd.env("RUSTC_FORCE_RUSTC_VERSION", "compiletest");
2419        cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
2420        builder.add_rust_test_threads(&mut cmd);
2421
2422        if builder.config.sanitizers_enabled(target) {
2423            cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
2424        }
2425
2426        if builder.config.profiler_enabled(target) {
2427            cmd.arg("--profiler-runtime");
2428        }
2429
2430        cmd.env("RUST_TEST_TMPDIR", builder.tempdir());
2431
2432        if builder.config.cmd.rustfix_coverage() {
2433            cmd.arg("--rustfix-coverage");
2434        }
2435
2436        cmd.arg("--channel").arg(&builder.config.channel);
2437
2438        if !builder.config.omit_git_hash {
2439            cmd.arg("--git-hash");
2440        }
2441
2442        let git_config = builder.config.git_config();
2443        cmd.arg("--nightly-branch").arg(git_config.nightly_branch);
2444        cmd.arg("--git-merge-commit-email").arg(git_config.git_merge_commit_email);
2445
2446        #[cfg(feature = "build-metrics")]
2447        builder.metrics.begin_test_suite(
2448            build_helper::metrics::TestSuiteMetadata::Compiletest {
2449                suite: suite.into(),
2450                mode: mode.to_string(),
2451                compare_mode: None,
2452                target: self.target.triple.to_string(),
2453                host: self.test_compiler.host.triple.to_string(),
2454                stage: self.test_compiler.stage,
2455            },
2456            builder,
2457        );
2458
2459        let _group = builder.msg_test(
2460            format!("with compiletest suite={suite} mode={mode}"),
2461            target,
2462            test_compiler.stage,
2463        );
2464        try_run_tests(builder, &mut cmd, false);
2465
2466        if let Some(compare_mode) = compare_mode {
2467            cmd.arg("--compare-mode").arg(compare_mode);
2468
2469            #[cfg(feature = "build-metrics")]
2470            builder.metrics.begin_test_suite(
2471                build_helper::metrics::TestSuiteMetadata::Compiletest {
2472                    suite: suite.into(),
2473                    mode: mode.to_string(),
2474                    compare_mode: Some(compare_mode.into()),
2475                    target: self.target.triple.to_string(),
2476                    host: self.test_compiler.host.triple.to_string(),
2477                    stage: self.test_compiler.stage,
2478                },
2479                builder,
2480            );
2481
2482            builder.info(&format!(
2483                "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
2484                suite, mode, compare_mode, &test_compiler.host, target
2485            ));
2486            let _time = helpers::timeit(builder);
2487            try_run_tests(builder, &mut cmd, false);
2488        }
2489    }
2490
2491    fn metadata(&self) -> Option<StepMetadata> {
2492        Some(
2493            StepMetadata::test(&format!("compiletest-{}", self.suite), self.target)
2494                .stage(self.test_compiler.stage),
2495        )
2496    }
2497}
2498
2499/// Runs the documentation tests for a book in `src/doc` using the `rustdoc` of `test_compiler`.
2500#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2501struct BookTest {
2502    test_compiler: Compiler,
2503    path: PathBuf,
2504    name: &'static str,
2505    is_ext_doc: bool,
2506    dependencies: Vec<&'static str>,
2507}
2508
2509impl Step for BookTest {
2510    type Output = ();
2511    const IS_HOST: bool = true;
2512
2513    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2514        run.never()
2515    }
2516
2517    fn run(self, builder: &Builder<'_>) {
2518        // External docs are different from local because:
2519        // - Some books need pre-processing by mdbook before being tested.
2520        // - They need to save their state to toolstate.
2521        // - They are only tested on the "checktools" builders.
2522        //
2523        // The local docs are tested by default, and we don't want to pay the
2524        // cost of building mdbook, so they use `rustdoc --test` directly.
2525        // Also, the unstable book is special because SUMMARY.md is generated,
2526        // so it is easier to just run `rustdoc` on its files.
2527        if self.is_ext_doc {
2528            self.run_ext_doc(builder);
2529        } else {
2530            self.run_local_doc(builder);
2531        }
2532    }
2533}
2534
2535impl BookTest {
2536    /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
2537    /// which in turn runs `rustdoc --test` on each file in the book.
2538    fn run_ext_doc(self, builder: &Builder<'_>) {
2539        let test_compiler = self.test_compiler;
2540
2541        builder.std(test_compiler, test_compiler.host);
2542
2543        // mdbook just executes a binary named "rustdoc", so we need to update
2544        // PATH so that it points to our rustdoc.
2545        let mut rustdoc_path = builder.rustdoc_for_compiler(test_compiler);
2546        rustdoc_path.pop();
2547        let old_path = env::var_os("PATH").unwrap_or_default();
2548        let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
2549            .expect("could not add rustdoc to PATH");
2550
2551        let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
2552        let path = builder.src.join(&self.path);
2553        // Books often have feature-gated example text.
2554        rustbook_cmd.env("RUSTC_BOOTSTRAP", "1");
2555        rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
2556
2557        // Books may also need to build dependencies. For example, `TheBook` has
2558        // code samples which use the `trpl` crate. For the `rustdoc` invocation
2559        // to find them them successfully, they need to be built first and their
2560        // paths used to generate the
2561        let libs = if !self.dependencies.is_empty() {
2562            let mut lib_paths = vec![];
2563            for dep in self.dependencies {
2564                let mode = Mode::ToolRustcPrivate;
2565                let target = builder.config.host_target;
2566                let cargo = tool::prepare_tool_cargo(
2567                    builder,
2568                    test_compiler,
2569                    mode,
2570                    target,
2571                    Kind::Build,
2572                    dep,
2573                    SourceType::Submodule,
2574                    &[],
2575                );
2576
2577                let stamp = BuildStamp::new(&builder.cargo_out(test_compiler, mode, target))
2578                    .with_prefix(PathBuf::from(dep).file_name().and_then(|v| v.to_str()).unwrap());
2579
2580                let output_paths = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
2581                let directories = output_paths
2582                    .into_iter()
2583                    .filter_map(|p| p.parent().map(ToOwned::to_owned))
2584                    .fold(HashSet::new(), |mut set, dir| {
2585                        set.insert(dir);
2586                        set
2587                    });
2588
2589                lib_paths.extend(directories);
2590            }
2591            lib_paths
2592        } else {
2593            vec![]
2594        };
2595
2596        if !libs.is_empty() {
2597            let paths = libs
2598                .into_iter()
2599                .map(|path| path.into_os_string())
2600                .collect::<Vec<OsString>>()
2601                .join(OsStr::new(","));
2602            rustbook_cmd.args([OsString::from("--library-path"), paths]);
2603        }
2604
2605        builder.add_rust_test_threads(&mut rustbook_cmd);
2606        let _guard = builder.msg_test(
2607            format_args!("mdbook {}", self.path.display()),
2608            test_compiler.host,
2609            test_compiler.stage,
2610        );
2611        let _time = helpers::timeit(builder);
2612        let toolstate = if rustbook_cmd.delay_failure().run(builder) {
2613            ToolState::TestPass
2614        } else {
2615            ToolState::TestFail
2616        };
2617        builder.save_toolstate(self.name, toolstate);
2618    }
2619
2620    /// This runs `rustdoc --test` on all `.md` files in the path.
2621    fn run_local_doc(self, builder: &Builder<'_>) {
2622        let test_compiler = self.test_compiler;
2623        let host = self.test_compiler.host;
2624
2625        builder.std(test_compiler, host);
2626
2627        let _guard = builder.msg_test(
2628            format!("book {}", self.name),
2629            test_compiler.host,
2630            test_compiler.stage,
2631        );
2632
2633        // Do a breadth-first traversal of the `src/doc` directory and just run
2634        // tests for all files that end in `*.md`
2635        let mut stack = vec![builder.src.join(self.path)];
2636        let _time = helpers::timeit(builder);
2637        let mut files = Vec::new();
2638        while let Some(p) = stack.pop() {
2639            if p.is_dir() {
2640                stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
2641                continue;
2642            }
2643
2644            if p.extension().and_then(|s| s.to_str()) != Some("md") {
2645                continue;
2646            }
2647
2648            files.push(p);
2649        }
2650
2651        files.sort();
2652
2653        for file in files {
2654            markdown_test(builder, test_compiler, &file);
2655        }
2656    }
2657}
2658
2659macro_rules! test_book {
2660    ($(
2661        $name:ident, $path:expr, $book_name:expr,
2662        default=$default:expr
2663        $(,submodules = $submodules:expr)?
2664        $(,dependencies=$dependencies:expr)?
2665        ;
2666    )+) => {
2667        $(
2668            #[derive(Debug, Clone, PartialEq, Eq, Hash)]
2669            pub struct $name {
2670                test_compiler: Compiler,
2671            }
2672
2673            impl Step for $name {
2674                type Output = ();
2675                const IS_HOST: bool = true;
2676
2677                fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2678                    run.path($path)
2679                }
2680
2681                fn is_default_step(_builder: &Builder<'_>) -> bool {
2682                    const { $default }
2683                }
2684
2685                fn make_run(run: RunConfig<'_>) {
2686                    run.builder.ensure($name {
2687                        test_compiler: run.builder.compiler(run.builder.top_stage, run.target),
2688                    });
2689                }
2690
2691                fn run(self, builder: &Builder<'_>) {
2692                    $(
2693                        for submodule in $submodules {
2694                            builder.require_submodule(submodule, None);
2695                        }
2696                    )*
2697
2698                    let dependencies = vec![];
2699                    $(
2700                        let mut dependencies = dependencies;
2701                        for dep in $dependencies {
2702                            dependencies.push(dep);
2703                        }
2704                    )?
2705
2706                    builder.ensure(BookTest {
2707                        test_compiler: self.test_compiler,
2708                        path: PathBuf::from($path),
2709                        name: $book_name,
2710                        is_ext_doc: !$default,
2711                        dependencies,
2712                    });
2713                }
2714            }
2715        )+
2716    }
2717}
2718
2719test_book!(
2720    Nomicon, "src/doc/nomicon", "nomicon", default=false, submodules=["src/doc/nomicon"];
2721    Reference, "src/doc/reference", "reference", default=false, submodules=["src/doc/reference"];
2722    RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
2723    RustcBook, "src/doc/rustc", "rustc", default=true;
2724    RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false, submodules=["src/doc/rust-by-example"];
2725    EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false, submodules=["src/doc/embedded-book"];
2726    TheBook, "src/doc/book", "book", default=false, submodules=["src/doc/book"], dependencies=["src/doc/book/packages/trpl"];
2727    UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
2728    EditionGuide, "src/doc/edition-guide", "edition-guide", default=false, submodules=["src/doc/edition-guide"];
2729);
2730
2731#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2732pub struct ErrorIndex {
2733    compilers: RustcPrivateCompilers,
2734}
2735
2736impl Step for ErrorIndex {
2737    type Output = ();
2738    const IS_HOST: bool = true;
2739
2740    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2741        // Also add `error-index` here since that is what appears in the error message
2742        // when this fails.
2743        run.path("src/tools/error_index_generator").alias("error-index")
2744    }
2745
2746    fn is_default_step(_builder: &Builder<'_>) -> bool {
2747        true
2748    }
2749
2750    fn make_run(run: RunConfig<'_>) {
2751        // error_index_generator depends on librustdoc. Use the compiler that
2752        // is normally used to build rustdoc for other tests (like compiletest
2753        // tests in tests/rustdoc) so that it shares the same artifacts.
2754        let compilers = RustcPrivateCompilers::new(
2755            run.builder,
2756            run.builder.top_stage,
2757            run.builder.config.host_target,
2758        );
2759        run.builder.ensure(ErrorIndex { compilers });
2760    }
2761
2762    /// Runs the error index generator tool to execute the tests located in the error
2763    /// index.
2764    ///
2765    /// The `error_index_generator` tool lives in `src/tools` and is used to
2766    /// generate a markdown file from the error indexes of the code base which is
2767    /// then passed to `rustdoc --test`.
2768    fn run(self, builder: &Builder<'_>) {
2769        // The compiler that we are testing
2770        let target_compiler = self.compilers.target_compiler();
2771
2772        let dir = testdir(builder, target_compiler.host);
2773        t!(fs::create_dir_all(&dir));
2774        let output = dir.join("error-index.md");
2775
2776        let mut tool = tool::ErrorIndex::command(builder, self.compilers);
2777        tool.arg("markdown").arg(&output);
2778
2779        let guard = builder.msg_test("error-index", target_compiler.host, target_compiler.stage);
2780        let _time = helpers::timeit(builder);
2781        tool.run_capture(builder);
2782        drop(guard);
2783        // The tests themselves need to link to std, so make sure it is
2784        // available.
2785        builder.std(target_compiler, target_compiler.host);
2786        markdown_test(builder, target_compiler, &output);
2787    }
2788}
2789
2790fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
2791    if let Ok(contents) = fs::read_to_string(markdown)
2792        && !contents.contains("```")
2793    {
2794        return true;
2795    }
2796
2797    builder.do_if_verbose(|| println!("doc tests for: {}", markdown.display()));
2798    let mut cmd = builder.rustdoc_cmd(compiler);
2799    builder.add_rust_test_threads(&mut cmd);
2800    // allow for unstable options such as new editions
2801    cmd.arg("-Z");
2802    cmd.arg("unstable-options");
2803    cmd.arg("--test");
2804    cmd.arg(markdown);
2805    cmd.env("RUSTC_BOOTSTRAP", "1");
2806
2807    let test_args = builder.config.test_args().join(" ");
2808    cmd.arg("--test-args").arg(test_args);
2809
2810    cmd = cmd.delay_failure();
2811    if !builder.config.verbose_tests {
2812        cmd.run_capture(builder).is_success()
2813    } else {
2814        cmd.run(builder)
2815    }
2816}
2817
2818/// Runs `cargo test` for the compiler crates in `compiler/`.
2819///
2820/// (This step does not test `rustc_codegen_cranelift` or `rustc_codegen_gcc`,
2821/// which have their own separate test steps.)
2822#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2823pub struct CrateLibrustc {
2824    /// The compiler that will run unit tests and doctests on the in-tree rustc source.
2825    build_compiler: Compiler,
2826    target: TargetSelection,
2827    crates: Vec<String>,
2828}
2829
2830impl Step for CrateLibrustc {
2831    type Output = ();
2832    const IS_HOST: bool = true;
2833
2834    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2835        run.crate_or_deps("rustc-main").path("compiler")
2836    }
2837
2838    fn is_default_step(_builder: &Builder<'_>) -> bool {
2839        true
2840    }
2841
2842    fn make_run(run: RunConfig<'_>) {
2843        let builder = run.builder;
2844        let host = run.build_triple();
2845        let build_compiler = builder.compiler(builder.top_stage - 1, host);
2846        let crates = run.make_run_crates(Alias::Compiler);
2847
2848        builder.ensure(CrateLibrustc { build_compiler, target: run.target, crates });
2849    }
2850
2851    fn run(self, builder: &Builder<'_>) {
2852        builder.std(self.build_compiler, self.target);
2853
2854        // To actually run the tests, delegate to a copy of the `Crate` step.
2855        builder.ensure(Crate {
2856            build_compiler: self.build_compiler,
2857            target: self.target,
2858            mode: Mode::Rustc,
2859            crates: self.crates,
2860        });
2861    }
2862
2863    fn metadata(&self) -> Option<StepMetadata> {
2864        Some(StepMetadata::test("CrateLibrustc", self.target).built_by(self.build_compiler))
2865    }
2866}
2867
2868/// Given a `cargo test` subcommand, add the appropriate flags and run it.
2869///
2870/// Returns whether the test succeeded.
2871fn run_cargo_test<'a>(
2872    cargo: builder::Cargo,
2873    libtest_args: &[&str],
2874    crates: &[String],
2875    description: impl Into<Option<&'a str>>,
2876    target: TargetSelection,
2877    builder: &Builder<'_>,
2878) -> bool {
2879    let compiler = cargo.compiler();
2880    let stage = match cargo.mode() {
2881        Mode::Std => compiler.stage,
2882        _ => compiler.stage + 1,
2883    };
2884
2885    let mut cargo = prepare_cargo_test(cargo, libtest_args, crates, target, builder);
2886    let _time = helpers::timeit(builder);
2887
2888    let _group = description.into().and_then(|what| builder.msg_test(what, target, stage));
2889
2890    #[cfg(feature = "build-metrics")]
2891    builder.metrics.begin_test_suite(
2892        build_helper::metrics::TestSuiteMetadata::CargoPackage {
2893            crates: crates.iter().map(|c| c.to_string()).collect(),
2894            target: target.triple.to_string(),
2895            host: compiler.host.triple.to_string(),
2896            stage: compiler.stage,
2897        },
2898        builder,
2899    );
2900    add_flags_and_try_run_tests(builder, &mut cargo)
2901}
2902
2903/// Given a `cargo test` subcommand, pass it the appropriate test flags given a `builder`.
2904fn prepare_cargo_test(
2905    cargo: builder::Cargo,
2906    libtest_args: &[&str],
2907    crates: &[String],
2908    target: TargetSelection,
2909    builder: &Builder<'_>,
2910) -> BootstrapCommand {
2911    let compiler = cargo.compiler();
2912    let mut cargo: BootstrapCommand = cargo.into();
2913
2914    // Propagate `--bless` if it has not already been set/unset
2915    // Any tools that want to use this should bless if `RUSTC_BLESS` is set to
2916    // anything other than `0`.
2917    if builder.config.cmd.bless() && !cargo.get_envs().any(|v| v.0 == "RUSTC_BLESS") {
2918        cargo.env("RUSTC_BLESS", "Gesundheit");
2919    }
2920
2921    // Pass in some standard flags then iterate over the graph we've discovered
2922    // in `cargo metadata` with the maps above and figure out what `-p`
2923    // arguments need to get passed.
2924    if builder.kind == Kind::Test && !builder.fail_fast {
2925        cargo.arg("--no-fail-fast");
2926    }
2927
2928    if builder.config.json_output {
2929        cargo.arg("--message-format=json");
2930    }
2931
2932    match builder.doc_tests {
2933        DocTests::Only => {
2934            cargo.arg("--doc");
2935        }
2936        DocTests::No => {
2937            cargo.args(["--bins", "--examples", "--tests", "--benches"]);
2938        }
2939        DocTests::Yes => {}
2940    }
2941
2942    for krate in crates {
2943        cargo.arg("-p").arg(krate);
2944    }
2945
2946    cargo.arg("--").args(builder.config.test_args()).args(libtest_args);
2947    if !builder.config.verbose_tests {
2948        cargo.arg("--quiet");
2949    }
2950
2951    // The tests are going to run with the *target* libraries, so we need to
2952    // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
2953    //
2954    // Note that to run the compiler we need to run with the *host* libraries,
2955    // but our wrapper scripts arrange for that to be the case anyway.
2956    //
2957    // We skip everything on Miri as then this overwrites the libdir set up
2958    // by `Cargo::new` and that actually makes things go wrong.
2959    if builder.kind != Kind::Miri {
2960        let mut dylib_paths = builder.rustc_lib_paths(compiler);
2961        dylib_paths.push(builder.sysroot_target_libdir(compiler, target));
2962        helpers::add_dylib_path(dylib_paths, &mut cargo);
2963    }
2964
2965    if builder.remote_tested(target) {
2966        cargo.env(
2967            format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2968            format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
2969        );
2970    } else if let Some(tool) = builder.runner(target) {
2971        cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), tool);
2972    }
2973
2974    cargo
2975}
2976
2977/// Runs `cargo test` for standard library crates.
2978///
2979/// (Also used internally to run `cargo test` for compiler crates.)
2980///
2981/// FIXME(Zalathar): Try to split this into two separate steps: a user-visible
2982/// step for testing standard library crates, and an internal step used for both
2983/// library crates and compiler crates.
2984#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2985pub struct Crate {
2986    /// The compiler that will *build* libstd or rustc in test mode.
2987    build_compiler: Compiler,
2988    target: TargetSelection,
2989    mode: Mode,
2990    crates: Vec<String>,
2991}
2992
2993impl Step for Crate {
2994    type Output = ();
2995
2996    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2997        run.crate_or_deps("sysroot").crate_or_deps("coretests").crate_or_deps("alloctests")
2998    }
2999
3000    fn is_default_step(_builder: &Builder<'_>) -> bool {
3001        true
3002    }
3003
3004    fn make_run(run: RunConfig<'_>) {
3005        let builder = run.builder;
3006        let host = run.build_triple();
3007        let build_compiler = builder.compiler(builder.top_stage, host);
3008        let crates = run
3009            .paths
3010            .iter()
3011            .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
3012            .collect();
3013
3014        builder.ensure(Crate { build_compiler, target: run.target, mode: Mode::Std, crates });
3015    }
3016
3017    /// Runs all unit tests plus documentation tests for a given crate defined
3018    /// by a `Cargo.toml` (single manifest)
3019    ///
3020    /// This is what runs tests for crates like the standard library, compiler, etc.
3021    /// It essentially is the driver for running `cargo test`.
3022    ///
3023    /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
3024    /// arguments, and those arguments are discovered from `cargo metadata`.
3025    fn run(self, builder: &Builder<'_>) {
3026        let build_compiler = self.build_compiler;
3027        let target = self.target;
3028        let mode = self.mode;
3029
3030        // Prepare sysroot
3031        // See [field@compile::Std::force_recompile].
3032        builder.ensure(Std::new(build_compiler, build_compiler.host).force_recompile(true));
3033
3034        let mut cargo = if builder.kind == Kind::Miri {
3035            if builder.top_stage == 0 {
3036                eprintln!("ERROR: `x.py miri` requires stage 1 or higher");
3037                std::process::exit(1);
3038            }
3039
3040            // Build `cargo miri test` command
3041            // (Implicitly prepares target sysroot)
3042            let mut cargo = builder::Cargo::new(
3043                builder,
3044                build_compiler,
3045                mode,
3046                SourceType::InTree,
3047                target,
3048                Kind::MiriTest,
3049            );
3050            // This hack helps bootstrap run standard library tests in Miri. The issue is as
3051            // follows: when running `cargo miri test` on libcore, cargo builds a local copy of core
3052            // and makes it a dependency of the integration test crate. This copy duplicates all the
3053            // lang items, so the build fails. (Regular testing avoids this because the sysroot is a
3054            // literal copy of what `cargo build` produces, but since Miri builds its own sysroot
3055            // this does not work for us.) So we need to make it so that the locally built libcore
3056            // contains all the items from `core`, but does not re-define them -- we want to replace
3057            // the entire crate but a re-export of the sysroot crate. We do this by swapping out the
3058            // source file: if `MIRI_REPLACE_LIBRS_IF_NOT_TEST` is set and we are building a
3059            // `lib.rs` file, and a `lib.miri.rs` file exists in the same folder, we build that
3060            // instead. But crucially we only do that for the library, not the test builds.
3061            cargo.env("MIRI_REPLACE_LIBRS_IF_NOT_TEST", "1");
3062            // std needs to be built with `-Zforce-unstable-if-unmarked`. For some reason the builder
3063            // does not set this directly, but relies on the rustc wrapper to set it, and we are not using
3064            // the wrapper -- hence we have to set it ourselves.
3065            cargo.rustflag("-Zforce-unstable-if-unmarked");
3066            cargo
3067        } else {
3068            // Also prepare a sysroot for the target.
3069            if !builder.config.is_host_target(target) {
3070                builder.ensure(compile::Std::new(build_compiler, target).force_recompile(true));
3071                builder.ensure(RemoteCopyLibs { build_compiler, target });
3072            }
3073
3074            // Build `cargo test` command
3075            builder::Cargo::new(
3076                builder,
3077                build_compiler,
3078                mode,
3079                SourceType::InTree,
3080                target,
3081                builder.kind,
3082            )
3083        };
3084
3085        match mode {
3086            Mode::Std => {
3087                if builder.kind == Kind::Miri {
3088                    // We can't use `std_cargo` as that uses `optimized-compiler-builtins` which
3089                    // needs host tools for the given target. This is similar to what `compile::Std`
3090                    // does when `is_for_mir_opt_tests` is true. There's probably a chance for
3091                    // de-duplication here... `std_cargo` should support a mode that avoids needing
3092                    // host tools.
3093                    cargo
3094                        .arg("--manifest-path")
3095                        .arg(builder.src.join("library/sysroot/Cargo.toml"));
3096                } else {
3097                    compile::std_cargo(builder, target, &mut cargo, &[]);
3098                }
3099            }
3100            Mode::Rustc => {
3101                compile::rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
3102            }
3103            _ => panic!("can only test libraries"),
3104        };
3105
3106        let mut crates = self.crates.clone();
3107        // The core and alloc crates can't directly be tested. We
3108        // could silently ignore them, but adding their own test
3109        // crates is less confusing for users. We still keep core and
3110        // alloc themself for doctests
3111        if crates.iter().any(|crate_| crate_ == "core") {
3112            crates.push("coretests".to_owned());
3113        }
3114        if crates.iter().any(|crate_| crate_ == "alloc") {
3115            crates.push("alloctests".to_owned());
3116        }
3117
3118        run_cargo_test(cargo, &[], &crates, &*crate_description(&self.crates), target, builder);
3119    }
3120}
3121
3122/// Run cargo tests for the rustdoc crate.
3123/// Rustdoc is special in various ways, which is why this step is different from `Crate`.
3124#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3125pub struct CrateRustdoc {
3126    host: TargetSelection,
3127}
3128
3129impl Step for CrateRustdoc {
3130    type Output = ();
3131    const IS_HOST: bool = true;
3132
3133    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3134        run.paths(&["src/librustdoc", "src/tools/rustdoc"])
3135    }
3136
3137    fn is_default_step(_builder: &Builder<'_>) -> bool {
3138        true
3139    }
3140
3141    fn make_run(run: RunConfig<'_>) {
3142        let builder = run.builder;
3143
3144        builder.ensure(CrateRustdoc { host: run.target });
3145    }
3146
3147    fn run(self, builder: &Builder<'_>) {
3148        let target = self.host;
3149
3150        let compiler = if builder.download_rustc() {
3151            builder.compiler(builder.top_stage, target)
3152        } else {
3153            // Use the previous stage compiler to reuse the artifacts that are
3154            // created when running compiletest for tests/rustdoc. If this used
3155            // `compiler`, then it would cause rustdoc to be built *again*, which
3156            // isn't really necessary.
3157            builder.compiler_for(builder.top_stage, target, target)
3158        };
3159        // NOTE: normally `ensure(Rustc)` automatically runs `ensure(Std)` for us. However, when
3160        // using `download-rustc`, the rustc_private artifacts may be in a *different sysroot* from
3161        // the target rustdoc (`ci-rustc-sysroot` vs `stage2`). In that case, we need to ensure this
3162        // explicitly to make sure it ends up in the stage2 sysroot.
3163        builder.std(compiler, target);
3164        builder.ensure(compile::Rustc::new(compiler, target));
3165
3166        let mut cargo = tool::prepare_tool_cargo(
3167            builder,
3168            compiler,
3169            Mode::ToolRustcPrivate,
3170            target,
3171            builder.kind,
3172            "src/tools/rustdoc",
3173            SourceType::InTree,
3174            &[],
3175        );
3176        if self.host.contains("musl") {
3177            cargo.arg("'-Ctarget-feature=-crt-static'");
3178        }
3179
3180        // This is needed for running doctests on librustdoc. This is a bit of
3181        // an unfortunate interaction with how bootstrap works and how cargo
3182        // sets up the dylib path, and the fact that the doctest (in
3183        // html/markdown.rs) links to rustc-private libs. For stage1, the
3184        // compiler host dylibs (in stage1/lib) are not the same as the target
3185        // dylibs (in stage1/lib/rustlib/...). This is different from a normal
3186        // rust distribution where they are the same.
3187        //
3188        // On the cargo side, normal tests use `target_process` which handles
3189        // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
3190        // case). However, for doctests it uses `rustdoc_process` which only
3191        // sets up the dylib path for the *host* (stage1/lib), which is the
3192        // wrong directory.
3193        //
3194        // Recall that we special-cased `compiler_for(top_stage)` above, so we always use stage1.
3195        //
3196        // It should be considered to just stop running doctests on
3197        // librustdoc. There is only one test, and it doesn't look too
3198        // important. There might be other ways to avoid this, but it seems
3199        // pretty convoluted.
3200        //
3201        // See also https://github.com/rust-lang/rust/issues/13983 where the
3202        // host vs target dylibs for rustdoc are consistently tricky to deal
3203        // with.
3204        //
3205        // Note that this set the host libdir for `download_rustc`, which uses a normal rust distribution.
3206        let libdir = if builder.download_rustc() {
3207            builder.rustc_libdir(compiler)
3208        } else {
3209            builder.sysroot_target_libdir(compiler, target).to_path_buf()
3210        };
3211        let mut dylib_path = dylib_path();
3212        dylib_path.insert(0, PathBuf::from(&*libdir));
3213        cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
3214
3215        run_cargo_test(cargo, &[], &["rustdoc:0.0.0".to_string()], "rustdoc", target, builder);
3216    }
3217}
3218
3219#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3220pub struct CrateRustdocJsonTypes {
3221    build_compiler: Compiler,
3222    target: TargetSelection,
3223}
3224
3225impl Step for CrateRustdocJsonTypes {
3226    type Output = ();
3227    const IS_HOST: bool = true;
3228
3229    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3230        run.path("src/rustdoc-json-types")
3231    }
3232
3233    fn is_default_step(_builder: &Builder<'_>) -> bool {
3234        true
3235    }
3236
3237    fn make_run(run: RunConfig<'_>) {
3238        let builder = run.builder;
3239
3240        builder.ensure(CrateRustdocJsonTypes {
3241            build_compiler: get_tool_target_compiler(
3242                builder,
3243                ToolTargetBuildMode::Build(run.target),
3244            ),
3245            target: run.target,
3246        });
3247    }
3248
3249    fn run(self, builder: &Builder<'_>) {
3250        let target = self.target;
3251
3252        let cargo = tool::prepare_tool_cargo(
3253            builder,
3254            self.build_compiler,
3255            Mode::ToolTarget,
3256            target,
3257            builder.kind,
3258            "src/rustdoc-json-types",
3259            SourceType::InTree,
3260            &[],
3261        );
3262
3263        // FIXME: this looks very wrong, libtest doesn't accept `-C` arguments and the quotes are fishy.
3264        let libtest_args = if target.contains("musl") {
3265            ["'-Ctarget-feature=-crt-static'"].as_slice()
3266        } else {
3267            &[]
3268        };
3269
3270        run_cargo_test(
3271            cargo,
3272            libtest_args,
3273            &["rustdoc-json-types".to_string()],
3274            "rustdoc-json-types",
3275            target,
3276            builder,
3277        );
3278    }
3279}
3280
3281/// Some test suites are run inside emulators or on remote devices, and most
3282/// of our test binaries are linked dynamically which means we need to ship
3283/// the standard library and such to the emulator ahead of time. This step
3284/// represents this and is a dependency of all test suites.
3285///
3286/// Most of the time this is a no-op. For some steps such as shipping data to
3287/// QEMU we have to build our own tools so we've got conditional dependencies
3288/// on those programs as well. Note that the remote test client is built for
3289/// the build target (us) and the server is built for the target.
3290#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3291pub struct RemoteCopyLibs {
3292    build_compiler: Compiler,
3293    target: TargetSelection,
3294}
3295
3296impl Step for RemoteCopyLibs {
3297    type Output = ();
3298
3299    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3300        run.never()
3301    }
3302
3303    fn run(self, builder: &Builder<'_>) {
3304        let build_compiler = self.build_compiler;
3305        let target = self.target;
3306        if !builder.remote_tested(target) {
3307            return;
3308        }
3309
3310        builder.std(build_compiler, target);
3311
3312        builder.info(&format!("REMOTE copy libs to emulator ({target})"));
3313
3314        let remote_test_server = builder.ensure(tool::RemoteTestServer { build_compiler, target });
3315
3316        // Spawn the emulator and wait for it to come online
3317        let tool = builder.tool_exe(Tool::RemoteTestClient);
3318        let mut cmd = command(&tool);
3319        cmd.arg("spawn-emulator")
3320            .arg(target.triple)
3321            .arg(&remote_test_server.tool_path)
3322            .arg(builder.tempdir());
3323        if let Some(rootfs) = builder.qemu_rootfs(target) {
3324            cmd.arg(rootfs);
3325        }
3326        cmd.run(builder);
3327
3328        // Push all our dylibs to the emulator
3329        for f in t!(builder.sysroot_target_libdir(build_compiler, target).read_dir()) {
3330            let f = t!(f);
3331            if helpers::is_dylib(&f.path()) {
3332                command(&tool).arg("push").arg(f.path()).run(builder);
3333            }
3334        }
3335    }
3336}
3337
3338#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3339pub struct Distcheck;
3340
3341impl Step for Distcheck {
3342    type Output = ();
3343
3344    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3345        run.alias("distcheck")
3346    }
3347
3348    fn make_run(run: RunConfig<'_>) {
3349        run.builder.ensure(Distcheck);
3350    }
3351
3352    /// Runs `distcheck`, which is a collection of smoke tests:
3353    ///
3354    /// - Run `make check` from an unpacked dist tarball to make sure we can at the minimum run
3355    ///   check steps from those sources.
3356    /// - Check that selected dist components (`rust-src` only at the moment) at least have expected
3357    ///   directory shape and crate manifests that cargo can generate a lockfile from.
3358    /// - Check that we can run `cargo metadata` on the workspace in the `rustc-dev` component
3359    ///
3360    /// FIXME(#136822): dist components are under-tested.
3361    fn run(self, builder: &Builder<'_>) {
3362        // Use a temporary directory completely outside the current checkout, to avoid reusing any
3363        // local source code, built artifacts or configuration by accident
3364        let root_dir = std::env::temp_dir().join("distcheck");
3365
3366        distcheck_plain_source_tarball(builder, &root_dir.join("distcheck-rustc-src"));
3367        distcheck_rust_src(builder, &root_dir.join("distcheck-rust-src"));
3368        distcheck_rustc_dev(builder, &root_dir.join("distcheck-rustc-dev"));
3369    }
3370}
3371
3372/// Check that we can build some basic things from the plain source tarball
3373fn distcheck_plain_source_tarball(builder: &Builder<'_>, plain_src_dir: &Path) {
3374    builder.info("Distcheck plain source tarball");
3375    let plain_src_tarball = builder.ensure(dist::PlainSourceTarball);
3376    builder.clear_dir(plain_src_dir);
3377
3378    let configure_args: Vec<String> = std::env::var("DISTCHECK_CONFIGURE_ARGS")
3379        .map(|args| args.split(" ").map(|s| s.to_string()).collect::<Vec<String>>())
3380        .unwrap_or_default();
3381
3382    command("tar")
3383        .arg("-xf")
3384        .arg(plain_src_tarball.tarball())
3385        .arg("--strip-components=1")
3386        .current_dir(plain_src_dir)
3387        .run(builder);
3388    command("./configure")
3389        .arg("--set")
3390        .arg("rust.omit-git-hash=false")
3391        .args(&configure_args)
3392        .arg("--enable-vendor")
3393        .current_dir(plain_src_dir)
3394        .run(builder);
3395    command(helpers::make(&builder.config.host_target.triple))
3396        .arg("check")
3397        // Do not run the build as if we were in CI, otherwise git would be assumed to be
3398        // present, but we build from a tarball here
3399        .env("GITHUB_ACTIONS", "0")
3400        .current_dir(plain_src_dir)
3401        .run(builder);
3402    // Mitigate pressure on small-capacity disks.
3403    builder.remove_dir(plain_src_dir);
3404}
3405
3406/// Check that rust-src has all of libstd's dependencies
3407fn distcheck_rust_src(builder: &Builder<'_>, src_dir: &Path) {
3408    builder.info("Distcheck rust-src");
3409    let src_tarball = builder.ensure(dist::Src);
3410    builder.clear_dir(src_dir);
3411
3412    command("tar")
3413        .arg("-xf")
3414        .arg(src_tarball.tarball())
3415        .arg("--strip-components=1")
3416        .current_dir(src_dir)
3417        .run(builder);
3418
3419    let toml = src_dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
3420    command(&builder.initial_cargo)
3421        // Will read the libstd Cargo.toml
3422        // which uses the unstable `public-dependency` feature.
3423        .env("RUSTC_BOOTSTRAP", "1")
3424        .arg("generate-lockfile")
3425        .arg("--manifest-path")
3426        .arg(&toml)
3427        .current_dir(src_dir)
3428        .run(builder);
3429    // Mitigate pressure on small-capacity disks.
3430    builder.remove_dir(src_dir);
3431}
3432
3433/// Check that rustc-dev's compiler crate source code can be loaded with `cargo metadata`
3434fn distcheck_rustc_dev(builder: &Builder<'_>, dir: &Path) {
3435    builder.info("Distcheck rustc-dev");
3436    let tarball = builder.ensure(dist::RustcDev::new(builder, builder.host_target)).unwrap();
3437    builder.clear_dir(dir);
3438
3439    command("tar")
3440        .arg("-xf")
3441        .arg(tarball.tarball())
3442        .arg("--strip-components=1")
3443        .current_dir(dir)
3444        .run(builder);
3445
3446    command(&builder.initial_cargo)
3447        .arg("metadata")
3448        .arg("--manifest-path")
3449        .arg("rustc-dev/lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml")
3450        .env("RUSTC_BOOTSTRAP", "1")
3451        // We might not have a globally available `rustc` binary on CI
3452        .env("RUSTC", &builder.initial_rustc)
3453        .current_dir(dir)
3454        .run(builder);
3455    // Mitigate pressure on small-capacity disks.
3456    builder.remove_dir(dir);
3457}
3458
3459/// Runs unit tests in `bootstrap_test.py`, which test the Python parts of bootstrap.
3460#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3461pub(crate) struct BootstrapPy;
3462
3463impl Step for BootstrapPy {
3464    type Output = ();
3465    const IS_HOST: bool = true;
3466
3467    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3468        run.alias("bootstrap-py")
3469    }
3470
3471    fn is_default_step(builder: &Builder<'_>) -> bool {
3472        // Bootstrap tests might not be perfectly self-contained and can depend
3473        // on the environment, so only run them by default in CI, not locally.
3474        // See `test::Bootstrap::should_run`.
3475        builder.config.is_running_on_ci
3476    }
3477
3478    fn make_run(run: RunConfig<'_>) {
3479        run.builder.ensure(BootstrapPy)
3480    }
3481
3482    fn run(self, builder: &Builder<'_>) -> Self::Output {
3483        let mut check_bootstrap = command(
3484            builder.config.python.as_ref().expect("python is required for running bootstrap tests"),
3485        );
3486        check_bootstrap
3487            .args(["-m", "unittest", "bootstrap_test.py"])
3488            // Forward command-line args after `--` to unittest, for filtering etc.
3489            .args(builder.config.test_args())
3490            .env("BUILD_DIR", &builder.out)
3491            .env("BUILD_PLATFORM", builder.build.host_target.triple)
3492            .env("BOOTSTRAP_TEST_RUSTC_BIN", &builder.initial_rustc)
3493            .env("BOOTSTRAP_TEST_CARGO_BIN", &builder.initial_cargo)
3494            .current_dir(builder.src.join("src/bootstrap/"));
3495        check_bootstrap.delay_failure().run(builder);
3496    }
3497}
3498
3499#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3500pub struct Bootstrap;
3501
3502impl Step for Bootstrap {
3503    type Output = ();
3504    const IS_HOST: bool = true;
3505
3506    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3507        run.path("src/bootstrap")
3508    }
3509
3510    fn is_default_step(builder: &Builder<'_>) -> bool {
3511        // Bootstrap tests might not be perfectly self-contained and can depend on the external
3512        // environment, submodules that are checked out, etc.
3513        // Therefore we only run them by default on CI.
3514        builder.config.is_running_on_ci
3515    }
3516
3517    /// Tests the build system itself.
3518    fn run(self, builder: &Builder<'_>) {
3519        let host = builder.config.host_target;
3520        let build_compiler = builder.compiler(0, host);
3521
3522        // Some tests require cargo submodule to be present.
3523        builder.build.require_submodule("src/tools/cargo", None);
3524
3525        let mut cargo = tool::prepare_tool_cargo(
3526            builder,
3527            build_compiler,
3528            Mode::ToolBootstrap,
3529            host,
3530            Kind::Test,
3531            "src/bootstrap",
3532            SourceType::InTree,
3533            &[],
3534        );
3535
3536        cargo.release_build(false);
3537
3538        cargo
3539            .rustflag("-Cdebuginfo=2")
3540            .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
3541            // Needed for insta to correctly write pending snapshots to the right directories.
3542            .env("INSTA_WORKSPACE_ROOT", &builder.src)
3543            .env("RUSTC_BOOTSTRAP", "1");
3544
3545        if builder.config.cmd.bless() {
3546            // Tell `insta` to automatically bless any failing `.snap` files.
3547            // Unlike compiletest blessing, the tests might still report failure.
3548            // Does not bless inline snapshots.
3549            cargo.env("INSTA_UPDATE", "always");
3550        }
3551
3552        run_cargo_test(cargo, &[], &[], None, host, builder);
3553    }
3554
3555    fn make_run(run: RunConfig<'_>) {
3556        run.builder.ensure(Bootstrap);
3557    }
3558}
3559
3560fn get_compiler_to_test(builder: &Builder<'_>, target: TargetSelection) -> Compiler {
3561    builder.compiler(builder.top_stage, target)
3562}
3563
3564/// Tests the Platform Support page in the rustc book.
3565/// `test_compiler` is used to query the actual targets that are checked.
3566#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3567pub struct TierCheck {
3568    test_compiler: Compiler,
3569}
3570
3571impl Step for TierCheck {
3572    type Output = ();
3573    const IS_HOST: bool = true;
3574
3575    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3576        run.path("src/tools/tier-check")
3577    }
3578
3579    fn is_default_step(_builder: &Builder<'_>) -> bool {
3580        true
3581    }
3582
3583    fn make_run(run: RunConfig<'_>) {
3584        run.builder
3585            .ensure(TierCheck { test_compiler: get_compiler_to_test(run.builder, run.target) });
3586    }
3587
3588    fn run(self, builder: &Builder<'_>) {
3589        let tool_build_compiler = builder.compiler(0, builder.host_target);
3590
3591        let mut cargo = tool::prepare_tool_cargo(
3592            builder,
3593            tool_build_compiler,
3594            Mode::ToolBootstrap,
3595            tool_build_compiler.host,
3596            Kind::Run,
3597            "src/tools/tier-check",
3598            SourceType::InTree,
3599            &[],
3600        );
3601        cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
3602        cargo.arg(builder.rustc(self.test_compiler));
3603
3604        let _guard = builder.msg_test(
3605            "platform support check",
3606            self.test_compiler.host,
3607            self.test_compiler.stage,
3608        );
3609        BootstrapCommand::from(cargo).delay_failure().run(builder);
3610    }
3611
3612    fn metadata(&self) -> Option<StepMetadata> {
3613        Some(StepMetadata::test("tier-check", self.test_compiler.host))
3614    }
3615}
3616
3617#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3618pub struct LintDocs {
3619    build_compiler: Compiler,
3620    target: TargetSelection,
3621}
3622
3623impl Step for LintDocs {
3624    type Output = ();
3625    const IS_HOST: bool = true;
3626
3627    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3628        run.path("src/tools/lint-docs")
3629    }
3630
3631    fn is_default_step(builder: &Builder<'_>) -> bool {
3632        // Lint docs tests might not work with stage 1, so do not run this test by default in
3633        // `x test` below stage 2.
3634        builder.top_stage >= 2
3635    }
3636
3637    fn make_run(run: RunConfig<'_>) {
3638        if run.builder.top_stage < 2 {
3639            eprintln!("WARNING: lint-docs tests might not work below stage 2");
3640        }
3641
3642        run.builder.ensure(LintDocs {
3643            build_compiler: prepare_doc_compiler(
3644                run.builder,
3645                run.builder.config.host_target,
3646                run.builder.top_stage,
3647            ),
3648            target: run.target,
3649        });
3650    }
3651
3652    /// Tests that the lint examples in the rustc book generate the correct
3653    /// lints and have the expected format.
3654    fn run(self, builder: &Builder<'_>) {
3655        builder.ensure(crate::core::build_steps::doc::RustcBook::validate(
3656            self.build_compiler,
3657            self.target,
3658        ));
3659    }
3660
3661    fn metadata(&self) -> Option<StepMetadata> {
3662        Some(StepMetadata::test("lint-docs", self.target).built_by(self.build_compiler))
3663    }
3664}
3665
3666#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3667pub struct RustInstaller;
3668
3669impl Step for RustInstaller {
3670    type Output = ();
3671    const IS_HOST: bool = true;
3672
3673    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3674        run.path("src/tools/rust-installer")
3675    }
3676
3677    fn is_default_step(_builder: &Builder<'_>) -> bool {
3678        true
3679    }
3680
3681    fn make_run(run: RunConfig<'_>) {
3682        run.builder.ensure(Self);
3683    }
3684
3685    /// Ensure the version placeholder replacement tool builds
3686    fn run(self, builder: &Builder<'_>) {
3687        let bootstrap_host = builder.config.host_target;
3688        let build_compiler = builder.compiler(0, bootstrap_host);
3689        let cargo = tool::prepare_tool_cargo(
3690            builder,
3691            build_compiler,
3692            Mode::ToolBootstrap,
3693            bootstrap_host,
3694            Kind::Test,
3695            "src/tools/rust-installer",
3696            SourceType::InTree,
3697            &[],
3698        );
3699
3700        let _guard = builder.msg_test("rust-installer", bootstrap_host, 1);
3701        run_cargo_test(cargo, &[], &[], None, bootstrap_host, builder);
3702
3703        // We currently don't support running the test.sh script outside linux(?) environments.
3704        // Eventually this should likely migrate to #[test]s in rust-installer proper rather than a
3705        // set of scripts, which will likely allow dropping this if.
3706        if bootstrap_host != "x86_64-unknown-linux-gnu" {
3707            return;
3708        }
3709
3710        let mut cmd = command(builder.src.join("src/tools/rust-installer/test.sh"));
3711        let tmpdir = testdir(builder, build_compiler.host).join("rust-installer");
3712        let _ = std::fs::remove_dir_all(&tmpdir);
3713        let _ = std::fs::create_dir_all(&tmpdir);
3714        cmd.current_dir(&tmpdir);
3715        cmd.env("CARGO_TARGET_DIR", tmpdir.join("cargo-target"));
3716        cmd.env("CARGO", &builder.initial_cargo);
3717        cmd.env("RUSTC", &builder.initial_rustc);
3718        cmd.env("TMP_DIR", &tmpdir);
3719        cmd.delay_failure().run(builder);
3720    }
3721}
3722
3723#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3724pub struct TestHelpers {
3725    pub target: TargetSelection,
3726}
3727
3728impl Step for TestHelpers {
3729    type Output = ();
3730
3731    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3732        run.path("tests/auxiliary/rust_test_helpers.c")
3733    }
3734
3735    fn make_run(run: RunConfig<'_>) {
3736        run.builder.ensure(TestHelpers { target: run.target })
3737    }
3738
3739    /// Compiles the `rust_test_helpers.c` library which we used in various
3740    /// `run-pass` tests for ABI testing.
3741    fn run(self, builder: &Builder<'_>) {
3742        if builder.config.dry_run() {
3743            return;
3744        }
3745        // The x86_64-fortanix-unknown-sgx target doesn't have a working C
3746        // toolchain. However, some x86_64 ELF objects can be linked
3747        // without issues. Use this hack to compile the test helpers.
3748        let target = if self.target == "x86_64-fortanix-unknown-sgx" {
3749            TargetSelection::from_user("x86_64-unknown-linux-gnu")
3750        } else {
3751            self.target
3752        };
3753        let dst = builder.test_helpers_out(target);
3754        let src = builder.src.join("tests/auxiliary/rust_test_helpers.c");
3755        if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
3756            return;
3757        }
3758
3759        let _guard = builder.msg_unstaged(Kind::Build, "test helpers", target);
3760        t!(fs::create_dir_all(&dst));
3761        let mut cfg = cc::Build::new();
3762
3763        // We may have found various cross-compilers a little differently due to our
3764        // extra configuration, so inform cc of these compilers. Note, though, that
3765        // on MSVC we still need cc's detection of env vars (ugh).
3766        if !target.is_msvc() {
3767            if let Some(ar) = builder.ar(target) {
3768                cfg.archiver(ar);
3769            }
3770            cfg.compiler(builder.cc(target));
3771        }
3772        cfg.cargo_metadata(false)
3773            .out_dir(&dst)
3774            .target(&target.triple)
3775            .host(&builder.config.host_target.triple)
3776            .opt_level(0)
3777            .warnings(false)
3778            .debug(false)
3779            .file(builder.src.join("tests/auxiliary/rust_test_helpers.c"))
3780            .compile("rust_test_helpers");
3781    }
3782}
3783
3784#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3785pub struct CodegenCranelift {
3786    compilers: RustcPrivateCompilers,
3787    target: TargetSelection,
3788}
3789
3790impl Step for CodegenCranelift {
3791    type Output = ();
3792    const IS_HOST: bool = true;
3793
3794    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3795        run.paths(&["compiler/rustc_codegen_cranelift"])
3796    }
3797
3798    fn is_default_step(_builder: &Builder<'_>) -> bool {
3799        true
3800    }
3801
3802    fn make_run(run: RunConfig<'_>) {
3803        let builder = run.builder;
3804        let host = run.build_triple();
3805        let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, host);
3806
3807        if builder.doc_tests == DocTests::Only {
3808            return;
3809        }
3810
3811        if builder.download_rustc() {
3812            builder.info("CI rustc uses the default codegen backend. skipping");
3813            return;
3814        }
3815
3816        if !target_supports_cranelift_backend(run.target) {
3817            builder.info("target not supported by rustc_codegen_cranelift. skipping");
3818            return;
3819        }
3820
3821        if builder.remote_tested(run.target) {
3822            builder.info("remote testing is not supported by rustc_codegen_cranelift. skipping");
3823            return;
3824        }
3825
3826        if !builder
3827            .config
3828            .enabled_codegen_backends(run.target)
3829            .contains(&CodegenBackendKind::Cranelift)
3830        {
3831            builder.info("cranelift not in rust.codegen-backends. skipping");
3832            return;
3833        }
3834
3835        builder.ensure(CodegenCranelift { compilers, target: run.target });
3836    }
3837
3838    fn run(self, builder: &Builder<'_>) {
3839        let compilers = self.compilers;
3840        let build_compiler = compilers.build_compiler();
3841
3842        // We need to run the cranelift tests with the compiler against cranelift links to, not with
3843        // the build compiler.
3844        let target_compiler = compilers.target_compiler();
3845        let target = self.target;
3846
3847        builder.std(target_compiler, target);
3848
3849        let mut cargo = builder::Cargo::new(
3850            builder,
3851            target_compiler,
3852            Mode::Codegen, // Must be codegen to ensure dlopen on compiled dylibs works
3853            SourceType::InTree,
3854            target,
3855            Kind::Run,
3856        );
3857
3858        cargo.current_dir(&builder.src.join("compiler/rustc_codegen_cranelift"));
3859        cargo
3860            .arg("--manifest-path")
3861            .arg(builder.src.join("compiler/rustc_codegen_cranelift/build_system/Cargo.toml"));
3862        compile::rustc_cargo_env(builder, &mut cargo, target);
3863
3864        // Avoid incremental cache issues when changing rustc
3865        cargo.env("CARGO_BUILD_INCREMENTAL", "false");
3866
3867        let _guard = builder.msg_test(
3868            "rustc_codegen_cranelift",
3869            target_compiler.host,
3870            target_compiler.stage,
3871        );
3872
3873        // FIXME handle vendoring for source tarballs before removing the --skip-test below
3874        let download_dir = builder.out.join("cg_clif_download");
3875
3876        cargo
3877            .arg("--")
3878            .arg("test")
3879            .arg("--download-dir")
3880            .arg(&download_dir)
3881            .arg("--out-dir")
3882            .arg(builder.stage_out(build_compiler, Mode::Codegen).join("cg_clif"))
3883            .arg("--no-unstable-features")
3884            .arg("--use-backend")
3885            .arg("cranelift")
3886            // Avoid having to vendor the standard library dependencies
3887            .arg("--sysroot")
3888            .arg("llvm")
3889            // These tests depend on crates that are not yet vendored
3890            // FIXME remove once vendoring is handled
3891            .arg("--skip-test")
3892            .arg("testsuite.extended_sysroot");
3893
3894        cargo.into_cmd().run(builder);
3895    }
3896
3897    fn metadata(&self) -> Option<StepMetadata> {
3898        Some(
3899            StepMetadata::test("rustc_codegen_cranelift", self.target)
3900                .built_by(self.compilers.build_compiler()),
3901        )
3902    }
3903}
3904
3905#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3906pub struct CodegenGCC {
3907    compilers: RustcPrivateCompilers,
3908    target: TargetSelection,
3909}
3910
3911impl Step for CodegenGCC {
3912    type Output = ();
3913    const IS_HOST: bool = true;
3914
3915    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
3916        run.paths(&["compiler/rustc_codegen_gcc"])
3917    }
3918
3919    fn is_default_step(_builder: &Builder<'_>) -> bool {
3920        true
3921    }
3922
3923    fn make_run(run: RunConfig<'_>) {
3924        let builder = run.builder;
3925        let host = run.build_triple();
3926        let compilers = RustcPrivateCompilers::new(run.builder, run.builder.top_stage, host);
3927
3928        if builder.doc_tests == DocTests::Only {
3929            return;
3930        }
3931
3932        if builder.download_rustc() {
3933            builder.info("CI rustc uses the default codegen backend. skipping");
3934            return;
3935        }
3936
3937        let triple = run.target.triple;
3938        let target_supported =
3939            if triple.contains("linux") { triple.contains("x86_64") } else { false };
3940        if !target_supported {
3941            builder.info("target not supported by rustc_codegen_gcc. skipping");
3942            return;
3943        }
3944
3945        if builder.remote_tested(run.target) {
3946            builder.info("remote testing is not supported by rustc_codegen_gcc. skipping");
3947            return;
3948        }
3949
3950        if !builder.config.enabled_codegen_backends(run.target).contains(&CodegenBackendKind::Gcc) {
3951            builder.info("gcc not in rust.codegen-backends. skipping");
3952            return;
3953        }
3954
3955        builder.ensure(CodegenGCC { compilers, target: run.target });
3956    }
3957
3958    fn run(self, builder: &Builder<'_>) {
3959        let compilers = self.compilers;
3960        let target = self.target;
3961
3962        let gcc = builder.ensure(Gcc { target_pair: GccTargetPair::for_native_build(target) });
3963
3964        builder.ensure(
3965            compile::Std::new(compilers.build_compiler(), target)
3966                .extra_rust_args(&["-Csymbol-mangling-version=v0", "-Cpanic=abort"]),
3967        );
3968
3969        let _guard = builder.msg_test(
3970            "rustc_codegen_gcc",
3971            compilers.target(),
3972            compilers.target_compiler().stage,
3973        );
3974
3975        let mut cargo = builder::Cargo::new(
3976            builder,
3977            compilers.build_compiler(),
3978            Mode::Codegen, // Must be codegen to ensure dlopen on compiled dylibs works
3979            SourceType::InTree,
3980            target,
3981            Kind::Run,
3982        );
3983
3984        cargo.current_dir(&builder.src.join("compiler/rustc_codegen_gcc"));
3985        cargo
3986            .arg("--manifest-path")
3987            .arg(builder.src.join("compiler/rustc_codegen_gcc/build_system/Cargo.toml"));
3988        compile::rustc_cargo_env(builder, &mut cargo, target);
3989        add_cg_gcc_cargo_flags(&mut cargo, &gcc);
3990
3991        // Avoid incremental cache issues when changing rustc
3992        cargo.env("CARGO_BUILD_INCREMENTAL", "false");
3993        cargo.rustflag("-Cpanic=abort");
3994
3995        cargo
3996            // cg_gcc's build system ignores RUSTFLAGS. pass some flags through CG_RUSTFLAGS instead.
3997            .env("CG_RUSTFLAGS", "-Alinker-messages")
3998            .arg("--")
3999            .arg("test")
4000            .arg("--use-backend")
4001            .arg("gcc")
4002            .arg("--gcc-path")
4003            .arg(gcc.libgccjit().parent().unwrap())
4004            .arg("--out-dir")
4005            .arg(builder.stage_out(compilers.build_compiler(), Mode::Codegen).join("cg_gcc"))
4006            .arg("--release")
4007            .arg("--mini-tests")
4008            .arg("--std-tests");
4009
4010        cargo.args(builder.config.test_args());
4011
4012        cargo.into_cmd().run(builder);
4013    }
4014
4015    fn metadata(&self) -> Option<StepMetadata> {
4016        Some(
4017            StepMetadata::test("rustc_codegen_gcc", self.target)
4018                .built_by(self.compilers.build_compiler()),
4019        )
4020    }
4021}
4022
4023/// Test step that does two things:
4024/// - Runs `cargo test` for the `src/tools/test-float-parse` tool.
4025/// - Invokes the `test-float-parse` tool to test the standard library's
4026///   float parsing routines.
4027#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4028pub struct TestFloatParse {
4029    /// The build compiler which will build and run unit tests of `test-float-parse`, and which will
4030    /// build the `test-float-parse` tool itself.
4031    ///
4032    /// Note that the staging is a bit funny here, because this step essentially tests std, but it
4033    /// also needs to build the tool. So if we test stage1 std, we build:
4034    /// 1) stage1 rustc
4035    /// 2) Use that to build stage1 libstd
4036    /// 3) Use that to build and run *stage2* test-float-parse
4037    build_compiler: Compiler,
4038    /// Target for which we build std and test that std.
4039    target: TargetSelection,
4040}
4041
4042impl Step for TestFloatParse {
4043    type Output = ();
4044    const IS_HOST: bool = true;
4045
4046    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
4047        run.path("src/tools/test-float-parse")
4048    }
4049
4050    fn is_default_step(_builder: &Builder<'_>) -> bool {
4051        true
4052    }
4053
4054    fn make_run(run: RunConfig<'_>) {
4055        run.builder.ensure(Self {
4056            build_compiler: get_compiler_to_test(run.builder, run.target),
4057            target: run.target,
4058        });
4059    }
4060
4061    fn run(self, builder: &Builder<'_>) {
4062        let build_compiler = self.build_compiler;
4063        let target = self.target;
4064
4065        // Build the standard library that will be tested, and a stdlib for host code
4066        builder.std(build_compiler, target);
4067        builder.std(build_compiler, builder.host_target);
4068
4069        // Run any unit tests in the crate
4070        let mut cargo_test = tool::prepare_tool_cargo(
4071            builder,
4072            build_compiler,
4073            Mode::ToolStd,
4074            target,
4075            Kind::Test,
4076            "src/tools/test-float-parse",
4077            SourceType::InTree,
4078            &[],
4079        );
4080        cargo_test.allow_features(TEST_FLOAT_PARSE_ALLOW_FEATURES);
4081
4082        run_cargo_test(cargo_test, &[], &[], "test-float-parse", target, builder);
4083
4084        // Run the actual parse tests.
4085        let mut cargo_run = tool::prepare_tool_cargo(
4086            builder,
4087            build_compiler,
4088            Mode::ToolStd,
4089            target,
4090            Kind::Run,
4091            "src/tools/test-float-parse",
4092            SourceType::InTree,
4093            &[],
4094        );
4095        cargo_run.allow_features(TEST_FLOAT_PARSE_ALLOW_FEATURES);
4096
4097        if !matches!(env::var("FLOAT_PARSE_TESTS_NO_SKIP_HUGE").as_deref(), Ok("1") | Ok("true")) {
4098            cargo_run.args(["--", "--skip-huge"]);
4099        }
4100
4101        cargo_run.into_cmd().run(builder);
4102    }
4103}
4104
4105/// Runs the tool `src/tools/collect-license-metadata` in `ONLY_CHECK=1` mode,
4106/// which verifies that `license-metadata.json` is up-to-date and therefore
4107/// running the tool normally would not update anything.
4108#[derive(Debug, Clone, Hash, PartialEq, Eq)]
4109pub struct CollectLicenseMetadata;
4110
4111impl Step for CollectLicenseMetadata {
4112    type Output = PathBuf;
4113    const IS_HOST: bool = true;
4114
4115    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
4116        run.path("src/tools/collect-license-metadata")
4117    }
4118
4119    fn make_run(run: RunConfig<'_>) {
4120        run.builder.ensure(CollectLicenseMetadata);
4121    }
4122
4123    fn run(self, builder: &Builder<'_>) -> Self::Output {
4124        let Some(reuse) = &builder.config.reuse else {
4125            panic!("REUSE is required to collect the license metadata");
4126        };
4127
4128        let dest = builder.src.join("license-metadata.json");
4129
4130        let mut cmd = builder.tool_cmd(Tool::CollectLicenseMetadata);
4131        cmd.env("REUSE_EXE", reuse);
4132        cmd.env("DEST", &dest);
4133        cmd.env("ONLY_CHECK", "1");
4134        cmd.run(builder);
4135
4136        dest
4137    }
4138}
4139
4140#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4141pub struct RemoteTestClientTests {
4142    host: TargetSelection,
4143}
4144
4145impl Step for RemoteTestClientTests {
4146    type Output = ();
4147    const IS_HOST: bool = true;
4148
4149    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
4150        run.path("src/tools/remote-test-client")
4151    }
4152
4153    fn is_default_step(_builder: &Builder<'_>) -> bool {
4154        true
4155    }
4156
4157    fn make_run(run: RunConfig<'_>) {
4158        run.builder.ensure(Self { host: run.target });
4159    }
4160
4161    fn run(self, builder: &Builder<'_>) {
4162        let bootstrap_host = builder.config.host_target;
4163        let compiler = builder.compiler(0, bootstrap_host);
4164
4165        let cargo = tool::prepare_tool_cargo(
4166            builder,
4167            compiler,
4168            Mode::ToolBootstrap,
4169            bootstrap_host,
4170            Kind::Test,
4171            "src/tools/remote-test-client",
4172            SourceType::InTree,
4173            &[],
4174        );
4175
4176        run_cargo_test(cargo, &[], &[], "remote-test-client", bootstrap_host, builder);
4177    }
4178}