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