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