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