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