]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Auto merge of #107569 - petrochenkov:optattr, r=nnethercote
[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         builder.info("tidy check");
1118         try_run(builder, &mut cmd);
1119
1120         if builder.config.channel == "dev" || builder.config.channel == "nightly" {
1121             builder.info("fmt check");
1122             if builder.initial_rustfmt().is_none() {
1123                 let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
1124                 eprintln!(
1125                     "\
1126 error: no `rustfmt` binary found in {PATH}
1127 info: `rust.channel` is currently set to \"{CHAN}\"
1128 help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
1129 help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
1130                     PATH = inferred_rustfmt_dir.display(),
1131                     CHAN = builder.config.channel,
1132                 );
1133                 crate::detail_exit(1);
1134             }
1135             crate::format::format(&builder, !builder.config.cmd.bless(), &[]);
1136         }
1137     }
1138
1139     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1140         run.path("src/tools/tidy")
1141     }
1142
1143     fn make_run(run: RunConfig<'_>) {
1144         run.builder.ensure(Tidy);
1145     }
1146 }
1147
1148 /// Runs tidy's own tests.
1149 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1150 pub struct TidySelfTest;
1151
1152 impl Step for TidySelfTest {
1153     type Output = ();
1154     const DEFAULT: bool = true;
1155     const ONLY_HOSTS: bool = true;
1156
1157     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1158         run.alias("tidyselftest")
1159     }
1160
1161     fn make_run(run: RunConfig<'_>) {
1162         run.builder.ensure(TidySelfTest);
1163     }
1164
1165     fn run(self, builder: &Builder<'_>) {
1166         let bootstrap_host = builder.config.build;
1167         let compiler = builder.compiler(0, bootstrap_host);
1168         let cargo = tool::prepare_tool_cargo(
1169             builder,
1170             compiler,
1171             Mode::ToolBootstrap,
1172             bootstrap_host,
1173             "test",
1174             "src/tools/tidy",
1175             SourceType::InTree,
1176             &[],
1177         );
1178         try_run(builder, &mut cargo.into());
1179     }
1180 }
1181
1182 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1183 pub struct ExpandYamlAnchors;
1184
1185 impl Step for ExpandYamlAnchors {
1186     type Output = ();
1187     const ONLY_HOSTS: bool = true;
1188
1189     /// Ensure the `generate-ci-config` tool was run locally.
1190     ///
1191     /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
1192     /// appropriate configuration for all our CI providers. This step ensures the tool was called
1193     /// by the user before committing CI changes.
1194     fn run(self, builder: &Builder<'_>) {
1195         builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
1196         try_run(
1197             builder,
1198             &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
1199         );
1200     }
1201
1202     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1203         run.path("src/tools/expand-yaml-anchors")
1204     }
1205
1206     fn make_run(run: RunConfig<'_>) {
1207         run.builder.ensure(ExpandYamlAnchors);
1208     }
1209 }
1210
1211 fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
1212     builder.out.join(host.triple).join("test")
1213 }
1214
1215 macro_rules! default_test {
1216     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1217         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
1218     };
1219 }
1220
1221 macro_rules! default_test_with_compare_mode {
1222     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
1223                    compare_mode: $compare_mode:expr }) => {
1224         test_with_compare_mode!($name {
1225             path: $path,
1226             mode: $mode,
1227             suite: $suite,
1228             default: true,
1229             host: false,
1230             compare_mode: $compare_mode
1231         });
1232     };
1233 }
1234
1235 macro_rules! host_test {
1236     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1237         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
1238     };
1239 }
1240
1241 macro_rules! test {
1242     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1243                    host: $host:expr }) => {
1244         test_definitions!($name {
1245             path: $path,
1246             mode: $mode,
1247             suite: $suite,
1248             default: $default,
1249             host: $host,
1250             compare_mode: None
1251         });
1252     };
1253 }
1254
1255 macro_rules! test_with_compare_mode {
1256     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1257                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
1258         test_definitions!($name {
1259             path: $path,
1260             mode: $mode,
1261             suite: $suite,
1262             default: $default,
1263             host: $host,
1264             compare_mode: Some($compare_mode)
1265         });
1266     };
1267 }
1268
1269 macro_rules! test_definitions {
1270     ($name:ident {
1271         path: $path:expr,
1272         mode: $mode:expr,
1273         suite: $suite:expr,
1274         default: $default:expr,
1275         host: $host:expr,
1276         compare_mode: $compare_mode:expr
1277     }) => {
1278         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1279         pub struct $name {
1280             pub compiler: Compiler,
1281             pub target: TargetSelection,
1282         }
1283
1284         impl Step for $name {
1285             type Output = ();
1286             const DEFAULT: bool = $default;
1287             const ONLY_HOSTS: bool = $host;
1288
1289             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1290                 run.suite_path($path)
1291             }
1292
1293             fn make_run(run: RunConfig<'_>) {
1294                 let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1295
1296                 run.builder.ensure($name { compiler, target: run.target });
1297             }
1298
1299             fn run(self, builder: &Builder<'_>) {
1300                 builder.ensure(Compiletest {
1301                     compiler: self.compiler,
1302                     target: self.target,
1303                     mode: $mode,
1304                     suite: $suite,
1305                     path: $path,
1306                     compare_mode: $compare_mode,
1307                 })
1308             }
1309         }
1310     };
1311 }
1312
1313 default_test!(Ui { path: "tests/ui", mode: "ui", suite: "ui" });
1314
1315 default_test!(RunPassValgrind {
1316     path: "tests/run-pass-valgrind",
1317     mode: "run-pass-valgrind",
1318     suite: "run-pass-valgrind"
1319 });
1320
1321 default_test!(MirOpt { path: "tests/mir-opt", mode: "mir-opt", suite: "mir-opt" });
1322
1323 default_test!(Codegen { path: "tests/codegen", mode: "codegen", suite: "codegen" });
1324
1325 default_test!(CodegenUnits {
1326     path: "tests/codegen-units",
1327     mode: "codegen-units",
1328     suite: "codegen-units"
1329 });
1330
1331 default_test!(Incremental { path: "tests/incremental", mode: "incremental", suite: "incremental" });
1332
1333 default_test_with_compare_mode!(Debuginfo {
1334     path: "tests/debuginfo",
1335     mode: "debuginfo",
1336     suite: "debuginfo",
1337     compare_mode: "split-dwarf"
1338 });
1339
1340 host_test!(UiFullDeps { path: "tests/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
1341
1342 host_test!(Rustdoc { path: "tests/rustdoc", mode: "rustdoc", suite: "rustdoc" });
1343 host_test!(RustdocUi { path: "tests/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
1344
1345 host_test!(RustdocJson { path: "tests/rustdoc-json", mode: "rustdoc-json", suite: "rustdoc-json" });
1346
1347 host_test!(Pretty { path: "tests/pretty", mode: "pretty", suite: "pretty" });
1348
1349 default_test!(RunMake { path: "tests/run-make", mode: "run-make", suite: "run-make" });
1350
1351 host_test!(RunMakeFullDeps {
1352     path: "tests/run-make-fulldeps",
1353     mode: "run-make",
1354     suite: "run-make-fulldeps"
1355 });
1356
1357 default_test!(Assembly { path: "tests/assembly", mode: "assembly", suite: "assembly" });
1358
1359 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1360 struct Compiletest {
1361     compiler: Compiler,
1362     target: TargetSelection,
1363     mode: &'static str,
1364     suite: &'static str,
1365     path: &'static str,
1366     compare_mode: Option<&'static str>,
1367 }
1368
1369 impl Step for Compiletest {
1370     type Output = ();
1371
1372     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1373         run.never()
1374     }
1375
1376     /// Executes the `compiletest` tool to run a suite of tests.
1377     ///
1378     /// Compiles all tests with `compiler` for `target` with the specified
1379     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1380     /// "run-pass" or `suite` can be something like `debuginfo`.
1381     fn run(self, builder: &Builder<'_>) {
1382         if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
1383             eprintln!("\
1384 error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1385 help: to test the compiler, use `--stage 1` instead
1386 help: to test the standard library, use `--stage 0 library/std` instead
1387 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`."
1388             );
1389             crate::detail_exit(1);
1390         }
1391
1392         let compiler = self.compiler;
1393         let target = self.target;
1394         let mode = self.mode;
1395         let suite = self.suite;
1396
1397         // Path for test suite
1398         let suite_path = self.path;
1399
1400         // Skip codegen tests if they aren't enabled in configuration.
1401         if !builder.config.codegen_tests && suite == "codegen" {
1402             return;
1403         }
1404
1405         if suite == "debuginfo" {
1406             builder
1407                 .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1408         }
1409
1410         if suite.ends_with("fulldeps") {
1411             builder.ensure(compile::Rustc::new(compiler, target));
1412         }
1413
1414         builder.ensure(compile::Std::new(compiler, target));
1415         // ensure that `libproc_macro` is available on the host.
1416         builder.ensure(compile::Std::new(compiler, compiler.host));
1417
1418         // Also provide `rust_test_helpers` for the host.
1419         builder.ensure(native::TestHelpers { target: compiler.host });
1420
1421         // As well as the target, except for plain wasm32, which can't build it
1422         if !target.contains("wasm") || target.contains("emscripten") {
1423             builder.ensure(native::TestHelpers { target });
1424         }
1425
1426         builder.ensure(RemoteCopyLibs { compiler, target });
1427
1428         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1429
1430         // compiletest currently has... a lot of arguments, so let's just pass all
1431         // of them!
1432
1433         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
1434         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1435         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1436
1437         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1438
1439         // Avoid depending on rustdoc when we don't need it.
1440         if mode == "rustdoc"
1441             || mode == "run-make"
1442             || (mode == "ui" && is_rustdoc)
1443             || mode == "js-doc-test"
1444             || mode == "rustdoc-json"
1445         {
1446             cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1447         }
1448
1449         if mode == "rustdoc-json" {
1450             // Use the beta compiler for jsondocck
1451             let json_compiler = compiler.with_stage(0);
1452             cmd.arg("--jsondocck-path")
1453                 .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
1454             cmd.arg("--jsondoclint-path")
1455                 .arg(builder.ensure(tool::JsonDocLint { compiler: json_compiler, target }));
1456         }
1457
1458         if mode == "run-make" {
1459             let rust_demangler = builder
1460                 .ensure(tool::RustDemangler {
1461                     compiler,
1462                     target: compiler.host,
1463                     extra_features: Vec::new(),
1464                 })
1465                 .expect("in-tree tool");
1466             cmd.arg("--rust-demangler-path").arg(rust_demangler);
1467         }
1468
1469         cmd.arg("--src-base").arg(builder.src.join("tests").join(suite));
1470         cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
1471         cmd.arg("--sysroot-base").arg(builder.sysroot(compiler));
1472         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1473         cmd.arg("--suite").arg(suite);
1474         cmd.arg("--mode").arg(mode);
1475         cmd.arg("--target").arg(target.rustc_target_arg());
1476         cmd.arg("--host").arg(&*compiler.host.triple);
1477         cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1478
1479         if builder.config.cmd.bless() {
1480             cmd.arg("--bless");
1481         }
1482
1483         if builder.config.cmd.force_rerun() {
1484             cmd.arg("--force-rerun");
1485         }
1486
1487         let compare_mode =
1488             builder.config.cmd.compare_mode().or_else(|| {
1489                 if builder.config.test_compare_mode { self.compare_mode } else { None }
1490             });
1491
1492         if let Some(ref pass) = builder.config.cmd.pass() {
1493             cmd.arg("--pass");
1494             cmd.arg(pass);
1495         }
1496
1497         if let Some(ref run) = builder.config.cmd.run() {
1498             cmd.arg("--run");
1499             cmd.arg(run);
1500         }
1501
1502         if let Some(ref nodejs) = builder.config.nodejs {
1503             cmd.arg("--nodejs").arg(nodejs);
1504         }
1505         if let Some(ref npm) = builder.config.npm {
1506             cmd.arg("--npm").arg(npm);
1507         }
1508         if builder.config.rust_optimize_tests {
1509             cmd.arg("--optimize-tests");
1510         }
1511         let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1512         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1513         flags.extend(builder.config.cmd.rustc_args().iter().map(|s| s.to_string()));
1514
1515         if let Some(linker) = builder.linker(target) {
1516             cmd.arg("--linker").arg(linker);
1517         }
1518
1519         let mut hostflags = flags.clone();
1520         hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1521         hostflags.extend(builder.lld_flags(compiler.host));
1522         for flag in hostflags {
1523             cmd.arg("--host-rustcflags").arg(flag);
1524         }
1525
1526         let mut targetflags = flags;
1527         targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1528         targetflags.extend(builder.lld_flags(target));
1529         for flag in targetflags {
1530             cmd.arg("--target-rustcflags").arg(flag);
1531         }
1532
1533         cmd.arg("--python").arg(builder.python());
1534
1535         if let Some(ref gdb) = builder.config.gdb {
1536             cmd.arg("--gdb").arg(gdb);
1537         }
1538
1539         let run = |cmd: &mut Command| {
1540             cmd.output().map(|output| {
1541                 String::from_utf8_lossy(&output.stdout)
1542                     .lines()
1543                     .next()
1544                     .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
1545                     .to_string()
1546             })
1547         };
1548         let lldb_exe = "lldb";
1549         let lldb_version = Command::new(lldb_exe)
1550             .arg("--version")
1551             .output()
1552             .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1553             .ok();
1554         if let Some(ref vers) = lldb_version {
1555             cmd.arg("--lldb-version").arg(vers);
1556             let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1557             if let Some(ref dir) = lldb_python_dir {
1558                 cmd.arg("--lldb-python-dir").arg(dir);
1559             }
1560         }
1561
1562         if util::forcing_clang_based_tests() {
1563             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1564             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1565         }
1566
1567         for exclude in &builder.config.exclude {
1568             cmd.arg("--skip");
1569             cmd.arg(&exclude.path);
1570         }
1571
1572         // Get paths from cmd args
1573         let paths = match &builder.config.cmd {
1574             Subcommand::Test { ref paths, .. } => &paths[..],
1575             _ => &[],
1576         };
1577
1578         // Get test-args by striping suite path
1579         let mut test_args: Vec<&str> = paths
1580             .iter()
1581             .filter_map(|p| util::is_valid_test_suite_arg(p, suite_path, builder))
1582             .collect();
1583
1584         test_args.append(&mut builder.config.cmd.test_args());
1585
1586         // On Windows, replace forward slashes in test-args by backslashes
1587         // so the correct filters are passed to libtest
1588         if cfg!(windows) {
1589             let test_args_win: Vec<String> =
1590                 test_args.iter().map(|s| s.replace("/", "\\")).collect();
1591             cmd.args(&test_args_win);
1592         } else {
1593             cmd.args(&test_args);
1594         }
1595
1596         if builder.is_verbose() {
1597             cmd.arg("--verbose");
1598         }
1599
1600         if !builder.config.verbose_tests {
1601             cmd.arg("--quiet");
1602         }
1603
1604         let mut llvm_components_passed = false;
1605         let mut copts_passed = false;
1606         if builder.config.llvm_enabled() {
1607             let native::LlvmResult { llvm_config, .. } =
1608                 builder.ensure(native::Llvm { target: builder.config.build });
1609             if !builder.config.dry_run() {
1610                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1611                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1612                 // Remove trailing newline from llvm-config output.
1613                 cmd.arg("--llvm-version")
1614                     .arg(llvm_version.trim())
1615                     .arg("--llvm-components")
1616                     .arg(llvm_components.trim());
1617                 llvm_components_passed = true;
1618             }
1619             if !builder.is_rust_llvm(target) {
1620                 cmd.arg("--system-llvm");
1621             }
1622
1623             // Tests that use compiler libraries may inherit the `-lLLVM` link
1624             // requirement, but the `-L` library path is not propagated across
1625             // separate compilations. We can add LLVM's library path to the
1626             // platform-specific environment variable as a workaround.
1627             if !builder.config.dry_run() && suite.ends_with("fulldeps") {
1628                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1629                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
1630             }
1631
1632             // Only pass correct values for these flags for the `run-make` suite as it
1633             // requires that a C++ compiler was configured which isn't always the case.
1634             if !builder.config.dry_run() && matches!(suite, "run-make" | "run-make-fulldeps") {
1635                 // The llvm/bin directory contains many useful cross-platform
1636                 // tools. Pass the path to run-make tests so they can use them.
1637                 let llvm_bin_path = llvm_config
1638                     .parent()
1639                     .expect("Expected llvm-config to be contained in directory");
1640                 assert!(llvm_bin_path.is_dir());
1641                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1642
1643                 // If LLD is available, add it to the PATH
1644                 if builder.config.lld_enabled {
1645                     let lld_install_root =
1646                         builder.ensure(native::Lld { target: builder.config.build });
1647
1648                     let lld_bin_path = lld_install_root.join("bin");
1649
1650                     let old_path = env::var_os("PATH").unwrap_or_default();
1651                     let new_path = env::join_paths(
1652                         std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
1653                     )
1654                     .expect("Could not add LLD bin path to PATH");
1655                     cmd.env("PATH", new_path);
1656                 }
1657             }
1658         }
1659
1660         // Only pass correct values for these flags for the `run-make` suite as it
1661         // requires that a C++ compiler was configured which isn't always the case.
1662         if !builder.config.dry_run() && matches!(suite, "run-make" | "run-make-fulldeps") {
1663             cmd.arg("--cc")
1664                 .arg(builder.cc(target))
1665                 .arg("--cxx")
1666                 .arg(builder.cxx(target).unwrap())
1667                 .arg("--cflags")
1668                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::C).join(" "))
1669                 .arg("--cxxflags")
1670                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" "));
1671             copts_passed = true;
1672             if let Some(ar) = builder.ar(target) {
1673                 cmd.arg("--ar").arg(ar);
1674             }
1675         }
1676
1677         if !llvm_components_passed {
1678             cmd.arg("--llvm-components").arg("");
1679         }
1680         if !copts_passed {
1681             cmd.arg("--cc")
1682                 .arg("")
1683                 .arg("--cxx")
1684                 .arg("")
1685                 .arg("--cflags")
1686                 .arg("")
1687                 .arg("--cxxflags")
1688                 .arg("");
1689         }
1690
1691         if builder.remote_tested(target) {
1692             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1693         }
1694
1695         // Running a C compiler on MSVC requires a few env vars to be set, to be
1696         // sure to set them here.
1697         //
1698         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1699         // rather than stomp over it.
1700         if target.contains("msvc") {
1701             for &(ref k, ref v) in builder.cc[&target].env() {
1702                 if k != "PATH" {
1703                     cmd.env(k, v);
1704                 }
1705             }
1706         }
1707         cmd.env("RUSTC_BOOTSTRAP", "1");
1708         // Override the rustc version used in symbol hashes to reduce the amount of normalization
1709         // needed when diffing test output.
1710         cmd.env("RUSTC_FORCE_RUSTC_VERSION", "compiletest");
1711         cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
1712         builder.add_rust_test_threads(&mut cmd);
1713
1714         if builder.config.sanitizers_enabled(target) {
1715             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1716         }
1717
1718         if builder.config.profiler_enabled(target) {
1719             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1720         }
1721
1722         cmd.env("RUST_TEST_TMPDIR", builder.tempdir());
1723
1724         cmd.arg("--adb-path").arg("adb");
1725         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1726         if target.contains("android") {
1727             // Assume that cc for this target comes from the android sysroot
1728             cmd.arg("--android-cross-path")
1729                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1730         } else {
1731             cmd.arg("--android-cross-path").arg("");
1732         }
1733
1734         if builder.config.cmd.rustfix_coverage() {
1735             cmd.arg("--rustfix-coverage");
1736         }
1737
1738         cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);
1739
1740         cmd.arg("--channel").arg(&builder.config.channel);
1741
1742         if let Some(commit) = builder.config.download_rustc_commit() {
1743             cmd.env("FAKE_DOWNLOAD_RUSTC_PREFIX", format!("/rustc/{commit}"));
1744         }
1745
1746         builder.ci_env.force_coloring_in_ci(&mut cmd);
1747
1748         builder.info(&format!(
1749             "Check compiletest suite={} mode={} ({} -> {})",
1750             suite, mode, &compiler.host, target
1751         ));
1752         let _time = util::timeit(&builder);
1753         try_run(builder, &mut cmd);
1754
1755         if let Some(compare_mode) = compare_mode {
1756             cmd.arg("--compare-mode").arg(compare_mode);
1757             builder.info(&format!(
1758                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1759                 suite, mode, compare_mode, &compiler.host, target
1760             ));
1761             let _time = util::timeit(&builder);
1762             try_run(builder, &mut cmd);
1763         }
1764     }
1765 }
1766
1767 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1768 struct BookTest {
1769     compiler: Compiler,
1770     path: PathBuf,
1771     name: &'static str,
1772     is_ext_doc: bool,
1773 }
1774
1775 impl Step for BookTest {
1776     type Output = ();
1777     const ONLY_HOSTS: bool = true;
1778
1779     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1780         run.never()
1781     }
1782
1783     /// Runs the documentation tests for a book in `src/doc`.
1784     ///
1785     /// This uses the `rustdoc` that sits next to `compiler`.
1786     fn run(self, builder: &Builder<'_>) {
1787         // External docs are different from local because:
1788         // - Some books need pre-processing by mdbook before being tested.
1789         // - They need to save their state to toolstate.
1790         // - They are only tested on the "checktools" builders.
1791         //
1792         // The local docs are tested by default, and we don't want to pay the
1793         // cost of building mdbook, so they use `rustdoc --test` directly.
1794         // Also, the unstable book is special because SUMMARY.md is generated,
1795         // so it is easier to just run `rustdoc` on its files.
1796         if self.is_ext_doc {
1797             self.run_ext_doc(builder);
1798         } else {
1799             self.run_local_doc(builder);
1800         }
1801     }
1802 }
1803
1804 impl BookTest {
1805     /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
1806     /// which in turn runs `rustdoc --test` on each file in the book.
1807     fn run_ext_doc(self, builder: &Builder<'_>) {
1808         let compiler = self.compiler;
1809
1810         builder.ensure(compile::Std::new(compiler, compiler.host));
1811
1812         // mdbook just executes a binary named "rustdoc", so we need to update
1813         // PATH so that it points to our rustdoc.
1814         let mut rustdoc_path = builder.rustdoc(compiler);
1815         rustdoc_path.pop();
1816         let old_path = env::var_os("PATH").unwrap_or_default();
1817         let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
1818             .expect("could not add rustdoc to PATH");
1819
1820         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1821         let path = builder.src.join(&self.path);
1822         // Books often have feature-gated example text.
1823         rustbook_cmd.env("RUSTC_BOOTSTRAP", "1");
1824         rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
1825         builder.add_rust_test_threads(&mut rustbook_cmd);
1826         builder.info(&format!("Testing rustbook {}", self.path.display()));
1827         let _time = util::timeit(&builder);
1828         let toolstate = if try_run(builder, &mut rustbook_cmd) {
1829             ToolState::TestPass
1830         } else {
1831             ToolState::TestFail
1832         };
1833         builder.save_toolstate(self.name, toolstate);
1834     }
1835
1836     /// This runs `rustdoc --test` on all `.md` files in the path.
1837     fn run_local_doc(self, builder: &Builder<'_>) {
1838         let compiler = self.compiler;
1839
1840         builder.ensure(compile::Std::new(compiler, compiler.host));
1841
1842         // Do a breadth-first traversal of the `src/doc` directory and just run
1843         // tests for all files that end in `*.md`
1844         let mut stack = vec![builder.src.join(self.path)];
1845         let _time = util::timeit(&builder);
1846         let mut files = Vec::new();
1847         while let Some(p) = stack.pop() {
1848             if p.is_dir() {
1849                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1850                 continue;
1851             }
1852
1853             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1854                 continue;
1855             }
1856
1857             files.push(p);
1858         }
1859
1860         files.sort();
1861
1862         for file in files {
1863             markdown_test(builder, compiler, &file);
1864         }
1865     }
1866 }
1867
1868 macro_rules! test_book {
1869     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1870         $(
1871             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1872             pub struct $name {
1873                 compiler: Compiler,
1874             }
1875
1876             impl Step for $name {
1877                 type Output = ();
1878                 const DEFAULT: bool = $default;
1879                 const ONLY_HOSTS: bool = true;
1880
1881                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1882                     run.path($path)
1883                 }
1884
1885                 fn make_run(run: RunConfig<'_>) {
1886                     run.builder.ensure($name {
1887                         compiler: run.builder.compiler(run.builder.top_stage, run.target),
1888                     });
1889                 }
1890
1891                 fn run(self, builder: &Builder<'_>) {
1892                     builder.ensure(BookTest {
1893                         compiler: self.compiler,
1894                         path: PathBuf::from($path),
1895                         name: $book_name,
1896                         is_ext_doc: !$default,
1897                     });
1898                 }
1899             }
1900         )+
1901     }
1902 }
1903
1904 test_book!(
1905     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1906     Reference, "src/doc/reference", "reference", default=false;
1907     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1908     RustcBook, "src/doc/rustc", "rustc", default=true;
1909     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1910     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1911     TheBook, "src/doc/book", "book", default=false;
1912     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1913     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1914 );
1915
1916 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1917 pub struct ErrorIndex {
1918     compiler: Compiler,
1919 }
1920
1921 impl Step for ErrorIndex {
1922     type Output = ();
1923     const DEFAULT: bool = true;
1924     const ONLY_HOSTS: bool = true;
1925
1926     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1927         run.path("src/tools/error_index_generator")
1928     }
1929
1930     fn make_run(run: RunConfig<'_>) {
1931         // error_index_generator depends on librustdoc. Use the compiler that
1932         // is normally used to build rustdoc for other tests (like compiletest
1933         // tests in tests/rustdoc) so that it shares the same artifacts.
1934         let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
1935         run.builder.ensure(ErrorIndex { compiler });
1936     }
1937
1938     /// Runs the error index generator tool to execute the tests located in the error
1939     /// index.
1940     ///
1941     /// The `error_index_generator` tool lives in `src/tools` and is used to
1942     /// generate a markdown file from the error indexes of the code base which is
1943     /// then passed to `rustdoc --test`.
1944     fn run(self, builder: &Builder<'_>) {
1945         let compiler = self.compiler;
1946
1947         let dir = testdir(builder, compiler.host);
1948         t!(fs::create_dir_all(&dir));
1949         let output = dir.join("error-index.md");
1950
1951         let mut tool = tool::ErrorIndex::command(builder);
1952         tool.arg("markdown").arg(&output);
1953
1954         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1955         let _time = util::timeit(&builder);
1956         builder.run_quiet(&mut tool);
1957         // The tests themselves need to link to std, so make sure it is
1958         // available.
1959         builder.ensure(compile::Std::new(compiler, compiler.host));
1960         markdown_test(builder, compiler, &output);
1961     }
1962 }
1963
1964 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1965     if let Ok(contents) = fs::read_to_string(markdown) {
1966         if !contents.contains("```") {
1967             return true;
1968         }
1969     }
1970
1971     builder.info(&format!("doc tests for: {}", markdown.display()));
1972     let mut cmd = builder.rustdoc_cmd(compiler);
1973     builder.add_rust_test_threads(&mut cmd);
1974     // allow for unstable options such as new editions
1975     cmd.arg("-Z");
1976     cmd.arg("unstable-options");
1977     cmd.arg("--test");
1978     cmd.arg(markdown);
1979     cmd.env("RUSTC_BOOTSTRAP", "1");
1980
1981     let test_args = builder.config.cmd.test_args().join(" ");
1982     cmd.arg("--test-args").arg(test_args);
1983
1984     if builder.config.verbose_tests {
1985         try_run(builder, &mut cmd)
1986     } else {
1987         try_run_quiet(builder, &mut cmd)
1988     }
1989 }
1990
1991 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1992 pub struct RustcGuide;
1993
1994 impl Step for RustcGuide {
1995     type Output = ();
1996     const DEFAULT: bool = false;
1997     const ONLY_HOSTS: bool = true;
1998
1999     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2000         run.path("src/doc/rustc-dev-guide")
2001     }
2002
2003     fn make_run(run: RunConfig<'_>) {
2004         run.builder.ensure(RustcGuide);
2005     }
2006
2007     fn run(self, builder: &Builder<'_>) {
2008         let relative_path = Path::new("src").join("doc").join("rustc-dev-guide");
2009         builder.update_submodule(&relative_path);
2010
2011         let src = builder.src.join(relative_path);
2012         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
2013         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
2014             ToolState::TestPass
2015         } else {
2016             ToolState::TestFail
2017         };
2018         builder.save_toolstate("rustc-dev-guide", toolstate);
2019     }
2020 }
2021
2022 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
2023 pub struct CrateLibrustc {
2024     compiler: Compiler,
2025     target: TargetSelection,
2026     test_kind: TestKind,
2027     crates: Vec<Interned<String>>,
2028 }
2029
2030 impl Step for CrateLibrustc {
2031     type Output = ();
2032     const DEFAULT: bool = true;
2033     const ONLY_HOSTS: bool = true;
2034
2035     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2036         run.crate_or_deps("rustc-main")
2037     }
2038
2039     fn make_run(run: RunConfig<'_>) {
2040         let builder = run.builder;
2041         let host = run.build_triple();
2042         let compiler = builder.compiler_for(builder.top_stage, host, host);
2043         let crates = run
2044             .paths
2045             .iter()
2046             .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
2047             .collect();
2048         let test_kind = builder.kind.into();
2049
2050         builder.ensure(CrateLibrustc { compiler, target: run.target, test_kind, crates });
2051     }
2052
2053     fn run(self, builder: &Builder<'_>) {
2054         builder.ensure(Crate {
2055             compiler: self.compiler,
2056             target: self.target,
2057             mode: Mode::Rustc,
2058             test_kind: self.test_kind,
2059             crates: self.crates,
2060         });
2061     }
2062 }
2063
2064 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2065 pub struct Crate {
2066     pub compiler: Compiler,
2067     pub target: TargetSelection,
2068     pub mode: Mode,
2069     pub test_kind: TestKind,
2070     pub crates: Vec<Interned<String>>,
2071 }
2072
2073 impl Step for Crate {
2074     type Output = ();
2075     const DEFAULT: bool = true;
2076
2077     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2078         run.crate_or_deps("test")
2079     }
2080
2081     fn make_run(run: RunConfig<'_>) {
2082         let builder = run.builder;
2083         let host = run.build_triple();
2084         let compiler = builder.compiler_for(builder.top_stage, host, host);
2085         let test_kind = builder.kind.into();
2086         let crates = run
2087             .paths
2088             .iter()
2089             .map(|p| builder.crate_paths[&p.assert_single_path().path].clone())
2090             .collect();
2091
2092         builder.ensure(Crate { compiler, target: run.target, mode: Mode::Std, test_kind, crates });
2093     }
2094
2095     /// Runs all unit tests plus documentation tests for a given crate defined
2096     /// by a `Cargo.toml` (single manifest)
2097     ///
2098     /// This is what runs tests for crates like the standard library, compiler, etc.
2099     /// It essentially is the driver for running `cargo test`.
2100     ///
2101     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
2102     /// arguments, and those arguments are discovered from `cargo metadata`.
2103     fn run(self, builder: &Builder<'_>) {
2104         let compiler = self.compiler;
2105         let target = self.target;
2106         let mode = self.mode;
2107         let test_kind = self.test_kind;
2108
2109         builder.ensure(compile::Std::new(compiler, target));
2110         builder.ensure(RemoteCopyLibs { compiler, target });
2111
2112         // If we're not doing a full bootstrap but we're testing a stage2
2113         // version of libstd, then what we're actually testing is the libstd
2114         // produced in stage1. Reflect that here by updating the compiler that
2115         // we're working with automatically.
2116         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
2117
2118         let mut cargo =
2119             builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
2120         match mode {
2121             Mode::Std => {
2122                 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
2123             }
2124             Mode::Rustc => {
2125                 compile::rustc_cargo(builder, &mut cargo, target);
2126             }
2127             _ => panic!("can only test libraries"),
2128         };
2129
2130         // Build up the base `cargo test` command.
2131         //
2132         // Pass in some standard flags then iterate over the graph we've discovered
2133         // in `cargo metadata` with the maps above and figure out what `-p`
2134         // arguments need to get passed.
2135         if test_kind.subcommand() == "test" && !builder.fail_fast {
2136             cargo.arg("--no-fail-fast");
2137         }
2138         match builder.doc_tests {
2139             DocTests::Only => {
2140                 cargo.arg("--doc");
2141             }
2142             DocTests::No => {
2143                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2144             }
2145             DocTests::Yes => {}
2146         }
2147
2148         for krate in &self.crates {
2149             cargo.arg("-p").arg(krate);
2150         }
2151
2152         // The tests are going to run with the *target* libraries, so we need to
2153         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
2154         //
2155         // Note that to run the compiler we need to run with the *host* libraries,
2156         // but our wrapper scripts arrange for that to be the case anyway.
2157         let mut dylib_path = dylib_path();
2158         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
2159         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2160
2161         cargo.arg("--");
2162         cargo.args(&builder.config.cmd.test_args());
2163
2164         if !builder.config.verbose_tests {
2165             cargo.arg("--quiet");
2166         }
2167
2168         if target.contains("emscripten") {
2169             cargo.env(
2170                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2171                 builder.config.nodejs.as_ref().expect("nodejs not configured"),
2172             );
2173         } else if target.starts_with("wasm32") {
2174             let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
2175             let runner =
2176                 format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
2177             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
2178         } else if builder.remote_tested(target) {
2179             cargo.env(
2180                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2181                 format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
2182             );
2183         }
2184
2185         builder.info(&format!(
2186             "{}{} stage{} ({} -> {})",
2187             test_kind,
2188             crate_description(&self.crates),
2189             compiler.stage,
2190             &compiler.host,
2191             target
2192         ));
2193         let _time = util::timeit(&builder);
2194         try_run(builder, &mut cargo.into());
2195     }
2196 }
2197
2198 /// Rustdoc is special in various ways, which is why this step is different from `Crate`.
2199 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2200 pub struct CrateRustdoc {
2201     host: TargetSelection,
2202     test_kind: TestKind,
2203 }
2204
2205 impl Step for CrateRustdoc {
2206     type Output = ();
2207     const DEFAULT: bool = true;
2208     const ONLY_HOSTS: bool = true;
2209
2210     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2211         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
2212     }
2213
2214     fn make_run(run: RunConfig<'_>) {
2215         let builder = run.builder;
2216
2217         let test_kind = builder.kind.into();
2218
2219         builder.ensure(CrateRustdoc { host: run.target, test_kind });
2220     }
2221
2222     fn run(self, builder: &Builder<'_>) {
2223         let test_kind = self.test_kind;
2224         let target = self.host;
2225
2226         let compiler = if builder.download_rustc() {
2227             builder.compiler(builder.top_stage, target)
2228         } else {
2229             // Use the previous stage compiler to reuse the artifacts that are
2230             // created when running compiletest for tests/rustdoc. If this used
2231             // `compiler`, then it would cause rustdoc to be built *again*, which
2232             // isn't really necessary.
2233             builder.compiler_for(builder.top_stage, target, target)
2234         };
2235         builder.ensure(compile::Rustc::new(compiler, target));
2236
2237         let mut cargo = tool::prepare_tool_cargo(
2238             builder,
2239             compiler,
2240             Mode::ToolRustc,
2241             target,
2242             test_kind.subcommand(),
2243             "src/tools/rustdoc",
2244             SourceType::InTree,
2245             &[],
2246         );
2247         if test_kind.subcommand() == "test" && !builder.fail_fast {
2248             cargo.arg("--no-fail-fast");
2249         }
2250         match builder.doc_tests {
2251             DocTests::Only => {
2252                 cargo.arg("--doc");
2253             }
2254             DocTests::No => {
2255                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2256             }
2257             DocTests::Yes => {}
2258         }
2259
2260         cargo.arg("-p").arg("rustdoc:0.0.0");
2261
2262         cargo.arg("--");
2263         cargo.args(&builder.config.cmd.test_args());
2264
2265         if self.host.contains("musl") {
2266             cargo.arg("'-Ctarget-feature=-crt-static'");
2267         }
2268
2269         // This is needed for running doctests on librustdoc. This is a bit of
2270         // an unfortunate interaction with how bootstrap works and how cargo
2271         // sets up the dylib path, and the fact that the doctest (in
2272         // html/markdown.rs) links to rustc-private libs. For stage1, the
2273         // compiler host dylibs (in stage1/lib) are not the same as the target
2274         // dylibs (in stage1/lib/rustlib/...). This is different from a normal
2275         // rust distribution where they are the same.
2276         //
2277         // On the cargo side, normal tests use `target_process` which handles
2278         // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
2279         // case). However, for doctests it uses `rustdoc_process` which only
2280         // sets up the dylib path for the *host* (stage1/lib), which is the
2281         // wrong directory.
2282         //
2283         // Recall that we special-cased `compiler_for(top_stage)` above, so we always use stage1.
2284         //
2285         // It should be considered to just stop running doctests on
2286         // librustdoc. There is only one test, and it doesn't look too
2287         // important. There might be other ways to avoid this, but it seems
2288         // pretty convoluted.
2289         //
2290         // See also https://github.com/rust-lang/rust/issues/13983 where the
2291         // host vs target dylibs for rustdoc are consistently tricky to deal
2292         // with.
2293         //
2294         // Note that this set the host libdir for `download_rustc`, which uses a normal rust distribution.
2295         let libdir = if builder.download_rustc() {
2296             builder.rustc_libdir(compiler)
2297         } else {
2298             builder.sysroot_libdir(compiler, target).to_path_buf()
2299         };
2300         let mut dylib_path = dylib_path();
2301         dylib_path.insert(0, PathBuf::from(&*libdir));
2302         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2303
2304         if !builder.config.verbose_tests {
2305             cargo.arg("--quiet");
2306         }
2307
2308         builder.info(&format!(
2309             "{} rustdoc stage{} ({} -> {})",
2310             test_kind, compiler.stage, &compiler.host, target
2311         ));
2312         let _time = util::timeit(&builder);
2313
2314         try_run(builder, &mut cargo.into());
2315     }
2316 }
2317
2318 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2319 pub struct CrateRustdocJsonTypes {
2320     host: TargetSelection,
2321     test_kind: TestKind,
2322 }
2323
2324 impl Step for CrateRustdocJsonTypes {
2325     type Output = ();
2326     const DEFAULT: bool = true;
2327     const ONLY_HOSTS: bool = true;
2328
2329     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2330         run.path("src/rustdoc-json-types")
2331     }
2332
2333     fn make_run(run: RunConfig<'_>) {
2334         let builder = run.builder;
2335
2336         let test_kind = builder.kind.into();
2337
2338         builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
2339     }
2340
2341     fn run(self, builder: &Builder<'_>) {
2342         let test_kind = self.test_kind;
2343         let target = self.host;
2344
2345         // Use the previous stage compiler to reuse the artifacts that are
2346         // created when running compiletest for tests/rustdoc. If this used
2347         // `compiler`, then it would cause rustdoc to be built *again*, which
2348         // isn't really necessary.
2349         let compiler = builder.compiler_for(builder.top_stage, target, target);
2350         builder.ensure(compile::Rustc::new(compiler, target));
2351
2352         let mut cargo = tool::prepare_tool_cargo(
2353             builder,
2354             compiler,
2355             Mode::ToolRustc,
2356             target,
2357             test_kind.subcommand(),
2358             "src/rustdoc-json-types",
2359             SourceType::InTree,
2360             &[],
2361         );
2362         if test_kind.subcommand() == "test" && !builder.fail_fast {
2363             cargo.arg("--no-fail-fast");
2364         }
2365
2366         cargo.arg("-p").arg("rustdoc-json-types");
2367
2368         cargo.arg("--");
2369         cargo.args(&builder.config.cmd.test_args());
2370
2371         if self.host.contains("musl") {
2372             cargo.arg("'-Ctarget-feature=-crt-static'");
2373         }
2374
2375         if !builder.config.verbose_tests {
2376             cargo.arg("--quiet");
2377         }
2378
2379         builder.info(&format!(
2380             "{} rustdoc-json-types stage{} ({} -> {})",
2381             test_kind, compiler.stage, &compiler.host, target
2382         ));
2383         let _time = util::timeit(&builder);
2384
2385         try_run(builder, &mut cargo.into());
2386     }
2387 }
2388
2389 /// Some test suites are run inside emulators or on remote devices, and most
2390 /// of our test binaries are linked dynamically which means we need to ship
2391 /// the standard library and such to the emulator ahead of time. This step
2392 /// represents this and is a dependency of all test suites.
2393 ///
2394 /// Most of the time this is a no-op. For some steps such as shipping data to
2395 /// QEMU we have to build our own tools so we've got conditional dependencies
2396 /// on those programs as well. Note that the remote test client is built for
2397 /// the build target (us) and the server is built for the target.
2398 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2399 pub struct RemoteCopyLibs {
2400     compiler: Compiler,
2401     target: TargetSelection,
2402 }
2403
2404 impl Step for RemoteCopyLibs {
2405     type Output = ();
2406
2407     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2408         run.never()
2409     }
2410
2411     fn run(self, builder: &Builder<'_>) {
2412         let compiler = self.compiler;
2413         let target = self.target;
2414         if !builder.remote_tested(target) {
2415             return;
2416         }
2417
2418         builder.ensure(compile::Std::new(compiler, target));
2419
2420         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
2421
2422         let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2423
2424         // Spawn the emulator and wait for it to come online
2425         let tool = builder.tool_exe(Tool::RemoteTestClient);
2426         let mut cmd = Command::new(&tool);
2427         cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.tempdir());
2428         if let Some(rootfs) = builder.qemu_rootfs(target) {
2429             cmd.arg(rootfs);
2430         }
2431         builder.run(&mut cmd);
2432
2433         // Push all our dylibs to the emulator
2434         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2435             let f = t!(f);
2436             let name = f.file_name().into_string().unwrap();
2437             if util::is_dylib(&name) {
2438                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
2439             }
2440         }
2441     }
2442 }
2443
2444 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2445 pub struct Distcheck;
2446
2447 impl Step for Distcheck {
2448     type Output = ();
2449
2450     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2451         run.alias("distcheck")
2452     }
2453
2454     fn make_run(run: RunConfig<'_>) {
2455         run.builder.ensure(Distcheck);
2456     }
2457
2458     /// Runs "distcheck", a 'make check' from a tarball
2459     fn run(self, builder: &Builder<'_>) {
2460         builder.info("Distcheck");
2461         let dir = builder.tempdir().join("distcheck");
2462         let _ = fs::remove_dir_all(&dir);
2463         t!(fs::create_dir_all(&dir));
2464
2465         // Guarantee that these are built before we begin running.
2466         builder.ensure(dist::PlainSourceTarball);
2467         builder.ensure(dist::Src);
2468
2469         let mut cmd = Command::new("tar");
2470         cmd.arg("-xf")
2471             .arg(builder.ensure(dist::PlainSourceTarball).tarball())
2472             .arg("--strip-components=1")
2473             .current_dir(&dir);
2474         builder.run(&mut cmd);
2475         builder.run(
2476             Command::new("./configure")
2477                 .args(&builder.config.configure_args)
2478                 .arg("--enable-vendor")
2479                 .current_dir(&dir),
2480         );
2481         builder.run(
2482             Command::new(util::make(&builder.config.build.triple)).arg("check").current_dir(&dir),
2483         );
2484
2485         // Now make sure that rust-src has all of libstd's dependencies
2486         builder.info("Distcheck rust-src");
2487         let dir = builder.tempdir().join("distcheck-src");
2488         let _ = fs::remove_dir_all(&dir);
2489         t!(fs::create_dir_all(&dir));
2490
2491         let mut cmd = Command::new("tar");
2492         cmd.arg("-xf")
2493             .arg(builder.ensure(dist::Src).tarball())
2494             .arg("--strip-components=1")
2495             .current_dir(&dir);
2496         builder.run(&mut cmd);
2497
2498         let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
2499         builder.run(
2500             Command::new(&builder.initial_cargo)
2501                 .arg("generate-lockfile")
2502                 .arg("--manifest-path")
2503                 .arg(&toml)
2504                 .current_dir(&dir),
2505         );
2506     }
2507 }
2508
2509 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2510 pub struct Bootstrap;
2511
2512 impl Step for Bootstrap {
2513     type Output = ();
2514     const DEFAULT: bool = true;
2515     const ONLY_HOSTS: bool = true;
2516
2517     /// Tests the build system itself.
2518     fn run(self, builder: &Builder<'_>) {
2519         let mut check_bootstrap = Command::new(&builder.python());
2520         check_bootstrap.arg("bootstrap_test.py").current_dir(builder.src.join("src/bootstrap/"));
2521         try_run(builder, &mut check_bootstrap);
2522
2523         let mut cmd = Command::new(&builder.initial_cargo);
2524         cmd.arg("test")
2525             .current_dir(builder.src.join("src/bootstrap"))
2526             .env("RUSTFLAGS", "-Cdebuginfo=2")
2527             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2528             .env("RUSTC_BOOTSTRAP", "1")
2529             .env("RUSTDOC", builder.rustdoc(builder.compiler(0, builder.build.build)))
2530             .env("RUSTC", &builder.initial_rustc);
2531         if let Some(flags) = option_env!("RUSTFLAGS") {
2532             // Use the same rustc flags for testing as for "normal" compilation,
2533             // so that Cargo doesn’t recompile the entire dependency graph every time:
2534             // https://github.com/rust-lang/rust/issues/49215
2535             cmd.env("RUSTFLAGS", flags);
2536         }
2537         if !builder.fail_fast {
2538             cmd.arg("--no-fail-fast");
2539         }
2540         match builder.doc_tests {
2541             DocTests::Only => {
2542                 cmd.arg("--doc");
2543             }
2544             DocTests::No => {
2545                 cmd.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2546             }
2547             DocTests::Yes => {}
2548         }
2549
2550         cmd.arg("--").args(&builder.config.cmd.test_args());
2551         // rustbuild tests are racy on directory creation so just run them one at a time.
2552         // Since there's not many this shouldn't be a problem.
2553         cmd.arg("--test-threads=1");
2554         try_run(builder, &mut cmd);
2555     }
2556
2557     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2558         run.path("src/bootstrap")
2559     }
2560
2561     fn make_run(run: RunConfig<'_>) {
2562         run.builder.ensure(Bootstrap);
2563     }
2564 }
2565
2566 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2567 pub struct TierCheck {
2568     pub compiler: Compiler,
2569 }
2570
2571 impl Step for TierCheck {
2572     type Output = ();
2573     const DEFAULT: bool = true;
2574     const ONLY_HOSTS: bool = true;
2575
2576     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2577         run.path("src/tools/tier-check")
2578     }
2579
2580     fn make_run(run: RunConfig<'_>) {
2581         let compiler =
2582             run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
2583         run.builder.ensure(TierCheck { compiler });
2584     }
2585
2586     /// Tests the Platform Support page in the rustc book.
2587     fn run(self, builder: &Builder<'_>) {
2588         builder.ensure(compile::Std::new(self.compiler, self.compiler.host));
2589         let mut cargo = tool::prepare_tool_cargo(
2590             builder,
2591             self.compiler,
2592             Mode::ToolStd,
2593             self.compiler.host,
2594             "run",
2595             "src/tools/tier-check",
2596             SourceType::InTree,
2597             &[],
2598         );
2599         cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
2600         cargo.arg(&builder.rustc(self.compiler));
2601         if builder.is_verbose() {
2602             cargo.arg("--verbose");
2603         }
2604
2605         builder.info("platform support check");
2606         try_run(builder, &mut cargo.into());
2607     }
2608 }
2609
2610 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2611 pub struct ReplacePlaceholderTest;
2612
2613 impl Step for ReplacePlaceholderTest {
2614     type Output = ();
2615     const ONLY_HOSTS: bool = true;
2616     const DEFAULT: bool = true;
2617
2618     /// Ensure the version placeholder replacement tool builds
2619     fn run(self, builder: &Builder<'_>) {
2620         builder.info("build check for version replacement placeholder");
2621
2622         // Test the version placeholder replacement tool itself.
2623         let bootstrap_host = builder.config.build;
2624         let compiler = builder.compiler(0, bootstrap_host);
2625         let cargo = tool::prepare_tool_cargo(
2626             builder,
2627             compiler,
2628             Mode::ToolBootstrap,
2629             bootstrap_host,
2630             "test",
2631             "src/tools/replace-version-placeholder",
2632             SourceType::InTree,
2633             &[],
2634         );
2635         try_run(builder, &mut cargo.into());
2636     }
2637
2638     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2639         run.path("src/tools/replace-version-placeholder")
2640     }
2641
2642     fn make_run(run: RunConfig<'_>) {
2643         run.builder.ensure(Self);
2644     }
2645 }
2646
2647 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2648 pub struct LintDocs {
2649     pub compiler: Compiler,
2650     pub target: TargetSelection,
2651 }
2652
2653 impl Step for LintDocs {
2654     type Output = ();
2655     const DEFAULT: bool = true;
2656     const ONLY_HOSTS: bool = true;
2657
2658     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2659         run.path("src/tools/lint-docs")
2660     }
2661
2662     fn make_run(run: RunConfig<'_>) {
2663         run.builder.ensure(LintDocs {
2664             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
2665             target: run.target,
2666         });
2667     }
2668
2669     /// Tests that the lint examples in the rustc book generate the correct
2670     /// lints and have the expected format.
2671     fn run(self, builder: &Builder<'_>) {
2672         builder.ensure(crate::doc::RustcBook {
2673             compiler: self.compiler,
2674             target: self.target,
2675             validate: true,
2676         });
2677     }
2678 }