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