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