]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Ignore new test on Windows
[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!(RunPass {
759     path: "src/test/run-pass",
760     mode: "run-pass",
761     suite: "run-pass"
762 });
763
764 default_test!(CompileFail {
765     path: "src/test/compile-fail",
766     mode: "compile-fail",
767     suite: "compile-fail"
768 });
769
770 default_test!(ParseFail {
771     path: "src/test/parse-fail",
772     mode: "parse-fail",
773     suite: "parse-fail"
774 });
775
776 default_test!(RunFail {
777     path: "src/test/run-fail",
778     mode: "run-fail",
779     suite: "run-fail"
780 });
781
782 default_test!(RunPassValgrind {
783     path: "src/test/run-pass-valgrind",
784     mode: "run-pass-valgrind",
785     suite: "run-pass-valgrind"
786 });
787
788 default_test!(MirOpt {
789     path: "src/test/mir-opt",
790     mode: "mir-opt",
791     suite: "mir-opt"
792 });
793
794 default_test!(Codegen {
795     path: "src/test/codegen",
796     mode: "codegen",
797     suite: "codegen"
798 });
799
800 default_test!(CodegenUnits {
801     path: "src/test/codegen-units",
802     mode: "codegen-units",
803     suite: "codegen-units"
804 });
805
806 default_test!(Incremental {
807     path: "src/test/incremental",
808     mode: "incremental",
809     suite: "incremental"
810 });
811
812 default_test!(Debuginfo {
813     path: "src/test/debuginfo",
814     // What this runs varies depending on the native platform being apple
815     mode: "debuginfo-XXX",
816     suite: "debuginfo"
817 });
818
819 host_test!(UiFullDeps {
820     path: "src/test/ui-fulldeps",
821     mode: "ui",
822     suite: "ui-fulldeps"
823 });
824
825 host_test!(RunPassFullDeps {
826     path: "src/test/run-pass-fulldeps",
827     mode: "run-pass",
828     suite: "run-pass-fulldeps"
829 });
830
831 host_test!(RunFailFullDeps {
832     path: "src/test/run-fail-fulldeps",
833     mode: "run-fail",
834     suite: "run-fail-fulldeps"
835 });
836
837 host_test!(CompileFailFullDeps {
838     path: "src/test/compile-fail-fulldeps",
839     mode: "compile-fail",
840     suite: "compile-fail-fulldeps"
841 });
842
843 host_test!(IncrementalFullDeps {
844     path: "src/test/incremental-fulldeps",
845     mode: "incremental",
846     suite: "incremental-fulldeps"
847 });
848
849 host_test!(Rustdoc {
850     path: "src/test/rustdoc",
851     mode: "rustdoc",
852     suite: "rustdoc"
853 });
854
855 test!(Pretty {
856     path: "src/test/pretty",
857     mode: "pretty",
858     suite: "pretty",
859     default: false,
860     host: true
861 });
862 test!(RunPassPretty {
863     path: "src/test/run-pass/pretty",
864     mode: "pretty",
865     suite: "run-pass",
866     default: false,
867     host: true
868 });
869 test!(RunFailPretty {
870     path: "src/test/run-fail/pretty",
871     mode: "pretty",
872     suite: "run-fail",
873     default: false,
874     host: true
875 });
876 test!(RunPassValgrindPretty {
877     path: "src/test/run-pass-valgrind/pretty",
878     mode: "pretty",
879     suite: "run-pass-valgrind",
880     default: false,
881     host: true
882 });
883 test!(RunPassFullDepsPretty {
884     path: "src/test/run-pass-fulldeps/pretty",
885     mode: "pretty",
886     suite: "run-pass-fulldeps",
887     default: false,
888     host: true
889 });
890 test!(RunFailFullDepsPretty {
891     path: "src/test/run-fail-fulldeps/pretty",
892     mode: "pretty",
893     suite: "run-fail-fulldeps",
894     default: false,
895     host: true
896 });
897
898 default_test!(RunMake {
899     path: "src/test/run-make",
900     mode: "run-make",
901     suite: "run-make"
902 });
903
904 host_test!(RunMakeFullDeps {
905     path: "src/test/run-make-fulldeps",
906     mode: "run-make",
907     suite: "run-make-fulldeps"
908 });
909
910 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
911 struct Compiletest {
912     compiler: Compiler,
913     target: Interned<String>,
914     mode: &'static str,
915     suite: &'static str,
916     path: Option<&'static str>,
917     compare_mode: Option<&'static str>,
918 }
919
920 impl Step for Compiletest {
921     type Output = ();
922
923     fn should_run(run: ShouldRun) -> ShouldRun {
924         run.never()
925     }
926
927     /// Executes the `compiletest` tool to run a suite of tests.
928     ///
929     /// Compiles all tests with `compiler` for `target` with the specified
930     /// compiletest `mode` and `suite` arguments. For example `mode` can be
931     /// "run-pass" or `suite` can be something like `debuginfo`.
932     fn run(self, builder: &Builder) {
933         let compiler = self.compiler;
934         let target = self.target;
935         let mode = self.mode;
936         let suite = self.suite;
937
938         // Path for test suite
939         let suite_path = self.path.unwrap_or("");
940
941         // Skip codegen tests if they aren't enabled in configuration.
942         if !builder.config.codegen_tests && suite == "codegen" {
943             return;
944         }
945
946         if suite == "debuginfo" {
947             // Skip debuginfo tests on MSVC
948             if builder.config.build.contains("msvc") {
949                 return;
950             }
951
952             if mode == "debuginfo-XXX" {
953                 return if builder.config.build.contains("apple") {
954                     builder.ensure(Compiletest {
955                         mode: "debuginfo-lldb",
956                         ..self
957                     });
958                 } else {
959                     builder.ensure(Compiletest {
960                         mode: "debuginfo-gdb",
961                         ..self
962                     });
963                 };
964             }
965
966             builder.ensure(dist::DebuggerScripts {
967                 sysroot: builder.sysroot(compiler),
968                 host: target,
969             });
970         }
971
972         if suite.ends_with("fulldeps") ||
973             // FIXME: Does pretty need librustc compiled? Note that there are
974             // fulldeps test suites with mode = pretty as well.
975             mode == "pretty"
976         {
977             builder.ensure(compile::Rustc { compiler, target });
978         }
979
980         if builder.no_std(target) == Some(true) {
981             // the `test` doesn't compile for no-std targets
982             builder.ensure(compile::Std { compiler, target });
983         } else {
984             builder.ensure(compile::Test { compiler, target });
985         }
986
987         if builder.no_std(target) == Some(true) {
988             // for no_std run-make (e.g. thumb*),
989             // we need a host compiler which is called by cargo.
990             builder.ensure(compile::Std { compiler, target: compiler.host });
991         }
992
993         builder.ensure(native::TestHelpers { target });
994         builder.ensure(RemoteCopyLibs { compiler, target });
995
996         let mut cmd = builder.tool_cmd(Tool::Compiletest);
997
998         // compiletest currently has... a lot of arguments, so let's just pass all
999         // of them!
1000
1001         cmd.arg("--compile-lib-path")
1002             .arg(builder.rustc_libdir(compiler));
1003         cmd.arg("--run-lib-path")
1004             .arg(builder.sysroot_libdir(compiler, target));
1005         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1006
1007         let is_rustdoc_ui = suite.ends_with("rustdoc-ui");
1008
1009         // Avoid depending on rustdoc when we don't need it.
1010         if mode == "rustdoc"
1011             || (mode == "run-make" && suite.ends_with("fulldeps"))
1012             || (mode == "ui" && is_rustdoc_ui)
1013         {
1014             cmd.arg("--rustdoc-path")
1015                 .arg(builder.rustdoc(compiler.host));
1016         }
1017
1018         cmd.arg("--src-base")
1019             .arg(builder.src.join("src/test").join(suite));
1020         cmd.arg("--build-base")
1021             .arg(testdir(builder, compiler.host).join(suite));
1022         cmd.arg("--stage-id")
1023             .arg(format!("stage{}-{}", compiler.stage, target));
1024         cmd.arg("--mode").arg(mode);
1025         cmd.arg("--target").arg(target);
1026         cmd.arg("--host").arg(&*compiler.host);
1027         cmd.arg("--llvm-filecheck")
1028             .arg(builder.llvm_filecheck(builder.config.build));
1029
1030         if builder.config.cmd.bless() {
1031             cmd.arg("--bless");
1032         }
1033
1034         let compare_mode = builder.config.cmd.compare_mode().or(self.compare_mode);
1035
1036         if let Some(ref nodejs) = builder.config.nodejs {
1037             cmd.arg("--nodejs").arg(nodejs);
1038         }
1039
1040         let mut flags = if is_rustdoc_ui {
1041             Vec::new()
1042         } else {
1043             vec!["-Crpath".to_string()]
1044         };
1045         if !is_rustdoc_ui {
1046             if builder.config.rust_optimize_tests {
1047                 flags.push("-O".to_string());
1048             }
1049             if builder.config.rust_debuginfo_tests {
1050                 flags.push("-g".to_string());
1051             }
1052         }
1053         flags.push("-Zunstable-options".to_string());
1054         flags.push(builder.config.cmd.rustc_args().join(" "));
1055
1056         if let Some(linker) = builder.linker(target) {
1057             cmd.arg("--linker").arg(linker);
1058         }
1059
1060         let hostflags = flags.clone();
1061         cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
1062
1063         let mut targetflags = flags.clone();
1064         targetflags.push(format!(
1065             "-Lnative={}",
1066             builder.test_helpers_out(target).display()
1067         ));
1068         cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
1069
1070         cmd.arg("--docck-python").arg(builder.python());
1071
1072         if builder.config.build.ends_with("apple-darwin") {
1073             // Force /usr/bin/python on macOS for LLDB tests because we're loading the
1074             // LLDB plugin's compiled module which only works with the system python
1075             // (namely not Homebrew-installed python)
1076             cmd.arg("--lldb-python").arg("/usr/bin/python");
1077         } else {
1078             cmd.arg("--lldb-python").arg(builder.python());
1079         }
1080
1081         if let Some(ref gdb) = builder.config.gdb {
1082             cmd.arg("--gdb").arg(gdb);
1083         }
1084         if let Some(ref vers) = builder.lldb_version {
1085             cmd.arg("--lldb-version").arg(vers);
1086         }
1087         if let Some(ref dir) = builder.lldb_python_dir {
1088             cmd.arg("--lldb-python-dir").arg(dir);
1089         }
1090
1091         // Get paths from cmd args
1092         let paths = match &builder.config.cmd {
1093             Subcommand::Test { ref paths, .. } => &paths[..],
1094             _ => &[],
1095         };
1096
1097         // Get test-args by striping suite path
1098         let mut test_args: Vec<&str> = paths
1099             .iter()
1100             .map(|p| {
1101                 match p.strip_prefix(".") {
1102                     Ok(path) => path,
1103                     Err(_) => p,
1104                 }
1105             })
1106             .filter(|p| p.starts_with(suite_path) && p.is_file())
1107             .map(|p| p.strip_prefix(suite_path).unwrap().to_str().unwrap())
1108             .collect();
1109
1110         test_args.append(&mut builder.config.cmd.test_args());
1111
1112         cmd.args(&test_args);
1113
1114         if builder.is_verbose() {
1115             cmd.arg("--verbose");
1116         }
1117
1118         if !builder.config.verbose_tests {
1119             cmd.arg("--quiet");
1120         }
1121
1122         if builder.config.llvm_enabled {
1123             let llvm_config = builder.ensure(native::Llvm {
1124                 target: builder.config.build,
1125                 emscripten: false,
1126             });
1127             if !builder.config.dry_run {
1128                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1129                 cmd.arg("--llvm-version").arg(llvm_version);
1130             }
1131             if !builder.is_rust_llvm(target) {
1132                 cmd.arg("--system-llvm");
1133             }
1134
1135             // Only pass correct values for these flags for the `run-make` suite as it
1136             // requires that a C++ compiler was configured which isn't always the case.
1137             if !builder.config.dry_run && suite == "run-make-fulldeps" {
1138                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1139                 let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
1140                 cmd.arg("--cc")
1141                     .arg(builder.cc(target))
1142                     .arg("--cxx")
1143                     .arg(builder.cxx(target).unwrap())
1144                     .arg("--cflags")
1145                     .arg(builder.cflags(target, GitRepo::Rustc).join(" "))
1146                     .arg("--llvm-components")
1147                     .arg(llvm_components.trim())
1148                     .arg("--llvm-cxxflags")
1149                     .arg(llvm_cxxflags.trim());
1150                 if let Some(ar) = builder.ar(target) {
1151                     cmd.arg("--ar").arg(ar);
1152                 }
1153             }
1154         }
1155         if suite == "run-make-fulldeps" && !builder.config.llvm_enabled {
1156             builder.info(&format!(
1157                 "Ignoring run-make test suite as they generally don't work without LLVM"
1158             ));
1159             return;
1160         }
1161
1162         if suite != "run-make-fulldeps" {
1163             cmd.arg("--cc")
1164                 .arg("")
1165                 .arg("--cxx")
1166                 .arg("")
1167                 .arg("--cflags")
1168                 .arg("")
1169                 .arg("--llvm-components")
1170                 .arg("")
1171                 .arg("--llvm-cxxflags")
1172                 .arg("");
1173         }
1174
1175         if builder.remote_tested(target) {
1176             cmd.arg("--remote-test-client")
1177                 .arg(builder.tool_exe(Tool::RemoteTestClient));
1178         }
1179
1180         // Running a C compiler on MSVC requires a few env vars to be set, to be
1181         // sure to set them here.
1182         //
1183         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1184         // rather than stomp over it.
1185         if target.contains("msvc") {
1186             for &(ref k, ref v) in builder.cc[&target].env() {
1187                 if k != "PATH" {
1188                     cmd.env(k, v);
1189                 }
1190             }
1191         }
1192         cmd.env("RUSTC_BOOTSTRAP", "1");
1193         builder.add_rust_test_threads(&mut cmd);
1194
1195         if builder.config.sanitizers {
1196             cmd.env("SANITIZER_SUPPORT", "1");
1197         }
1198
1199         if builder.config.profiler {
1200             cmd.env("PROFILER_SUPPORT", "1");
1201         }
1202
1203         cmd.env("RUST_TEST_TMPDIR", builder.out.join("tmp"));
1204
1205         cmd.arg("--adb-path").arg("adb");
1206         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1207         if target.contains("android") {
1208             // Assume that cc for this target comes from the android sysroot
1209             cmd.arg("--android-cross-path")
1210                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1211         } else {
1212             cmd.arg("--android-cross-path").arg("");
1213         }
1214
1215         builder.ci_env.force_coloring_in_ci(&mut cmd);
1216
1217         let _folder = builder.fold_output(|| format!("test_{}", suite));
1218         builder.info(&format!(
1219             "Check compiletest suite={} mode={} ({} -> {})",
1220             suite, mode, &compiler.host, target
1221         ));
1222         let _time = util::timeit(&builder);
1223         try_run(builder, &mut cmd);
1224
1225         if let Some(compare_mode) = compare_mode {
1226             cmd.arg("--compare-mode").arg(compare_mode);
1227             let _folder = builder.fold_output(|| format!("test_{}_{}", suite, compare_mode));
1228             builder.info(&format!(
1229                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1230                 suite, mode, compare_mode, &compiler.host, target
1231             ));
1232             let _time = util::timeit(&builder);
1233             try_run(builder, &mut cmd);
1234         }
1235     }
1236 }
1237
1238 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1239 struct DocTest {
1240     compiler: Compiler,
1241     path: &'static str,
1242     name: &'static str,
1243     is_ext_doc: bool,
1244 }
1245
1246 impl Step for DocTest {
1247     type Output = ();
1248     const ONLY_HOSTS: bool = true;
1249
1250     fn should_run(run: ShouldRun) -> ShouldRun {
1251         run.never()
1252     }
1253
1254     /// Run `rustdoc --test` for all documentation in `src/doc`.
1255     ///
1256     /// This will run all tests in our markdown documentation (e.g. the book)
1257     /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
1258     /// `compiler`.
1259     fn run(self, builder: &Builder) {
1260         let compiler = self.compiler;
1261
1262         builder.ensure(compile::Test {
1263             compiler,
1264             target: compiler.host,
1265         });
1266
1267         // Do a breadth-first traversal of the `src/doc` directory and just run
1268         // tests for all files that end in `*.md`
1269         let mut stack = vec![builder.src.join(self.path)];
1270         let _time = util::timeit(&builder);
1271         let _folder = builder.fold_output(|| format!("test_{}", self.name));
1272
1273         let mut files = Vec::new();
1274         while let Some(p) = stack.pop() {
1275             if p.is_dir() {
1276                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1277                 continue;
1278             }
1279
1280             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1281                 continue;
1282             }
1283
1284             // The nostarch directory in the book is for no starch, and so isn't
1285             // guaranteed to builder. We don't care if it doesn't build, so skip it.
1286             if p.to_str().map_or(false, |p| p.contains("nostarch")) {
1287                 continue;
1288             }
1289
1290             files.push(p);
1291         }
1292
1293         files.sort();
1294
1295         let mut toolstate = ToolState::TestPass;
1296         for file in files {
1297             if !markdown_test(builder, compiler, &file) {
1298                 toolstate = ToolState::TestFail;
1299             }
1300         }
1301         if self.is_ext_doc {
1302             builder.save_toolstate(self.name, toolstate);
1303         }
1304     }
1305 }
1306
1307 macro_rules! test_book {
1308     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1309         $(
1310             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1311             pub struct $name {
1312                 compiler: Compiler,
1313             }
1314
1315             impl Step for $name {
1316                 type Output = ();
1317                 const DEFAULT: bool = $default;
1318                 const ONLY_HOSTS: bool = true;
1319
1320                 fn should_run(run: ShouldRun) -> ShouldRun {
1321                     run.path($path)
1322                 }
1323
1324                 fn make_run(run: RunConfig) {
1325                     run.builder.ensure($name {
1326                         compiler: run.builder.compiler(run.builder.top_stage, run.host),
1327                     });
1328                 }
1329
1330                 fn run(self, builder: &Builder) {
1331                     builder.ensure(DocTest {
1332                         compiler: self.compiler,
1333                         path: $path,
1334                         name: $book_name,
1335                         is_ext_doc: !$default,
1336                     });
1337                 }
1338             }
1339         )+
1340     }
1341 }
1342
1343 test_book!(
1344     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1345     Reference, "src/doc/reference", "reference", default=false;
1346     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1347     RustcBook, "src/doc/rustc", "rustc", default=true;
1348     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1349     TheBook, "src/doc/book", "book", default=false;
1350     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1351 );
1352
1353 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1354 pub struct ErrorIndex {
1355     compiler: Compiler,
1356 }
1357
1358 impl Step for ErrorIndex {
1359     type Output = ();
1360     const DEFAULT: bool = true;
1361     const ONLY_HOSTS: bool = true;
1362
1363     fn should_run(run: ShouldRun) -> ShouldRun {
1364         run.path("src/tools/error_index_generator")
1365     }
1366
1367     fn make_run(run: RunConfig) {
1368         run.builder.ensure(ErrorIndex {
1369             compiler: run.builder.compiler(run.builder.top_stage, run.host),
1370         });
1371     }
1372
1373     /// Run the error index generator tool to execute the tests located in the error
1374     /// index.
1375     ///
1376     /// The `error_index_generator` tool lives in `src/tools` and is used to
1377     /// generate a markdown file from the error indexes of the code base which is
1378     /// then passed to `rustdoc --test`.
1379     fn run(self, builder: &Builder) {
1380         let compiler = self.compiler;
1381
1382         builder.ensure(compile::Std {
1383             compiler,
1384             target: compiler.host,
1385         });
1386
1387         let dir = testdir(builder, compiler.host);
1388         t!(fs::create_dir_all(&dir));
1389         let output = dir.join("error-index.md");
1390
1391         let mut tool = builder.tool_cmd(Tool::ErrorIndex);
1392         tool.arg("markdown")
1393             .arg(&output)
1394             .env("CFG_BUILD", &builder.config.build)
1395             .env("RUSTC_ERROR_METADATA_DST", builder.extended_error_dir());
1396
1397         let _folder = builder.fold_output(|| "test_error_index");
1398         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1399         let _time = util::timeit(&builder);
1400         builder.run(&mut tool);
1401         markdown_test(builder, compiler, &output);
1402     }
1403 }
1404
1405 fn markdown_test(builder: &Builder, compiler: Compiler, markdown: &Path) -> bool {
1406     match File::open(markdown) {
1407         Ok(mut file) => {
1408             let mut contents = String::new();
1409             t!(file.read_to_string(&mut contents));
1410             if !contents.contains("```") {
1411                 return true;
1412             }
1413         }
1414         Err(_) => {}
1415     }
1416
1417     builder.info(&format!("doc tests for: {}", markdown.display()));
1418     let mut cmd = builder.rustdoc_cmd(compiler.host);
1419     builder.add_rust_test_threads(&mut cmd);
1420     cmd.arg("--test");
1421     cmd.arg(markdown);
1422     cmd.env("RUSTC_BOOTSTRAP", "1");
1423
1424     let test_args = builder.config.cmd.test_args().join(" ");
1425     cmd.arg("--test-args").arg(test_args);
1426
1427     if builder.config.verbose_tests {
1428         try_run(builder, &mut cmd)
1429     } else {
1430         try_run_quiet(builder, &mut cmd)
1431     }
1432 }
1433
1434 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1435 pub struct CrateLibrustc {
1436     compiler: Compiler,
1437     target: Interned<String>,
1438     test_kind: TestKind,
1439     krate: Interned<String>,
1440 }
1441
1442 impl Step for CrateLibrustc {
1443     type Output = ();
1444     const DEFAULT: bool = true;
1445     const ONLY_HOSTS: bool = true;
1446
1447     fn should_run(run: ShouldRun) -> ShouldRun {
1448         run.krate("rustc-main")
1449     }
1450
1451     fn make_run(run: RunConfig) {
1452         let builder = run.builder;
1453         let compiler = builder.compiler(builder.top_stage, run.host);
1454
1455         for krate in builder.in_tree_crates("rustc-main") {
1456             if run.path.ends_with(&krate.path) {
1457                 let test_kind = builder.kind.into();
1458
1459                 builder.ensure(CrateLibrustc {
1460                     compiler,
1461                     target: run.target,
1462                     test_kind,
1463                     krate: krate.name,
1464                 });
1465             }
1466         }
1467     }
1468
1469     fn run(self, builder: &Builder) {
1470         builder.ensure(Crate {
1471             compiler: self.compiler,
1472             target: self.target,
1473             mode: Mode::Rustc,
1474             test_kind: self.test_kind,
1475             krate: self.krate,
1476         });
1477     }
1478 }
1479
1480 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1481 pub struct CrateNotDefault {
1482     compiler: Compiler,
1483     target: Interned<String>,
1484     test_kind: TestKind,
1485     krate: &'static str,
1486 }
1487
1488 impl Step for CrateNotDefault {
1489     type Output = ();
1490
1491     fn should_run(run: ShouldRun) -> ShouldRun {
1492         run.path("src/liballoc_jemalloc")
1493             .path("src/librustc_asan")
1494             .path("src/librustc_lsan")
1495             .path("src/librustc_msan")
1496             .path("src/librustc_tsan")
1497     }
1498
1499     fn make_run(run: RunConfig) {
1500         let builder = run.builder;
1501         let compiler = builder.compiler(builder.top_stage, run.host);
1502
1503         let test_kind = builder.kind.into();
1504
1505         builder.ensure(CrateNotDefault {
1506             compiler,
1507             target: run.target,
1508             test_kind,
1509             krate: match run.path {
1510                 _ if run.path.ends_with("src/liballoc_jemalloc") => "alloc_jemalloc",
1511                 _ if run.path.ends_with("src/librustc_asan") => "rustc_asan",
1512                 _ if run.path.ends_with("src/librustc_lsan") => "rustc_lsan",
1513                 _ if run.path.ends_with("src/librustc_msan") => "rustc_msan",
1514                 _ if run.path.ends_with("src/librustc_tsan") => "rustc_tsan",
1515                 _ => panic!("unexpected path {:?}", run.path),
1516             },
1517         });
1518     }
1519
1520     fn run(self, builder: &Builder) {
1521         builder.ensure(Crate {
1522             compiler: self.compiler,
1523             target: self.target,
1524             mode: Mode::Std,
1525             test_kind: self.test_kind,
1526             krate: INTERNER.intern_str(self.krate),
1527         });
1528     }
1529 }
1530
1531 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1532 pub struct Crate {
1533     pub compiler: Compiler,
1534     pub target: Interned<String>,
1535     pub mode: Mode,
1536     pub test_kind: TestKind,
1537     pub krate: Interned<String>,
1538 }
1539
1540 impl Step for Crate {
1541     type Output = ();
1542     const DEFAULT: bool = true;
1543
1544     fn should_run(mut run: ShouldRun) -> ShouldRun {
1545         let builder = run.builder;
1546         run = run.krate("test");
1547         for krate in run.builder.in_tree_crates("std") {
1548             if krate.is_local(&run.builder)
1549                 && !krate.name.contains("jemalloc")
1550                 && !(krate.name.starts_with("rustc_") && krate.name.ends_with("san"))
1551                 && krate.name != "dlmalloc"
1552             {
1553                 run = run.path(krate.local_path(&builder).to_str().unwrap());
1554             }
1555         }
1556         run
1557     }
1558
1559     fn make_run(run: RunConfig) {
1560         let builder = run.builder;
1561         let compiler = builder.compiler(builder.top_stage, run.host);
1562
1563         let make = |mode: Mode, krate: &CargoCrate| {
1564             let test_kind = builder.kind.into();
1565
1566             builder.ensure(Crate {
1567                 compiler,
1568                 target: run.target,
1569                 mode,
1570                 test_kind,
1571                 krate: krate.name,
1572             });
1573         };
1574
1575         for krate in builder.in_tree_crates("std") {
1576             if run.path.ends_with(&krate.local_path(&builder)) {
1577                 make(Mode::Std, krate);
1578             }
1579         }
1580         for krate in builder.in_tree_crates("test") {
1581             if run.path.ends_with(&krate.local_path(&builder)) {
1582                 make(Mode::Test, krate);
1583             }
1584         }
1585     }
1586
1587     /// Run all unit tests plus documentation tests for a given crate defined
1588     /// by a `Cargo.toml` (single manifest)
1589     ///
1590     /// This is what runs tests for crates like the standard library, compiler, etc.
1591     /// It essentially is the driver for running `cargo test`.
1592     ///
1593     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
1594     /// arguments, and those arguments are discovered from `cargo metadata`.
1595     fn run(self, builder: &Builder) {
1596         let compiler = self.compiler;
1597         let target = self.target;
1598         let mode = self.mode;
1599         let test_kind = self.test_kind;
1600         let krate = self.krate;
1601
1602         builder.ensure(compile::Test { compiler, target });
1603         builder.ensure(RemoteCopyLibs { compiler, target });
1604
1605         // If we're not doing a full bootstrap but we're testing a stage2 version of
1606         // libstd, then what we're actually testing is the libstd produced in
1607         // stage1. Reflect that here by updating the compiler that we're working
1608         // with automatically.
1609         let compiler = if builder.force_use_stage1(compiler, target) {
1610             builder.compiler(1, compiler.host)
1611         } else {
1612             compiler.clone()
1613         };
1614
1615         let mut cargo = builder.cargo(compiler, mode, target, test_kind.subcommand());
1616         match mode {
1617             Mode::Std => {
1618                 compile::std_cargo(builder, &compiler, target, &mut cargo);
1619             }
1620             Mode::Test => {
1621                 compile::test_cargo(builder, &compiler, target, &mut cargo);
1622             }
1623             Mode::Rustc => {
1624                 builder.ensure(compile::Rustc { compiler, target });
1625                 compile::rustc_cargo(builder, &mut cargo);
1626             }
1627             _ => panic!("can only test libraries"),
1628         };
1629
1630         // Build up the base `cargo test` command.
1631         //
1632         // Pass in some standard flags then iterate over the graph we've discovered
1633         // in `cargo metadata` with the maps above and figure out what `-p`
1634         // arguments need to get passed.
1635         if test_kind.subcommand() == "test" && !builder.fail_fast {
1636             cargo.arg("--no-fail-fast");
1637         }
1638         match builder.doc_tests {
1639             DocTests::Only => {
1640                 cargo.arg("--doc");
1641             }
1642             DocTests::No => {
1643                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
1644             }
1645             DocTests::Yes => {}
1646         }
1647
1648         cargo.arg("-p").arg(krate);
1649
1650         // The tests are going to run with the *target* libraries, so we need to
1651         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
1652         //
1653         // Note that to run the compiler we need to run with the *host* libraries,
1654         // but our wrapper scripts arrange for that to be the case anyway.
1655         let mut dylib_path = dylib_path();
1656         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1657         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1658
1659         cargo.arg("--");
1660         cargo.args(&builder.config.cmd.test_args());
1661
1662         if !builder.config.verbose_tests {
1663             cargo.arg("--quiet");
1664         }
1665
1666         if target.contains("emscripten") {
1667             cargo.env(
1668                 format!("CARGO_TARGET_{}_RUNNER", envify(&target)),
1669                 builder
1670                     .config
1671                     .nodejs
1672                     .as_ref()
1673                     .expect("nodejs not configured"),
1674             );
1675         } else if target.starts_with("wasm32") {
1676             // Warn about running tests without the `wasm_syscall` feature enabled.
1677             // The javascript shim implements the syscall interface so that test
1678             // output can be correctly reported.
1679             if !builder.config.wasm_syscall {
1680                 builder.info(&format!(
1681                     "Libstd was built without `wasm_syscall` feature enabled: \
1682                      test output may not be visible."
1683                 ));
1684             }
1685
1686             // On the wasm32-unknown-unknown target we're using LTO which is
1687             // incompatible with `-C prefer-dynamic`, so disable that here
1688             cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
1689
1690             let node = builder
1691                 .config
1692                 .nodejs
1693                 .as_ref()
1694                 .expect("nodejs not configured");
1695             let runner = format!(
1696                 "{} {}/src/etc/wasm32-shim.js",
1697                 node.display(),
1698                 builder.src.display()
1699             );
1700             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target)), &runner);
1701         } else if builder.remote_tested(target) {
1702             cargo.env(
1703                 format!("CARGO_TARGET_{}_RUNNER", envify(&target)),
1704                 format!("{} run", builder.tool_exe(Tool::RemoteTestClient).display()),
1705             );
1706         }
1707
1708         let _folder = builder.fold_output(|| {
1709             format!(
1710                 "{}_stage{}-{}",
1711                 test_kind.subcommand(),
1712                 compiler.stage,
1713                 krate
1714             )
1715         });
1716         builder.info(&format!(
1717             "{} {} stage{} ({} -> {})",
1718             test_kind, krate, compiler.stage, &compiler.host, target
1719         ));
1720         let _time = util::timeit(&builder);
1721         try_run(builder, &mut cargo);
1722     }
1723 }
1724
1725 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1726 pub struct CrateRustdoc {
1727     host: Interned<String>,
1728     test_kind: TestKind,
1729 }
1730
1731 impl Step for CrateRustdoc {
1732     type Output = ();
1733     const DEFAULT: bool = true;
1734     const ONLY_HOSTS: bool = true;
1735
1736     fn should_run(run: ShouldRun) -> ShouldRun {
1737         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
1738     }
1739
1740     fn make_run(run: RunConfig) {
1741         let builder = run.builder;
1742
1743         let test_kind = builder.kind.into();
1744
1745         builder.ensure(CrateRustdoc {
1746             host: run.host,
1747             test_kind,
1748         });
1749     }
1750
1751     fn run(self, builder: &Builder) {
1752         let test_kind = self.test_kind;
1753
1754         let compiler = builder.compiler(builder.top_stage, self.host);
1755         let target = compiler.host;
1756         builder.ensure(compile::Rustc { compiler, target });
1757
1758         let mut cargo = tool::prepare_tool_cargo(builder,
1759                                                  compiler,
1760                                                  Mode::ToolRustc,
1761                                                  target,
1762                                                  test_kind.subcommand(),
1763                                                  "src/tools/rustdoc",
1764                                                  SourceType::InTree);
1765         if test_kind.subcommand() == "test" && !builder.fail_fast {
1766             cargo.arg("--no-fail-fast");
1767         }
1768
1769         cargo.arg("-p").arg("rustdoc:0.0.0");
1770
1771         cargo.arg("--");
1772         cargo.args(&builder.config.cmd.test_args());
1773
1774         if !builder.config.verbose_tests {
1775             cargo.arg("--quiet");
1776         }
1777
1778         let _folder = builder
1779             .fold_output(|| format!("{}_stage{}-rustdoc", test_kind.subcommand(), compiler.stage));
1780         builder.info(&format!(
1781             "{} rustdoc stage{} ({} -> {})",
1782             test_kind, compiler.stage, &compiler.host, target
1783         ));
1784         let _time = util::timeit(&builder);
1785
1786         try_run(builder, &mut cargo);
1787     }
1788 }
1789
1790 fn envify(s: &str) -> String {
1791     s.chars()
1792         .map(|c| match c {
1793             '-' => '_',
1794             c => c,
1795         })
1796         .flat_map(|c| c.to_uppercase())
1797         .collect()
1798 }
1799
1800 /// Some test suites are run inside emulators or on remote devices, and most
1801 /// of our test binaries are linked dynamically which means we need to ship
1802 /// the standard library and such to the emulator ahead of time. This step
1803 /// represents this and is a dependency of all test suites.
1804 ///
1805 /// Most of the time this is a noop. For some steps such as shipping data to
1806 /// QEMU we have to build our own tools so we've got conditional dependencies
1807 /// on those programs as well. Note that the remote test client is built for
1808 /// the build target (us) and the server is built for the target.
1809 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1810 pub struct RemoteCopyLibs {
1811     compiler: Compiler,
1812     target: Interned<String>,
1813 }
1814
1815 impl Step for RemoteCopyLibs {
1816     type Output = ();
1817
1818     fn should_run(run: ShouldRun) -> ShouldRun {
1819         run.never()
1820     }
1821
1822     fn run(self, builder: &Builder) {
1823         let compiler = self.compiler;
1824         let target = self.target;
1825         if !builder.remote_tested(target) {
1826             return;
1827         }
1828
1829         builder.ensure(compile::Test { compiler, target });
1830
1831         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
1832         t!(fs::create_dir_all(builder.out.join("tmp")));
1833
1834         let server = builder.ensure(tool::RemoteTestServer {
1835             compiler: compiler.with_stage(0),
1836             target,
1837         });
1838
1839         // Spawn the emulator and wait for it to come online
1840         let tool = builder.tool_exe(Tool::RemoteTestClient);
1841         let mut cmd = Command::new(&tool);
1842         cmd.arg("spawn-emulator")
1843             .arg(target)
1844             .arg(&server)
1845             .arg(builder.out.join("tmp"));
1846         if let Some(rootfs) = builder.qemu_rootfs(target) {
1847             cmd.arg(rootfs);
1848         }
1849         builder.run(&mut cmd);
1850
1851         // Push all our dylibs to the emulator
1852         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
1853             let f = t!(f);
1854             let name = f.file_name().into_string().unwrap();
1855             if util::is_dylib(&name) {
1856                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
1857             }
1858         }
1859     }
1860 }
1861
1862 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1863 pub struct Distcheck;
1864
1865 impl Step for Distcheck {
1866     type Output = ();
1867
1868     fn should_run(run: ShouldRun) -> ShouldRun {
1869         run.path("distcheck")
1870     }
1871
1872     fn make_run(run: RunConfig) {
1873         run.builder.ensure(Distcheck);
1874     }
1875
1876     /// Run "distcheck", a 'make check' from a tarball
1877     fn run(self, builder: &Builder) {
1878         builder.info(&format!("Distcheck"));
1879         let dir = builder.out.join("tmp").join("distcheck");
1880         let _ = fs::remove_dir_all(&dir);
1881         t!(fs::create_dir_all(&dir));
1882
1883         // Guarantee that these are built before we begin running.
1884         builder.ensure(dist::PlainSourceTarball);
1885         builder.ensure(dist::Src);
1886
1887         let mut cmd = Command::new("tar");
1888         cmd.arg("-xzf")
1889             .arg(builder.ensure(dist::PlainSourceTarball))
1890             .arg("--strip-components=1")
1891             .current_dir(&dir);
1892         builder.run(&mut cmd);
1893         builder.run(
1894             Command::new("./configure")
1895                 .args(&builder.config.configure_args)
1896                 .arg("--enable-vendor")
1897                 .current_dir(&dir),
1898         );
1899         builder.run(
1900             Command::new(build_helper::make(&builder.config.build))
1901                 .arg("check")
1902                 .current_dir(&dir),
1903         );
1904
1905         // Now make sure that rust-src has all of libstd's dependencies
1906         builder.info(&format!("Distcheck rust-src"));
1907         let dir = builder.out.join("tmp").join("distcheck-src");
1908         let _ = fs::remove_dir_all(&dir);
1909         t!(fs::create_dir_all(&dir));
1910
1911         let mut cmd = Command::new("tar");
1912         cmd.arg("-xzf")
1913             .arg(builder.ensure(dist::Src))
1914             .arg("--strip-components=1")
1915             .current_dir(&dir);
1916         builder.run(&mut cmd);
1917
1918         let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
1919         builder.run(
1920             Command::new(&builder.initial_cargo)
1921                 .arg("generate-lockfile")
1922                 .arg("--manifest-path")
1923                 .arg(&toml)
1924                 .current_dir(&dir),
1925         );
1926     }
1927 }
1928
1929 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1930 pub struct Bootstrap;
1931
1932 impl Step for Bootstrap {
1933     type Output = ();
1934     const DEFAULT: bool = true;
1935     const ONLY_HOSTS: bool = true;
1936
1937     /// Test the build system itself
1938     fn run(self, builder: &Builder) {
1939         let mut cmd = Command::new(&builder.initial_cargo);
1940         cmd.arg("test")
1941             .current_dir(builder.src.join("src/bootstrap"))
1942             .env("RUSTFLAGS", "-Cdebuginfo=2")
1943             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
1944             .env("RUSTC_BOOTSTRAP", "1")
1945             .env("RUSTC", &builder.initial_rustc);
1946         if let Some(flags) = option_env!("RUSTFLAGS") {
1947             // Use the same rustc flags for testing as for "normal" compilation,
1948             // so that Cargo doesn’t recompile the entire dependency graph every time:
1949             // https://github.com/rust-lang/rust/issues/49215
1950             cmd.env("RUSTFLAGS", flags);
1951         }
1952         if !builder.fail_fast {
1953             cmd.arg("--no-fail-fast");
1954         }
1955         cmd.arg("--").args(&builder.config.cmd.test_args());
1956         // rustbuild tests are racy on directory creation so just run them one at a time.
1957         // Since there's not many this shouldn't be a problem.
1958         cmd.arg("--test-threads=1");
1959         try_run(builder, &mut cmd);
1960     }
1961
1962     fn should_run(run: ShouldRun) -> ShouldRun {
1963         run.path("src/bootstrap")
1964     }
1965
1966     fn make_run(run: RunConfig) {
1967         run.builder.ensure(Bootstrap);
1968     }
1969 }