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