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