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