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