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