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