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