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