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