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