]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Auto merge of #83314 - Aaron1011:print-unstable-value, r=lcnr
[rust.git] / src / bootstrap / test.rs
1 //! Implementation of the test-related targets of the build system.
2 //!
3 //! This file implements the various regression test suites that we execute on
4 //! our CI.
5
6 use std::env;
7 use std::ffi::OsString;
8 use std::fmt;
9 use std::fs;
10 use std::iter;
11 use std::path::{Path, PathBuf};
12 use std::process::Command;
13
14 use build_helper::{self, output, t};
15
16 use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
17 use crate::cache::Interned;
18 use crate::compile;
19 use crate::config::TargetSelection;
20 use crate::dist;
21 use crate::flags::Subcommand;
22 use crate::native;
23 use crate::tool::{self, SourceType, Tool};
24 use crate::toolstate::ToolState;
25 use crate::util::{self, add_link_lib_path, dylib_path, dylib_path_var};
26 use crate::Crate as CargoCrate;
27 use crate::{envify, DocTests, GitRepo, Mode};
28
29 const ADB_TEST_DIR: &str = "/data/tmp/work";
30
31 /// The two modes of the test runner; tests or benchmarks.
32 #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, PartialOrd, Ord)]
33 pub enum TestKind {
34     /// Run `cargo test`.
35     Test,
36     /// Run `cargo bench`.
37     Bench,
38 }
39
40 impl From<Kind> for TestKind {
41     fn from(kind: Kind) -> Self {
42         match kind {
43             Kind::Test => TestKind::Test,
44             Kind::Bench => TestKind::Bench,
45             _ => panic!("unexpected kind in crate: {:?}", kind),
46         }
47     }
48 }
49
50 impl TestKind {
51     // Return the cargo subcommand for this test kind
52     fn subcommand(self) -> &'static str {
53         match self {
54             TestKind::Test => "test",
55             TestKind::Bench => "bench",
56         }
57     }
58 }
59
60 impl fmt::Display for TestKind {
61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62         f.write_str(match *self {
63             TestKind::Test => "Testing",
64             TestKind::Bench => "Benchmarking",
65         })
66     }
67 }
68
69 fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool {
70     if !builder.fail_fast {
71         if !builder.try_run(cmd) {
72             let mut failures = builder.delayed_failures.borrow_mut();
73             failures.push(format!("{:?}", cmd));
74             return false;
75         }
76     } else {
77         builder.run(cmd);
78     }
79     true
80 }
81
82 fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool {
83     if !builder.fail_fast {
84         if !builder.try_run_quiet(cmd) {
85             let mut failures = builder.delayed_failures.borrow_mut();
86             failures.push(format!("{:?}", cmd));
87             return false;
88         }
89     } else {
90         builder.run_quiet(cmd);
91     }
92     true
93 }
94
95 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
96 pub struct Linkcheck {
97     host: TargetSelection,
98 }
99
100 impl Step for Linkcheck {
101     type Output = ();
102     const ONLY_HOSTS: bool = true;
103     const DEFAULT: bool = true;
104
105     /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
106     ///
107     /// This tool in `src/tools` will verify the validity of all our links in the
108     /// documentation to ensure we don't have a bunch of dead ones.
109     fn run(self, builder: &Builder<'_>) {
110         let host = self.host;
111
112         builder.info(&format!("Linkcheck ({})", host));
113
114         builder.default_doc(&[]);
115
116         let _time = util::timeit(&builder);
117         try_run(
118             builder,
119             builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")),
120         );
121     }
122
123     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
124         let builder = run.builder;
125         run.path("src/tools/linkchecker").default_condition(builder.config.docs)
126     }
127
128     fn make_run(run: RunConfig<'_>) {
129         run.builder.ensure(Linkcheck { host: run.target });
130     }
131 }
132
133 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
134 pub struct Cargotest {
135     stage: u32,
136     host: TargetSelection,
137 }
138
139 impl Step for Cargotest {
140     type Output = ();
141     const ONLY_HOSTS: bool = true;
142
143     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
144         run.path("src/tools/cargotest")
145     }
146
147     fn make_run(run: RunConfig<'_>) {
148         run.builder.ensure(Cargotest { stage: run.builder.top_stage, host: run.target });
149     }
150
151     /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
152     ///
153     /// This tool in `src/tools` will check out a few Rust projects and run `cargo
154     /// test` to ensure that we don't regress the test suites there.
155     fn run(self, builder: &Builder<'_>) {
156         let compiler = builder.compiler(self.stage, self.host);
157         builder.ensure(compile::Rustc { compiler, target: compiler.host });
158         let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host });
159
160         // Note that this is a short, cryptic, and not scoped directory name. This
161         // is currently to minimize the length of path on Windows where we otherwise
162         // quickly run into path name limit constraints.
163         let out_dir = builder.out.join("ct");
164         t!(fs::create_dir_all(&out_dir));
165
166         let _time = util::timeit(&builder);
167         let mut cmd = builder.tool_cmd(Tool::CargoTest);
168         try_run(
169             builder,
170             cmd.arg(&cargo)
171                 .arg(&out_dir)
172                 .env("RUSTC", builder.rustc(compiler))
173                 .env("RUSTDOC", builder.rustdoc(compiler)),
174         );
175     }
176 }
177
178 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
179 pub struct Cargo {
180     stage: u32,
181     host: TargetSelection,
182 }
183
184 impl Step for Cargo {
185     type Output = ();
186     const ONLY_HOSTS: bool = true;
187
188     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
189         run.path("src/tools/cargo")
190     }
191
192     fn make_run(run: RunConfig<'_>) {
193         run.builder.ensure(Cargo { stage: run.builder.top_stage, host: run.target });
194     }
195
196     /// Runs `cargo test` for `cargo` packaged with Rust.
197     fn run(self, builder: &Builder<'_>) {
198         let compiler = builder.compiler(self.stage, self.host);
199
200         builder.ensure(tool::Cargo { compiler, target: self.host });
201         let mut cargo = tool::prepare_tool_cargo(
202             builder,
203             compiler,
204             Mode::ToolRustc,
205             self.host,
206             "test",
207             "src/tools/cargo",
208             SourceType::Submodule,
209             &[],
210         );
211
212         if !builder.fail_fast {
213             cargo.arg("--no-fail-fast");
214         }
215         cargo.arg("--").args(builder.config.cmd.test_args());
216
217         // Don't run cross-compile tests, we may not have cross-compiled libstd libs
218         // available.
219         cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
220         // Disable a test that has issues with mingw.
221         cargo.env("CARGO_TEST_DISABLE_GIT_CLI", "1");
222         // Forcibly disable tests using nightly features since any changes to
223         // those features won't be able to land.
224         cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
225
226         cargo.env("PATH", &path_for_cargo(builder, compiler));
227
228         try_run(builder, &mut cargo.into());
229     }
230 }
231
232 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
233 pub struct Rls {
234     stage: u32,
235     host: TargetSelection,
236 }
237
238 impl Step for Rls {
239     type Output = ();
240     const ONLY_HOSTS: bool = true;
241
242     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
243         run.path("src/tools/rls")
244     }
245
246     fn make_run(run: RunConfig<'_>) {
247         run.builder.ensure(Rls { stage: run.builder.top_stage, host: run.target });
248     }
249
250     /// Runs `cargo test` for the rls.
251     fn run(self, builder: &Builder<'_>) {
252         let stage = self.stage;
253         let host = self.host;
254         let compiler = builder.compiler(stage, host);
255
256         let build_result =
257             builder.ensure(tool::Rls { compiler, target: self.host, extra_features: Vec::new() });
258         if build_result.is_none() {
259             eprintln!("failed to test rls: could not build");
260             return;
261         }
262
263         let mut cargo = tool::prepare_tool_cargo(
264             builder,
265             compiler,
266             Mode::ToolRustc,
267             host,
268             "test",
269             "src/tools/rls",
270             SourceType::Submodule,
271             &[],
272         );
273
274         cargo.add_rustc_lib_path(builder, compiler);
275         cargo.arg("--").args(builder.config.cmd.test_args());
276
277         if try_run(builder, &mut cargo.into()) {
278             builder.save_toolstate("rls", ToolState::TestPass);
279         }
280     }
281 }
282
283 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
284 pub struct Rustfmt {
285     stage: u32,
286     host: TargetSelection,
287 }
288
289 impl Step for Rustfmt {
290     type Output = ();
291     const ONLY_HOSTS: bool = true;
292
293     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
294         run.path("src/tools/rustfmt")
295     }
296
297     fn make_run(run: RunConfig<'_>) {
298         run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target });
299     }
300
301     /// Runs `cargo test` for rustfmt.
302     fn run(self, builder: &Builder<'_>) {
303         let stage = self.stage;
304         let host = self.host;
305         let compiler = builder.compiler(stage, host);
306
307         let build_result = builder.ensure(tool::Rustfmt {
308             compiler,
309             target: self.host,
310             extra_features: Vec::new(),
311         });
312         if build_result.is_none() {
313             eprintln!("failed to test rustfmt: could not build");
314             return;
315         }
316
317         let mut cargo = tool::prepare_tool_cargo(
318             builder,
319             compiler,
320             Mode::ToolRustc,
321             host,
322             "test",
323             "src/tools/rustfmt",
324             SourceType::Submodule,
325             &[],
326         );
327
328         let dir = testdir(builder, compiler.host);
329         t!(fs::create_dir_all(&dir));
330         cargo.env("RUSTFMT_TEST_DIR", dir);
331
332         cargo.add_rustc_lib_path(builder, compiler);
333
334         if try_run(builder, &mut cargo.into()) {
335             builder.save_toolstate("rustfmt", ToolState::TestPass);
336         }
337     }
338 }
339
340 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
341 pub struct Miri {
342     stage: u32,
343     host: TargetSelection,
344 }
345
346 impl Step for Miri {
347     type Output = ();
348     const ONLY_HOSTS: bool = true;
349
350     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
351         run.path("src/tools/miri")
352     }
353
354     fn make_run(run: RunConfig<'_>) {
355         run.builder.ensure(Miri { stage: run.builder.top_stage, host: run.target });
356     }
357
358     /// Runs `cargo test` for miri.
359     fn run(self, builder: &Builder<'_>) {
360         let stage = self.stage;
361         let host = self.host;
362         let compiler = builder.compiler(stage, host);
363
364         let miri =
365             builder.ensure(tool::Miri { compiler, target: self.host, extra_features: Vec::new() });
366         let cargo_miri = builder.ensure(tool::CargoMiri {
367             compiler,
368             target: self.host,
369             extra_features: Vec::new(),
370         });
371         if let (Some(miri), Some(_cargo_miri)) = (miri, cargo_miri) {
372             let mut cargo =
373                 builder.cargo(compiler, Mode::ToolRustc, SourceType::Submodule, host, "install");
374             cargo.arg("xargo");
375             // Configure `cargo install` path. cargo adds a `bin/`.
376             cargo.env("CARGO_INSTALL_ROOT", &builder.out);
377
378             let mut cargo = Command::from(cargo);
379             if !try_run(builder, &mut cargo) {
380                 return;
381             }
382
383             // # Run `cargo miri setup`.
384             let mut cargo = tool::prepare_tool_cargo(
385                 builder,
386                 compiler,
387                 Mode::ToolRustc,
388                 host,
389                 "run",
390                 "src/tools/miri/cargo-miri",
391                 SourceType::Submodule,
392                 &[],
393             );
394             cargo.arg("--").arg("miri").arg("setup");
395
396             // Tell `cargo miri setup` where to find the sources.
397             cargo.env("XARGO_RUST_SRC", builder.src.join("library"));
398             // Tell it where to find Miri.
399             cargo.env("MIRI", &miri);
400             // Debug things.
401             cargo.env("RUST_BACKTRACE", "1");
402             // Let cargo-miri know where xargo ended up.
403             cargo.env("XARGO_CHECK", builder.out.join("bin").join("xargo-check"));
404
405             let mut cargo = Command::from(cargo);
406             if !try_run(builder, &mut cargo) {
407                 return;
408             }
409
410             // # Determine where Miri put its sysroot.
411             // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
412             // (We do this separately from the above so that when the setup actually
413             // happens we get some output.)
414             // We re-use the `cargo` from above.
415             cargo.arg("--print-sysroot");
416
417             // FIXME: Is there a way in which we can re-use the usual `run` helpers?
418             let miri_sysroot = if builder.config.dry_run {
419                 String::new()
420             } else {
421                 builder.verbose(&format!("running: {:?}", cargo));
422                 let out = cargo
423                     .output()
424                     .expect("We already ran `cargo miri setup` before and that worked");
425                 assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code");
426                 // Output is "<sysroot>\n".
427                 let stdout = String::from_utf8(out.stdout)
428                     .expect("`cargo miri setup` stdout is not valid UTF-8");
429                 let sysroot = stdout.trim_end();
430                 builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
431                 sysroot.to_owned()
432             };
433
434             // # Run `cargo test`.
435             let mut cargo = tool::prepare_tool_cargo(
436                 builder,
437                 compiler,
438                 Mode::ToolRustc,
439                 host,
440                 "test",
441                 "src/tools/miri",
442                 SourceType::Submodule,
443                 &[],
444             );
445
446             // miri tests need to know about the stage sysroot
447             cargo.env("MIRI_SYSROOT", miri_sysroot);
448             cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
449             cargo.env("MIRI", miri);
450
451             cargo.arg("--").args(builder.config.cmd.test_args());
452
453             cargo.add_rustc_lib_path(builder, compiler);
454
455             if !try_run(builder, &mut cargo.into()) {
456                 return;
457             }
458
459             // # Done!
460             builder.save_toolstate("miri", ToolState::TestPass);
461         } else {
462             eprintln!("failed to test miri: could not build");
463         }
464     }
465 }
466
467 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
468 pub struct CompiletestTest {
469     host: TargetSelection,
470 }
471
472 impl Step for CompiletestTest {
473     type Output = ();
474
475     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
476         run.path("src/tools/compiletest")
477     }
478
479     fn make_run(run: RunConfig<'_>) {
480         run.builder.ensure(CompiletestTest { host: run.target });
481     }
482
483     /// Runs `cargo test` for compiletest.
484     fn run(self, builder: &Builder<'_>) {
485         let host = self.host;
486         let compiler = builder.compiler(0, host);
487
488         // We need `ToolStd` for the locally-built sysroot because
489         // compiletest uses unstable features of the `test` crate.
490         builder.ensure(compile::Std { compiler, target: host });
491         let cargo = tool::prepare_tool_cargo(
492             builder,
493             compiler,
494             Mode::ToolStd,
495             host,
496             "test",
497             "src/tools/compiletest",
498             SourceType::InTree,
499             &[],
500         );
501
502         try_run(builder, &mut cargo.into());
503     }
504 }
505
506 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
507 pub struct Clippy {
508     stage: u32,
509     host: TargetSelection,
510 }
511
512 impl Step for Clippy {
513     type Output = ();
514     const ONLY_HOSTS: bool = true;
515     const DEFAULT: bool = false;
516
517     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
518         run.path("src/tools/clippy")
519     }
520
521     fn make_run(run: RunConfig<'_>) {
522         run.builder.ensure(Clippy { stage: run.builder.top_stage, host: run.target });
523     }
524
525     /// Runs `cargo test` for clippy.
526     fn run(self, builder: &Builder<'_>) {
527         let stage = self.stage;
528         let host = self.host;
529         let compiler = builder.compiler(stage, host);
530
531         let clippy = builder
532             .ensure(tool::Clippy { compiler, target: self.host, extra_features: Vec::new() })
533             .expect("in-tree tool");
534         let mut cargo = tool::prepare_tool_cargo(
535             builder,
536             compiler,
537             Mode::ToolRustc,
538             host,
539             "test",
540             "src/tools/clippy",
541             SourceType::InTree,
542             &[],
543         );
544
545         // clippy tests need to know about the stage sysroot
546         cargo.env("SYSROOT", builder.sysroot(compiler));
547         cargo.env("RUSTC_TEST_SUITE", builder.rustc(compiler));
548         cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
549         let host_libs = builder.stage_out(compiler, Mode::ToolRustc).join(builder.cargo_dir());
550         let target_libs = builder
551             .stage_out(compiler, Mode::ToolRustc)
552             .join(&self.host.triple)
553             .join(builder.cargo_dir());
554         cargo.env("HOST_LIBS", host_libs);
555         cargo.env("TARGET_LIBS", target_libs);
556         // clippy tests need to find the driver
557         cargo.env("CLIPPY_DRIVER_PATH", clippy);
558
559         cargo.arg("--").args(builder.config.cmd.test_args());
560
561         cargo.add_rustc_lib_path(builder, compiler);
562
563         builder.run(&mut cargo.into());
564     }
565 }
566
567 fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
568     // Configure PATH to find the right rustc. NB. we have to use PATH
569     // and not RUSTC because the Cargo test suite has tests that will
570     // fail if rustc is not spelled `rustc`.
571     let path = builder.sysroot(compiler).join("bin");
572     let old_path = env::var_os("PATH").unwrap_or_default();
573     env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
574 }
575
576 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
577 pub struct RustdocTheme {
578     pub compiler: Compiler,
579 }
580
581 impl Step for RustdocTheme {
582     type Output = ();
583     const DEFAULT: bool = true;
584     const ONLY_HOSTS: bool = true;
585
586     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
587         run.path("src/tools/rustdoc-themes")
588     }
589
590     fn make_run(run: RunConfig<'_>) {
591         let compiler = run.builder.compiler(run.builder.top_stage, run.target);
592
593         run.builder.ensure(RustdocTheme { compiler });
594     }
595
596     fn run(self, builder: &Builder<'_>) {
597         let rustdoc = builder.out.join("bootstrap/debug/rustdoc");
598         let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
599         cmd.arg(rustdoc.to_str().unwrap())
600             .arg(builder.src.join("src/librustdoc/html/static/themes").to_str().unwrap())
601             .env("RUSTC_STAGE", self.compiler.stage.to_string())
602             .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
603             .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
604             .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
605             .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
606             .env("RUSTC_BOOTSTRAP", "1");
607         if let Some(linker) = builder.linker(self.compiler.host) {
608             cmd.env("RUSTDOC_LINKER", linker);
609         }
610         if builder.is_fuse_ld_lld(self.compiler.host) {
611             cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
612         }
613         try_run(builder, &mut cmd);
614     }
615 }
616
617 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
618 pub struct RustdocJSStd {
619     pub target: TargetSelection,
620 }
621
622 impl Step for RustdocJSStd {
623     type Output = ();
624     const DEFAULT: bool = true;
625     const ONLY_HOSTS: bool = true;
626
627     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
628         run.path("src/test/rustdoc-js-std")
629     }
630
631     fn make_run(run: RunConfig<'_>) {
632         run.builder.ensure(RustdocJSStd { target: run.target });
633     }
634
635     fn run(self, builder: &Builder<'_>) {
636         if let Some(ref nodejs) = builder.config.nodejs {
637             let mut command = Command::new(nodejs);
638             command
639                 .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
640                 .arg("--crate-name")
641                 .arg("std")
642                 .arg("--resource-suffix")
643                 .arg(&builder.version)
644                 .arg("--doc-folder")
645                 .arg(builder.doc_out(self.target))
646                 .arg("--test-folder")
647                 .arg(builder.src.join("src/test/rustdoc-js-std"));
648             builder.ensure(crate::doc::Std { target: self.target, stage: builder.top_stage });
649             builder.run(&mut command);
650         } else {
651             builder.info("No nodejs found, skipping \"src/test/rustdoc-js-std\" tests");
652         }
653     }
654 }
655
656 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
657 pub struct RustdocJSNotStd {
658     pub target: TargetSelection,
659     pub compiler: Compiler,
660 }
661
662 impl Step for RustdocJSNotStd {
663     type Output = ();
664     const DEFAULT: bool = true;
665     const ONLY_HOSTS: bool = true;
666
667     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
668         run.path("src/test/rustdoc-js")
669     }
670
671     fn make_run(run: RunConfig<'_>) {
672         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
673         run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
674     }
675
676     fn run(self, builder: &Builder<'_>) {
677         if builder.config.nodejs.is_some() {
678             builder.ensure(Compiletest {
679                 compiler: self.compiler,
680                 target: self.target,
681                 mode: "js-doc-test",
682                 suite: "rustdoc-js",
683                 path: "src/test/rustdoc-js",
684                 compare_mode: None,
685             });
686         } else {
687             builder.info("No nodejs found, skipping \"src/test/rustdoc-js\" tests");
688         }
689     }
690 }
691
692 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
693 pub struct RustdocGUI {
694     pub target: TargetSelection,
695     pub compiler: Compiler,
696 }
697
698 impl Step for RustdocGUI {
699     type Output = ();
700     const DEFAULT: bool = true;
701     const ONLY_HOSTS: bool = true;
702
703     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
704         run.path("src/test/rustdoc-gui")
705     }
706
707     fn make_run(run: RunConfig<'_>) {
708         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
709         run.builder.ensure(RustdocGUI { target: run.target, compiler });
710     }
711
712     fn run(self, builder: &Builder<'_>) {
713         if let (Some(nodejs), Some(npm)) = (&builder.config.nodejs, &builder.config.npm) {
714             builder.ensure(compile::Std { compiler: self.compiler, target: self.target });
715
716             // The goal here is to check if the necessary packages are installed, and if not, we
717             // display a warning and move on.
718             let mut command = Command::new(&npm);
719             command.arg("list").arg("--depth=0");
720             let lines = command
721                 .output()
722                 .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
723                 .unwrap_or(String::new());
724             if !lines.contains(&" browser-ui-test@") {
725                 println!(
726                     "warning: rustdoc-gui test suite cannot be run because npm `browser-ui-test` \
727                      dependency is missing",
728                 );
729                 println!(
730                     "If you want to install the `{0}` dependency, run `npm install {0}`",
731                     "browser-ui-test",
732                 );
733                 return;
734             }
735
736             let out_dir = builder.test_out(self.target).join("rustdoc-gui");
737             let mut command = builder.rustdoc_cmd(self.compiler);
738             command.arg("src/test/rustdoc-gui/lib.rs").arg("-o").arg(&out_dir);
739             builder.run(&mut command);
740
741             for file in fs::read_dir("src/test/rustdoc-gui").unwrap() {
742                 let file = file.unwrap();
743                 let file_path = file.path();
744                 let file_name = file.file_name();
745
746                 if !file_name.to_str().unwrap().ends_with(".goml") {
747                     continue;
748                 }
749                 let mut command = Command::new(&nodejs);
750                 command
751                     .arg("src/tools/rustdoc-gui/tester.js")
752                     .arg("--doc-folder")
753                     .arg(out_dir.join("test_docs"))
754                     .arg("--test-file")
755                     .arg(file_path);
756                 builder.run(&mut command);
757             }
758         } else {
759             builder.info("No nodejs found, skipping \"src/test/rustdoc-gui\" tests");
760         }
761     }
762 }
763
764 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
765 pub struct Tidy;
766
767 impl Step for Tidy {
768     type Output = ();
769     const DEFAULT: bool = true;
770     const ONLY_HOSTS: bool = true;
771
772     /// Runs the `tidy` tool.
773     ///
774     /// This tool in `src/tools` checks up on various bits and pieces of style and
775     /// otherwise just implements a few lint-like checks that are specific to the
776     /// compiler itself.
777     ///
778     /// Once tidy passes, this step also runs `fmt --check` if tests are being run
779     /// for the `dev` or `nightly` channels.
780     fn run(self, builder: &Builder<'_>) {
781         let mut cmd = builder.tool_cmd(Tool::Tidy);
782         cmd.arg(&builder.src);
783         cmd.arg(&builder.initial_cargo);
784         cmd.arg(&builder.out);
785         if builder.is_verbose() {
786             cmd.arg("--verbose");
787         }
788
789         builder.info("tidy check");
790         try_run(builder, &mut cmd);
791
792         if builder.config.channel == "dev" || builder.config.channel == "nightly" {
793             builder.info("fmt check");
794             if builder.config.initial_rustfmt.is_none() {
795                 let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
796                 eprintln!(
797                     "\
798 error: no `rustfmt` binary found in {PATH}
799 info: `rust.channel` is currently set to \"{CHAN}\"
800 help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
801 help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
802                     PATH = inferred_rustfmt_dir.display(),
803                     CHAN = builder.config.channel,
804                 );
805                 std::process::exit(1);
806             }
807             crate::format::format(&builder.build, !builder.config.cmd.bless());
808         }
809     }
810
811     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
812         run.path("src/tools/tidy")
813     }
814
815     fn make_run(run: RunConfig<'_>) {
816         run.builder.ensure(Tidy);
817     }
818 }
819
820 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
821 pub struct ExpandYamlAnchors;
822
823 impl Step for ExpandYamlAnchors {
824     type Output = ();
825     const ONLY_HOSTS: bool = true;
826
827     /// Ensure the `generate-ci-config` tool was run locally.
828     ///
829     /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
830     /// appropriate configuration for all our CI providers. This step ensures the tool was called
831     /// by the user before committing CI changes.
832     fn run(self, builder: &Builder<'_>) {
833         builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
834         try_run(
835             builder,
836             &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
837         );
838     }
839
840     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
841         run.path("src/tools/expand-yaml-anchors")
842     }
843
844     fn make_run(run: RunConfig<'_>) {
845         run.builder.ensure(ExpandYamlAnchors);
846     }
847 }
848
849 fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
850     builder.out.join(host.triple).join("test")
851 }
852
853 macro_rules! default_test {
854     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
855         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
856     };
857 }
858
859 macro_rules! default_test_with_compare_mode {
860     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
861                    compare_mode: $compare_mode:expr }) => {
862         test_with_compare_mode!($name {
863             path: $path,
864             mode: $mode,
865             suite: $suite,
866             default: true,
867             host: false,
868             compare_mode: $compare_mode
869         });
870     };
871 }
872
873 macro_rules! host_test {
874     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
875         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
876     };
877 }
878
879 macro_rules! test {
880     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
881                    host: $host:expr }) => {
882         test_definitions!($name {
883             path: $path,
884             mode: $mode,
885             suite: $suite,
886             default: $default,
887             host: $host,
888             compare_mode: None
889         });
890     };
891 }
892
893 macro_rules! test_with_compare_mode {
894     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
895                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
896         test_definitions!($name {
897             path: $path,
898             mode: $mode,
899             suite: $suite,
900             default: $default,
901             host: $host,
902             compare_mode: Some($compare_mode)
903         });
904     };
905 }
906
907 macro_rules! test_definitions {
908     ($name:ident {
909         path: $path:expr,
910         mode: $mode:expr,
911         suite: $suite:expr,
912         default: $default:expr,
913         host: $host:expr,
914         compare_mode: $compare_mode:expr
915     }) => {
916         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
917         pub struct $name {
918             pub compiler: Compiler,
919             pub target: TargetSelection,
920         }
921
922         impl Step for $name {
923             type Output = ();
924             const DEFAULT: bool = $default;
925             const ONLY_HOSTS: bool = $host;
926
927             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
928                 run.suite_path($path)
929             }
930
931             fn make_run(run: RunConfig<'_>) {
932                 let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
933
934                 run.builder.ensure($name { compiler, target: run.target });
935             }
936
937             fn run(self, builder: &Builder<'_>) {
938                 builder.ensure(Compiletest {
939                     compiler: self.compiler,
940                     target: self.target,
941                     mode: $mode,
942                     suite: $suite,
943                     path: $path,
944                     compare_mode: $compare_mode,
945                 })
946             }
947         }
948     };
949 }
950
951 default_test_with_compare_mode!(Ui {
952     path: "src/test/ui",
953     mode: "ui",
954     suite: "ui",
955     compare_mode: "nll"
956 });
957
958 default_test!(RunPassValgrind {
959     path: "src/test/run-pass-valgrind",
960     mode: "run-pass-valgrind",
961     suite: "run-pass-valgrind"
962 });
963
964 default_test!(MirOpt { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" });
965
966 default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
967
968 default_test!(CodegenUnits {
969     path: "src/test/codegen-units",
970     mode: "codegen-units",
971     suite: "codegen-units"
972 });
973
974 default_test!(Incremental {
975     path: "src/test/incremental",
976     mode: "incremental",
977     suite: "incremental"
978 });
979
980 default_test_with_compare_mode!(Debuginfo {
981     path: "src/test/debuginfo",
982     mode: "debuginfo",
983     suite: "debuginfo",
984     compare_mode: "split-dwarf"
985 });
986
987 host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
988
989 host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" });
990 host_test!(RustdocUi { path: "src/test/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
991
992 host_test!(RustdocJson {
993     path: "src/test/rustdoc-json",
994     mode: "rustdoc-json",
995     suite: "rustdoc-json"
996 });
997
998 host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" });
999
1000 default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" });
1001
1002 host_test!(RunMakeFullDeps {
1003     path: "src/test/run-make-fulldeps",
1004     mode: "run-make",
1005     suite: "run-make-fulldeps"
1006 });
1007
1008 default_test!(Assembly { path: "src/test/assembly", mode: "assembly", suite: "assembly" });
1009
1010 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1011 struct Compiletest {
1012     compiler: Compiler,
1013     target: TargetSelection,
1014     mode: &'static str,
1015     suite: &'static str,
1016     path: &'static str,
1017     compare_mode: Option<&'static str>,
1018 }
1019
1020 impl Step for Compiletest {
1021     type Output = ();
1022
1023     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1024         run.never()
1025     }
1026
1027     /// Executes the `compiletest` tool to run a suite of tests.
1028     ///
1029     /// Compiles all tests with `compiler` for `target` with the specified
1030     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1031     /// "run-pass" or `suite` can be something like `debuginfo`.
1032     fn run(self, builder: &Builder<'_>) {
1033         if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
1034             eprintln!("\
1035 error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1036 help: to test the compiler, use `--stage 1` instead
1037 help: to test the standard library, use `--stage 0 library/std` instead
1038 note: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`."
1039             );
1040             std::process::exit(1);
1041         }
1042
1043         let compiler = self.compiler;
1044         let target = self.target;
1045         let mode = self.mode;
1046         let suite = self.suite;
1047
1048         // Path for test suite
1049         let suite_path = self.path;
1050
1051         // Skip codegen tests if they aren't enabled in configuration.
1052         if !builder.config.codegen_tests && suite == "codegen" {
1053             return;
1054         }
1055
1056         if suite == "debuginfo" {
1057             builder
1058                 .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1059         }
1060
1061         if suite.ends_with("fulldeps") {
1062             builder.ensure(compile::Rustc { compiler, target });
1063         }
1064
1065         builder.ensure(compile::Std { compiler, target });
1066         // ensure that `libproc_macro` is available on the host.
1067         builder.ensure(compile::Std { compiler, target: compiler.host });
1068
1069         // Also provide `rust_test_helpers` for the host.
1070         builder.ensure(native::TestHelpers { target: compiler.host });
1071
1072         // As well as the target, except for plain wasm32, which can't build it
1073         if !target.contains("wasm32") || target.contains("emscripten") {
1074             builder.ensure(native::TestHelpers { target });
1075         }
1076
1077         builder.ensure(RemoteCopyLibs { compiler, target });
1078
1079         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1080
1081         // compiletest currently has... a lot of arguments, so let's just pass all
1082         // of them!
1083
1084         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
1085         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1086         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1087
1088         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1089
1090         // Avoid depending on rustdoc when we don't need it.
1091         if mode == "rustdoc"
1092             || mode == "run-make"
1093             || (mode == "ui" && is_rustdoc)
1094             || mode == "js-doc-test"
1095             || mode == "rustdoc-json"
1096         {
1097             cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1098         }
1099
1100         if mode == "rustdoc-json" {
1101             // Use the beta compiler for jsondocck
1102             let json_compiler = compiler.with_stage(0);
1103             cmd.arg("--jsondocck-path")
1104                 .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
1105         }
1106
1107         if mode == "run-make" && suite.ends_with("fulldeps") {
1108             cmd.arg("--rust-demangler-path").arg(builder.tool_exe(Tool::RustDemangler));
1109         }
1110
1111         cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite));
1112         cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
1113         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1114         cmd.arg("--suite").arg(suite);
1115         cmd.arg("--mode").arg(mode);
1116         cmd.arg("--target").arg(target.rustc_target_arg());
1117         cmd.arg("--host").arg(&*compiler.host.triple);
1118         cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1119
1120         if builder.config.cmd.bless() {
1121             cmd.arg("--bless");
1122         }
1123
1124         let compare_mode =
1125             builder.config.cmd.compare_mode().or_else(|| {
1126                 if builder.config.test_compare_mode { self.compare_mode } else { None }
1127             });
1128
1129         if let Some(ref pass) = builder.config.cmd.pass() {
1130             cmd.arg("--pass");
1131             cmd.arg(pass);
1132         }
1133
1134         if let Some(ref nodejs) = builder.config.nodejs {
1135             cmd.arg("--nodejs").arg(nodejs);
1136         }
1137         if let Some(ref npm) = builder.config.npm {
1138             cmd.arg("--npm").arg(npm);
1139         }
1140
1141         let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1142         if !is_rustdoc {
1143             if builder.config.rust_optimize_tests {
1144                 flags.push("-O".to_string());
1145             }
1146         }
1147         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1148         flags.push("-Zunstable-options".to_string());
1149         flags.push(builder.config.cmd.rustc_args().join(" "));
1150
1151         if let Some(linker) = builder.linker(target) {
1152             cmd.arg("--linker").arg(linker);
1153         }
1154
1155         let mut hostflags = flags.clone();
1156         hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1157         if builder.is_fuse_ld_lld(compiler.host) {
1158             hostflags.push("-Clink-args=-fuse-ld=lld".to_string());
1159         }
1160         cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
1161
1162         let mut targetflags = flags;
1163         targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1164         if builder.is_fuse_ld_lld(target) {
1165             targetflags.push("-Clink-args=-fuse-ld=lld".to_string());
1166         }
1167         cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
1168
1169         cmd.arg("--docck-python").arg(builder.python());
1170
1171         if builder.config.build.ends_with("apple-darwin") {
1172             // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1173             // LLDB plugin's compiled module which only works with the system python
1174             // (namely not Homebrew-installed python)
1175             cmd.arg("--lldb-python").arg("/usr/bin/python3");
1176         } else {
1177             cmd.arg("--lldb-python").arg(builder.python());
1178         }
1179
1180         if let Some(ref gdb) = builder.config.gdb {
1181             cmd.arg("--gdb").arg(gdb);
1182         }
1183
1184         let run = |cmd: &mut Command| {
1185             cmd.output().map(|output| {
1186                 String::from_utf8_lossy(&output.stdout)
1187                     .lines()
1188                     .next()
1189                     .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
1190                     .to_string()
1191             })
1192         };
1193         let lldb_exe = "lldb";
1194         let lldb_version = Command::new(lldb_exe)
1195             .arg("--version")
1196             .output()
1197             .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1198             .ok();
1199         if let Some(ref vers) = lldb_version {
1200             cmd.arg("--lldb-version").arg(vers);
1201             let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1202             if let Some(ref dir) = lldb_python_dir {
1203                 cmd.arg("--lldb-python-dir").arg(dir);
1204             }
1205         }
1206
1207         if util::forcing_clang_based_tests() {
1208             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1209             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1210         }
1211
1212         // Get paths from cmd args
1213         let paths = match &builder.config.cmd {
1214             Subcommand::Test { ref paths, .. } => &paths[..],
1215             _ => &[],
1216         };
1217
1218         // Get test-args by striping suite path
1219         let mut test_args: Vec<&str> = paths
1220             .iter()
1221             .map(|p| match p.strip_prefix(".") {
1222                 Ok(path) => path,
1223                 Err(_) => p,
1224             })
1225             .filter(|p| p.starts_with(suite_path))
1226             .filter(|p| {
1227                 let exists = p.is_dir() || p.is_file();
1228                 if !exists {
1229                     if let Some(p) = p.to_str() {
1230                         builder.info(&format!(
1231                             "Warning: Skipping \"{}\": not a regular file or directory",
1232                             p
1233                         ));
1234                     }
1235                 }
1236                 exists
1237             })
1238             .filter_map(|p| {
1239                 // Since test suite paths are themselves directories, if we don't
1240                 // specify a directory or file, we'll get an empty string here
1241                 // (the result of the test suite directory without its suite prefix).
1242                 // Therefore, we need to filter these out, as only the first --test-args
1243                 // flag is respected, so providing an empty --test-args conflicts with
1244                 // any following it.
1245                 match p.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
1246                     Some(s) if !s.is_empty() => Some(s),
1247                     _ => None,
1248                 }
1249             })
1250             .collect();
1251
1252         test_args.append(&mut builder.config.cmd.test_args());
1253
1254         cmd.args(&test_args);
1255
1256         if builder.is_verbose() {
1257             cmd.arg("--verbose");
1258         }
1259
1260         if !builder.config.verbose_tests {
1261             cmd.arg("--quiet");
1262         }
1263
1264         let mut llvm_components_passed = false;
1265         let mut copts_passed = false;
1266         if builder.config.llvm_enabled() {
1267             let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1268             if !builder.config.dry_run {
1269                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1270                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1271                 // Remove trailing newline from llvm-config output.
1272                 cmd.arg("--llvm-version")
1273                     .arg(llvm_version.trim())
1274                     .arg("--llvm-components")
1275                     .arg(llvm_components.trim());
1276                 llvm_components_passed = true;
1277             }
1278             if !builder.is_rust_llvm(target) {
1279                 cmd.arg("--system-llvm");
1280             }
1281
1282             // Tests that use compiler libraries may inherit the `-lLLVM` link
1283             // requirement, but the `-L` library path is not propagated across
1284             // separate compilations. We can add LLVM's library path to the
1285             // platform-specific environment variable as a workaround.
1286             if !builder.config.dry_run && suite.ends_with("fulldeps") {
1287                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1288                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
1289             }
1290
1291             // Only pass correct values for these flags for the `run-make` suite as it
1292             // requires that a C++ compiler was configured which isn't always the case.
1293             if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1294                 // The llvm/bin directory contains many useful cross-platform
1295                 // tools. Pass the path to run-make tests so they can use them.
1296                 let llvm_bin_path = llvm_config
1297                     .parent()
1298                     .expect("Expected llvm-config to be contained in directory");
1299                 assert!(llvm_bin_path.is_dir());
1300                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1301
1302                 // If LLD is available, add it to the PATH
1303                 if builder.config.lld_enabled {
1304                     let lld_install_root =
1305                         builder.ensure(native::Lld { target: builder.config.build });
1306
1307                     let lld_bin_path = lld_install_root.join("bin");
1308
1309                     let old_path = env::var_os("PATH").unwrap_or_default();
1310                     let new_path = env::join_paths(
1311                         std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
1312                     )
1313                     .expect("Could not add LLD bin path to PATH");
1314                     cmd.env("PATH", new_path);
1315                 }
1316             }
1317         }
1318
1319         // Only pass correct values for these flags for the `run-make` suite as it
1320         // requires that a C++ compiler was configured which isn't always the case.
1321         if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1322             cmd.arg("--cc")
1323                 .arg(builder.cc(target))
1324                 .arg("--cxx")
1325                 .arg(builder.cxx(target).unwrap())
1326                 .arg("--cflags")
1327                 .arg(builder.cflags(target, GitRepo::Rustc).join(" "));
1328             copts_passed = true;
1329             if let Some(ar) = builder.ar(target) {
1330                 cmd.arg("--ar").arg(ar);
1331             }
1332         }
1333
1334         if !llvm_components_passed {
1335             cmd.arg("--llvm-components").arg("");
1336         }
1337         if !copts_passed {
1338             cmd.arg("--cc").arg("").arg("--cxx").arg("").arg("--cflags").arg("");
1339         }
1340
1341         if builder.remote_tested(target) {
1342             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1343         }
1344
1345         // Running a C compiler on MSVC requires a few env vars to be set, to be
1346         // sure to set them here.
1347         //
1348         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1349         // rather than stomp over it.
1350         if target.contains("msvc") {
1351             for &(ref k, ref v) in builder.cc[&target].env() {
1352                 if k != "PATH" {
1353                     cmd.env(k, v);
1354                 }
1355             }
1356         }
1357         cmd.env("RUSTC_BOOTSTRAP", "1");
1358         builder.add_rust_test_threads(&mut cmd);
1359
1360         if builder.config.sanitizers_enabled(target) {
1361             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1362         }
1363
1364         if builder.config.profiler_enabled(target) {
1365             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1366         }
1367
1368         let tmp = builder.out.join("tmp");
1369         std::fs::create_dir_all(&tmp).unwrap();
1370         cmd.env("RUST_TEST_TMPDIR", tmp);
1371
1372         cmd.arg("--adb-path").arg("adb");
1373         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1374         if target.contains("android") {
1375             // Assume that cc for this target comes from the android sysroot
1376             cmd.arg("--android-cross-path")
1377                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1378         } else {
1379             cmd.arg("--android-cross-path").arg("");
1380         }
1381
1382         if builder.config.cmd.rustfix_coverage() {
1383             cmd.arg("--rustfix-coverage");
1384         }
1385
1386         cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);
1387
1388         builder.ci_env.force_coloring_in_ci(&mut cmd);
1389
1390         builder.info(&format!(
1391             "Check compiletest suite={} mode={} ({} -> {})",
1392             suite, mode, &compiler.host, target
1393         ));
1394         let _time = util::timeit(&builder);
1395         try_run(builder, &mut cmd);
1396
1397         if let Some(compare_mode) = compare_mode {
1398             cmd.arg("--compare-mode").arg(compare_mode);
1399             builder.info(&format!(
1400                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1401                 suite, mode, compare_mode, &compiler.host, target
1402             ));
1403             let _time = util::timeit(&builder);
1404             try_run(builder, &mut cmd);
1405         }
1406     }
1407 }
1408
1409 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1410 struct BookTest {
1411     compiler: Compiler,
1412     path: PathBuf,
1413     name: &'static str,
1414     is_ext_doc: bool,
1415 }
1416
1417 impl Step for BookTest {
1418     type Output = ();
1419     const ONLY_HOSTS: bool = true;
1420
1421     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1422         run.never()
1423     }
1424
1425     /// Runs the documentation tests for a book in `src/doc`.
1426     ///
1427     /// This uses the `rustdoc` that sits next to `compiler`.
1428     fn run(self, builder: &Builder<'_>) {
1429         // External docs are different from local because:
1430         // - Some books need pre-processing by mdbook before being tested.
1431         // - They need to save their state to toolstate.
1432         // - They are only tested on the "checktools" builders.
1433         //
1434         // The local docs are tested by default, and we don't want to pay the
1435         // cost of building mdbook, so they use `rustdoc --test` directly.
1436         // Also, the unstable book is special because SUMMARY.md is generated,
1437         // so it is easier to just run `rustdoc` on its files.
1438         if self.is_ext_doc {
1439             self.run_ext_doc(builder);
1440         } else {
1441             self.run_local_doc(builder);
1442         }
1443     }
1444 }
1445
1446 impl BookTest {
1447     /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
1448     /// which in turn runs `rustdoc --test` on each file in the book.
1449     fn run_ext_doc(self, builder: &Builder<'_>) {
1450         let compiler = self.compiler;
1451
1452         builder.ensure(compile::Std { compiler, target: compiler.host });
1453
1454         // mdbook just executes a binary named "rustdoc", so we need to update
1455         // PATH so that it points to our rustdoc.
1456         let mut rustdoc_path = builder.rustdoc(compiler);
1457         rustdoc_path.pop();
1458         let old_path = env::var_os("PATH").unwrap_or_default();
1459         let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
1460             .expect("could not add rustdoc to PATH");
1461
1462         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1463         let path = builder.src.join(&self.path);
1464         rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
1465         builder.add_rust_test_threads(&mut rustbook_cmd);
1466         builder.info(&format!("Testing rustbook {}", self.path.display()));
1467         let _time = util::timeit(&builder);
1468         let toolstate = if try_run(builder, &mut rustbook_cmd) {
1469             ToolState::TestPass
1470         } else {
1471             ToolState::TestFail
1472         };
1473         builder.save_toolstate(self.name, toolstate);
1474     }
1475
1476     /// This runs `rustdoc --test` on all `.md` files in the path.
1477     fn run_local_doc(self, builder: &Builder<'_>) {
1478         let compiler = self.compiler;
1479
1480         builder.ensure(compile::Std { compiler, target: compiler.host });
1481
1482         // Do a breadth-first traversal of the `src/doc` directory and just run
1483         // tests for all files that end in `*.md`
1484         let mut stack = vec![builder.src.join(self.path)];
1485         let _time = util::timeit(&builder);
1486         let mut files = Vec::new();
1487         while let Some(p) = stack.pop() {
1488             if p.is_dir() {
1489                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1490                 continue;
1491             }
1492
1493             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1494                 continue;
1495             }
1496
1497             files.push(p);
1498         }
1499
1500         files.sort();
1501
1502         for file in files {
1503             markdown_test(builder, compiler, &file);
1504         }
1505     }
1506 }
1507
1508 macro_rules! test_book {
1509     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1510         $(
1511             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1512             pub struct $name {
1513                 compiler: Compiler,
1514             }
1515
1516             impl Step for $name {
1517                 type Output = ();
1518                 const DEFAULT: bool = $default;
1519                 const ONLY_HOSTS: bool = true;
1520
1521                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1522                     run.path($path)
1523                 }
1524
1525                 fn make_run(run: RunConfig<'_>) {
1526                     run.builder.ensure($name {
1527                         compiler: run.builder.compiler(run.builder.top_stage, run.target),
1528                     });
1529                 }
1530
1531                 fn run(self, builder: &Builder<'_>) {
1532                     builder.ensure(BookTest {
1533                         compiler: self.compiler,
1534                         path: PathBuf::from($path),
1535                         name: $book_name,
1536                         is_ext_doc: !$default,
1537                     });
1538                 }
1539             }
1540         )+
1541     }
1542 }
1543
1544 test_book!(
1545     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1546     Reference, "src/doc/reference", "reference", default=false;
1547     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1548     RustcBook, "src/doc/rustc", "rustc", default=true;
1549     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1550     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1551     TheBook, "src/doc/book", "book", default=false;
1552     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1553     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1554 );
1555
1556 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1557 pub struct ErrorIndex {
1558     compiler: Compiler,
1559 }
1560
1561 impl Step for ErrorIndex {
1562     type Output = ();
1563     const DEFAULT: bool = true;
1564     const ONLY_HOSTS: bool = true;
1565
1566     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1567         run.path("src/tools/error_index_generator")
1568     }
1569
1570     fn make_run(run: RunConfig<'_>) {
1571         // error_index_generator depends on librustdoc. Use the compiler that
1572         // is normally used to build rustdoc for other tests (like compiletest
1573         // tests in src/test/rustdoc) so that it shares the same artifacts.
1574         let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
1575         run.builder.ensure(ErrorIndex { compiler });
1576     }
1577
1578     /// Runs the error index generator tool to execute the tests located in the error
1579     /// index.
1580     ///
1581     /// The `error_index_generator` tool lives in `src/tools` and is used to
1582     /// generate a markdown file from the error indexes of the code base which is
1583     /// then passed to `rustdoc --test`.
1584     fn run(self, builder: &Builder<'_>) {
1585         let compiler = self.compiler;
1586
1587         let dir = testdir(builder, compiler.host);
1588         t!(fs::create_dir_all(&dir));
1589         let output = dir.join("error-index.md");
1590
1591         let mut tool = tool::ErrorIndex::command(builder);
1592         tool.arg("markdown").arg(&output);
1593
1594         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1595         let _time = util::timeit(&builder);
1596         builder.run_quiet(&mut tool);
1597         // The tests themselves need to link to std, so make sure it is
1598         // available.
1599         builder.ensure(compile::Std { compiler, target: compiler.host });
1600         markdown_test(builder, compiler, &output);
1601     }
1602 }
1603
1604 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1605     if let Ok(contents) = fs::read_to_string(markdown) {
1606         if !contents.contains("```") {
1607             return true;
1608         }
1609     }
1610
1611     builder.info(&format!("doc tests for: {}", markdown.display()));
1612     let mut cmd = builder.rustdoc_cmd(compiler);
1613     builder.add_rust_test_threads(&mut cmd);
1614     cmd.arg("--test");
1615     cmd.arg(markdown);
1616     cmd.env("RUSTC_BOOTSTRAP", "1");
1617
1618     let test_args = builder.config.cmd.test_args().join(" ");
1619     cmd.arg("--test-args").arg(test_args);
1620
1621     if builder.config.verbose_tests {
1622         try_run(builder, &mut cmd)
1623     } else {
1624         try_run_quiet(builder, &mut cmd)
1625     }
1626 }
1627
1628 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1629 pub struct RustcGuide;
1630
1631 impl Step for RustcGuide {
1632     type Output = ();
1633     const DEFAULT: bool = false;
1634     const ONLY_HOSTS: bool = true;
1635
1636     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1637         run.path("src/doc/rustc-dev-guide")
1638     }
1639
1640     fn make_run(run: RunConfig<'_>) {
1641         run.builder.ensure(RustcGuide);
1642     }
1643
1644     fn run(self, builder: &Builder<'_>) {
1645         let src = builder.src.join("src/doc/rustc-dev-guide");
1646         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1647         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
1648             ToolState::TestPass
1649         } else {
1650             ToolState::TestFail
1651         };
1652         builder.save_toolstate("rustc-dev-guide", toolstate);
1653     }
1654 }
1655
1656 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1657 pub struct CrateLibrustc {
1658     compiler: Compiler,
1659     target: TargetSelection,
1660     test_kind: TestKind,
1661     krate: Interned<String>,
1662 }
1663
1664 impl Step for CrateLibrustc {
1665     type Output = ();
1666     const DEFAULT: bool = true;
1667     const ONLY_HOSTS: bool = true;
1668
1669     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1670         run.krate("rustc-main")
1671     }
1672
1673     fn make_run(run: RunConfig<'_>) {
1674         let builder = run.builder;
1675         let compiler = builder.compiler(builder.top_stage, run.build_triple());
1676
1677         for krate in builder.in_tree_crates("rustc-main", Some(run.target)) {
1678             if krate.path.ends_with(&run.path) {
1679                 let test_kind = builder.kind.into();
1680
1681                 builder.ensure(CrateLibrustc {
1682                     compiler,
1683                     target: run.target,
1684                     test_kind,
1685                     krate: krate.name,
1686                 });
1687             }
1688         }
1689     }
1690
1691     fn run(self, builder: &Builder<'_>) {
1692         builder.ensure(Crate {
1693             compiler: self.compiler,
1694             target: self.target,
1695             mode: Mode::Rustc,
1696             test_kind: self.test_kind,
1697             krate: self.krate,
1698         });
1699     }
1700 }
1701
1702 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1703 pub struct Crate {
1704     pub compiler: Compiler,
1705     pub target: TargetSelection,
1706     pub mode: Mode,
1707     pub test_kind: TestKind,
1708     pub krate: Interned<String>,
1709 }
1710
1711 impl Step for Crate {
1712     type Output = ();
1713     const DEFAULT: bool = true;
1714
1715     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1716         run.krate("test")
1717     }
1718
1719     fn make_run(run: RunConfig<'_>) {
1720         let builder = run.builder;
1721         let compiler = builder.compiler(builder.top_stage, run.build_triple());
1722
1723         let make = |mode: Mode, krate: &CargoCrate| {
1724             let test_kind = builder.kind.into();
1725
1726             builder.ensure(Crate {
1727                 compiler,
1728                 target: run.target,
1729                 mode,
1730                 test_kind,
1731                 krate: krate.name,
1732             });
1733         };
1734
1735         for krate in builder.in_tree_crates("test", Some(run.target)) {
1736             if krate.path.ends_with(&run.path) {
1737                 make(Mode::Std, krate);
1738             }
1739         }
1740     }
1741
1742     /// Runs all unit tests plus documentation tests for a given crate defined
1743     /// by a `Cargo.toml` (single manifest)
1744     ///
1745     /// This is what runs tests for crates like the standard library, compiler, etc.
1746     /// It essentially is the driver for running `cargo test`.
1747     ///
1748     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
1749     /// arguments, and those arguments are discovered from `cargo metadata`.
1750     fn run(self, builder: &Builder<'_>) {
1751         let compiler = self.compiler;
1752         let target = self.target;
1753         let mode = self.mode;
1754         let test_kind = self.test_kind;
1755         let krate = self.krate;
1756
1757         builder.ensure(compile::Std { compiler, target });
1758         builder.ensure(RemoteCopyLibs { compiler, target });
1759
1760         // If we're not doing a full bootstrap but we're testing a stage2
1761         // version of libstd, then what we're actually testing is the libstd
1762         // produced in stage1. Reflect that here by updating the compiler that
1763         // we're working with automatically.
1764         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
1765
1766         let mut cargo =
1767             builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
1768         match mode {
1769             Mode::Std => {
1770                 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
1771             }
1772             Mode::Rustc => {
1773                 builder.ensure(compile::Rustc { compiler, target });
1774                 compile::rustc_cargo(builder, &mut cargo, target);
1775             }
1776             _ => panic!("can only test libraries"),
1777         };
1778
1779         // Build up the base `cargo test` command.
1780         //
1781         // Pass in some standard flags then iterate over the graph we've discovered
1782         // in `cargo metadata` with the maps above and figure out what `-p`
1783         // arguments need to get passed.
1784         if test_kind.subcommand() == "test" && !builder.fail_fast {
1785             cargo.arg("--no-fail-fast");
1786         }
1787         match builder.doc_tests {
1788             DocTests::Only => {
1789                 cargo.arg("--doc");
1790             }
1791             DocTests::No => {
1792                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
1793             }
1794             DocTests::Yes => {}
1795         }
1796
1797         cargo.arg("-p").arg(krate);
1798
1799         // The tests are going to run with the *target* libraries, so we need to
1800         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
1801         //
1802         // Note that to run the compiler we need to run with the *host* libraries,
1803         // but our wrapper scripts arrange for that to be the case anyway.
1804         let mut dylib_path = dylib_path();
1805         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1806         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1807
1808         cargo.arg("--");
1809         cargo.args(&builder.config.cmd.test_args());
1810
1811         if !builder.config.verbose_tests {
1812             cargo.arg("--quiet");
1813         }
1814
1815         if target.contains("emscripten") {
1816             cargo.env(
1817                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
1818                 builder.config.nodejs.as_ref().expect("nodejs not configured"),
1819             );
1820         } else if target.starts_with("wasm32") {
1821             let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
1822             let runner =
1823                 format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
1824             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
1825         } else if builder.remote_tested(target) {
1826             cargo.env(
1827                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
1828                 format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
1829             );
1830         }
1831
1832         builder.info(&format!(
1833             "{} {} stage{} ({} -> {})",
1834             test_kind, krate, compiler.stage, &compiler.host, target
1835         ));
1836         let _time = util::timeit(&builder);
1837         try_run(builder, &mut cargo.into());
1838     }
1839 }
1840
1841 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1842 pub struct CrateRustdoc {
1843     host: TargetSelection,
1844     test_kind: TestKind,
1845 }
1846
1847 impl Step for CrateRustdoc {
1848     type Output = ();
1849     const DEFAULT: bool = true;
1850     const ONLY_HOSTS: bool = true;
1851
1852     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1853         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
1854     }
1855
1856     fn make_run(run: RunConfig<'_>) {
1857         let builder = run.builder;
1858
1859         let test_kind = builder.kind.into();
1860
1861         builder.ensure(CrateRustdoc { host: run.target, test_kind });
1862     }
1863
1864     fn run(self, builder: &Builder<'_>) {
1865         let test_kind = self.test_kind;
1866         let target = self.host;
1867
1868         // Use the previous stage compiler to reuse the artifacts that are
1869         // created when running compiletest for src/test/rustdoc. If this used
1870         // `compiler`, then it would cause rustdoc to be built *again*, which
1871         // isn't really necessary.
1872         let compiler = builder.compiler_for(builder.top_stage, target, target);
1873         builder.ensure(compile::Rustc { compiler, target });
1874
1875         let mut cargo = tool::prepare_tool_cargo(
1876             builder,
1877             compiler,
1878             Mode::ToolRustc,
1879             target,
1880             test_kind.subcommand(),
1881             "src/tools/rustdoc",
1882             SourceType::InTree,
1883             &[],
1884         );
1885         if test_kind.subcommand() == "test" && !builder.fail_fast {
1886             cargo.arg("--no-fail-fast");
1887         }
1888
1889         cargo.arg("-p").arg("rustdoc:0.0.0");
1890
1891         cargo.arg("--");
1892         cargo.args(&builder.config.cmd.test_args());
1893
1894         if self.host.contains("musl") {
1895             cargo.arg("'-Ctarget-feature=-crt-static'");
1896         }
1897
1898         // This is needed for running doctests on librustdoc. This is a bit of
1899         // an unfortunate interaction with how bootstrap works and how cargo
1900         // sets up the dylib path, and the fact that the doctest (in
1901         // html/markdown.rs) links to rustc-private libs. For stage1, the
1902         // compiler host dylibs (in stage1/lib) are not the same as the target
1903         // dylibs (in stage1/lib/rustlib/...). This is different from a normal
1904         // rust distribution where they are the same.
1905         //
1906         // On the cargo side, normal tests use `target_process` which handles
1907         // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
1908         // case). However, for doctests it uses `rustdoc_process` which only
1909         // sets up the dylib path for the *host* (stage1/lib), which is the
1910         // wrong directory.
1911         //
1912         // It should be considered to just stop running doctests on
1913         // librustdoc. There is only one test, and it doesn't look too
1914         // important. There might be other ways to avoid this, but it seems
1915         // pretty convoluted.
1916         //
1917         // See also https://github.com/rust-lang/rust/issues/13983 where the
1918         // host vs target dylibs for rustdoc are consistently tricky to deal
1919         // with.
1920         let mut dylib_path = dylib_path();
1921         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1922         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1923
1924         if !builder.config.verbose_tests {
1925             cargo.arg("--quiet");
1926         }
1927
1928         builder.info(&format!(
1929             "{} rustdoc stage{} ({} -> {})",
1930             test_kind, compiler.stage, &compiler.host, target
1931         ));
1932         let _time = util::timeit(&builder);
1933
1934         try_run(builder, &mut cargo.into());
1935     }
1936 }
1937
1938 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1939 pub struct CrateRustdocJsonTypes {
1940     host: TargetSelection,
1941     test_kind: TestKind,
1942 }
1943
1944 impl Step for CrateRustdocJsonTypes {
1945     type Output = ();
1946     const DEFAULT: bool = true;
1947     const ONLY_HOSTS: bool = true;
1948
1949     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1950         run.path("src/rustdoc-json-types")
1951     }
1952
1953     fn make_run(run: RunConfig<'_>) {
1954         let builder = run.builder;
1955
1956         let test_kind = builder.kind.into();
1957
1958         builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
1959     }
1960
1961     fn run(self, builder: &Builder<'_>) {
1962         let test_kind = self.test_kind;
1963         let target = self.host;
1964
1965         // Use the previous stage compiler to reuse the artifacts that are
1966         // created when running compiletest for src/test/rustdoc. If this used
1967         // `compiler`, then it would cause rustdoc to be built *again*, which
1968         // isn't really necessary.
1969         let compiler = builder.compiler_for(builder.top_stage, target, target);
1970         builder.ensure(compile::Rustc { compiler, target });
1971
1972         let mut cargo = tool::prepare_tool_cargo(
1973             builder,
1974             compiler,
1975             Mode::ToolRustc,
1976             target,
1977             test_kind.subcommand(),
1978             "src/rustdoc-json-types",
1979             SourceType::InTree,
1980             &[],
1981         );
1982         if test_kind.subcommand() == "test" && !builder.fail_fast {
1983             cargo.arg("--no-fail-fast");
1984         }
1985
1986         cargo.arg("-p").arg("rustdoc-json-types");
1987
1988         cargo.arg("--");
1989         cargo.args(&builder.config.cmd.test_args());
1990
1991         if self.host.contains("musl") {
1992             cargo.arg("'-Ctarget-feature=-crt-static'");
1993         }
1994
1995         if !builder.config.verbose_tests {
1996             cargo.arg("--quiet");
1997         }
1998
1999         builder.info(&format!(
2000             "{} rustdoc-json-types stage{} ({} -> {})",
2001             test_kind, compiler.stage, &compiler.host, target
2002         ));
2003         let _time = util::timeit(&builder);
2004
2005         try_run(builder, &mut cargo.into());
2006     }
2007 }
2008
2009 /// Some test suites are run inside emulators or on remote devices, and most
2010 /// of our test binaries are linked dynamically which means we need to ship
2011 /// the standard library and such to the emulator ahead of time. This step
2012 /// represents this and is a dependency of all test suites.
2013 ///
2014 /// Most of the time this is a no-op. For some steps such as shipping data to
2015 /// QEMU we have to build our own tools so we've got conditional dependencies
2016 /// on those programs as well. Note that the remote test client is built for
2017 /// the build target (us) and the server is built for the target.
2018 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2019 pub struct RemoteCopyLibs {
2020     compiler: Compiler,
2021     target: TargetSelection,
2022 }
2023
2024 impl Step for RemoteCopyLibs {
2025     type Output = ();
2026
2027     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2028         run.never()
2029     }
2030
2031     fn run(self, builder: &Builder<'_>) {
2032         let compiler = self.compiler;
2033         let target = self.target;
2034         if !builder.remote_tested(target) {
2035             return;
2036         }
2037
2038         builder.ensure(compile::Std { compiler, target });
2039
2040         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
2041         t!(fs::create_dir_all(builder.out.join("tmp")));
2042
2043         let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2044
2045         // Spawn the emulator and wait for it to come online
2046         let tool = builder.tool_exe(Tool::RemoteTestClient);
2047         let mut cmd = Command::new(&tool);
2048         cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.out.join("tmp"));
2049         if let Some(rootfs) = builder.qemu_rootfs(target) {
2050             cmd.arg(rootfs);
2051         }
2052         builder.run(&mut cmd);
2053
2054         // Push all our dylibs to the emulator
2055         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2056             let f = t!(f);
2057             let name = f.file_name().into_string().unwrap();
2058             if util::is_dylib(&name) {
2059                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
2060             }
2061         }
2062     }
2063 }
2064
2065 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2066 pub struct Distcheck;
2067
2068 impl Step for Distcheck {
2069     type Output = ();
2070
2071     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2072         run.path("distcheck")
2073     }
2074
2075     fn make_run(run: RunConfig<'_>) {
2076         run.builder.ensure(Distcheck);
2077     }
2078
2079     /// Runs "distcheck", a 'make check' from a tarball
2080     fn run(self, builder: &Builder<'_>) {
2081         builder.info("Distcheck");
2082         let dir = builder.out.join("tmp").join("distcheck");
2083         let _ = fs::remove_dir_all(&dir);
2084         t!(fs::create_dir_all(&dir));
2085
2086         // Guarantee that these are built before we begin running.
2087         builder.ensure(dist::PlainSourceTarball);
2088         builder.ensure(dist::Src);
2089
2090         let mut cmd = Command::new("tar");
2091         cmd.arg("-xf")
2092             .arg(builder.ensure(dist::PlainSourceTarball).tarball())
2093             .arg("--strip-components=1")
2094             .current_dir(&dir);
2095         builder.run(&mut cmd);
2096         builder.run(
2097             Command::new("./configure")
2098                 .args(&builder.config.configure_args)
2099                 .arg("--enable-vendor")
2100                 .current_dir(&dir),
2101         );
2102         builder.run(
2103             Command::new(build_helper::make(&builder.config.build.triple))
2104                 .arg("check")
2105                 .current_dir(&dir),
2106         );
2107
2108         // Now make sure that rust-src has all of libstd's dependencies
2109         builder.info("Distcheck rust-src");
2110         let dir = builder.out.join("tmp").join("distcheck-src");
2111         let _ = fs::remove_dir_all(&dir);
2112         t!(fs::create_dir_all(&dir));
2113
2114         let mut cmd = Command::new("tar");
2115         cmd.arg("-xf")
2116             .arg(builder.ensure(dist::Src).tarball())
2117             .arg("--strip-components=1")
2118             .current_dir(&dir);
2119         builder.run(&mut cmd);
2120
2121         let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
2122         builder.run(
2123             Command::new(&builder.initial_cargo)
2124                 .arg("generate-lockfile")
2125                 .arg("--manifest-path")
2126                 .arg(&toml)
2127                 .current_dir(&dir),
2128         );
2129     }
2130 }
2131
2132 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2133 pub struct Bootstrap;
2134
2135 impl Step for Bootstrap {
2136     type Output = ();
2137     const DEFAULT: bool = true;
2138     const ONLY_HOSTS: bool = true;
2139
2140     /// Tests the build system itself.
2141     fn run(self, builder: &Builder<'_>) {
2142         let mut cmd = Command::new(&builder.initial_cargo);
2143         cmd.arg("test")
2144             .current_dir(builder.src.join("src/bootstrap"))
2145             .env("RUSTFLAGS", "-Cdebuginfo=2")
2146             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2147             .env("BOOTSTRAP_OUTPUT_DIRECTORY", &builder.config.out)
2148             .env("BOOTSTRAP_INITIAL_CARGO", &builder.config.initial_cargo)
2149             .env("RUSTC_BOOTSTRAP", "1")
2150             .env("RUSTC", &builder.initial_rustc);
2151         if let Some(flags) = option_env!("RUSTFLAGS") {
2152             // Use the same rustc flags for testing as for "normal" compilation,
2153             // so that Cargo doesn’t recompile the entire dependency graph every time:
2154             // https://github.com/rust-lang/rust/issues/49215
2155             cmd.env("RUSTFLAGS", flags);
2156         }
2157         if !builder.fail_fast {
2158             cmd.arg("--no-fail-fast");
2159         }
2160         cmd.arg("--").args(&builder.config.cmd.test_args());
2161         // rustbuild tests are racy on directory creation so just run them one at a time.
2162         // Since there's not many this shouldn't be a problem.
2163         cmd.arg("--test-threads=1");
2164         try_run(builder, &mut cmd);
2165     }
2166
2167     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2168         run.path("src/bootstrap")
2169     }
2170
2171     fn make_run(run: RunConfig<'_>) {
2172         run.builder.ensure(Bootstrap);
2173     }
2174 }
2175
2176 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2177 pub struct TierCheck {
2178     pub compiler: Compiler,
2179 }
2180
2181 impl Step for TierCheck {
2182     type Output = ();
2183     const DEFAULT: bool = true;
2184     const ONLY_HOSTS: bool = true;
2185
2186     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2187         run.path("src/tools/tier-check")
2188     }
2189
2190     fn make_run(run: RunConfig<'_>) {
2191         let compiler =
2192             run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
2193         run.builder.ensure(TierCheck { compiler });
2194     }
2195
2196     /// Tests the Platform Support page in the rustc book.
2197     fn run(self, builder: &Builder<'_>) {
2198         builder.ensure(compile::Std { compiler: self.compiler, target: self.compiler.host });
2199         let mut cargo = tool::prepare_tool_cargo(
2200             builder,
2201             self.compiler,
2202             Mode::ToolStd,
2203             self.compiler.host,
2204             "run",
2205             "src/tools/tier-check",
2206             SourceType::InTree,
2207             &[],
2208         );
2209         cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
2210         cargo.arg(&builder.rustc(self.compiler));
2211         if builder.is_verbose() {
2212             cargo.arg("--verbose");
2213         }
2214
2215         builder.info("platform support check");
2216         try_run(builder, &mut cargo.into());
2217     }
2218 }
2219
2220 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2221 pub struct LintDocs {
2222     pub compiler: Compiler,
2223     pub target: TargetSelection,
2224 }
2225
2226 impl Step for LintDocs {
2227     type Output = ();
2228     const DEFAULT: bool = true;
2229     const ONLY_HOSTS: bool = true;
2230
2231     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2232         run.path("src/tools/lint-docs")
2233     }
2234
2235     fn make_run(run: RunConfig<'_>) {
2236         run.builder.ensure(LintDocs {
2237             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
2238             target: run.target,
2239         });
2240     }
2241
2242     /// Tests that the lint examples in the rustc book generate the correct
2243     /// lints and have the expected format.
2244     fn run(self, builder: &Builder<'_>) {
2245         builder.ensure(crate::doc::RustcBook {
2246             compiler: self.compiler,
2247             target: self.target,
2248             validate: true,
2249         });
2250     }
2251 }