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