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