]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Auto merge of #65324 - Centril:organize-syntax, r=petrochenkov
[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             cargo.env("HOST_LIBS", host_libs);
574             // clippy tests need to find the driver
575             cargo.env("CLIPPY_DRIVER_PATH", clippy);
576
577             builder.add_rustc_lib_path(compiler, &mut cargo);
578
579             if try_run(builder, &mut cargo.into()) {
580                 builder.save_toolstate("clippy-driver", ToolState::TestPass);
581             }
582         } else {
583             eprintln!("failed to test clippy: could not build");
584         }
585     }
586 }
587
588 fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
589     // Configure PATH to find the right rustc. NB. we have to use PATH
590     // and not RUSTC because the Cargo test suite has tests that will
591     // fail if rustc is not spelled `rustc`.
592     let path = builder.sysroot(compiler).join("bin");
593     let old_path = env::var_os("PATH").unwrap_or_default();
594     env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
595 }
596
597 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
598 pub struct RustdocTheme {
599     pub compiler: Compiler,
600 }
601
602 impl Step for RustdocTheme {
603     type Output = ();
604     const DEFAULT: bool = true;
605     const ONLY_HOSTS: bool = true;
606
607     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
608         run.path("src/tools/rustdoc-themes")
609     }
610
611     fn make_run(run: RunConfig<'_>) {
612         let compiler = run.builder.compiler(run.builder.top_stage, run.host);
613
614         run.builder.ensure(RustdocTheme { compiler });
615     }
616
617     fn run(self, builder: &Builder<'_>) {
618         let rustdoc = builder.out.join("bootstrap/debug/rustdoc");
619         let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
620         cmd.arg(rustdoc.to_str().unwrap())
621             .arg(
622                 builder
623                     .src
624                     .join("src/librustdoc/html/static/themes")
625                     .to_str()
626                     .unwrap(),
627             )
628             .env("RUSTC_STAGE", self.compiler.stage.to_string())
629             .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
630             .env(
631                 "RUSTDOC_LIBDIR",
632                 builder.sysroot_libdir(self.compiler, self.compiler.host),
633             )
634             .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
635             .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
636             .env("RUSTDOC_CRATE_VERSION", builder.rust_version())
637             .env("RUSTC_BOOTSTRAP", "1");
638         if let Some(linker) = builder.linker(self.compiler.host) {
639             cmd.env("RUSTC_TARGET_LINKER", linker);
640         }
641         try_run(builder, &mut cmd);
642     }
643 }
644
645 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
646 pub struct RustdocJSStd {
647     pub host: Interned<String>,
648     pub target: Interned<String>,
649 }
650
651 impl Step for RustdocJSStd {
652     type Output = ();
653     const DEFAULT: bool = true;
654     const ONLY_HOSTS: bool = true;
655
656     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
657         run.path("src/test/rustdoc-js-std")
658     }
659
660     fn make_run(run: RunConfig<'_>) {
661         run.builder.ensure(RustdocJSStd {
662             host: run.host,
663             target: run.target,
664         });
665     }
666
667     fn run(self, builder: &Builder<'_>) {
668         if let Some(ref nodejs) = builder.config.nodejs {
669             let mut command = Command::new(nodejs);
670             command.args(&["src/tools/rustdoc-js-std/tester.js", &*self.host]);
671             builder.ensure(crate::doc::Std {
672                 target: self.target,
673                 stage: builder.top_stage,
674             });
675             builder.run(&mut command);
676         } else {
677             builder.info(
678                 "No nodejs found, skipping \"src/test/rustdoc-js-std\" tests"
679             );
680         }
681     }
682 }
683
684 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
685 pub struct RustdocJSNotStd {
686     pub host: Interned<String>,
687     pub target: Interned<String>,
688     pub compiler: Compiler,
689 }
690
691 impl Step for RustdocJSNotStd {
692     type Output = ();
693     const DEFAULT: bool = true;
694     const ONLY_HOSTS: bool = true;
695
696     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
697         run.path("src/test/rustdoc-js")
698     }
699
700     fn make_run(run: RunConfig<'_>) {
701         let compiler = run.builder.compiler(run.builder.top_stage, run.host);
702         run.builder.ensure(RustdocJSNotStd {
703             host: run.host,
704             target: run.target,
705             compiler,
706         });
707     }
708
709     fn run(self, builder: &Builder<'_>) {
710         if builder.config.nodejs.is_some() {
711             builder.ensure(Compiletest {
712                 compiler: self.compiler,
713                 target: self.target,
714                 mode: "js-doc-test",
715                 suite: "rustdoc-js",
716                 path: None,
717                 compare_mode: None,
718             });
719         } else {
720             builder.info(
721                 "No nodejs found, skipping \"src/test/rustdoc-js\" tests"
722             );
723         }
724     }
725 }
726
727 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
728 pub struct RustdocUi {
729     pub host: Interned<String>,
730     pub target: Interned<String>,
731     pub compiler: Compiler,
732 }
733
734 impl Step for RustdocUi {
735     type Output = ();
736     const DEFAULT: bool = true;
737     const ONLY_HOSTS: bool = true;
738
739     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
740         run.path("src/test/rustdoc-ui")
741     }
742
743     fn make_run(run: RunConfig<'_>) {
744         let compiler = run.builder.compiler(run.builder.top_stage, run.host);
745         run.builder.ensure(RustdocUi {
746             host: run.host,
747             target: run.target,
748             compiler,
749         });
750     }
751
752     fn run(self, builder: &Builder<'_>) {
753         builder.ensure(Compiletest {
754             compiler: self.compiler,
755             target: self.target,
756             mode: "ui",
757             suite: "rustdoc-ui",
758             path: Some("src/test/rustdoc-ui"),
759             compare_mode: None,
760         })
761     }
762 }
763
764 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
765 pub struct Tidy;
766
767 impl Step for Tidy {
768     type Output = ();
769     const DEFAULT: bool = true;
770     const ONLY_HOSTS: bool = true;
771
772     /// Runs the `tidy` tool.
773     ///
774     /// This tool in `src/tools` checks up on various bits and pieces of style and
775     /// otherwise just implements a few lint-like checks that are specific to the
776     /// compiler itself.
777     fn run(self, builder: &Builder<'_>) {
778         let mut cmd = builder.tool_cmd(Tool::Tidy);
779         cmd.arg(builder.src.join("src"));
780         cmd.arg(&builder.initial_cargo);
781         if !builder.config.vendor {
782             cmd.arg("--no-vendor");
783         }
784         if builder.is_verbose() {
785             cmd.arg("--verbose");
786         }
787
788         builder.info("tidy check");
789         try_run(builder, &mut cmd);
790     }
791
792     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
793         run.path("src/tools/tidy")
794     }
795
796     fn make_run(run: RunConfig<'_>) {
797         run.builder.ensure(Tidy);
798     }
799 }
800
801 fn testdir(builder: &Builder<'_>, host: Interned<String>) -> PathBuf {
802     builder.out.join(host).join("test")
803 }
804
805 macro_rules! default_test {
806     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
807         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
808     }
809 }
810
811 macro_rules! default_test_with_compare_mode {
812     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
813                    compare_mode: $compare_mode:expr }) => {
814         test_with_compare_mode!($name { path: $path, mode: $mode, suite: $suite, default: true,
815                                         host: false, compare_mode: $compare_mode });
816     }
817 }
818
819 macro_rules! host_test {
820     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
821         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
822     }
823 }
824
825 macro_rules! test {
826     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
827                    host: $host:expr }) => {
828         test_definitions!($name { path: $path, mode: $mode, suite: $suite, default: $default,
829                                   host: $host, compare_mode: None });
830     }
831 }
832
833 macro_rules! test_with_compare_mode {
834     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
835                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
836         test_definitions!($name { path: $path, mode: $mode, suite: $suite, default: $default,
837                                   host: $host, compare_mode: Some($compare_mode) });
838     }
839 }
840
841 macro_rules! test_definitions {
842     ($name:ident {
843         path: $path:expr,
844         mode: $mode:expr,
845         suite: $suite:expr,
846         default: $default:expr,
847         host: $host:expr,
848         compare_mode: $compare_mode:expr
849     }) => {
850         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
851         pub struct $name {
852             pub compiler: Compiler,
853             pub target: Interned<String>,
854         }
855
856         impl Step for $name {
857             type Output = ();
858             const DEFAULT: bool = $default;
859             const ONLY_HOSTS: bool = $host;
860
861             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
862                 run.suite_path($path)
863             }
864
865             fn make_run(run: RunConfig<'_>) {
866                 let compiler = run.builder.compiler(run.builder.top_stage, run.host);
867
868                 run.builder.ensure($name {
869                     compiler,
870                     target: run.target,
871                 });
872             }
873
874             fn run(self, builder: &Builder<'_>) {
875                 builder.ensure(Compiletest {
876                     compiler: self.compiler,
877                     target: self.target,
878                     mode: $mode,
879                     suite: $suite,
880                     path: Some($path),
881                     compare_mode: $compare_mode,
882                 })
883             }
884         }
885     }
886 }
887
888 default_test_with_compare_mode!(Ui {
889     path: "src/test/ui",
890     mode: "ui",
891     suite: "ui",
892     compare_mode: "nll"
893 });
894
895 default_test!(CompileFail {
896     path: "src/test/compile-fail",
897     mode: "compile-fail",
898     suite: "compile-fail"
899 });
900
901 default_test!(RunFail {
902     path: "src/test/run-fail",
903     mode: "run-fail",
904     suite: "run-fail"
905 });
906
907 default_test!(RunPassValgrind {
908     path: "src/test/run-pass-valgrind",
909     mode: "run-pass-valgrind",
910     suite: "run-pass-valgrind"
911 });
912
913 default_test!(MirOpt {
914     path: "src/test/mir-opt",
915     mode: "mir-opt",
916     suite: "mir-opt"
917 });
918
919 default_test!(Codegen {
920     path: "src/test/codegen",
921     mode: "codegen",
922     suite: "codegen"
923 });
924
925 default_test!(CodegenUnits {
926     path: "src/test/codegen-units",
927     mode: "codegen-units",
928     suite: "codegen-units"
929 });
930
931 default_test!(Incremental {
932     path: "src/test/incremental",
933     mode: "incremental",
934     suite: "incremental"
935 });
936
937 default_test!(Debuginfo {
938     path: "src/test/debuginfo",
939     mode: "debuginfo",
940     suite: "debuginfo"
941 });
942
943 host_test!(UiFullDeps {
944     path: "src/test/ui-fulldeps",
945     mode: "ui",
946     suite: "ui-fulldeps"
947 });
948
949 host_test!(Rustdoc {
950     path: "src/test/rustdoc",
951     mode: "rustdoc",
952     suite: "rustdoc"
953 });
954
955 host_test!(Pretty {
956     path: "src/test/pretty",
957     mode: "pretty",
958     suite: "pretty"
959 });
960 test!(RunFailPretty {
961     path: "src/test/run-fail/pretty",
962     mode: "pretty",
963     suite: "run-fail",
964     default: false,
965     host: true
966 });
967 test!(RunPassValgrindPretty {
968     path: "src/test/run-pass-valgrind/pretty",
969     mode: "pretty",
970     suite: "run-pass-valgrind",
971     default: false,
972     host: true
973 });
974
975 default_test!(RunMake {
976     path: "src/test/run-make",
977     mode: "run-make",
978     suite: "run-make"
979 });
980
981 host_test!(RunMakeFullDeps {
982     path: "src/test/run-make-fulldeps",
983     mode: "run-make",
984     suite: "run-make-fulldeps"
985 });
986
987 default_test!(Assembly {
988     path: "src/test/assembly",
989     mode: "assembly",
990     suite: "assembly"
991 });
992
993 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
994 struct Compiletest {
995     compiler: Compiler,
996     target: Interned<String>,
997     mode: &'static str,
998     suite: &'static str,
999     path: Option<&'static str>,
1000     compare_mode: Option<&'static str>,
1001 }
1002
1003 impl Step for Compiletest {
1004     type Output = ();
1005
1006     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1007         run.never()
1008     }
1009
1010     /// Executes the `compiletest` tool to run a suite of tests.
1011     ///
1012     /// Compiles all tests with `compiler` for `target` with the specified
1013     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1014     /// "run-pass" or `suite` can be something like `debuginfo`.
1015     fn run(self, builder: &Builder<'_>) {
1016         let compiler = self.compiler;
1017         let target = self.target;
1018         let mode = self.mode;
1019         let suite = self.suite;
1020
1021         // Path for test suite
1022         let suite_path = self.path.unwrap_or("");
1023
1024         // Skip codegen tests if they aren't enabled in configuration.
1025         if !builder.config.codegen_tests && suite == "codegen" {
1026             return;
1027         }
1028
1029         if suite == "debuginfo" {
1030             let msvc = builder.config.build.contains("msvc");
1031             if mode == "debuginfo" {
1032                 return builder.ensure(Compiletest {
1033                     mode: if msvc { "debuginfo-cdb" } else { "debuginfo-gdb+lldb" },
1034                     ..self
1035                 });
1036             }
1037
1038             builder.ensure(dist::DebuggerScripts {
1039                 sysroot: builder.sysroot(compiler),
1040                 host: target,
1041             });
1042         }
1043
1044         if suite.ends_with("fulldeps") {
1045             builder.ensure(compile::Rustc { compiler, target });
1046         }
1047
1048         builder.ensure(compile::Std { compiler, target });
1049         // ensure that `libproc_macro` is available on the host.
1050         builder.ensure(compile::Std { compiler, target: compiler.host });
1051
1052         // Also provide `rust_test_helpers` for the host.
1053         builder.ensure(native::TestHelpers { target: compiler.host });
1054
1055         // As well as the target, except for plain wasm32, which can't build it
1056         if !target.contains("wasm32") || target.contains("emscripten") {
1057             builder.ensure(native::TestHelpers { target });
1058         }
1059
1060         builder.ensure(RemoteCopyLibs { compiler, target });
1061
1062         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1063
1064         // compiletest currently has... a lot of arguments, so let's just pass all
1065         // of them!
1066
1067         cmd.arg("--compile-lib-path")
1068             .arg(builder.rustc_libdir(compiler));
1069         cmd.arg("--run-lib-path")
1070             .arg(builder.sysroot_libdir(compiler, target));
1071         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1072
1073         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1074
1075         // Avoid depending on rustdoc when we don't need it.
1076         if mode == "rustdoc"
1077             || (mode == "run-make" && suite.ends_with("fulldeps"))
1078             || (mode == "ui" && is_rustdoc)
1079             || mode == "js-doc-test"
1080         {
1081             cmd.arg("--rustdoc-path")
1082                 .arg(builder.rustdoc(compiler));
1083         }
1084
1085         cmd.arg("--src-base")
1086             .arg(builder.src.join("src/test").join(suite));
1087         cmd.arg("--build-base")
1088             .arg(testdir(builder, compiler.host).join(suite));
1089         cmd.arg("--stage-id")
1090             .arg(format!("stage{}-{}", compiler.stage, target));
1091         cmd.arg("--mode").arg(mode);
1092         cmd.arg("--target").arg(target);
1093         cmd.arg("--host").arg(&*compiler.host);
1094         cmd.arg("--llvm-filecheck")
1095             .arg(builder.llvm_filecheck(builder.config.build));
1096
1097         if builder.config.cmd.bless() {
1098             cmd.arg("--bless");
1099         }
1100
1101         let compare_mode = builder.config.cmd.compare_mode().or_else(|| {
1102             if builder.config.test_compare_mode {
1103                 self.compare_mode
1104             } else {
1105                 None
1106             }
1107         });
1108
1109         if let Some(ref pass) = builder.config.cmd.pass() {
1110             cmd.arg("--pass");
1111             cmd.arg(pass);
1112         }
1113
1114         if let Some(ref nodejs) = builder.config.nodejs {
1115             cmd.arg("--nodejs").arg(nodejs);
1116         }
1117
1118         let mut flags = if is_rustdoc {
1119             Vec::new()
1120         } else {
1121             vec!["-Crpath".to_string()]
1122         };
1123         if !is_rustdoc {
1124             if builder.config.rust_optimize_tests {
1125                 flags.push("-O".to_string());
1126             }
1127         }
1128         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1129         flags.push("-Zunstable-options".to_string());
1130         flags.push(builder.config.cmd.rustc_args().join(" "));
1131
1132         if let Some(linker) = builder.linker(target) {
1133             cmd.arg("--linker").arg(linker);
1134         }
1135
1136         let mut hostflags = flags.clone();
1137         hostflags.push(format!(
1138             "-Lnative={}",
1139             builder.test_helpers_out(compiler.host).display()
1140         ));
1141         cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
1142
1143         let mut targetflags = flags;
1144         targetflags.push(format!(
1145             "-Lnative={}",
1146             builder.test_helpers_out(target).display()
1147         ));
1148         cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
1149
1150         cmd.arg("--docck-python").arg(builder.python());
1151
1152         if builder.config.build.ends_with("apple-darwin") {
1153             // Force /usr/bin/python on macOS for LLDB tests because we're loading the
1154             // LLDB plugin's compiled module which only works with the system python
1155             // (namely not Homebrew-installed python)
1156             cmd.arg("--lldb-python").arg("/usr/bin/python");
1157         } else {
1158             cmd.arg("--lldb-python").arg(builder.python());
1159         }
1160
1161         if let Some(ref gdb) = builder.config.gdb {
1162             cmd.arg("--gdb").arg(gdb);
1163         }
1164
1165         let run = |cmd: &mut Command| {
1166             cmd.output().map(|output| {
1167                 String::from_utf8_lossy(&output.stdout)
1168                     .lines().next().unwrap_or_else(|| {
1169                         panic!("{:?} failed {:?}", cmd, output)
1170                     }).to_string()
1171             })
1172         };
1173         let lldb_exe = if builder.config.lldb_enabled {
1174             // Test against the lldb that was just built.
1175             builder.llvm_out(target).join("bin").join("lldb")
1176         } else {
1177             PathBuf::from("lldb")
1178         };
1179         let lldb_version = Command::new(&lldb_exe)
1180             .arg("--version")
1181             .output()
1182             .map(|output| { String::from_utf8_lossy(&output.stdout).to_string() })
1183             .ok();
1184         if let Some(ref vers) = lldb_version {
1185             cmd.arg("--lldb-version").arg(vers);
1186             let lldb_python_dir = run(Command::new(&lldb_exe).arg("-P")).ok();
1187             if let Some(ref dir) = lldb_python_dir {
1188                 cmd.arg("--lldb-python-dir").arg(dir);
1189             }
1190         }
1191
1192         if util::forcing_clang_based_tests() {
1193             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1194             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1195         }
1196
1197         // Get paths from cmd args
1198         let paths = match &builder.config.cmd {
1199             Subcommand::Test { ref paths, .. } => &paths[..],
1200             _ => &[],
1201         };
1202
1203         // Get test-args by striping suite path
1204         let mut test_args: Vec<&str> = paths
1205             .iter()
1206             .map(|p| {
1207                 match p.strip_prefix(".") {
1208                     Ok(path) => path,
1209                     Err(_) => p,
1210                 }
1211             })
1212             .filter(|p| p.starts_with(suite_path) && (p.is_dir() || p.is_file()))
1213             .filter_map(|p| {
1214                 // Since test suite paths are themselves directories, if we don't
1215                 // specify a directory or file, we'll get an empty string here
1216                 // (the result of the test suite directory without its suite prefix).
1217                 // Therefore, we need to filter these out, as only the first --test-args
1218                 // flag is respected, so providing an empty --test-args conflicts with
1219                 // any following it.
1220                 match p.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
1221                     Some(s) if s != "" => Some(s),
1222                     _ => None,
1223                 }
1224             })
1225             .collect();
1226
1227         test_args.append(&mut builder.config.cmd.test_args());
1228
1229         cmd.args(&test_args);
1230
1231         if builder.is_verbose() {
1232             cmd.arg("--verbose");
1233         }
1234
1235         if !builder.config.verbose_tests {
1236             cmd.arg("--quiet");
1237         }
1238
1239         if builder.config.llvm_enabled() {
1240             let llvm_config = builder.ensure(native::Llvm {
1241                 target: builder.config.build,
1242             });
1243             if !builder.config.dry_run {
1244                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1245                 cmd.arg("--llvm-version").arg(llvm_version);
1246             }
1247             if !builder.is_rust_llvm(target) {
1248                 cmd.arg("--system-llvm");
1249             }
1250
1251             // Only pass correct values for these flags for the `run-make` suite as it
1252             // requires that a C++ compiler was configured which isn't always the case.
1253             if !builder.config.dry_run && suite == "run-make-fulldeps" {
1254                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1255                 let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
1256                 cmd.arg("--cc")
1257                     .arg(builder.cc(target))
1258                     .arg("--cxx")
1259                     .arg(builder.cxx(target).unwrap())
1260                     .arg("--cflags")
1261                     .arg(builder.cflags(target, GitRepo::Rustc).join(" "))
1262                     .arg("--llvm-components")
1263                     .arg(llvm_components.trim())
1264                     .arg("--llvm-cxxflags")
1265                     .arg(llvm_cxxflags.trim());
1266                 if let Some(ar) = builder.ar(target) {
1267                     cmd.arg("--ar").arg(ar);
1268                 }
1269
1270                 // The llvm/bin directory contains many useful cross-platform
1271                 // tools. Pass the path to run-make tests so they can use them.
1272                 let llvm_bin_path = llvm_config.parent()
1273                     .expect("Expected llvm-config to be contained in directory");
1274                 assert!(llvm_bin_path.is_dir());
1275                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1276
1277                 // If LLD is available, add it to the PATH
1278                 if builder.config.lld_enabled {
1279                     let lld_install_root = builder.ensure(native::Lld {
1280                         target: builder.config.build,
1281                     });
1282
1283                     let lld_bin_path = lld_install_root.join("bin");
1284
1285                     let old_path = env::var_os("PATH").unwrap_or_default();
1286                     let new_path = env::join_paths(std::iter::once(lld_bin_path)
1287                         .chain(env::split_paths(&old_path)))
1288                         .expect("Could not add LLD bin path to PATH");
1289                     cmd.env("PATH", new_path);
1290                 }
1291             }
1292         }
1293
1294         if suite != "run-make-fulldeps" {
1295             cmd.arg("--cc")
1296                 .arg("")
1297                 .arg("--cxx")
1298                 .arg("")
1299                 .arg("--cflags")
1300                 .arg("")
1301                 .arg("--llvm-components")
1302                 .arg("")
1303                 .arg("--llvm-cxxflags")
1304                 .arg("");
1305         }
1306
1307         if builder.remote_tested(target) {
1308             cmd.arg("--remote-test-client")
1309                 .arg(builder.tool_exe(Tool::RemoteTestClient));
1310         }
1311
1312         // Running a C compiler on MSVC requires a few env vars to be set, to be
1313         // sure to set them here.
1314         //
1315         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1316         // rather than stomp over it.
1317         if target.contains("msvc") {
1318             for &(ref k, ref v) in builder.cc[&target].env() {
1319                 if k != "PATH" {
1320                     cmd.env(k, v);
1321                 }
1322             }
1323         }
1324         cmd.env("RUSTC_BOOTSTRAP", "1");
1325         builder.add_rust_test_threads(&mut cmd);
1326
1327         if builder.config.sanitizers {
1328             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1329         }
1330
1331         if builder.config.profiler {
1332             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1333         }
1334
1335         let tmp = builder.out.join("tmp");
1336         std::fs::create_dir_all(&tmp).unwrap();
1337         cmd.env("RUST_TEST_TMPDIR", tmp);
1338
1339
1340         cmd.arg("--adb-path").arg("adb");
1341         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1342         if target.contains("android") {
1343             // Assume that cc for this target comes from the android sysroot
1344             cmd.arg("--android-cross-path")
1345                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1346         } else {
1347             cmd.arg("--android-cross-path").arg("");
1348         }
1349
1350         if builder.config.cmd.rustfix_coverage() {
1351             cmd.arg("--rustfix-coverage");
1352         }
1353
1354         builder.ci_env.force_coloring_in_ci(&mut cmd);
1355
1356         builder.info(&format!(
1357             "Check compiletest suite={} mode={} ({} -> {})",
1358             suite, mode, &compiler.host, target
1359         ));
1360         let _time = util::timeit(&builder);
1361         try_run(builder, &mut cmd);
1362
1363         if let Some(compare_mode) = compare_mode {
1364             cmd.arg("--compare-mode").arg(compare_mode);
1365             builder.info(&format!(
1366                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1367                 suite, mode, compare_mode, &compiler.host, target
1368             ));
1369             let _time = util::timeit(&builder);
1370             try_run(builder, &mut cmd);
1371         }
1372     }
1373 }
1374
1375 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1376 struct DocTest {
1377     compiler: Compiler,
1378     path: &'static str,
1379     name: &'static str,
1380     is_ext_doc: bool,
1381 }
1382
1383 impl Step for DocTest {
1384     type Output = ();
1385     const ONLY_HOSTS: bool = true;
1386
1387     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1388         run.never()
1389     }
1390
1391     /// Runs `rustdoc --test` for all documentation in `src/doc`.
1392     ///
1393     /// This will run all tests in our markdown documentation (e.g., the book)
1394     /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
1395     /// `compiler`.
1396     fn run(self, builder: &Builder<'_>) {
1397         let compiler = self.compiler;
1398
1399         builder.ensure(compile::Std {
1400             compiler,
1401             target: compiler.host,
1402         });
1403
1404         // Do a breadth-first traversal of the `src/doc` directory and just run
1405         // tests for all files that end in `*.md`
1406         let mut stack = vec![builder.src.join(self.path)];
1407         let _time = util::timeit(&builder);
1408
1409         let mut files = Vec::new();
1410         while let Some(p) = stack.pop() {
1411             if p.is_dir() {
1412                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1413                 continue;
1414             }
1415
1416             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1417                 continue;
1418             }
1419
1420             // The nostarch directory in the book is for no starch, and so isn't
1421             // guaranteed to builder. We don't care if it doesn't build, so skip it.
1422             if p.to_str().map_or(false, |p| p.contains("nostarch")) {
1423                 continue;
1424             }
1425
1426             files.push(p);
1427         }
1428
1429         files.sort();
1430
1431         let mut toolstate = ToolState::TestPass;
1432         for file in files {
1433             if !markdown_test(builder, compiler, &file) {
1434                 toolstate = ToolState::TestFail;
1435             }
1436         }
1437         if self.is_ext_doc {
1438             builder.save_toolstate(self.name, toolstate);
1439         }
1440     }
1441 }
1442
1443 macro_rules! test_book {
1444     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1445         $(
1446             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1447             pub struct $name {
1448                 compiler: Compiler,
1449             }
1450
1451             impl Step for $name {
1452                 type Output = ();
1453                 const DEFAULT: bool = $default;
1454                 const ONLY_HOSTS: bool = true;
1455
1456                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1457                     run.path($path)
1458                 }
1459
1460                 fn make_run(run: RunConfig<'_>) {
1461                     run.builder.ensure($name {
1462                         compiler: run.builder.compiler(run.builder.top_stage, run.host),
1463                     });
1464                 }
1465
1466                 fn run(self, builder: &Builder<'_>) {
1467                     builder.ensure(DocTest {
1468                         compiler: self.compiler,
1469                         path: $path,
1470                         name: $book_name,
1471                         is_ext_doc: !$default,
1472                     });
1473                 }
1474             }
1475         )+
1476     }
1477 }
1478
1479 test_book!(
1480     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1481     Reference, "src/doc/reference", "reference", default=false;
1482     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1483     RustcBook, "src/doc/rustc", "rustc", default=true;
1484     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1485     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1486     TheBook, "src/doc/book", "book", default=false;
1487     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1488     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1489 );
1490
1491 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1492 pub struct ErrorIndex {
1493     compiler: Compiler,
1494 }
1495
1496 impl Step for ErrorIndex {
1497     type Output = ();
1498     const DEFAULT: bool = true;
1499     const ONLY_HOSTS: bool = true;
1500
1501     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1502         run.path("src/tools/error_index_generator")
1503     }
1504
1505     fn make_run(run: RunConfig<'_>) {
1506         run.builder.ensure(ErrorIndex {
1507             compiler: run.builder.compiler(run.builder.top_stage, run.host),
1508         });
1509     }
1510
1511     /// Runs the error index generator tool to execute the tests located in the error
1512     /// index.
1513     ///
1514     /// The `error_index_generator` tool lives in `src/tools` and is used to
1515     /// generate a markdown file from the error indexes of the code base which is
1516     /// then passed to `rustdoc --test`.
1517     fn run(self, builder: &Builder<'_>) {
1518         let compiler = self.compiler;
1519
1520         builder.ensure(compile::Std {
1521             compiler,
1522             target: compiler.host,
1523         });
1524
1525         let dir = testdir(builder, compiler.host);
1526         t!(fs::create_dir_all(&dir));
1527         let output = dir.join("error-index.md");
1528
1529         let mut tool = tool::ErrorIndex::command(
1530             builder,
1531             builder.compiler(compiler.stage, builder.config.build),
1532         );
1533         tool.arg("markdown")
1534             .arg(&output)
1535             .env("CFG_BUILD", &builder.config.build);
1536
1537         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1538         let _time = util::timeit(&builder);
1539         builder.run_quiet(&mut tool);
1540         markdown_test(builder, compiler, &output);
1541     }
1542 }
1543
1544 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1545     match fs::read_to_string(markdown) {
1546         Ok(contents) => {
1547             if !contents.contains("```") {
1548                 return true;
1549             }
1550         }
1551         Err(_) => {}
1552     }
1553
1554     builder.info(&format!("doc tests for: {}", markdown.display()));
1555     let mut cmd = builder.rustdoc_cmd(compiler);
1556     builder.add_rust_test_threads(&mut cmd);
1557     cmd.arg("--test");
1558     cmd.arg(markdown);
1559     cmd.env("RUSTC_BOOTSTRAP", "1");
1560
1561     let test_args = builder.config.cmd.test_args().join(" ");
1562     cmd.arg("--test-args").arg(test_args);
1563
1564     if builder.config.verbose_tests {
1565         try_run(builder, &mut cmd)
1566     } else {
1567         try_run_quiet(builder, &mut cmd)
1568     }
1569 }
1570
1571 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1572 pub struct RustcGuide;
1573
1574 impl Step for RustcGuide {
1575     type Output = ();
1576     const DEFAULT: bool = false;
1577     const ONLY_HOSTS: bool = true;
1578
1579     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1580         run.path("src/doc/rustc-guide")
1581     }
1582
1583     fn make_run(run: RunConfig<'_>) {
1584         run.builder.ensure(RustcGuide);
1585     }
1586
1587     fn run(self, builder: &Builder<'_>) {
1588         let src = builder.src.join("src/doc/rustc-guide");
1589         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1590         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
1591             ToolState::TestPass
1592         } else {
1593             ToolState::TestFail
1594         };
1595         builder.save_toolstate("rustc-guide", toolstate);
1596     }
1597 }
1598
1599 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1600 pub struct CrateLibrustc {
1601     compiler: Compiler,
1602     target: Interned<String>,
1603     test_kind: TestKind,
1604     krate: Interned<String>,
1605 }
1606
1607 impl Step for CrateLibrustc {
1608     type Output = ();
1609     const DEFAULT: bool = true;
1610     const ONLY_HOSTS: bool = true;
1611
1612     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1613         run.krate("rustc-main")
1614     }
1615
1616     fn make_run(run: RunConfig<'_>) {
1617         let builder = run.builder;
1618         let compiler = builder.compiler(builder.top_stage, run.host);
1619
1620         for krate in builder.in_tree_crates("rustc-main") {
1621             if run.path.ends_with(&krate.path) {
1622                 let test_kind = builder.kind.into();
1623
1624                 builder.ensure(CrateLibrustc {
1625                     compiler,
1626                     target: run.target,
1627                     test_kind,
1628                     krate: krate.name,
1629                 });
1630             }
1631         }
1632     }
1633
1634     fn run(self, builder: &Builder<'_>) {
1635         builder.ensure(Crate {
1636             compiler: self.compiler,
1637             target: self.target,
1638             mode: Mode::Rustc,
1639             test_kind: self.test_kind,
1640             krate: self.krate,
1641         });
1642     }
1643 }
1644
1645 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1646 pub struct CrateNotDefault {
1647     compiler: Compiler,
1648     target: Interned<String>,
1649     test_kind: TestKind,
1650     krate: &'static str,
1651 }
1652
1653 impl Step for CrateNotDefault {
1654     type Output = ();
1655
1656     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1657         run.path("src/librustc_asan")
1658             .path("src/librustc_lsan")
1659             .path("src/librustc_msan")
1660             .path("src/librustc_tsan")
1661     }
1662
1663     fn make_run(run: RunConfig<'_>) {
1664         let builder = run.builder;
1665         let compiler = builder.compiler(builder.top_stage, run.host);
1666
1667         let test_kind = builder.kind.into();
1668
1669         builder.ensure(CrateNotDefault {
1670             compiler,
1671             target: run.target,
1672             test_kind,
1673             krate: match run.path {
1674                 _ if run.path.ends_with("src/librustc_asan") => "rustc_asan",
1675                 _ if run.path.ends_with("src/librustc_lsan") => "rustc_lsan",
1676                 _ if run.path.ends_with("src/librustc_msan") => "rustc_msan",
1677                 _ if run.path.ends_with("src/librustc_tsan") => "rustc_tsan",
1678                 _ => panic!("unexpected path {:?}", run.path),
1679             },
1680         });
1681     }
1682
1683     fn run(self, builder: &Builder<'_>) {
1684         builder.ensure(Crate {
1685             compiler: self.compiler,
1686             target: self.target,
1687             mode: Mode::Std,
1688             test_kind: self.test_kind,
1689             krate: INTERNER.intern_str(self.krate),
1690         });
1691     }
1692 }
1693
1694 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1695 pub struct Crate {
1696     pub compiler: Compiler,
1697     pub target: Interned<String>,
1698     pub mode: Mode,
1699     pub test_kind: TestKind,
1700     pub krate: Interned<String>,
1701 }
1702
1703 impl Step for Crate {
1704     type Output = ();
1705     const DEFAULT: bool = true;
1706
1707     fn should_run(mut run: ShouldRun<'_>) -> ShouldRun<'_> {
1708         let builder = run.builder;
1709         for krate in run.builder.in_tree_crates("test") {
1710             if !(krate.name.starts_with("rustc_") && krate.name.ends_with("san")) {
1711                 run = run.path(krate.local_path(&builder).to_str().unwrap());
1712             }
1713         }
1714         run
1715     }
1716
1717     fn make_run(run: RunConfig<'_>) {
1718         let builder = run.builder;
1719         let compiler = builder.compiler(builder.top_stage, run.host);
1720
1721         let make = |mode: Mode, krate: &CargoCrate| {
1722             let test_kind = builder.kind.into();
1723
1724             builder.ensure(Crate {
1725                 compiler,
1726                 target: run.target,
1727                 mode,
1728                 test_kind,
1729                 krate: krate.name,
1730             });
1731         };
1732
1733         for krate in builder.in_tree_crates("test") {
1734             if run.path.ends_with(&krate.local_path(&builder)) {
1735                 make(Mode::Std, krate);
1736             }
1737         }
1738     }
1739
1740     /// Runs all unit tests plus documentation tests for a given crate defined
1741     /// by a `Cargo.toml` (single manifest)
1742     ///
1743     /// This is what runs tests for crates like the standard library, compiler, etc.
1744     /// It essentially is the driver for running `cargo test`.
1745     ///
1746     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
1747     /// arguments, and those arguments are discovered from `cargo metadata`.
1748     fn run(self, builder: &Builder<'_>) {
1749         let compiler = self.compiler;
1750         let target = self.target;
1751         let mode = self.mode;
1752         let test_kind = self.test_kind;
1753         let krate = self.krate;
1754
1755         builder.ensure(compile::Std { compiler, target });
1756         builder.ensure(RemoteCopyLibs { compiler, target });
1757
1758         // If we're not doing a full bootstrap but we're testing a stage2
1759         // version of libstd, then what we're actually testing is the libstd
1760         // produced in stage1. Reflect that here by updating the compiler that
1761         // we're working with automatically.
1762         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
1763
1764         let mut cargo = builder.cargo(compiler, mode, target, test_kind.subcommand());
1765         match mode {
1766             Mode::Std => {
1767                 compile::std_cargo(builder, &compiler, target, &mut cargo);
1768             }
1769             Mode::Rustc => {
1770                 builder.ensure(compile::Rustc { compiler, target });
1771                 compile::rustc_cargo(builder, &mut cargo);
1772             }
1773             _ => panic!("can only test libraries"),
1774         };
1775
1776         // Build up the base `cargo test` command.
1777         //
1778         // Pass in some standard flags then iterate over the graph we've discovered
1779         // in `cargo metadata` with the maps above and figure out what `-p`
1780         // arguments need to get passed.
1781         if test_kind.subcommand() == "test" && !builder.fail_fast {
1782             cargo.arg("--no-fail-fast");
1783         }
1784         match builder.doc_tests {
1785             DocTests::Only => {
1786                 cargo.arg("--doc");
1787             }
1788             DocTests::No => {
1789                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
1790             }
1791             DocTests::Yes => {}
1792         }
1793
1794         cargo.arg("-p").arg(krate);
1795
1796         // The tests are going to run with the *target* libraries, so we need to
1797         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
1798         //
1799         // Note that to run the compiler we need to run with the *host* libraries,
1800         // but our wrapper scripts arrange for that to be the case anyway.
1801         let mut dylib_path = dylib_path();
1802         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1803         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1804
1805         cargo.arg("--");
1806         cargo.args(&builder.config.cmd.test_args());
1807
1808         if !builder.config.verbose_tests {
1809             cargo.arg("--quiet");
1810         }
1811
1812         if target.contains("emscripten") {
1813             cargo.env(
1814                 format!("CARGO_TARGET_{}_RUNNER", envify(&target)),
1815                 builder
1816                     .config
1817                     .nodejs
1818                     .as_ref()
1819                     .expect("nodejs not configured"),
1820             );
1821         } else if target.starts_with("wasm32") {
1822             let node = builder
1823                 .config
1824                 .nodejs
1825                 .as_ref()
1826                 .expect("nodejs not configured");
1827             let runner = format!(
1828                 "{} {}/src/etc/wasm32-shim.js",
1829                 node.display(),
1830                 builder.src.display()
1831             );
1832             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target)), &runner);
1833         } else if builder.remote_tested(target) {
1834             cargo.env(
1835                 format!("CARGO_TARGET_{}_RUNNER", envify(&target)),
1836                 format!("{} run", builder.tool_exe(Tool::RemoteTestClient).display()),
1837             );
1838         }
1839
1840         builder.info(&format!(
1841             "{} {} stage{} ({} -> {})",
1842             test_kind, krate, compiler.stage, &compiler.host, target
1843         ));
1844         let _time = util::timeit(&builder);
1845         try_run(builder, &mut cargo.into());
1846     }
1847 }
1848
1849 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1850 pub struct CrateRustdoc {
1851     host: Interned<String>,
1852     test_kind: TestKind,
1853 }
1854
1855 impl Step for CrateRustdoc {
1856     type Output = ();
1857     const DEFAULT: bool = true;
1858     const ONLY_HOSTS: bool = true;
1859
1860     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1861         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
1862     }
1863
1864     fn make_run(run: RunConfig<'_>) {
1865         let builder = run.builder;
1866
1867         let test_kind = builder.kind.into();
1868
1869         builder.ensure(CrateRustdoc {
1870             host: run.host,
1871             test_kind,
1872         });
1873     }
1874
1875     fn run(self, builder: &Builder<'_>) {
1876         let test_kind = self.test_kind;
1877
1878         let compiler = builder.compiler(builder.top_stage, self.host);
1879         let target = compiler.host;
1880         builder.ensure(compile::Rustc { compiler, target });
1881
1882         let mut cargo = tool::prepare_tool_cargo(builder,
1883                                                  compiler,
1884                                                  Mode::ToolRustc,
1885                                                  target,
1886                                                  test_kind.subcommand(),
1887                                                  "src/tools/rustdoc",
1888                                                  SourceType::InTree,
1889                                                  &[]);
1890         if test_kind.subcommand() == "test" && !builder.fail_fast {
1891             cargo.arg("--no-fail-fast");
1892         }
1893
1894         cargo.arg("-p").arg("rustdoc:0.0.0");
1895
1896         cargo.arg("--");
1897         cargo.args(&builder.config.cmd.test_args());
1898
1899         if self.host.contains("musl") {
1900             cargo.arg("'-Ctarget-feature=-crt-static'");
1901         }
1902
1903         if !builder.config.verbose_tests {
1904             cargo.arg("--quiet");
1905         }
1906
1907         builder.info(&format!(
1908             "{} rustdoc stage{} ({} -> {})",
1909             test_kind, compiler.stage, &compiler.host, target
1910         ));
1911         let _time = util::timeit(&builder);
1912
1913         try_run(builder, &mut cargo.into());
1914     }
1915 }
1916
1917 /// Some test suites are run inside emulators or on remote devices, and most
1918 /// of our test binaries are linked dynamically which means we need to ship
1919 /// the standard library and such to the emulator ahead of time. This step
1920 /// represents this and is a dependency of all test suites.
1921 ///
1922 /// Most of the time this is a no-op. For some steps such as shipping data to
1923 /// QEMU we have to build our own tools so we've got conditional dependencies
1924 /// on those programs as well. Note that the remote test client is built for
1925 /// the build target (us) and the server is built for the target.
1926 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1927 pub struct RemoteCopyLibs {
1928     compiler: Compiler,
1929     target: Interned<String>,
1930 }
1931
1932 impl Step for RemoteCopyLibs {
1933     type Output = ();
1934
1935     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1936         run.never()
1937     }
1938
1939     fn run(self, builder: &Builder<'_>) {
1940         let compiler = self.compiler;
1941         let target = self.target;
1942         if !builder.remote_tested(target) {
1943             return;
1944         }
1945
1946         builder.ensure(compile::Std { compiler, target });
1947
1948         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
1949         t!(fs::create_dir_all(builder.out.join("tmp")));
1950
1951         let server = builder.ensure(tool::RemoteTestServer {
1952             compiler: compiler.with_stage(0),
1953             target,
1954         });
1955
1956         // Spawn the emulator and wait for it to come online
1957         let tool = builder.tool_exe(Tool::RemoteTestClient);
1958         let mut cmd = Command::new(&tool);
1959         cmd.arg("spawn-emulator")
1960             .arg(target)
1961             .arg(&server)
1962             .arg(builder.out.join("tmp"));
1963         if let Some(rootfs) = builder.qemu_rootfs(target) {
1964             cmd.arg(rootfs);
1965         }
1966         builder.run(&mut cmd);
1967
1968         // Push all our dylibs to the emulator
1969         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
1970             let f = t!(f);
1971             let name = f.file_name().into_string().unwrap();
1972             if util::is_dylib(&name) {
1973                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
1974             }
1975         }
1976     }
1977 }
1978
1979 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1980 pub struct Distcheck;
1981
1982 impl Step for Distcheck {
1983     type Output = ();
1984
1985     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1986         run.path("distcheck")
1987     }
1988
1989     fn make_run(run: RunConfig<'_>) {
1990         run.builder.ensure(Distcheck);
1991     }
1992
1993     /// Runs "distcheck", a 'make check' from a tarball
1994     fn run(self, builder: &Builder<'_>) {
1995         builder.info("Distcheck");
1996         let dir = builder.out.join("tmp").join("distcheck");
1997         let _ = fs::remove_dir_all(&dir);
1998         t!(fs::create_dir_all(&dir));
1999
2000         // Guarantee that these are built before we begin running.
2001         builder.ensure(dist::PlainSourceTarball);
2002         builder.ensure(dist::Src);
2003
2004         let mut cmd = Command::new("tar");
2005         cmd.arg("-xzf")
2006             .arg(builder.ensure(dist::PlainSourceTarball))
2007             .arg("--strip-components=1")
2008             .current_dir(&dir);
2009         builder.run(&mut cmd);
2010         builder.run(
2011             Command::new("./configure")
2012                 .args(&builder.config.configure_args)
2013                 .arg("--enable-vendor")
2014                 .current_dir(&dir),
2015         );
2016         builder.run(
2017             Command::new(build_helper::make(&builder.config.build))
2018                 .arg("check")
2019                 .current_dir(&dir),
2020         );
2021
2022         // Now make sure that rust-src has all of libstd's dependencies
2023         builder.info("Distcheck rust-src");
2024         let dir = builder.out.join("tmp").join("distcheck-src");
2025         let _ = fs::remove_dir_all(&dir);
2026         t!(fs::create_dir_all(&dir));
2027
2028         let mut cmd = Command::new("tar");
2029         cmd.arg("-xzf")
2030             .arg(builder.ensure(dist::Src))
2031             .arg("--strip-components=1")
2032             .current_dir(&dir);
2033         builder.run(&mut cmd);
2034
2035         let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
2036         builder.run(
2037             Command::new(&builder.initial_cargo)
2038                 .arg("generate-lockfile")
2039                 .arg("--manifest-path")
2040                 .arg(&toml)
2041                 .current_dir(&dir),
2042         );
2043     }
2044 }
2045
2046 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2047 pub struct Bootstrap;
2048
2049 impl Step for Bootstrap {
2050     type Output = ();
2051     const DEFAULT: bool = true;
2052     const ONLY_HOSTS: bool = true;
2053
2054     /// Tests the build system itself.
2055     fn run(self, builder: &Builder<'_>) {
2056         let mut cmd = Command::new(&builder.initial_cargo);
2057         cmd.arg("test")
2058             .current_dir(builder.src.join("src/bootstrap"))
2059             .env("RUSTFLAGS", "-Cdebuginfo=2")
2060             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2061             .env("RUSTC_BOOTSTRAP", "1")
2062             .env("RUSTC", &builder.initial_rustc);
2063         if let Some(flags) = option_env!("RUSTFLAGS") {
2064             // Use the same rustc flags for testing as for "normal" compilation,
2065             // so that Cargo doesn’t recompile the entire dependency graph every time:
2066             // https://github.com/rust-lang/rust/issues/49215
2067             cmd.env("RUSTFLAGS", flags);
2068         }
2069         if !builder.fail_fast {
2070             cmd.arg("--no-fail-fast");
2071         }
2072         cmd.arg("--").args(&builder.config.cmd.test_args());
2073         // rustbuild tests are racy on directory creation so just run them one at a time.
2074         // Since there's not many this shouldn't be a problem.
2075         cmd.arg("--test-threads=1");
2076         try_run(builder, &mut cmd);
2077     }
2078
2079     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2080         run.path("src/bootstrap")
2081     }
2082
2083     fn make_run(run: RunConfig<'_>) {
2084         run.builder.ensure(Bootstrap);
2085     }
2086 }