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