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