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