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