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