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