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