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