]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Rollup merge of #104654 - thomcc:alloc-tests-unsafe_op_in_unsafe_fn, r=Mark-Simulacrum
[rust.git] / src / bootstrap / test.rs
1 //! Implementation of the test-related targets of the build system.
2 //!
3 //! This file implements the various regression test suites that we execute on
4 //! our CI.
5
6 use std::env;
7 use std::ffi::OsString;
8 use std::fmt;
9 use std::fs;
10 use std::iter;
11 use std::path::{Path, PathBuf};
12 use std::process::{Command, Stdio};
13
14 use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
15 use crate::cache::Interned;
16 use crate::compile;
17 use crate::config::TargetSelection;
18 use crate::dist;
19 use crate::doc::DocumentationFormat;
20 use crate::flags::Subcommand;
21 use crate::native;
22 use crate::tool::{self, SourceType, Tool};
23 use crate::toolstate::ToolState;
24 use crate::util::{self, add_link_lib_path, dylib_path, dylib_path_var, output, t};
25 use crate::{envify, CLang, DocTests, GitRepo, Mode};
26
27 const ADB_TEST_DIR: &str = "/data/local/tmp/work";
28
29 /// The two modes of the test runner; tests or benchmarks.
30 #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, PartialOrd, Ord)]
31 pub enum TestKind {
32     /// Run `cargo test`.
33     Test,
34     /// Run `cargo bench`.
35     Bench,
36 }
37
38 impl From<Kind> for TestKind {
39     fn from(kind: Kind) -> Self {
40         match kind {
41             Kind::Test => TestKind::Test,
42             Kind::Bench => TestKind::Bench,
43             _ => panic!("unexpected kind in crate: {:?}", kind),
44         }
45     }
46 }
47
48 impl TestKind {
49     // Return the cargo subcommand for this test kind
50     fn subcommand(self) -> &'static str {
51         match self {
52             TestKind::Test => "test",
53             TestKind::Bench => "bench",
54         }
55     }
56 }
57
58 impl fmt::Display for TestKind {
59     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60         f.write_str(match *self {
61             TestKind::Test => "Testing",
62             TestKind::Bench => "Benchmarking",
63         })
64     }
65 }
66
67 fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool {
68     if !builder.fail_fast {
69         if !builder.try_run(cmd) {
70             let mut failures = builder.delayed_failures.borrow_mut();
71             failures.push(format!("{:?}", cmd));
72             return false;
73         }
74     } else {
75         builder.run(cmd);
76     }
77     true
78 }
79
80 fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool {
81     if !builder.fail_fast {
82         if !builder.try_run_quiet(cmd) {
83             let mut failures = builder.delayed_failures.borrow_mut();
84             failures.push(format!("{:?}", cmd));
85             return false;
86         }
87     } else {
88         builder.run_quiet(cmd);
89     }
90     true
91 }
92
93 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
94 pub struct Linkcheck {
95     host: TargetSelection,
96 }
97
98 impl Step for Linkcheck {
99     type Output = ();
100     const ONLY_HOSTS: bool = true;
101     const DEFAULT: bool = true;
102
103     /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
104     ///
105     /// This tool in `src/tools` will verify the validity of all our links in the
106     /// documentation to ensure we don't have a bunch of dead ones.
107     fn run(self, builder: &Builder<'_>) {
108         let host = self.host;
109         let hosts = &builder.hosts;
110         let targets = &builder.targets;
111
112         // if we have different hosts and targets, some things may be built for
113         // the host (e.g. rustc) and others for the target (e.g. std). The
114         // documentation built for each will contain broken links to
115         // docs built for the other platform (e.g. rustc linking to cargo)
116         if (hosts != targets) && !hosts.is_empty() && !targets.is_empty() {
117             panic!(
118                 "Linkcheck currently does not support builds with different hosts and targets.
119 You can skip linkcheck with --exclude src/tools/linkchecker"
120             );
121         }
122
123         builder.info(&format!("Linkcheck ({})", host));
124
125         // Test the linkchecker itself.
126         let bootstrap_host = builder.config.build;
127         let compiler = builder.compiler(0, bootstrap_host);
128         let cargo = tool::prepare_tool_cargo(
129             builder,
130             compiler,
131             Mode::ToolBootstrap,
132             bootstrap_host,
133             "test",
134             "src/tools/linkchecker",
135             SourceType::InTree,
136             &[],
137         );
138         try_run(builder, &mut cargo.into());
139
140         // Build all the default documentation.
141         builder.default_doc(&[]);
142
143         // Run the linkchecker.
144         let _time = util::timeit(&builder);
145         try_run(
146             builder,
147             builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")),
148         );
149     }
150
151     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
152         let builder = run.builder;
153         let run = run.path("src/tools/linkchecker");
154         run.default_condition(builder.config.docs)
155     }
156
157     fn make_run(run: RunConfig<'_>) {
158         run.builder.ensure(Linkcheck { host: run.target });
159     }
160 }
161
162 fn check_if_tidy_is_installed() -> bool {
163     Command::new("tidy")
164         .arg("--version")
165         .stdout(Stdio::null())
166         .status()
167         .map_or(false, |status| status.success())
168 }
169
170 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
171 pub struct HtmlCheck {
172     target: TargetSelection,
173 }
174
175 impl Step for HtmlCheck {
176     type Output = ();
177     const DEFAULT: bool = true;
178     const ONLY_HOSTS: bool = true;
179
180     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
181         let run = run.path("src/tools/html-checker");
182         run.lazy_default_condition(Box::new(check_if_tidy_is_installed))
183     }
184
185     fn make_run(run: RunConfig<'_>) {
186         run.builder.ensure(HtmlCheck { target: run.target });
187     }
188
189     fn run(self, builder: &Builder<'_>) {
190         if !check_if_tidy_is_installed() {
191             eprintln!("not running HTML-check tool because `tidy` is missing");
192             eprintln!(
193                 "Note that `tidy` is not the in-tree `src/tools/tidy` but needs to be installed"
194             );
195             panic!("Cannot run html-check tests");
196         }
197         // Ensure that a few different kinds of documentation are available.
198         builder.default_doc(&[]);
199         builder.ensure(crate::doc::Rustc { target: self.target, stage: builder.top_stage });
200
201         try_run(builder, builder.tool_cmd(Tool::HtmlChecker).arg(builder.doc_out(self.target)));
202     }
203 }
204
205 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
206 pub struct Cargotest {
207     stage: u32,
208     host: TargetSelection,
209 }
210
211 impl Step for Cargotest {
212     type Output = ();
213     const ONLY_HOSTS: bool = true;
214
215     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
216         run.path("src/tools/cargotest")
217     }
218
219     fn make_run(run: RunConfig<'_>) {
220         run.builder.ensure(Cargotest { stage: run.builder.top_stage, host: run.target });
221     }
222
223     /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
224     ///
225     /// This tool in `src/tools` will check out a few Rust projects and run `cargo
226     /// test` to ensure that we don't regress the test suites there.
227     fn run(self, builder: &Builder<'_>) {
228         let compiler = builder.compiler(self.stage, self.host);
229         builder.ensure(compile::Rustc::new(compiler, compiler.host));
230         let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host });
231
232         // Note that this is a short, cryptic, and not scoped directory name. This
233         // is currently to minimize the length of path on Windows where we otherwise
234         // quickly run into path name limit constraints.
235         let out_dir = builder.out.join("ct");
236         t!(fs::create_dir_all(&out_dir));
237
238         let _time = util::timeit(&builder);
239         let mut cmd = builder.tool_cmd(Tool::CargoTest);
240         try_run(
241             builder,
242             cmd.arg(&cargo)
243                 .arg(&out_dir)
244                 .args(builder.config.cmd.test_args())
245                 .env("RUSTC", builder.rustc(compiler))
246                 .env("RUSTDOC", builder.rustdoc(compiler)),
247         );
248     }
249 }
250
251 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
252 pub struct Cargo {
253     stage: u32,
254     host: TargetSelection,
255 }
256
257 impl Step for Cargo {
258     type Output = ();
259     const ONLY_HOSTS: bool = true;
260
261     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
262         run.path("src/tools/cargo")
263     }
264
265     fn make_run(run: RunConfig<'_>) {
266         run.builder.ensure(Cargo { stage: run.builder.top_stage, host: run.target });
267     }
268
269     /// Runs `cargo test` for `cargo` packaged with Rust.
270     fn run(self, builder: &Builder<'_>) {
271         let compiler = builder.compiler(self.stage, self.host);
272
273         builder.ensure(tool::Cargo { compiler, target: self.host });
274         let mut cargo = tool::prepare_tool_cargo(
275             builder,
276             compiler,
277             Mode::ToolRustc,
278             self.host,
279             "test",
280             "src/tools/cargo",
281             SourceType::Submodule,
282             &[],
283         );
284
285         if !builder.fail_fast {
286             cargo.arg("--no-fail-fast");
287         }
288         cargo.arg("--").args(builder.config.cmd.test_args());
289
290         // Don't run cross-compile tests, we may not have cross-compiled libstd libs
291         // available.
292         cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
293         // Forcibly disable tests using nightly features since any changes to
294         // those features won't be able to land.
295         cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
296
297         cargo.env("PATH", &path_for_cargo(builder, compiler));
298
299         try_run(builder, &mut cargo.into());
300     }
301 }
302
303 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
304 pub struct RustAnalyzer {
305     stage: u32,
306     host: TargetSelection,
307 }
308
309 impl Step for RustAnalyzer {
310     type Output = ();
311     const ONLY_HOSTS: bool = true;
312     const DEFAULT: bool = true;
313
314     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
315         run.path("src/tools/rust-analyzer")
316     }
317
318     fn make_run(run: RunConfig<'_>) {
319         run.builder.ensure(Self { stage: run.builder.top_stage, host: run.target });
320     }
321
322     /// Runs `cargo test` for rust-analyzer
323     fn run(self, builder: &Builder<'_>) {
324         let stage = self.stage;
325         let host = self.host;
326         let compiler = builder.compiler(stage, host);
327
328         builder.ensure(tool::RustAnalyzer { compiler, target: self.host }).expect("in-tree tool");
329
330         let workspace_path = "src/tools/rust-analyzer";
331         // until the whole RA test suite runs on `i686`, we only run
332         // `proc-macro-srv` tests
333         let crate_path = "src/tools/rust-analyzer/crates/proc-macro-srv";
334         let mut cargo = tool::prepare_tool_cargo(
335             builder,
336             compiler,
337             Mode::ToolStd,
338             host,
339             "test",
340             crate_path,
341             SourceType::InTree,
342             &["sysroot-abi".to_owned()],
343         );
344
345         let dir = builder.src.join(workspace_path);
346         // needed by rust-analyzer to find its own text fixtures, cf.
347         // https://github.com/rust-analyzer/expect-test/issues/33
348         cargo.env("CARGO_WORKSPACE_DIR", &dir);
349
350         // RA's test suite tries to write to the source directory, that can't
351         // work in Rust CI
352         cargo.env("SKIP_SLOW_TESTS", "1");
353
354         cargo.add_rustc_lib_path(builder, compiler);
355         cargo.arg("--").args(builder.config.cmd.test_args());
356
357         builder.run(&mut cargo.into());
358     }
359 }
360
361 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
362 pub struct Rustfmt {
363     stage: u32,
364     host: TargetSelection,
365 }
366
367 impl Step for Rustfmt {
368     type Output = ();
369     const ONLY_HOSTS: bool = true;
370
371     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
372         run.path("src/tools/rustfmt")
373     }
374
375     fn make_run(run: RunConfig<'_>) {
376         run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target });
377     }
378
379     /// Runs `cargo test` for rustfmt.
380     fn run(self, builder: &Builder<'_>) {
381         let stage = self.stage;
382         let host = self.host;
383         let compiler = builder.compiler(stage, host);
384
385         builder
386             .ensure(tool::Rustfmt { compiler, target: self.host, extra_features: Vec::new() })
387             .expect("in-tree tool");
388
389         let mut cargo = tool::prepare_tool_cargo(
390             builder,
391             compiler,
392             Mode::ToolRustc,
393             host,
394             "test",
395             "src/tools/rustfmt",
396             SourceType::InTree,
397             &[],
398         );
399
400         let dir = testdir(builder, compiler.host);
401         t!(fs::create_dir_all(&dir));
402         cargo.env("RUSTFMT_TEST_DIR", dir);
403
404         cargo.add_rustc_lib_path(builder, compiler);
405
406         builder.run(&mut cargo.into());
407     }
408 }
409
410 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
411 pub struct RustDemangler {
412     stage: u32,
413     host: TargetSelection,
414 }
415
416 impl Step for RustDemangler {
417     type Output = ();
418     const ONLY_HOSTS: bool = true;
419
420     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
421         run.path("src/tools/rust-demangler")
422     }
423
424     fn make_run(run: RunConfig<'_>) {
425         run.builder.ensure(RustDemangler { stage: run.builder.top_stage, host: run.target });
426     }
427
428     /// Runs `cargo test` for rust-demangler.
429     fn run(self, builder: &Builder<'_>) {
430         let stage = self.stage;
431         let host = self.host;
432         let compiler = builder.compiler(stage, host);
433
434         let rust_demangler = builder
435             .ensure(tool::RustDemangler { compiler, target: self.host, extra_features: Vec::new() })
436             .expect("in-tree tool");
437         let mut cargo = tool::prepare_tool_cargo(
438             builder,
439             compiler,
440             Mode::ToolRustc,
441             host,
442             "test",
443             "src/tools/rust-demangler",
444             SourceType::InTree,
445             &[],
446         );
447
448         let dir = testdir(builder, compiler.host);
449         t!(fs::create_dir_all(&dir));
450
451         cargo.env("RUST_DEMANGLER_DRIVER_PATH", rust_demangler);
452
453         cargo.arg("--").args(builder.config.cmd.test_args());
454
455         cargo.add_rustc_lib_path(builder, compiler);
456
457         builder.run(&mut cargo.into());
458     }
459 }
460
461 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
462 pub struct Miri {
463     stage: u32,
464     host: TargetSelection,
465     target: TargetSelection,
466 }
467
468 impl Miri {
469     /// Run `cargo miri setup` for the given target, return where the Miri sysroot was put.
470     pub fn build_miri_sysroot(
471         builder: &Builder<'_>,
472         compiler: Compiler,
473         miri: &Path,
474         target: TargetSelection,
475     ) -> String {
476         let miri_sysroot = builder.out.join(compiler.host.triple).join("miri-sysrot");
477         let mut cargo = tool::prepare_tool_cargo(
478             builder,
479             compiler,
480             Mode::ToolRustc,
481             compiler.host,
482             "run",
483             "src/tools/miri/cargo-miri",
484             SourceType::InTree,
485             &[],
486         );
487         cargo.add_rustc_lib_path(builder, compiler);
488         cargo.arg("--").arg("miri").arg("setup");
489         cargo.arg("--target").arg(target.rustc_target_arg());
490
491         // Tell `cargo miri setup` where to find the sources.
492         cargo.env("MIRI_LIB_SRC", builder.src.join("library"));
493         // Tell it where to find Miri.
494         cargo.env("MIRI", &miri);
495         // Tell it where to put the sysroot.
496         cargo.env("MIRI_SYSROOT", &miri_sysroot);
497         // Debug things.
498         cargo.env("RUST_BACKTRACE", "1");
499
500         let mut cargo = Command::from(cargo);
501         builder.run(&mut cargo);
502
503         // # Determine where Miri put its sysroot.
504         // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
505         // (We do this separately from the above so that when the setup actually
506         // happens we get some output.)
507         // We re-use the `cargo` from above.
508         cargo.arg("--print-sysroot");
509
510         // FIXME: Is there a way in which we can re-use the usual `run` helpers?
511         if builder.config.dry_run() {
512             String::new()
513         } else {
514             builder.verbose(&format!("running: {:?}", cargo));
515             let out =
516                 cargo.output().expect("We already ran `cargo miri setup` before and that worked");
517             assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code");
518             // Output is "<sysroot>\n".
519             let stdout = String::from_utf8(out.stdout)
520                 .expect("`cargo miri setup` stdout is not valid UTF-8");
521             let sysroot = stdout.trim_end();
522             builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
523             sysroot.to_owned()
524         }
525     }
526 }
527
528 impl Step for Miri {
529     type Output = ();
530     const ONLY_HOSTS: bool = false;
531
532     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
533         run.path("src/tools/miri")
534     }
535
536     fn make_run(run: RunConfig<'_>) {
537         run.builder.ensure(Miri {
538             stage: run.builder.top_stage,
539             host: run.build_triple(),
540             target: run.target,
541         });
542     }
543
544     /// Runs `cargo test` for miri.
545     fn run(self, builder: &Builder<'_>) {
546         let stage = self.stage;
547         let host = self.host;
548         let target = self.target;
549         let compiler = builder.compiler(stage, host);
550         // We need the stdlib for the *next* stage, as it was built with this compiler that also built Miri.
551         // Except if we are at stage 2, the bootstrap loop is complete and we can stick with our current stage.
552         let compiler_std = builder.compiler(if stage < 2 { stage + 1 } else { stage }, host);
553
554         let miri = builder
555             .ensure(tool::Miri { compiler, target: self.host, extra_features: Vec::new() })
556             .expect("in-tree tool");
557         let _cargo_miri = builder
558             .ensure(tool::CargoMiri { compiler, target: self.host, extra_features: Vec::new() })
559             .expect("in-tree tool");
560         // The stdlib we need might be at a different stage. And just asking for the
561         // sysroot does not seem to populate it, so we do that first.
562         builder.ensure(compile::Std::new(compiler_std, host));
563         let sysroot = builder.sysroot(compiler_std);
564         // We also need a Miri sysroot.
565         let miri_sysroot = Miri::build_miri_sysroot(builder, compiler, &miri, target);
566
567         // # Run `cargo test`.
568         let mut cargo = tool::prepare_tool_cargo(
569             builder,
570             compiler,
571             Mode::ToolRustc,
572             host,
573             "test",
574             "src/tools/miri",
575             SourceType::InTree,
576             &[],
577         );
578         cargo.add_rustc_lib_path(builder, compiler);
579
580         // miri tests need to know about the stage sysroot
581         cargo.env("MIRI_SYSROOT", &miri_sysroot);
582         cargo.env("MIRI_HOST_SYSROOT", sysroot);
583         cargo.env("MIRI", &miri);
584         // propagate --bless
585         if builder.config.cmd.bless() {
586             cargo.env("MIRI_BLESS", "Gesundheit");
587         }
588
589         // Set the target.
590         cargo.env("MIRI_TEST_TARGET", target.rustc_target_arg());
591         // Forward test filters.
592         cargo.arg("--").args(builder.config.cmd.test_args());
593
594         let mut cargo = Command::from(cargo);
595         builder.run(&mut cargo);
596
597         // # Run `cargo miri test`.
598         // This is just a smoke test (Miri's own CI invokes this in a bunch of different ways and ensures
599         // that we get the desired output), but that is sufficient to make sure that the libtest harness
600         // itself executes properly under Miri.
601         let mut cargo = tool::prepare_tool_cargo(
602             builder,
603             compiler,
604             Mode::ToolRustc,
605             host,
606             "run",
607             "src/tools/miri/cargo-miri",
608             SourceType::Submodule,
609             &[],
610         );
611         cargo.add_rustc_lib_path(builder, compiler);
612         cargo.arg("--").arg("miri").arg("test");
613         cargo
614             .arg("--manifest-path")
615             .arg(builder.src.join("src/tools/miri/test-cargo-miri/Cargo.toml"));
616         cargo.arg("--target").arg(target.rustc_target_arg());
617         cargo.arg("--tests"); // don't run doctests, they are too confused by the staging
618         cargo.arg("--").args(builder.config.cmd.test_args());
619
620         // Tell `cargo miri` where to find things.
621         cargo.env("MIRI_SYSROOT", &miri_sysroot);
622         cargo.env("MIRI_HOST_SYSROOT", sysroot);
623         cargo.env("MIRI", &miri);
624         // Debug things.
625         cargo.env("RUST_BACKTRACE", "1");
626
627         let mut cargo = Command::from(cargo);
628         builder.run(&mut cargo);
629     }
630 }
631
632 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
633 pub struct CompiletestTest {
634     host: TargetSelection,
635 }
636
637 impl Step for CompiletestTest {
638     type Output = ();
639
640     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
641         run.path("src/tools/compiletest")
642     }
643
644     fn make_run(run: RunConfig<'_>) {
645         run.builder.ensure(CompiletestTest { host: run.target });
646     }
647
648     /// Runs `cargo test` for compiletest.
649     fn run(self, builder: &Builder<'_>) {
650         let host = self.host;
651         let compiler = builder.compiler(0, host);
652
653         // We need `ToolStd` for the locally-built sysroot because
654         // compiletest uses unstable features of the `test` crate.
655         builder.ensure(compile::Std::new(compiler, host));
656         let cargo = tool::prepare_tool_cargo(
657             builder,
658             compiler,
659             Mode::ToolStd,
660             host,
661             "test",
662             "src/tools/compiletest",
663             SourceType::InTree,
664             &[],
665         );
666
667         try_run(builder, &mut cargo.into());
668     }
669 }
670
671 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
672 pub struct Clippy {
673     stage: u32,
674     host: TargetSelection,
675 }
676
677 impl Step for Clippy {
678     type Output = ();
679     const ONLY_HOSTS: bool = true;
680     const DEFAULT: bool = false;
681
682     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
683         run.path("src/tools/clippy")
684     }
685
686     fn make_run(run: RunConfig<'_>) {
687         run.builder.ensure(Clippy { stage: run.builder.top_stage, host: run.target });
688     }
689
690     /// Runs `cargo test` for clippy.
691     fn run(self, builder: &Builder<'_>) {
692         let stage = self.stage;
693         let host = self.host;
694         let compiler = builder.compiler(stage, host);
695
696         builder
697             .ensure(tool::Clippy { compiler, target: self.host, extra_features: Vec::new() })
698             .expect("in-tree tool");
699         let mut cargo = tool::prepare_tool_cargo(
700             builder,
701             compiler,
702             Mode::ToolRustc,
703             host,
704             "test",
705             "src/tools/clippy",
706             SourceType::InTree,
707             &[],
708         );
709
710         cargo.env("RUSTC_TEST_SUITE", builder.rustc(compiler));
711         cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
712         let host_libs = builder.stage_out(compiler, Mode::ToolRustc).join(builder.cargo_dir());
713         cargo.env("HOST_LIBS", host_libs);
714
715         cargo.arg("--").args(builder.config.cmd.test_args());
716
717         cargo.add_rustc_lib_path(builder, compiler);
718
719         if builder.try_run(&mut cargo.into()) {
720             // The tests succeeded; nothing to do.
721             return;
722         }
723
724         if !builder.config.cmd.bless() {
725             crate::detail_exit(1);
726         }
727
728         let mut cargo = builder.cargo(compiler, Mode::ToolRustc, SourceType::InTree, host, "run");
729         cargo.arg("-p").arg("clippy_dev");
730         // clippy_dev gets confused if it can't find `clippy/Cargo.toml`
731         cargo.current_dir(&builder.src.join("src").join("tools").join("clippy"));
732         if builder.config.rust_optimize {
733             cargo.env("PROFILE", "release");
734         } else {
735             cargo.env("PROFILE", "debug");
736         }
737         cargo.arg("--");
738         cargo.arg("bless");
739         builder.run(&mut cargo.into());
740     }
741 }
742
743 fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
744     // Configure PATH to find the right rustc. NB. we have to use PATH
745     // and not RUSTC because the Cargo test suite has tests that will
746     // fail if rustc is not spelled `rustc`.
747     let path = builder.sysroot(compiler).join("bin");
748     let old_path = env::var_os("PATH").unwrap_or_default();
749     env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
750 }
751
752 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
753 pub struct RustdocTheme {
754     pub compiler: Compiler,
755 }
756
757 impl Step for RustdocTheme {
758     type Output = ();
759     const DEFAULT: bool = true;
760     const ONLY_HOSTS: bool = true;
761
762     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
763         run.path("src/tools/rustdoc-themes")
764     }
765
766     fn make_run(run: RunConfig<'_>) {
767         let compiler = run.builder.compiler(run.builder.top_stage, run.target);
768
769         run.builder.ensure(RustdocTheme { compiler });
770     }
771
772     fn run(self, builder: &Builder<'_>) {
773         let rustdoc = builder.bootstrap_out.join("rustdoc");
774         let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
775         cmd.arg(rustdoc.to_str().unwrap())
776             .arg(builder.src.join("src/librustdoc/html/static/css/themes").to_str().unwrap())
777             .env("RUSTC_STAGE", self.compiler.stage.to_string())
778             .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
779             .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
780             .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
781             .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
782             .env("RUSTC_BOOTSTRAP", "1");
783         if let Some(linker) = builder.linker(self.compiler.host) {
784             cmd.env("RUSTDOC_LINKER", linker);
785         }
786         if builder.is_fuse_ld_lld(self.compiler.host) {
787             cmd.env(
788                 "RUSTDOC_LLD_NO_THREADS",
789                 util::lld_flag_no_threads(self.compiler.host.contains("windows")),
790             );
791         }
792         try_run(builder, &mut cmd);
793     }
794 }
795
796 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
797 pub struct RustdocJSStd {
798     pub target: TargetSelection,
799 }
800
801 impl Step for RustdocJSStd {
802     type Output = ();
803     const DEFAULT: bool = true;
804     const ONLY_HOSTS: bool = true;
805
806     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
807         run.suite_path("src/test/rustdoc-js-std")
808     }
809
810     fn make_run(run: RunConfig<'_>) {
811         run.builder.ensure(RustdocJSStd { target: run.target });
812     }
813
814     fn run(self, builder: &Builder<'_>) {
815         if let Some(ref nodejs) = builder.config.nodejs {
816             let mut command = Command::new(nodejs);
817             command
818                 .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
819                 .arg("--crate-name")
820                 .arg("std")
821                 .arg("--resource-suffix")
822                 .arg(&builder.version)
823                 .arg("--doc-folder")
824                 .arg(builder.doc_out(self.target))
825                 .arg("--test-folder")
826                 .arg(builder.src.join("src/test/rustdoc-js-std"));
827             for path in &builder.paths {
828                 if let Some(p) =
829                     util::is_valid_test_suite_arg(path, "src/test/rustdoc-js-std", builder)
830                 {
831                     if !p.ends_with(".js") {
832                         eprintln!("A non-js file was given: `{}`", path.display());
833                         panic!("Cannot run rustdoc-js-std tests");
834                     }
835                     command.arg("--test-file").arg(path);
836                 }
837             }
838             builder.ensure(crate::doc::Std {
839                 target: self.target,
840                 stage: builder.top_stage,
841                 format: DocumentationFormat::HTML,
842             });
843             builder.run(&mut command);
844         } else {
845             builder.info("No nodejs found, skipping \"src/test/rustdoc-js-std\" tests");
846         }
847     }
848 }
849
850 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
851 pub struct RustdocJSNotStd {
852     pub target: TargetSelection,
853     pub compiler: Compiler,
854 }
855
856 impl Step for RustdocJSNotStd {
857     type Output = ();
858     const DEFAULT: bool = true;
859     const ONLY_HOSTS: bool = true;
860
861     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
862         run.suite_path("src/test/rustdoc-js")
863     }
864
865     fn make_run(run: RunConfig<'_>) {
866         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
867         run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
868     }
869
870     fn run(self, builder: &Builder<'_>) {
871         if builder.config.nodejs.is_some() {
872             builder.ensure(Compiletest {
873                 compiler: self.compiler,
874                 target: self.target,
875                 mode: "js-doc-test",
876                 suite: "rustdoc-js",
877                 path: "src/test/rustdoc-js",
878                 compare_mode: None,
879             });
880         } else {
881             builder.info("No nodejs found, skipping \"src/test/rustdoc-js\" tests");
882         }
883     }
884 }
885
886 fn get_browser_ui_test_version_inner(npm: &Path, global: bool) -> Option<String> {
887     let mut command = Command::new(&npm);
888     command.arg("list").arg("--parseable").arg("--long").arg("--depth=0");
889     if global {
890         command.arg("--global");
891     }
892     let lines = command
893         .output()
894         .map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
895         .unwrap_or(String::new());
896     lines
897         .lines()
898         .find_map(|l| l.split(':').nth(1)?.strip_prefix("browser-ui-test@"))
899         .map(|v| v.to_owned())
900 }
901
902 fn get_browser_ui_test_version(npm: &Path) -> Option<String> {
903     get_browser_ui_test_version_inner(npm, false)
904         .or_else(|| get_browser_ui_test_version_inner(npm, true))
905 }
906
907 fn compare_browser_ui_test_version(installed_version: &str, src: &Path) {
908     match fs::read_to_string(
909         src.join("src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version"),
910     ) {
911         Ok(v) => {
912             if v.trim() != installed_version {
913                 eprintln!(
914                     "⚠️ Installed version of browser-ui-test (`{}`) is different than the \
915                      one used in the CI (`{}`)",
916                     installed_version, v
917                 );
918                 eprintln!(
919                     "You can install this version using `npm update browser-ui-test` or by using \
920                      `npm install browser-ui-test@{}`",
921                     v,
922                 );
923             }
924         }
925         Err(e) => eprintln!("Couldn't find the CI browser-ui-test version: {:?}", e),
926     }
927 }
928
929 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
930 pub struct RustdocGUI {
931     pub target: TargetSelection,
932     pub compiler: Compiler,
933 }
934
935 impl Step for RustdocGUI {
936     type Output = ();
937     const DEFAULT: bool = true;
938     const ONLY_HOSTS: bool = true;
939
940     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
941         let builder = run.builder;
942         let run = run.suite_path("src/test/rustdoc-gui");
943         run.lazy_default_condition(Box::new(move || {
944             builder.config.nodejs.is_some()
945                 && builder
946                     .config
947                     .npm
948                     .as_ref()
949                     .map(|p| get_browser_ui_test_version(p).is_some())
950                     .unwrap_or(false)
951         }))
952     }
953
954     fn make_run(run: RunConfig<'_>) {
955         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
956         run.builder.ensure(RustdocGUI { target: run.target, compiler });
957     }
958
959     fn run(self, builder: &Builder<'_>) {
960         let nodejs = builder.config.nodejs.as_ref().expect("nodejs isn't available");
961         let npm = builder.config.npm.as_ref().expect("npm isn't available");
962
963         builder.ensure(compile::Std::new(self.compiler, self.target));
964
965         // The goal here is to check if the necessary packages are installed, and if not, we
966         // panic.
967         match get_browser_ui_test_version(&npm) {
968             Some(version) => {
969                 // We also check the version currently used in CI and emit a warning if it's not the
970                 // same one.
971                 compare_browser_ui_test_version(&version, &builder.build.src);
972             }
973             None => {
974                 eprintln!(
975                     "error: rustdoc-gui test suite cannot be run because npm `browser-ui-test` \
976                      dependency is missing",
977                 );
978                 eprintln!(
979                     "If you want to install the `{0}` dependency, run `npm install {0}`",
980                     "browser-ui-test",
981                 );
982                 panic!("Cannot run rustdoc-gui tests");
983             }
984         }
985
986         let out_dir = builder.test_out(self.target).join("rustdoc-gui");
987
988         // We remove existing folder to be sure there won't be artifacts remaining.
989         builder.clear_if_dirty(&out_dir, &builder.rustdoc(self.compiler));
990
991         let src_path = builder.build.src.join("src/test/rustdoc-gui/src");
992         // We generate docs for the libraries present in the rustdoc-gui's src folder.
993         for entry in src_path.read_dir().expect("read_dir call failed") {
994             if let Ok(entry) = entry {
995                 let path = entry.path();
996
997                 if !path.is_dir() {
998                     continue;
999                 }
1000
1001                 let mut cargo = Command::new(&builder.initial_cargo);
1002                 cargo
1003                     .arg("doc")
1004                     .arg("--target-dir")
1005                     .arg(&out_dir)
1006                     .env("RUSTC_BOOTSTRAP", "1")
1007                     .env("RUSTDOC", builder.rustdoc(self.compiler))
1008                     .env("RUSTC", builder.rustc(self.compiler))
1009                     .current_dir(path);
1010                 // FIXME: implement a `// compile-flags` command or similar
1011                 //        instead of hard-coding this test
1012                 if entry.file_name() == "link_to_definition" {
1013                     cargo.env("RUSTDOCFLAGS", "-Zunstable-options --generate-link-to-definition");
1014                 } else if entry.file_name() == "scrape_examples" {
1015                     cargo.arg("-Zrustdoc-scrape-examples=examples");
1016                 }
1017                 builder.run(&mut cargo);
1018             }
1019         }
1020
1021         // We now run GUI tests.
1022         let mut command = Command::new(&nodejs);
1023         command
1024             .arg(builder.build.src.join("src/tools/rustdoc-gui/tester.js"))
1025             .arg("--jobs")
1026             .arg(&builder.jobs().to_string())
1027             .arg("--doc-folder")
1028             .arg(out_dir.join("doc"))
1029             .arg("--tests-folder")
1030             .arg(builder.build.src.join("src/test/rustdoc-gui"));
1031         for path in &builder.paths {
1032             if let Some(p) = util::is_valid_test_suite_arg(path, "src/test/rustdoc-gui", builder) {
1033                 if !p.ends_with(".goml") {
1034                     eprintln!("A non-goml file was given: `{}`", path.display());
1035                     panic!("Cannot run rustdoc-gui tests");
1036                 }
1037                 if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
1038                     command.arg("--file").arg(name);
1039                 }
1040             }
1041         }
1042         for test_arg in builder.config.cmd.test_args() {
1043             command.arg(test_arg);
1044         }
1045         builder.run(&mut command);
1046     }
1047 }
1048
1049 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1050 pub struct Tidy;
1051
1052 impl Step for Tidy {
1053     type Output = ();
1054     const DEFAULT: bool = true;
1055     const ONLY_HOSTS: bool = true;
1056
1057     /// Runs the `tidy` tool.
1058     ///
1059     /// This tool in `src/tools` checks up on various bits and pieces of style and
1060     /// otherwise just implements a few lint-like checks that are specific to the
1061     /// compiler itself.
1062     ///
1063     /// Once tidy passes, this step also runs `fmt --check` if tests are being run
1064     /// for the `dev` or `nightly` channels.
1065     fn run(self, builder: &Builder<'_>) {
1066         let mut cmd = builder.tool_cmd(Tool::Tidy);
1067         cmd.arg(&builder.src);
1068         cmd.arg(&builder.initial_cargo);
1069         cmd.arg(&builder.out);
1070         cmd.arg(builder.jobs().to_string());
1071         if builder.is_verbose() {
1072             cmd.arg("--verbose");
1073         }
1074         if builder.config.cmd.bless() {
1075             cmd.arg("--bless");
1076         }
1077
1078         builder.info("tidy check");
1079         try_run(builder, &mut cmd);
1080
1081         if builder.config.channel == "dev" || builder.config.channel == "nightly" {
1082             builder.info("fmt check");
1083             if builder.initial_rustfmt().is_none() {
1084                 let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
1085                 eprintln!(
1086                     "\
1087 error: no `rustfmt` binary found in {PATH}
1088 info: `rust.channel` is currently set to \"{CHAN}\"
1089 help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
1090 help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
1091                     PATH = inferred_rustfmt_dir.display(),
1092                     CHAN = builder.config.channel,
1093                 );
1094                 crate::detail_exit(1);
1095             }
1096             crate::format::format(&builder, !builder.config.cmd.bless(), &[]);
1097         }
1098     }
1099
1100     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1101         run.path("src/tools/tidy")
1102     }
1103
1104     fn make_run(run: RunConfig<'_>) {
1105         run.builder.ensure(Tidy);
1106     }
1107 }
1108
1109 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1110 pub struct ExpandYamlAnchors;
1111
1112 impl Step for ExpandYamlAnchors {
1113     type Output = ();
1114     const ONLY_HOSTS: bool = true;
1115
1116     /// Ensure the `generate-ci-config` tool was run locally.
1117     ///
1118     /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
1119     /// appropriate configuration for all our CI providers. This step ensures the tool was called
1120     /// by the user before committing CI changes.
1121     fn run(self, builder: &Builder<'_>) {
1122         builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
1123         try_run(
1124             builder,
1125             &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
1126         );
1127     }
1128
1129     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1130         run.path("src/tools/expand-yaml-anchors")
1131     }
1132
1133     fn make_run(run: RunConfig<'_>) {
1134         run.builder.ensure(ExpandYamlAnchors);
1135     }
1136 }
1137
1138 fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
1139     builder.out.join(host.triple).join("test")
1140 }
1141
1142 macro_rules! default_test {
1143     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1144         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
1145     };
1146 }
1147
1148 macro_rules! default_test_with_compare_mode {
1149     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
1150                    compare_mode: $compare_mode:expr }) => {
1151         test_with_compare_mode!($name {
1152             path: $path,
1153             mode: $mode,
1154             suite: $suite,
1155             default: true,
1156             host: false,
1157             compare_mode: $compare_mode
1158         });
1159     };
1160 }
1161
1162 macro_rules! host_test {
1163     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1164         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
1165     };
1166 }
1167
1168 macro_rules! test {
1169     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1170                    host: $host:expr }) => {
1171         test_definitions!($name {
1172             path: $path,
1173             mode: $mode,
1174             suite: $suite,
1175             default: $default,
1176             host: $host,
1177             compare_mode: None
1178         });
1179     };
1180 }
1181
1182 macro_rules! test_with_compare_mode {
1183     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1184                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
1185         test_definitions!($name {
1186             path: $path,
1187             mode: $mode,
1188             suite: $suite,
1189             default: $default,
1190             host: $host,
1191             compare_mode: Some($compare_mode)
1192         });
1193     };
1194 }
1195
1196 macro_rules! test_definitions {
1197     ($name:ident {
1198         path: $path:expr,
1199         mode: $mode:expr,
1200         suite: $suite:expr,
1201         default: $default:expr,
1202         host: $host:expr,
1203         compare_mode: $compare_mode:expr
1204     }) => {
1205         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1206         pub struct $name {
1207             pub compiler: Compiler,
1208             pub target: TargetSelection,
1209         }
1210
1211         impl Step for $name {
1212             type Output = ();
1213             const DEFAULT: bool = $default;
1214             const ONLY_HOSTS: bool = $host;
1215
1216             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1217                 run.suite_path($path)
1218             }
1219
1220             fn make_run(run: RunConfig<'_>) {
1221                 let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1222
1223                 run.builder.ensure($name { compiler, target: run.target });
1224             }
1225
1226             fn run(self, builder: &Builder<'_>) {
1227                 builder.ensure(Compiletest {
1228                     compiler: self.compiler,
1229                     target: self.target,
1230                     mode: $mode,
1231                     suite: $suite,
1232                     path: $path,
1233                     compare_mode: $compare_mode,
1234                 })
1235             }
1236         }
1237     };
1238 }
1239
1240 default_test!(Ui { path: "src/test/ui", mode: "ui", suite: "ui" });
1241
1242 default_test!(RunPassValgrind {
1243     path: "src/test/run-pass-valgrind",
1244     mode: "run-pass-valgrind",
1245     suite: "run-pass-valgrind"
1246 });
1247
1248 default_test!(MirOpt { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" });
1249
1250 default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
1251
1252 default_test!(CodegenUnits {
1253     path: "src/test/codegen-units",
1254     mode: "codegen-units",
1255     suite: "codegen-units"
1256 });
1257
1258 default_test!(Incremental {
1259     path: "src/test/incremental",
1260     mode: "incremental",
1261     suite: "incremental"
1262 });
1263
1264 default_test_with_compare_mode!(Debuginfo {
1265     path: "src/test/debuginfo",
1266     mode: "debuginfo",
1267     suite: "debuginfo",
1268     compare_mode: "split-dwarf"
1269 });
1270
1271 host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
1272
1273 host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" });
1274 host_test!(RustdocUi { path: "src/test/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
1275
1276 host_test!(RustdocJson {
1277     path: "src/test/rustdoc-json",
1278     mode: "rustdoc-json",
1279     suite: "rustdoc-json"
1280 });
1281
1282 host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" });
1283
1284 default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" });
1285
1286 host_test!(RunMakeFullDeps {
1287     path: "src/test/run-make-fulldeps",
1288     mode: "run-make",
1289     suite: "run-make-fulldeps"
1290 });
1291
1292 default_test!(Assembly { path: "src/test/assembly", mode: "assembly", suite: "assembly" });
1293
1294 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1295 struct Compiletest {
1296     compiler: Compiler,
1297     target: TargetSelection,
1298     mode: &'static str,
1299     suite: &'static str,
1300     path: &'static str,
1301     compare_mode: Option<&'static str>,
1302 }
1303
1304 impl Step for Compiletest {
1305     type Output = ();
1306
1307     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1308         run.never()
1309     }
1310
1311     /// Executes the `compiletest` tool to run a suite of tests.
1312     ///
1313     /// Compiles all tests with `compiler` for `target` with the specified
1314     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1315     /// "run-pass" or `suite` can be something like `debuginfo`.
1316     fn run(self, builder: &Builder<'_>) {
1317         if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
1318             eprintln!("\
1319 error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1320 help: to test the compiler, use `--stage 1` instead
1321 help: to test the standard library, use `--stage 0 library/std` instead
1322 note: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`."
1323             );
1324             crate::detail_exit(1);
1325         }
1326
1327         let compiler = self.compiler;
1328         let target = self.target;
1329         let mode = self.mode;
1330         let suite = self.suite;
1331
1332         // Path for test suite
1333         let suite_path = self.path;
1334
1335         // Skip codegen tests if they aren't enabled in configuration.
1336         if !builder.config.codegen_tests && suite == "codegen" {
1337             return;
1338         }
1339
1340         if suite == "debuginfo" {
1341             builder
1342                 .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1343         }
1344
1345         if suite.ends_with("fulldeps") {
1346             builder.ensure(compile::Rustc::new(compiler, target));
1347         }
1348
1349         builder.ensure(compile::Std::new(compiler, target));
1350         // ensure that `libproc_macro` is available on the host.
1351         builder.ensure(compile::Std::new(compiler, compiler.host));
1352
1353         // Also provide `rust_test_helpers` for the host.
1354         builder.ensure(native::TestHelpers { target: compiler.host });
1355
1356         // As well as the target, except for plain wasm32, which can't build it
1357         if !target.contains("wasm") || target.contains("emscripten") {
1358             builder.ensure(native::TestHelpers { target });
1359         }
1360
1361         builder.ensure(RemoteCopyLibs { compiler, target });
1362
1363         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1364
1365         // compiletest currently has... a lot of arguments, so let's just pass all
1366         // of them!
1367
1368         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
1369         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1370         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1371
1372         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1373
1374         // Avoid depending on rustdoc when we don't need it.
1375         if mode == "rustdoc"
1376             || mode == "run-make"
1377             || (mode == "ui" && is_rustdoc)
1378             || mode == "js-doc-test"
1379             || mode == "rustdoc-json"
1380         {
1381             cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1382         }
1383
1384         if mode == "rustdoc-json" {
1385             // Use the beta compiler for jsondocck
1386             let json_compiler = compiler.with_stage(0);
1387             cmd.arg("--jsondocck-path")
1388                 .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
1389             cmd.arg("--jsondoclint-path")
1390                 .arg(builder.ensure(tool::JsonDocLint { compiler: json_compiler, target }));
1391         }
1392
1393         if mode == "run-make" {
1394             let rust_demangler = builder
1395                 .ensure(tool::RustDemangler {
1396                     compiler,
1397                     target: compiler.host,
1398                     extra_features: Vec::new(),
1399                 })
1400                 .expect("in-tree tool");
1401             cmd.arg("--rust-demangler-path").arg(rust_demangler);
1402         }
1403
1404         cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite));
1405         cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
1406         cmd.arg("--sysroot-base").arg(builder.sysroot(compiler));
1407         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1408         cmd.arg("--suite").arg(suite);
1409         cmd.arg("--mode").arg(mode);
1410         cmd.arg("--target").arg(target.rustc_target_arg());
1411         cmd.arg("--host").arg(&*compiler.host.triple);
1412         cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1413
1414         if builder.config.cmd.bless() {
1415             cmd.arg("--bless");
1416         }
1417
1418         if builder.config.cmd.force_rerun() {
1419             cmd.arg("--force-rerun");
1420         }
1421
1422         let compare_mode =
1423             builder.config.cmd.compare_mode().or_else(|| {
1424                 if builder.config.test_compare_mode { self.compare_mode } else { None }
1425             });
1426
1427         if let Some(ref pass) = builder.config.cmd.pass() {
1428             cmd.arg("--pass");
1429             cmd.arg(pass);
1430         }
1431
1432         if let Some(ref run) = builder.config.cmd.run() {
1433             cmd.arg("--run");
1434             cmd.arg(run);
1435         }
1436
1437         if let Some(ref nodejs) = builder.config.nodejs {
1438             cmd.arg("--nodejs").arg(nodejs);
1439         }
1440         if let Some(ref npm) = builder.config.npm {
1441             cmd.arg("--npm").arg(npm);
1442         }
1443         if builder.config.rust_optimize_tests {
1444             cmd.arg("--optimize-tests");
1445         }
1446         let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1447         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1448         flags.extend(builder.config.cmd.rustc_args().iter().map(|s| s.to_string()));
1449
1450         if let Some(linker) = builder.linker(target) {
1451             cmd.arg("--linker").arg(linker);
1452         }
1453
1454         let mut hostflags = flags.clone();
1455         hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1456         hostflags.extend(builder.lld_flags(compiler.host));
1457         for flag in hostflags {
1458             cmd.arg("--host-rustcflags").arg(flag);
1459         }
1460
1461         let mut targetflags = flags;
1462         targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1463         targetflags.extend(builder.lld_flags(target));
1464         for flag in targetflags {
1465             cmd.arg("--target-rustcflags").arg(flag);
1466         }
1467
1468         cmd.arg("--python").arg(builder.python());
1469
1470         if let Some(ref gdb) = builder.config.gdb {
1471             cmd.arg("--gdb").arg(gdb);
1472         }
1473
1474         let run = |cmd: &mut Command| {
1475             cmd.output().map(|output| {
1476                 String::from_utf8_lossy(&output.stdout)
1477                     .lines()
1478                     .next()
1479                     .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
1480                     .to_string()
1481             })
1482         };
1483         let lldb_exe = "lldb";
1484         let lldb_version = Command::new(lldb_exe)
1485             .arg("--version")
1486             .output()
1487             .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1488             .ok();
1489         if let Some(ref vers) = lldb_version {
1490             cmd.arg("--lldb-version").arg(vers);
1491             let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1492             if let Some(ref dir) = lldb_python_dir {
1493                 cmd.arg("--lldb-python-dir").arg(dir);
1494             }
1495         }
1496
1497         if util::forcing_clang_based_tests() {
1498             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1499             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1500         }
1501
1502         for exclude in &builder.config.exclude {
1503             cmd.arg("--skip");
1504             cmd.arg(&exclude.path);
1505         }
1506
1507         // Get paths from cmd args
1508         let paths = match &builder.config.cmd {
1509             Subcommand::Test { ref paths, .. } => &paths[..],
1510             _ => &[],
1511         };
1512
1513         // Get test-args by striping suite path
1514         let mut test_args: Vec<&str> = paths
1515             .iter()
1516             .filter_map(|p| util::is_valid_test_suite_arg(p, suite_path, builder))
1517             .collect();
1518
1519         test_args.append(&mut builder.config.cmd.test_args());
1520
1521         // On Windows, replace forward slashes in test-args by backslashes
1522         // so the correct filters are passed to libtest
1523         if cfg!(windows) {
1524             let test_args_win: Vec<String> =
1525                 test_args.iter().map(|s| s.replace("/", "\\")).collect();
1526             cmd.args(&test_args_win);
1527         } else {
1528             cmd.args(&test_args);
1529         }
1530
1531         if builder.is_verbose() {
1532             cmd.arg("--verbose");
1533         }
1534
1535         if !builder.config.verbose_tests {
1536             cmd.arg("--quiet");
1537         }
1538
1539         let mut llvm_components_passed = false;
1540         let mut copts_passed = false;
1541         if builder.config.llvm_enabled() {
1542             let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1543             if !builder.config.dry_run() {
1544                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1545                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1546                 // Remove trailing newline from llvm-config output.
1547                 cmd.arg("--llvm-version")
1548                     .arg(llvm_version.trim())
1549                     .arg("--llvm-components")
1550                     .arg(llvm_components.trim());
1551                 llvm_components_passed = true;
1552             }
1553             if !builder.is_rust_llvm(target) {
1554                 cmd.arg("--system-llvm");
1555             }
1556
1557             // Tests that use compiler libraries may inherit the `-lLLVM` link
1558             // requirement, but the `-L` library path is not propagated across
1559             // separate compilations. We can add LLVM's library path to the
1560             // platform-specific environment variable as a workaround.
1561             if !builder.config.dry_run() && suite.ends_with("fulldeps") {
1562                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1563                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
1564             }
1565
1566             // Only pass correct values for these flags for the `run-make` suite as it
1567             // requires that a C++ compiler was configured which isn't always the case.
1568             if !builder.config.dry_run() && matches!(suite, "run-make" | "run-make-fulldeps") {
1569                 // The llvm/bin directory contains many useful cross-platform
1570                 // tools. Pass the path to run-make tests so they can use them.
1571                 let llvm_bin_path = llvm_config
1572                     .parent()
1573                     .expect("Expected llvm-config to be contained in directory");
1574                 assert!(llvm_bin_path.is_dir());
1575                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1576
1577                 // If LLD is available, add it to the PATH
1578                 if builder.config.lld_enabled {
1579                     let lld_install_root =
1580                         builder.ensure(native::Lld { target: builder.config.build });
1581
1582                     let lld_bin_path = lld_install_root.join("bin");
1583
1584                     let old_path = env::var_os("PATH").unwrap_or_default();
1585                     let new_path = env::join_paths(
1586                         std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
1587                     )
1588                     .expect("Could not add LLD bin path to PATH");
1589                     cmd.env("PATH", new_path);
1590                 }
1591             }
1592         }
1593
1594         // Only pass correct values for these flags for the `run-make` suite as it
1595         // requires that a C++ compiler was configured which isn't always the case.
1596         if !builder.config.dry_run() && matches!(suite, "run-make" | "run-make-fulldeps") {
1597             cmd.arg("--cc")
1598                 .arg(builder.cc(target))
1599                 .arg("--cxx")
1600                 .arg(builder.cxx(target).unwrap())
1601                 .arg("--cflags")
1602                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::C).join(" "))
1603                 .arg("--cxxflags")
1604                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" "));
1605             copts_passed = true;
1606             if let Some(ar) = builder.ar(target) {
1607                 cmd.arg("--ar").arg(ar);
1608             }
1609         }
1610
1611         if !llvm_components_passed {
1612             cmd.arg("--llvm-components").arg("");
1613         }
1614         if !copts_passed {
1615             cmd.arg("--cc")
1616                 .arg("")
1617                 .arg("--cxx")
1618                 .arg("")
1619                 .arg("--cflags")
1620                 .arg("")
1621                 .arg("--cxxflags")
1622                 .arg("");
1623         }
1624
1625         if builder.remote_tested(target) {
1626             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1627         }
1628
1629         // Running a C compiler on MSVC requires a few env vars to be set, to be
1630         // sure to set them here.
1631         //
1632         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1633         // rather than stomp over it.
1634         if target.contains("msvc") {
1635             for &(ref k, ref v) in builder.cc[&target].env() {
1636                 if k != "PATH" {
1637                     cmd.env(k, v);
1638                 }
1639             }
1640         }
1641         cmd.env("RUSTC_BOOTSTRAP", "1");
1642         // Override the rustc version used in symbol hashes to reduce the amount of normalization
1643         // needed when diffing test output.
1644         cmd.env("RUSTC_FORCE_RUSTC_VERSION", "compiletest");
1645         cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
1646         builder.add_rust_test_threads(&mut cmd);
1647
1648         if builder.config.sanitizers_enabled(target) {
1649             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1650         }
1651
1652         if builder.config.profiler_enabled(target) {
1653             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1654         }
1655
1656         cmd.env("RUST_TEST_TMPDIR", builder.tempdir());
1657
1658         cmd.arg("--adb-path").arg("adb");
1659         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1660         if target.contains("android") {
1661             // Assume that cc for this target comes from the android sysroot
1662             cmd.arg("--android-cross-path")
1663                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1664         } else {
1665             cmd.arg("--android-cross-path").arg("");
1666         }
1667
1668         if builder.config.cmd.rustfix_coverage() {
1669             cmd.arg("--rustfix-coverage");
1670         }
1671
1672         cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);
1673
1674         cmd.arg("--channel").arg(&builder.config.channel);
1675
1676         if let Some(commit) = builder.config.download_rustc_commit() {
1677             cmd.env("FAKE_DOWNLOAD_RUSTC_PREFIX", format!("/rustc/{commit}"));
1678         }
1679
1680         builder.ci_env.force_coloring_in_ci(&mut cmd);
1681
1682         builder.info(&format!(
1683             "Check compiletest suite={} mode={} ({} -> {})",
1684             suite, mode, &compiler.host, target
1685         ));
1686         let _time = util::timeit(&builder);
1687         try_run(builder, &mut cmd);
1688
1689         if let Some(compare_mode) = compare_mode {
1690             cmd.arg("--compare-mode").arg(compare_mode);
1691             builder.info(&format!(
1692                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1693                 suite, mode, compare_mode, &compiler.host, target
1694             ));
1695             let _time = util::timeit(&builder);
1696             try_run(builder, &mut cmd);
1697         }
1698     }
1699 }
1700
1701 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1702 struct BookTest {
1703     compiler: Compiler,
1704     path: PathBuf,
1705     name: &'static str,
1706     is_ext_doc: bool,
1707 }
1708
1709 impl Step for BookTest {
1710     type Output = ();
1711     const ONLY_HOSTS: bool = true;
1712
1713     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1714         run.never()
1715     }
1716
1717     /// Runs the documentation tests for a book in `src/doc`.
1718     ///
1719     /// This uses the `rustdoc` that sits next to `compiler`.
1720     fn run(self, builder: &Builder<'_>) {
1721         // External docs are different from local because:
1722         // - Some books need pre-processing by mdbook before being tested.
1723         // - They need to save their state to toolstate.
1724         // - They are only tested on the "checktools" builders.
1725         //
1726         // The local docs are tested by default, and we don't want to pay the
1727         // cost of building mdbook, so they use `rustdoc --test` directly.
1728         // Also, the unstable book is special because SUMMARY.md is generated,
1729         // so it is easier to just run `rustdoc` on its files.
1730         if self.is_ext_doc {
1731             self.run_ext_doc(builder);
1732         } else {
1733             self.run_local_doc(builder);
1734         }
1735     }
1736 }
1737
1738 impl BookTest {
1739     /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
1740     /// which in turn runs `rustdoc --test` on each file in the book.
1741     fn run_ext_doc(self, builder: &Builder<'_>) {
1742         let compiler = self.compiler;
1743
1744         builder.ensure(compile::Std::new(compiler, compiler.host));
1745
1746         // mdbook just executes a binary named "rustdoc", so we need to update
1747         // PATH so that it points to our rustdoc.
1748         let mut rustdoc_path = builder.rustdoc(compiler);
1749         rustdoc_path.pop();
1750         let old_path = env::var_os("PATH").unwrap_or_default();
1751         let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
1752             .expect("could not add rustdoc to PATH");
1753
1754         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1755         let path = builder.src.join(&self.path);
1756         // Books often have feature-gated example text.
1757         rustbook_cmd.env("RUSTC_BOOTSTRAP", "1");
1758         rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
1759         builder.add_rust_test_threads(&mut rustbook_cmd);
1760         builder.info(&format!("Testing rustbook {}", self.path.display()));
1761         let _time = util::timeit(&builder);
1762         let toolstate = if try_run(builder, &mut rustbook_cmd) {
1763             ToolState::TestPass
1764         } else {
1765             ToolState::TestFail
1766         };
1767         builder.save_toolstate(self.name, toolstate);
1768     }
1769
1770     /// This runs `rustdoc --test` on all `.md` files in the path.
1771     fn run_local_doc(self, builder: &Builder<'_>) {
1772         let compiler = self.compiler;
1773
1774         builder.ensure(compile::Std::new(compiler, compiler.host));
1775
1776         // Do a breadth-first traversal of the `src/doc` directory and just run
1777         // tests for all files that end in `*.md`
1778         let mut stack = vec![builder.src.join(self.path)];
1779         let _time = util::timeit(&builder);
1780         let mut files = Vec::new();
1781         while let Some(p) = stack.pop() {
1782             if p.is_dir() {
1783                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1784                 continue;
1785             }
1786
1787             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1788                 continue;
1789             }
1790
1791             files.push(p);
1792         }
1793
1794         files.sort();
1795
1796         for file in files {
1797             markdown_test(builder, compiler, &file);
1798         }
1799     }
1800 }
1801
1802 macro_rules! test_book {
1803     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1804         $(
1805             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1806             pub struct $name {
1807                 compiler: Compiler,
1808             }
1809
1810             impl Step for $name {
1811                 type Output = ();
1812                 const DEFAULT: bool = $default;
1813                 const ONLY_HOSTS: bool = true;
1814
1815                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1816                     run.path($path)
1817                 }
1818
1819                 fn make_run(run: RunConfig<'_>) {
1820                     run.builder.ensure($name {
1821                         compiler: run.builder.compiler(run.builder.top_stage, run.target),
1822                     });
1823                 }
1824
1825                 fn run(self, builder: &Builder<'_>) {
1826                     builder.ensure(BookTest {
1827                         compiler: self.compiler,
1828                         path: PathBuf::from($path),
1829                         name: $book_name,
1830                         is_ext_doc: !$default,
1831                     });
1832                 }
1833             }
1834         )+
1835     }
1836 }
1837
1838 test_book!(
1839     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1840     Reference, "src/doc/reference", "reference", default=false;
1841     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1842     RustcBook, "src/doc/rustc", "rustc", default=true;
1843     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1844     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1845     TheBook, "src/doc/book", "book", default=false;
1846     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1847     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1848 );
1849
1850 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1851 pub struct ErrorIndex {
1852     compiler: Compiler,
1853 }
1854
1855 impl Step for ErrorIndex {
1856     type Output = ();
1857     const DEFAULT: bool = true;
1858     const ONLY_HOSTS: bool = true;
1859
1860     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1861         run.path("src/tools/error_index_generator")
1862     }
1863
1864     fn make_run(run: RunConfig<'_>) {
1865         // error_index_generator depends on librustdoc. Use the compiler that
1866         // is normally used to build rustdoc for other tests (like compiletest
1867         // tests in src/test/rustdoc) so that it shares the same artifacts.
1868         let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
1869         run.builder.ensure(ErrorIndex { compiler });
1870     }
1871
1872     /// Runs the error index generator tool to execute the tests located in the error
1873     /// index.
1874     ///
1875     /// The `error_index_generator` tool lives in `src/tools` and is used to
1876     /// generate a markdown file from the error indexes of the code base which is
1877     /// then passed to `rustdoc --test`.
1878     fn run(self, builder: &Builder<'_>) {
1879         let compiler = self.compiler;
1880
1881         let dir = testdir(builder, compiler.host);
1882         t!(fs::create_dir_all(&dir));
1883         let output = dir.join("error-index.md");
1884
1885         let mut tool = tool::ErrorIndex::command(builder);
1886         tool.arg("markdown").arg(&output);
1887
1888         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1889         let _time = util::timeit(&builder);
1890         builder.run_quiet(&mut tool);
1891         // The tests themselves need to link to std, so make sure it is
1892         // available.
1893         builder.ensure(compile::Std::new(compiler, compiler.host));
1894         markdown_test(builder, compiler, &output);
1895     }
1896 }
1897
1898 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1899     if let Ok(contents) = fs::read_to_string(markdown) {
1900         if !contents.contains("```") {
1901             return true;
1902         }
1903     }
1904
1905     builder.info(&format!("doc tests for: {}", markdown.display()));
1906     let mut cmd = builder.rustdoc_cmd(compiler);
1907     builder.add_rust_test_threads(&mut cmd);
1908     // allow for unstable options such as new editions
1909     cmd.arg("-Z");
1910     cmd.arg("unstable-options");
1911     cmd.arg("--test");
1912     cmd.arg(markdown);
1913     cmd.env("RUSTC_BOOTSTRAP", "1");
1914
1915     let test_args = builder.config.cmd.test_args().join(" ");
1916     cmd.arg("--test-args").arg(test_args);
1917
1918     if builder.config.verbose_tests {
1919         try_run(builder, &mut cmd)
1920     } else {
1921         try_run_quiet(builder, &mut cmd)
1922     }
1923 }
1924
1925 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1926 pub struct RustcGuide;
1927
1928 impl Step for RustcGuide {
1929     type Output = ();
1930     const DEFAULT: bool = false;
1931     const ONLY_HOSTS: bool = true;
1932
1933     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1934         run.path("src/doc/rustc-dev-guide")
1935     }
1936
1937     fn make_run(run: RunConfig<'_>) {
1938         run.builder.ensure(RustcGuide);
1939     }
1940
1941     fn run(self, builder: &Builder<'_>) {
1942         let relative_path = Path::new("src").join("doc").join("rustc-dev-guide");
1943         builder.update_submodule(&relative_path);
1944
1945         let src = builder.src.join(relative_path);
1946         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1947         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
1948             ToolState::TestPass
1949         } else {
1950             ToolState::TestFail
1951         };
1952         builder.save_toolstate("rustc-dev-guide", toolstate);
1953     }
1954 }
1955
1956 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1957 pub struct CrateLibrustc {
1958     compiler: Compiler,
1959     target: TargetSelection,
1960     test_kind: TestKind,
1961     crates: Vec<Interned<String>>,
1962 }
1963
1964 impl Step for CrateLibrustc {
1965     type Output = ();
1966     const DEFAULT: bool = true;
1967     const ONLY_HOSTS: bool = true;
1968
1969     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1970         run.crate_or_deps("rustc-main")
1971     }
1972
1973     fn make_run(run: RunConfig<'_>) {
1974         let builder = run.builder;
1975         let host = run.build_triple();
1976         let compiler = builder.compiler_for(builder.top_stage, host, host);
1977         let crates = run
1978             .paths
1979             .iter()
1980             .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
1981             .collect();
1982         let test_kind = builder.kind.into();
1983
1984         builder.ensure(CrateLibrustc { compiler, target: run.target, test_kind, crates });
1985     }
1986
1987     fn run(self, builder: &Builder<'_>) {
1988         builder.ensure(Crate {
1989             compiler: self.compiler,
1990             target: self.target,
1991             mode: Mode::Rustc,
1992             test_kind: self.test_kind,
1993             crates: self.crates,
1994         });
1995     }
1996 }
1997
1998 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1999 pub struct Crate {
2000     pub compiler: Compiler,
2001     pub target: TargetSelection,
2002     pub mode: Mode,
2003     pub test_kind: TestKind,
2004     pub crates: Vec<Interned<String>>,
2005 }
2006
2007 impl Step for Crate {
2008     type Output = ();
2009     const DEFAULT: bool = true;
2010
2011     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2012         run.crate_or_deps("test")
2013     }
2014
2015     fn make_run(run: RunConfig<'_>) {
2016         let builder = run.builder;
2017         let host = run.build_triple();
2018         let compiler = builder.compiler_for(builder.top_stage, host, host);
2019         let test_kind = builder.kind.into();
2020         let crates = run
2021             .paths
2022             .iter()
2023             .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
2024             .collect();
2025
2026         builder.ensure(Crate { compiler, target: run.target, mode: Mode::Std, test_kind, crates });
2027     }
2028
2029     /// Runs all unit tests plus documentation tests for a given crate defined
2030     /// by a `Cargo.toml` (single manifest)
2031     ///
2032     /// This is what runs tests for crates like the standard library, compiler, etc.
2033     /// It essentially is the driver for running `cargo test`.
2034     ///
2035     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
2036     /// arguments, and those arguments are discovered from `cargo metadata`.
2037     fn run(self, builder: &Builder<'_>) {
2038         let compiler = self.compiler;
2039         let target = self.target;
2040         let mode = self.mode;
2041         let test_kind = self.test_kind;
2042
2043         builder.ensure(compile::Std::new(compiler, target));
2044         builder.ensure(RemoteCopyLibs { compiler, target });
2045
2046         // If we're not doing a full bootstrap but we're testing a stage2
2047         // version of libstd, then what we're actually testing is the libstd
2048         // produced in stage1. Reflect that here by updating the compiler that
2049         // we're working with automatically.
2050         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
2051
2052         let mut cargo =
2053             builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
2054         match mode {
2055             Mode::Std => {
2056                 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
2057             }
2058             Mode::Rustc => {
2059                 compile::rustc_cargo(builder, &mut cargo, target);
2060             }
2061             _ => panic!("can only test libraries"),
2062         };
2063
2064         // Build up the base `cargo test` command.
2065         //
2066         // Pass in some standard flags then iterate over the graph we've discovered
2067         // in `cargo metadata` with the maps above and figure out what `-p`
2068         // arguments need to get passed.
2069         if test_kind.subcommand() == "test" && !builder.fail_fast {
2070             cargo.arg("--no-fail-fast");
2071         }
2072         match builder.doc_tests {
2073             DocTests::Only => {
2074                 cargo.arg("--doc");
2075             }
2076             DocTests::No => {
2077                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2078             }
2079             DocTests::Yes => {}
2080         }
2081
2082         for krate in &self.crates {
2083             cargo.arg("-p").arg(krate);
2084         }
2085
2086         // The tests are going to run with the *target* libraries, so we need to
2087         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
2088         //
2089         // Note that to run the compiler we need to run with the *host* libraries,
2090         // but our wrapper scripts arrange for that to be the case anyway.
2091         let mut dylib_path = dylib_path();
2092         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
2093         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2094
2095         cargo.arg("--");
2096         cargo.args(&builder.config.cmd.test_args());
2097
2098         if !builder.config.verbose_tests {
2099             cargo.arg("--quiet");
2100         }
2101
2102         if target.contains("emscripten") {
2103             cargo.env(
2104                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2105                 builder.config.nodejs.as_ref().expect("nodejs not configured"),
2106             );
2107         } else if target.starts_with("wasm32") {
2108             let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
2109             let runner =
2110                 format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
2111             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
2112         } else if builder.remote_tested(target) {
2113             cargo.env(
2114                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2115                 format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
2116             );
2117         }
2118
2119         builder.info(&format!(
2120             "{} {:?} stage{} ({} -> {})",
2121             test_kind, self.crates, compiler.stage, &compiler.host, target
2122         ));
2123         let _time = util::timeit(&builder);
2124         try_run(builder, &mut cargo.into());
2125     }
2126 }
2127
2128 /// Rustdoc is special in various ways, which is why this step is different from `Crate`.
2129 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2130 pub struct CrateRustdoc {
2131     host: TargetSelection,
2132     test_kind: TestKind,
2133 }
2134
2135 impl Step for CrateRustdoc {
2136     type Output = ();
2137     const DEFAULT: bool = true;
2138     const ONLY_HOSTS: bool = true;
2139
2140     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2141         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
2142     }
2143
2144     fn make_run(run: RunConfig<'_>) {
2145         let builder = run.builder;
2146
2147         let test_kind = builder.kind.into();
2148
2149         builder.ensure(CrateRustdoc { host: run.target, test_kind });
2150     }
2151
2152     fn run(self, builder: &Builder<'_>) {
2153         let test_kind = self.test_kind;
2154         let target = self.host;
2155
2156         let compiler = if builder.download_rustc() {
2157             builder.compiler(builder.top_stage, target)
2158         } else {
2159             // Use the previous stage compiler to reuse the artifacts that are
2160             // created when running compiletest for src/test/rustdoc. If this used
2161             // `compiler`, then it would cause rustdoc to be built *again*, which
2162             // isn't really necessary.
2163             builder.compiler_for(builder.top_stage, target, target)
2164         };
2165         builder.ensure(compile::Rustc::new(compiler, target));
2166
2167         let mut cargo = tool::prepare_tool_cargo(
2168             builder,
2169             compiler,
2170             Mode::ToolRustc,
2171             target,
2172             test_kind.subcommand(),
2173             "src/tools/rustdoc",
2174             SourceType::InTree,
2175             &[],
2176         );
2177         if test_kind.subcommand() == "test" && !builder.fail_fast {
2178             cargo.arg("--no-fail-fast");
2179         }
2180         match builder.doc_tests {
2181             DocTests::Only => {
2182                 cargo.arg("--doc");
2183             }
2184             DocTests::No => {
2185                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2186             }
2187             DocTests::Yes => {}
2188         }
2189
2190         cargo.arg("-p").arg("rustdoc:0.0.0");
2191
2192         cargo.arg("--");
2193         cargo.args(&builder.config.cmd.test_args());
2194
2195         if self.host.contains("musl") {
2196             cargo.arg("'-Ctarget-feature=-crt-static'");
2197         }
2198
2199         // This is needed for running doctests on librustdoc. This is a bit of
2200         // an unfortunate interaction with how bootstrap works and how cargo
2201         // sets up the dylib path, and the fact that the doctest (in
2202         // html/markdown.rs) links to rustc-private libs. For stage1, the
2203         // compiler host dylibs (in stage1/lib) are not the same as the target
2204         // dylibs (in stage1/lib/rustlib/...). This is different from a normal
2205         // rust distribution where they are the same.
2206         //
2207         // On the cargo side, normal tests use `target_process` which handles
2208         // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
2209         // case). However, for doctests it uses `rustdoc_process` which only
2210         // sets up the dylib path for the *host* (stage1/lib), which is the
2211         // wrong directory.
2212         //
2213         // Recall that we special-cased `compiler_for(top_stage)` above, so we always use stage1.
2214         //
2215         // It should be considered to just stop running doctests on
2216         // librustdoc. There is only one test, and it doesn't look too
2217         // important. There might be other ways to avoid this, but it seems
2218         // pretty convoluted.
2219         //
2220         // See also https://github.com/rust-lang/rust/issues/13983 where the
2221         // host vs target dylibs for rustdoc are consistently tricky to deal
2222         // with.
2223         //
2224         // Note that this set the host libdir for `download_rustc`, which uses a normal rust distribution.
2225         let libdir = if builder.download_rustc() {
2226             builder.rustc_libdir(compiler)
2227         } else {
2228             builder.sysroot_libdir(compiler, target).to_path_buf()
2229         };
2230         let mut dylib_path = dylib_path();
2231         dylib_path.insert(0, PathBuf::from(&*libdir));
2232         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2233
2234         if !builder.config.verbose_tests {
2235             cargo.arg("--quiet");
2236         }
2237
2238         builder.info(&format!(
2239             "{} rustdoc stage{} ({} -> {})",
2240             test_kind, compiler.stage, &compiler.host, target
2241         ));
2242         let _time = util::timeit(&builder);
2243
2244         try_run(builder, &mut cargo.into());
2245     }
2246 }
2247
2248 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2249 pub struct CrateRustdocJsonTypes {
2250     host: TargetSelection,
2251     test_kind: TestKind,
2252 }
2253
2254 impl Step for CrateRustdocJsonTypes {
2255     type Output = ();
2256     const DEFAULT: bool = true;
2257     const ONLY_HOSTS: bool = true;
2258
2259     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2260         run.path("src/rustdoc-json-types")
2261     }
2262
2263     fn make_run(run: RunConfig<'_>) {
2264         let builder = run.builder;
2265
2266         let test_kind = builder.kind.into();
2267
2268         builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
2269     }
2270
2271     fn run(self, builder: &Builder<'_>) {
2272         let test_kind = self.test_kind;
2273         let target = self.host;
2274
2275         // Use the previous stage compiler to reuse the artifacts that are
2276         // created when running compiletest for src/test/rustdoc. If this used
2277         // `compiler`, then it would cause rustdoc to be built *again*, which
2278         // isn't really necessary.
2279         let compiler = builder.compiler_for(builder.top_stage, target, target);
2280         builder.ensure(compile::Rustc::new(compiler, target));
2281
2282         let mut cargo = tool::prepare_tool_cargo(
2283             builder,
2284             compiler,
2285             Mode::ToolRustc,
2286             target,
2287             test_kind.subcommand(),
2288             "src/rustdoc-json-types",
2289             SourceType::InTree,
2290             &[],
2291         );
2292         if test_kind.subcommand() == "test" && !builder.fail_fast {
2293             cargo.arg("--no-fail-fast");
2294         }
2295
2296         cargo.arg("-p").arg("rustdoc-json-types");
2297
2298         cargo.arg("--");
2299         cargo.args(&builder.config.cmd.test_args());
2300
2301         if self.host.contains("musl") {
2302             cargo.arg("'-Ctarget-feature=-crt-static'");
2303         }
2304
2305         if !builder.config.verbose_tests {
2306             cargo.arg("--quiet");
2307         }
2308
2309         builder.info(&format!(
2310             "{} rustdoc-json-types stage{} ({} -> {})",
2311             test_kind, compiler.stage, &compiler.host, target
2312         ));
2313         let _time = util::timeit(&builder);
2314
2315         try_run(builder, &mut cargo.into());
2316     }
2317 }
2318
2319 /// Some test suites are run inside emulators or on remote devices, and most
2320 /// of our test binaries are linked dynamically which means we need to ship
2321 /// the standard library and such to the emulator ahead of time. This step
2322 /// represents this and is a dependency of all test suites.
2323 ///
2324 /// Most of the time this is a no-op. For some steps such as shipping data to
2325 /// QEMU we have to build our own tools so we've got conditional dependencies
2326 /// on those programs as well. Note that the remote test client is built for
2327 /// the build target (us) and the server is built for the target.
2328 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2329 pub struct RemoteCopyLibs {
2330     compiler: Compiler,
2331     target: TargetSelection,
2332 }
2333
2334 impl Step for RemoteCopyLibs {
2335     type Output = ();
2336
2337     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2338         run.never()
2339     }
2340
2341     fn run(self, builder: &Builder<'_>) {
2342         let compiler = self.compiler;
2343         let target = self.target;
2344         if !builder.remote_tested(target) {
2345             return;
2346         }
2347
2348         builder.ensure(compile::Std::new(compiler, target));
2349
2350         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
2351
2352         let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2353
2354         // Spawn the emulator and wait for it to come online
2355         let tool = builder.tool_exe(Tool::RemoteTestClient);
2356         let mut cmd = Command::new(&tool);
2357         cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.tempdir());
2358         if let Some(rootfs) = builder.qemu_rootfs(target) {
2359             cmd.arg(rootfs);
2360         }
2361         builder.run(&mut cmd);
2362
2363         // Push all our dylibs to the emulator
2364         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2365             let f = t!(f);
2366             let name = f.file_name().into_string().unwrap();
2367             if util::is_dylib(&name) {
2368                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
2369             }
2370         }
2371     }
2372 }
2373
2374 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2375 pub struct Distcheck;
2376
2377 impl Step for Distcheck {
2378     type Output = ();
2379
2380     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2381         run.alias("distcheck")
2382     }
2383
2384     fn make_run(run: RunConfig<'_>) {
2385         run.builder.ensure(Distcheck);
2386     }
2387
2388     /// Runs "distcheck", a 'make check' from a tarball
2389     fn run(self, builder: &Builder<'_>) {
2390         builder.info("Distcheck");
2391         let dir = builder.tempdir().join("distcheck");
2392         let _ = fs::remove_dir_all(&dir);
2393         t!(fs::create_dir_all(&dir));
2394
2395         // Guarantee that these are built before we begin running.
2396         builder.ensure(dist::PlainSourceTarball);
2397         builder.ensure(dist::Src);
2398
2399         let mut cmd = Command::new("tar");
2400         cmd.arg("-xf")
2401             .arg(builder.ensure(dist::PlainSourceTarball).tarball())
2402             .arg("--strip-components=1")
2403             .current_dir(&dir);
2404         builder.run(&mut cmd);
2405         builder.run(
2406             Command::new("./configure")
2407                 .args(&builder.config.configure_args)
2408                 .arg("--enable-vendor")
2409                 .current_dir(&dir),
2410         );
2411         builder.run(
2412             Command::new(util::make(&builder.config.build.triple)).arg("check").current_dir(&dir),
2413         );
2414
2415         // Now make sure that rust-src has all of libstd's dependencies
2416         builder.info("Distcheck rust-src");
2417         let dir = builder.tempdir().join("distcheck-src");
2418         let _ = fs::remove_dir_all(&dir);
2419         t!(fs::create_dir_all(&dir));
2420
2421         let mut cmd = Command::new("tar");
2422         cmd.arg("-xf")
2423             .arg(builder.ensure(dist::Src).tarball())
2424             .arg("--strip-components=1")
2425             .current_dir(&dir);
2426         builder.run(&mut cmd);
2427
2428         let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
2429         builder.run(
2430             Command::new(&builder.initial_cargo)
2431                 .arg("generate-lockfile")
2432                 .arg("--manifest-path")
2433                 .arg(&toml)
2434                 .current_dir(&dir),
2435         );
2436     }
2437 }
2438
2439 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2440 pub struct Bootstrap;
2441
2442 impl Step for Bootstrap {
2443     type Output = ();
2444     const DEFAULT: bool = true;
2445     const ONLY_HOSTS: bool = true;
2446
2447     /// Tests the build system itself.
2448     fn run(self, builder: &Builder<'_>) {
2449         let mut check_bootstrap = Command::new(&builder.python());
2450         check_bootstrap.arg("bootstrap_test.py").current_dir(builder.src.join("src/bootstrap/"));
2451         try_run(builder, &mut check_bootstrap);
2452
2453         let mut cmd = Command::new(&builder.initial_cargo);
2454         cmd.arg("test")
2455             .current_dir(builder.src.join("src/bootstrap"))
2456             .env("RUSTFLAGS", "-Cdebuginfo=2")
2457             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2458             .env("RUSTC_BOOTSTRAP", "1")
2459             .env("RUSTDOC", builder.rustdoc(builder.compiler(0, builder.build.build)))
2460             .env("RUSTC", &builder.initial_rustc);
2461         if let Some(flags) = option_env!("RUSTFLAGS") {
2462             // Use the same rustc flags for testing as for "normal" compilation,
2463             // so that Cargo doesn’t recompile the entire dependency graph every time:
2464             // https://github.com/rust-lang/rust/issues/49215
2465             cmd.env("RUSTFLAGS", flags);
2466         }
2467         if !builder.fail_fast {
2468             cmd.arg("--no-fail-fast");
2469         }
2470         match builder.doc_tests {
2471             DocTests::Only => {
2472                 cmd.arg("--doc");
2473             }
2474             DocTests::No => {
2475                 cmd.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2476             }
2477             DocTests::Yes => {}
2478         }
2479
2480         cmd.arg("--").args(&builder.config.cmd.test_args());
2481         // rustbuild tests are racy on directory creation so just run them one at a time.
2482         // Since there's not many this shouldn't be a problem.
2483         cmd.arg("--test-threads=1");
2484         try_run(builder, &mut cmd);
2485     }
2486
2487     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2488         run.path("src/bootstrap")
2489     }
2490
2491     fn make_run(run: RunConfig<'_>) {
2492         run.builder.ensure(Bootstrap);
2493     }
2494 }
2495
2496 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2497 pub struct TierCheck {
2498     pub compiler: Compiler,
2499 }
2500
2501 impl Step for TierCheck {
2502     type Output = ();
2503     const DEFAULT: bool = true;
2504     const ONLY_HOSTS: bool = true;
2505
2506     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2507         run.path("src/tools/tier-check")
2508     }
2509
2510     fn make_run(run: RunConfig<'_>) {
2511         let compiler =
2512             run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
2513         run.builder.ensure(TierCheck { compiler });
2514     }
2515
2516     /// Tests the Platform Support page in the rustc book.
2517     fn run(self, builder: &Builder<'_>) {
2518         builder.ensure(compile::Std::new(self.compiler, self.compiler.host));
2519         let mut cargo = tool::prepare_tool_cargo(
2520             builder,
2521             self.compiler,
2522             Mode::ToolStd,
2523             self.compiler.host,
2524             "run",
2525             "src/tools/tier-check",
2526             SourceType::InTree,
2527             &[],
2528         );
2529         cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
2530         cargo.arg(&builder.rustc(self.compiler));
2531         if builder.is_verbose() {
2532             cargo.arg("--verbose");
2533         }
2534
2535         builder.info("platform support check");
2536         try_run(builder, &mut cargo.into());
2537     }
2538 }
2539
2540 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2541 pub struct ReplacePlaceholderTest;
2542
2543 impl Step for ReplacePlaceholderTest {
2544     type Output = ();
2545     const ONLY_HOSTS: bool = true;
2546     const DEFAULT: bool = true;
2547
2548     /// Ensure the version placeholder replacement tool builds
2549     fn run(self, builder: &Builder<'_>) {
2550         builder.info("build check for version replacement placeholder");
2551
2552         // Test the version placeholder replacement tool itself.
2553         let bootstrap_host = builder.config.build;
2554         let compiler = builder.compiler(0, bootstrap_host);
2555         let cargo = tool::prepare_tool_cargo(
2556             builder,
2557             compiler,
2558             Mode::ToolBootstrap,
2559             bootstrap_host,
2560             "test",
2561             "src/tools/replace-version-placeholder",
2562             SourceType::InTree,
2563             &[],
2564         );
2565         try_run(builder, &mut cargo.into());
2566     }
2567
2568     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2569         run.path("src/tools/replace-version-placeholder")
2570     }
2571
2572     fn make_run(run: RunConfig<'_>) {
2573         run.builder.ensure(Self);
2574     }
2575 }
2576
2577 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2578 pub struct LintDocs {
2579     pub compiler: Compiler,
2580     pub target: TargetSelection,
2581 }
2582
2583 impl Step for LintDocs {
2584     type Output = ();
2585     const DEFAULT: bool = true;
2586     const ONLY_HOSTS: bool = true;
2587
2588     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2589         run.path("src/tools/lint-docs")
2590     }
2591
2592     fn make_run(run: RunConfig<'_>) {
2593         run.builder.ensure(LintDocs {
2594             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
2595             target: run.target,
2596         });
2597     }
2598
2599     /// Tests that the lint examples in the rustc book generate the correct
2600     /// lints and have the expected format.
2601     fn run(self, builder: &Builder<'_>) {
2602         builder.ensure(crate::doc::RustcBook {
2603             compiler: self.compiler,
2604             target: self.target,
2605             validate: true,
2606         });
2607     }
2608 }