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