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