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