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