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